Advertisement
Guest User

Untitled

a guest
Feb 5th, 2021
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import logging
  2.  
  3. import telegram
  4. import tweepy
  5. from pytz import timezone, utc
  6. from telegram import Bot
  7. from telegram.error import TelegramError
  8.  
  9. from models import TelegramChat, TwitterUser
  10. from util import escape_markdown, prepare_tweet_text
  11.  
  12.  
  13. class TwitterForwarderBot(Bot):
  14.  
  15.     def __init__(self, token, tweepy_api_object, update_offset=0):
  16.         super().__init__(token=token)
  17.         self.logger = logging.getLogger(self.__class__.__name__)
  18.         self.logger.info("Initializing")
  19.         self.update_offset = update_offset
  20.         self.tw = tweepy_api_object
  21.  
  22.     def reply(self, update, text, *args, **kwargs):
  23.         self.sendMessage(chat_id=update.message.chat.id, text=text, *args, **kwargs)
  24.  
  25.     def send_tweet(self, chat, tweet):
  26.         try:
  27.             self.logger.debug("Sending tweet {} to chat {}...".format(
  28.                 tweet.tw_id, chat.chat_id
  29.             ))
  30.  
  31.             '''
  32.            Use a soft-hyphen to put an invisible link to the first
  33.            image in the tweet, which will then be displayed as preview
  34.            '''
  35.             photo_url = ''
  36.             if tweet.photo_url:
  37.                 photo_url = '[\xad](%s)' % tweet.photo_url
  38.  
  39.             created_dt = utc.localize(tweet.created_at)
  40.             if chat.timezone_name is not None:
  41.                 tz = timezone(chat.timezone_name)
  42.                 created_dt = created_dt.astimezone(tz)
  43.             created_at = created_dt.strftime('%Y-%m-%d %H:%M:%S %Z')
  44.             self.sendMessage(
  45.                 chat_id=chat.chat_id,
  46.                 disable_web_page_preview=not photo_url,
  47.                 text="{link_preview}{text}".format(
  48.                     link_preview=photo_url,
  49.                     text=prepare_tweet_text(tweet.text),
  50.                 ), parse_mode=telegram.ParseMode.MARKDOWN)
  51.  
  52.         except TelegramError as e:
  53.             self.logger.info("Couldn't send tweet {} to chat {}: {}".format(
  54.                 tweet.tw_id, chat.chat_id, e.message
  55.             ))
  56.  
  57.             delet_this = None
  58.  
  59.             if e.message == 'Bad Request: group chat was migrated to a supergroup chat':
  60.                 delet_this = True
  61.  
  62.             if e.message == "Unauthorized":
  63.                 delet_this = True
  64.  
  65.             if delet_this:
  66.                 self.logger.info("Marking chat for deletion")
  67.                 chat.delete_soon = True
  68.                 chat.save()
  69.  
  70.     def get_chat(self, tg_chat):
  71.         db_chat, _created = TelegramChat.get_or_create(
  72.             chat_id=tg_chat.id,
  73.             tg_type=tg_chat.type,
  74.         )
  75.         return db_chat
  76.  
  77.     def get_tw_user(self, tw_username):
  78.         try:
  79.             tw_user = self.tw.get_user(tw_username)
  80.         except tweepy.error.TweepError as err:
  81.             self.logger.error(err)
  82.             return None
  83.  
  84.         db_user, _created = TwitterUser.get_or_create(
  85.             screen_name=tw_user.screen_name,
  86.             defaults={
  87.                 'name': tw_user.name,
  88.             },
  89.         )
  90.  
  91.         if not _created:
  92.             if db_user.name != tw_user.name:
  93.                 db_user.name = tw_user.name
  94.                 db_user.save()
  95.  
  96.         return db_user
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement