コード例 #1
0
class PostSender:

    def __init__(self, token: str):
        self.__bot = TeleBot(token)
        self.__api_worker = ApiWorker()

    def get_categories(self) -> List[Category]:
        return self.__api_worker.get_categories()

    def get_posts(self, category: Union[Category, str], limit: int = 1, likes: int = 1):
        if isinstance(category, Category):
            category = category.channel_id
        return self.__api_worker.get_items(category, limit=limit, likes=likes)

    def get_recomendation(self, limit=1, likes=1):
        return self.__api_worker.get_recomendations(limit=limit, likes=likes)

    def __send_post(self, chat_id: Union[str, int], post_item: PostItem) -> bool:
        if post_item:
            try:
                if post_item.type in ('pic', 'mem'):
                    self.__bot.send_photo(chat_id, photo=post_item.url, caption=post_item.title)
                elif post_item.type == 'gif_caption':
                    self.__bot.send_animation(chat_id, animation=post_item.url, caption=post_item.title)
                elif post_item.type == 'video_clip':
                    self.__bot.send_video(chat_id, data=post_item.url, caption=post_item.title)
            except ApiTelegramException as e:
                logging.error(f"Bot can't send message error_code: {e.error_code} - {e.result_json['description']}")
                if e.error_code == 429:
                    print('timeout ', e.result_json['parameters']['retry_after'])
                    time.sleep(e.result_json['parameters']['retry_after'])
                    return self.__send_post(chat_id, post_item)
                raise
            return True

    def _check_chat(self, chat_id) -> bool:
        try:
            self.__bot.get_chat(chat_id)
            return True
        except ApiTelegramException as e:
            logging.error(f'bad chat {chat_id}: {e.result_json["description"]}')
            raise

    def publish_post(self, chat_id: Union[int, str], post_items: Union[PostItem, List[PostItem]]) -> Union[
        bool, List[bool]]:
        if self._check_chat(chat_id):
            if isinstance(post_items, PostItem):
                return self.__send_post(chat_id, post_items)
            else:
                for it in post_items:
                    self.__send_post(chat_id, it)
                    time.sleep(1)
コード例 #2
0
class DoorAlertBot:
    def __init__(self, config_provider: TokenProvider,
                 telegram_bot_message_handler: BotMessageHandler):
        self._config_provider = config_provider
        self._message_handler = telegram_bot_message_handler
        self._bot = None

    def init_bot(self):
        token = self._config_provider.get_token()
        self._bot = TeleBot(token=token)

    def contains_chat(self, chat_id):
        return self._message_handler.contains_chat(chat_id)

    def get_chat(self, chat_id):
        self._check_bot_initialized()
        return self._bot.get_chat(chat_id)

    def get_chat_administrators(self, chat_id):
        self._check_bot_initialized()
        return self._bot.get_chat_administrators(chat_id)

    def process_new_messages(self, messages: list):
        self._check_bot_initialized()
        self._bot.process_new_messages(messages)

    def _check_bot_initialized(self):
        bot = self._bot
        if bot is None:
            msg = 'Bot is not initialized.'
            logger.critical(msg)
            raise DoorAlertBotException(msg)

    def init_handlers(self):
        self._check_bot_initialized()
        bot = self._bot
        bot_message_handler = self._message_handler

        @bot.message_handler(commands=['start', 'welcome'])
        @log
        def send_welcome(message):
            bot_message_handler.handle_welcome(bot, message)

        @bot.message_handler(commands=['help'])
        @log
        def send_help(message):
            bot_message_handler.handle_help(bot, message)

        @bot.message_handler(commands=['subscribe'])
        @log
        def subscribe_chat(message):
            bot_message_handler.handle_subscribe_chat(bot, message)

        @bot.message_handler(commands=['subscriptions'])
        @log
        def get_subscriptions(message):
            bot_message_handler.handle_get_subscriptions(bot, message)

        @bot.message_handler(commands=['unsubscribe'])
        @log
        def unsubscribe_chat(message):
            bot_message_handler.handle_unsubscribe_chat(bot, message)

        #### Just some test
        def find_at(msg):
            for text in msg:
                if '@' in text:
                    return text

        @bot.message_handler(
            func=lambda msg: msg.text is not None and '@' in msg.text)
        @log
        def at_answer(message):
            texts = message.text.split()
            at_text = find_at(texts)
            bot.reply_to(message,
                         'https://instagram.com/{}'.format(at_text[1:]))

        #### End

    def polling(self, *args, **kwargs):
        logger.info("Start polling...")
        self._bot.polling(*args, **kwargs)
        logger.info("Polling ended.")