import os
from pprint import pprint
from markdownify import MarkdownConverter
from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import ApplicationBuilder, CallbackContext, CommandHandler
from telegram.helpers import escape_markdown
from state import State
from tweets import get_tweets
async def start(update: Update, context: CallbackContext.DEFAULT_TYPE):
await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, hi.")
class TgMarkdownConverter(MarkdownConverter):
def convert_a(self, el, text, convert_as_inline):
el['href'] = escape_markdown(el['href'], version=2)
return super().convert_a(el, text, convert_as_inline)
def process_text(self, el):
text = super().process_text(el)
return escape_markdown(text, version=2)
def markdownify(html, **options):
return TgMarkdownConverter(**options).convert(html)
#print(markdownify("c"))
async def check(context: CallbackContext):
tweets = get_tweets(os.environ['TWITTER_USER'])
state = State(os.environ['DB_PATH'])
for tweet in tweets:
if state.has(tweet):
return
preamble = f"""\
{tweet.author}
Permalink
"""
md = markdownify(preamble+tweet.content)
try:
await context.bot.send_message(
chat_id=os.environ['TELEGRAM_CHANNEL'],
text=md,
parse_mode=ParseMode.MARKDOWN_V2,
disable_web_page_preview=True)
except Exception:
break
state.add(tweet)
if __name__ == '__main__':
application = ApplicationBuilder().token(
os.environ['TELEGRAM_TOKEN']).build()
start_handler = CommandHandler('start', start)
application.add_handler(start_handler)
application.job_queue.run_repeating(
check, int(os.environ['INTERVAL']), first=1, chat_id=os.environ['TELEGRAM_CHANNEL'])
application.run_polling()