def _respond_commands(self, update_response): if update_response.exception(): LOGGER.error(str(update_response.exception())) update_content = update_response.result().body if not update_content: return else: update_content = json.loads(update_content) for update in update_content["result"]: message = update["message"]["text"].encode("utf-8") msp = message.split() self._last_update = update["update_id"] if msp[0].startswith("/activate"): try: if msp[1] == self.bot_ident: LOGGER.debug( "Adding chat [%s] to notify list.", update["message"]["chat"]["id"]) self._chats.append(update["message"]["chat"]["id"]) yield self.client.fetch( self.url + "sendMessage", body=json.dumps({ "chat_id": update["message"]["chat"]["id"], "reply_to_message_id": update["message"]["message_id"], "text": "Activated!"}), method="POST", headers={"Content-Type": "application/json"}) except: continue else: continue
def _respond_commands(self, update_response): """Extract commands to bot from update and act accordingly. For description of commands, see HELP_MESSAGE variable on top of this module. """ chatfile = self.chatfile chats = self.chats exc, upd = update_response.exception(), update_response.result().body if exc: LOGGER.error(str(exc)) if not upd: return data = get_data(upd, self.bot_ident) for update_id, chat_id, message_id, command in data: self._last_update = update_id chat_is_known = chat_id in chats chats_changed = False reply_text = None if command == '/activate': if chat_is_known: reply_text = 'This chat is already activated.' else: LOGGER.debug('Adding chat [%s] to notify list.', chat_id) reply_text = 'Activated.' chats.add(chat_id) chats_changed = True elif command == '/deactivate': if chat_is_known: LOGGER.debug('Deleting chat [%s] from notify list.', chat_id) reply_text = 'Deactivated.' chats.remove(chat_id) chats_changed = True if chats_changed and chatfile: write_to_file(chats, chatfile) elif command == '/help': reply_text = HELP_MESSAGE else: LOGGER.warning('Could not parse command: ' 'bot ident is wrong or missing') if reply_text: yield self.client.send_message({ 'chat_id': chat_id, 'reply_to_message_id': message_id, 'text': reply_text, 'parse_mode': 'Markdown', })
def get_chatlist(chatfile): """Try reading ids of saved chats from file. If we fail, return empty set""" if not chatfile: return set() try: with open(chatfile) as file_contents: return set(int(chat) for chat in file_contents) except (OSError, IOError) as exc: LOGGER.error('could not load saved chats:\n%s', exc) return set()
def init_handler(self): token = self.options.get('token') assert token, 'Telegram bot API token is not defined.' self.client = CustomClient(token) self.bot_ident = self.options.get('bot_ident') assert self.bot_ident, 'Telegram bot ident token is not defined.' chatfile = self.options.get('chatfile') if not chatfile: LOGGER.warning('chatfile not found in configs') elif not exists(chatfile): LOGGER.error('chatfile specified in configs does not exist') chatfile = None self.chatfile = chatfile self.chats = get_chatlist(self.chatfile) self._listen_commands()