import asyncio
import yaml
import telegram
import html
import telegram.ext
ITEM_HTML = """
Resultados para: {search_name}
Artículo: {title}
{description}
Localidad: {location}
Acepta envíos: {shipping}
Modificado el: {modified_at}
{price} {currency}
Ir al anuncio
"""
class TelegramManager:
def __init__(self):
token, channel, chat_id = self.get_config()
self._channel = channel
self._chat_id = chat_id
# Use ApplicationBuilder to create the bot application with increased timeouts
self._application = telegram.ext.ApplicationBuilder() \
.token(token) \
.connect_timeout(60) \
.read_timeout(60) \
.write_timeout(60) \
.build()
self._bot = self._application.bot
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
def get_config(self):
config_file = 'config.yaml'
with open(config_file, 'r') as file:
config = yaml.safe_load(file)
token = config['telegram_token']
telegram_channel = config['telegram_channel']
telegram_chat_id = config['telegram_chat_id']
return token, telegram_channel, telegram_chat_id
def escape_html(self, text):
return html.escape(str(text))
def send_telegram_article(self, search_name, article):
self._loop.run_until_complete(self.send_telegram_article_async(search_name, article))
async def send_telegram_article_async(self, search_name, article):
message = ITEM_HTML.format(
search_name=self.escape_html(search_name),
title=self.escape_html(article.get_title()),
description=self.escape_html(article.get_description()),
location=self.escape_html(article.get_location()),
price=self.escape_html(article.get_price()),
currency=self.escape_html(article.get_currency()),
shipping=self.escape_html(article.get_allows_shipping()),
modified_at=self.escape_html(article.get_modified_at()),
url=self.escape_html(article.get_url())
)
images_url = article.get_images()
media = []
for idx, image_url in enumerate(images_url):
if idx == 0:
media.append(
telegram.InputMediaPhoto(
media=image_url,
caption=message,
parse_mode="HTML"
)
)
else:
media.append(
telegram.InputMediaPhoto(
media=image_url
)
)
await self._bot.send_media_group(
chat_id=self._chat_id,
media=media
)