def entry(self, message: Message, user: User, bot: TeleBot, competitor: Competitor = None): if competitor is None: competitor = user.check_association() res = user.check_result() if not res: pass # TODO opponent, opponent_user = get_opponent_and_opponent_user(competitor) if not opponent or not opponent_user: res.delete() return teardown_challenge( competitor, message, user, bot, 'challenge_confirm_cannot_find_opponent_msg' if not opponent else 'challenge_confirm_cannot_fin_opponents_user_msg') bot.send_message(message.chat.id, get_translation_for('result_confirmation_msg') + '\n' + render_result(res, final=False), reply_markup=get_result_confirmation_keyboard(), parse_mode='html') return RET.OK, None, None, None
def _forward_message_to_admin(self): token = db.get_client_bot_token(self._user_id) admin_bot = TeleBot(token) operators = db.get_operators(self._user_id) response = f'<b>{self._client_name}</b>\n\n{self._text}' for operator in operators: admin_bot.send_message(operator, response, parse_mode='HTML')
def process_message(self, message: Message, user: User, bot: TeleBot, competitor: Competitor): score = to_int(message.text, None) if score is None: return super().process_message(message, user, bot) res: Result = user.check_result() if res.result is not None: return RET.OK, None, None, None # TODO: checks if len(res.scores) > 10: bot.send_message( user.user_id, get_translation_for('results_maximum_scores_entered_msg'), reply_markup=self.__base_keyboard()) return RET.OK, None, None, None if score < 0 or score > 15: bot.send_message( user.user_id, get_translation_for('results_incorrect_score_msg'), reply_markup=self.__base_keyboard()) return RET.OK, None, None, None res.scores.append(score) res.save() return self.process_result(message, user, bot, competitor)
class TelegramBot: def __init__(self, token: str, user_id: str): self.user_id = user_id self.bot = TeleBot(token) # current answer from bot. # Can be '' or 'new_captcha' self.answer = None @self.bot.message_handler() def company_receiving(message): self.bot.send_message(message.from_user.id, 'Received') self.bot.stop_polling() self.answer = message.text @self.bot.callback_query_handler(lambda query: query.data == 'button_1' ) def process_callback(query): self.bot.stop_polling() self.answer = 'new_captcha' def send_photo(self, img: bytes): keyboard = button_add() self.answer = '' self.bot.send_photo(self.user_id, photo=img, reply_markup=keyboard) self.bot.polling()
def send_photo(bot: TeleBot, bot_state: BotState, message: Message, database: DataBase, ydisk: YandexDisk, is_canceled: bool = False): state_additional = bot_state.get_state(message.from_user.id)["additional"] keyboard = None if is_canceled: keyboard = state_additional["keyboard"]["with_cancel"] else: keyboard = state_additional["keyboard"]["normal"] photo = database.get_random_photos(1) if len(photo) > 0: photo = photo[0] photo_url = ydisk.disk.get_download_link(photo["filepath"]) bot.send_photo(message.chat.id, photo_url, reply_markup=keyboard, caption="https://www.instagram.com/{}".format( photo["source"])) else: bot.send_message( message.chat.id, "Фотографии закончились :(\nВведите /help, остановите эту хреновину." ) bot_state.add_state(message.chat.id, "help") return photo
def send_emails_telegram(bot: TeleBot, chat_id: str): os.chdir("INBOX") # Переход в папку с сохраненными письмами for mail in os.listdir("."): # Получаем список папок, в которых лежит само письмо и его влложения os.chdir(mail) # Переходим в папку с письмом if os.path.exists("text_plain.txt"): # Если существует текстовая версия письма with open("text_plain.txt") as f: message = split(f.read()) bot.send_message(chat_id, message[0]) # Отправляем ее первые 4092 символа if len(message) >= 2: # И высылаем файл письма целиком (если письмо содержит более 4092 символов) bot.send_document(chat_id, open("text_plain.txt", "rb"), caption="Продолжение письма") os.remove("text_plain.txt") # Удаляем отправленный файл if os.path.exists("text_html.html"): # Если существует веб версия версия письма, то отправляем ее файлом bot.send_document(chat_id, open("text_html.html", "rb"), caption="{} (веб версия письма)".format(mail)) os.remove("text_html.html") # Удаляем отправленный файл if os.path.exists("attachments"): # Если есть вложения в письме, то отправляем и их. for file in os.listdir("attachments"): bot.send_document(chat_id, open(file, "rb")) os.remove(file) # Удаляем отправленный файл os.rmdir("attachments") # Удаляем пустую папку os.chdir("../") # Выходим из папки с письмом os.rmdir(mail) # И удаляем ее, так как она пуста os.chdir("../") # Выходим из папки с сохраннеными письмами
def update_and_paginate(self, message: Message, user: User, bot: TeleBot, competitor: Competitor, page=1, update=False, updateText=False): if guard.get_allowed()[0] and guard.update_allowed()[0]: UsersSheet.update_model() possible_levels = ChallengeSendState.get_possible_levels( competitor.level) available_competitors = Competitor.objects( status__in=(COMPETITOR_STATUS.ACTIVE, COMPETITOR_STATUS.PASSIVE), level__in=possible_levels, id__ne=competitor.latest_challenge_sent_to.id if competitor.latest_challenge_sent_to is not None else ObjectId(), associated_user_vanished__ne=True).paginate(page=1, per_page=10) if not render_pagination(available_competitors, message, bot, get_translation_for('challenge_send_msg'), self.__base_keyboard, update=update, updateText=updateText): bot.send_message( message.chat.id, get_translation_for('challenge_no_applicable_competitors_msg')) return False return True
def send_venue(message: Message, bot: TeleBot): nearly_places = location(message) count = len(nearly_places) buttons = [] lang = redis_cache.get_language(message.chat.id) if lang == 'uz': txt = f'Sizga yaqin {count} mehmonxona' else: txt = text(count) bot.send_message(chat_id=message.chat.id, text=txt) for place in nearly_places: buttons.append(InlineKeyboardButton(text=places[place]['title'], callback_data=f'place_{place}')) bot.send_venue(chat_id=message.chat.id, latitude=places[place]['latitude'], longitude=places[place]['longitude'], title=places[place]['title'], address=places[place]['address']) markup = InlineKeyboardMarkup() for button in buttons: markup.add(button) if len(buttons) > 0: if lang == 'uz': txt = choose_place_uz else: txt = choose_place_ru bot.send_message(chat_id=message.chat.id, text=txt, reply_markup=markup)
def process_result(self, message: Message, user: User, bot: TeleBot, competitor: Competitor, final=False): opponent, opponent_user = get_opponent_and_opponent_user(competitor) if not opponent or not opponent_user: return teardown_challenge( competitor, message, user, bot, 'challenge_confirm_cannot_find_opponent_msg' if not opponent else 'challenge_confirm_cannot_fin_opponents_user_msg') res = user.check_result() if not res: res = Result(player_a=competitor, player_b=opponent, confirmged=False) res.save() user.current_result = res user.save() text = render_result(res, final) bot.send_message( message.chat.id, text, reply_markup=self.__base_keyboard(confirmation_stage=final), parse_mode='html') return RET.OK, None, None, None
def handle_subscribe_chat(self, bot: TeleBot, message: Message): chat_id = message.chat.id logger.debug('Subscribing chat {}'.format(chat_id)) self._subscriptions.add(chat_id) success_msg = 'Chat subscribed.' logger.debug('Sending success message to user: {}'.format(success_msg)) bot.send_message(message.chat.id, success_msg)
def handle_get_subscriptions(self, bot: TeleBot, message: Message): chat_id = message.chat.id response = 'No chats subscribed yet.' if len( self._subscriptions) == 0 else ', '.join( str(e) for e in self._subscriptions) logger.debug('Sending response to user: {}'.format(response)) bot.send_message(chat_id, response)
def echo(bot: TeleBot, bot_state: BotState, message: Message, database: DataBase, ydisk: YandexDisk): state_additional = bot_state.get_state(message.from_user.id)["additional"] last_photo = state_additional["last_photo"] # state_additional["penult_photo"] = if message.text == "Подтвердить": database.set_photo_status(last_photo["hash"], "checked", message.from_user.id) state_additional["penult_photo"] = last_photo state_additional["last_photo"] = send_photo(bot, bot_state, message, database, ydisk, True) elif message.text == "Удалить": database.set_photo_status(last_photo["hash"], "deleted", message.from_user.id) state_additional["penult_photo"] = last_photo state_additional["last_photo"] = send_photo(bot, bot_state, message, database, ydisk, True) elif message.text == "Отменить последнее решение": database.set_photo_status(state_additional["penult_photo"]["hash"], "unchecked", message.from_user.id) send_canceled_photo(state_additional["penult_photo"], bot, bot_state, message, ydisk) state_additional["last_photo"] = state_additional["penult_photo"] else: bot.send_message( message.chat.id, "Введите нормальный ответ или воспользуйтесь другой командой (/help), чтобы отменить действие этой." )
def _show_help(bot: TeleBot, message: Message, botan_key: str) -> None: """Help message. Showing all available commands. """ bot.send_message(message.chat.id, texts.help) if not botan_track(botan_key, message.chat.id, message, 'Обработка команды'): logging.error('botan problem')
def do_help(bot: TeleBot, bot_state, message: Message, database: DataBase, ydisk): is_admin = database.is_admin(message.from_user.id) help_str = "" for command in commands: if not command.is_admin_command or (command.is_admin_command and is_admin): help_str += "/{} - {}\n".format(command.command, command.short_description) bot.send_message(message.chat.id, help_str)
def _send_answer_for_voice_input(bot: TeleBot, message: Message, telegram_token: str, yandex_key: str, botan_key: str) -> None: """Finding out answer for voice input. First of all - convert voice to text via yandex service, then searching correct answer. """ file_info = bot.get_file(message.voice.file_id) file = requests.get('https://api.telegram.org/file/bot{0}/{1}'.format(telegram_token, file_info.file_path)) try: # обращение к нашему новому модулю text: str = speech_to_text(file_in_bytes=file.content, key=yandex_key) is_answer = _send_text_answer(bot, text, message.chat.id) if not botan_track(botan_key, message.chat.id, message, 'Обработка голоса', text=text): logging.error('botan problem') except SpeechException: # Обработка случая, когда распознавание не удалось bot.send_message(message.chat.id, 'Не удалось распознать Ваш акцент') if not botan_track(botan_key, message.chat.id, message, 'Обработка голоса', 'Не распознано', text=""): logging.error('botan problem') else: if not is_answer: # Бизнес-логика bot.send_message(message.chat.id, 'Вы сказали: "{}"\nЯ не знаю, как на это реагировать :-('.format(text)) if not botan_track(botan_key, message.chat.id, message, 'Обработка голоса', 'Нет ответа', text=text): logging.error('botan problem')
def _find_articles(bot: TeleBot, message: Message): """Searching for article and asking about warehouse.""" current_articles_chats.clear() for acticle in data.articles: if acticle['art'] == message.text: current_articles_chats.append( { 'art': acticle['art'], 'name': acticle['name'], 'butovo': acticle['butovo'], 'neva': acticle['neva'], 'id': message.chat.id }) if current_articles_chats: if len(current_articles_chats) > 1: pass keyboard: InlineKeyboardMarkup = _get_keyboard_warehouses() bot.send_message(message.chat.id, "Выберите склад:", reply_markup=keyboard) else: bot.send_message(message.chat.id, "Товар с таким артикулом не найден") chats_with_searching_articles.remove(message.chat.id)
def do(self, bot: TeleBot, bot_state, message: Message, database: DataBase, ydisk: YandexDisk): self.tools = { "bot": bot, "bot_state": bot_state, "database": database, "ydisk": ydisk } if (not self.is_admin_command) or (self.is_admin_command and database.is_admin( message.from_user.id)): last_state = bot_state.get_state(message.from_user.id) if last_state is not None and last_state["command"].end is not None: last_command = last_state["command"] if not last_state["additional"]["is_ends"]: last_command.end(bot, bot_state, message, database, ydisk) else: bot.send_message( message.chat.id, "Дождитесь окончания предыдущей команды!") return bot_state.add_state(message.from_user.id, self.command) self.__do(bot, bot_state, message, database, ydisk) else: bot.send_message(message.chat.id, "Данная команда вам не доступна!")
def inactive_btn(self, message: Message, user: User, bot: TeleBot): bot.send_message( message.chat.id, get_translation_for('menu_moved_to_inactive_pseudo1_btn') + '\n' + get_translation_for('menu_moved_to_inactive_pseudo2_btn'), parse_mode='html' ) return RET.OK, None, None, None
def send_telegram_message(token: str, chat_id: int, message: str) -> Result[bool]: try: bot = TeleBot(token) for text in split_string(message, 4096): bot.send_message(chat_id, text) return Result(ok=True) except Exception as e: return Result(error=str(e))
def add_bot(message: types.Message): token = util.extract_arguments(message.text) tokens[token] = True new_bot = TeleBot(token) new_bot.delete_webhook() new_bot.set_webhook(f"{config.WEBHOOK_HOST}/{config.WEBHOOK_PATH}/{token}") new_bot.send_message(message.chat.id, "Webhook was set.")
def _send_telegram_message(self, message: str): try: bot = TeleBot(self.get_bot().telegram_token) chat_id = self.get_bot().telegram_channel_id for text in split_string(message, 4096): bot.send_message(chat_id, text) except Exception as e: self.log.error(f"send_telegram_message: {str(e)}") return str(e)
def entry(self, message: Message, user: User, bot: TeleBot, competitor=None): if not competitor: logger.warning('Check_wrapper not provided Competitor object') competitor = user.associated_with.fetch() bot.send_message( message.chat.id, get_translation_for('menu_msg'), reply_markup=self.__base_keyboard(status=competitor.status) ) return RET.OK, None, None, None
def paint(self, text, text_color=GREEN, bot_message: telebot.TeleBot = None, cid: int = None, reply_keyboard: telebot.types=None): if text_color not in self.__colors: raise ConsoleColorError() print(self.__colors[text_color] + text + self.__colors[END_COLOR]) if bot_message: if reply_keyboard: bot_message.send_message(cid, text, reply_markup=reply_keyboard) else: bot_message.send_message(cid, text)
def confirm_scores(self, message: Message, user: User, bot: TeleBot, competitor: Competitor): res = user.check_result() if not len(res.scores) or len(res.scores) % 2: bot.send_message( message.chat.id, get_translation_for('result_scores_count_must_be_odd_msg'), reply_markup=self.__base_keyboard()) return RET.OK, None, None, None return self.process_result(message, user, bot, competitor, True)
def handle_unsubscribe_chat(self, bot: TeleBot, message: Message): chat_id = message.chat.id logger.debug('Removing chat {}'.format(chat_id)) if not chat_id in self._subscriptions: msg = 'This chat is not subscribed yet.' else: self._subscriptions.remove(chat_id) msg = 'Chat unsubscribed. You will no longer receive updates from this chat.' logger.debug('Sending message to user: {}'.format(msg)) bot.send_message(message.chat.id, msg)
def _send_answer_for_text_input(bot: TeleBot, message: Message, botan_key: str) -> None: """Getting answer fot text input.""" for id in chats_with_searching_articles: if id == message.chat.id: return is_answer: bool = _send_text_answer(bot, message.text, message.chat.id) if not is_answer: bot.send_message(message.chat.id, 'Таки я не понял, чего Вы хотите') if not botan_track(botan_key, message.chat.id, message, 'Обработка текста', '' if is_answer else 'Нет ответа'): logging.error('botan problem')
def confirm_cancellation_opponent(self, message: Message, user: User, bot: TeleBot, competitor: Competitor): if competitor.status != COMPETITOR_STATUS.CHALLENGE_NEED_CANCELLATION_CONFIRMATION: return RET.OK, None, None, None if not user.dismiss_confirmed: bot.send_message( message.chat.id, get_translation_for('challenge_cancel_msg'), reply_markup=self.__base_keyboard(status=competitor.status) ) user.dismiss_confirmed = True user.save() return RET.OK, None, None, None else: user.dismiss_confirmed = False user.save() opponent, opponent_user = get_opponent_and_opponent_user(competitor) if not opponent or not opponent_user: return teardown_challenge( competitor, message, user, bot, 'challenge_confirm_cannot_find_opponent_msg' if not opponent else 'challenge_confirm_cannot_fin_opponents_user_msg' ) opponent.change_status(opponent.previous_status) opponent.previous_status = None opponent.previous_challenge_status = None opponent.in_challenge_with = None opponent.challenge_started_at = None opponent.save() competitor.change_status(competitor.previous_status) competitor.previous_status = None competitor.previous_challenge_status = None competitor.in_challenge_with = None competitor.challenge_started_at = None competitor.save() smwae_check( opponent_user.user_id, get_translation_for('challenge_canceled_msg').format(competitor.name), opponent_user, reply_markup=self.__base_keyboard(status=opponent.status) ) bot.send_message( message.chat.id, get_translation_for('challenge_canceled_msg').format(opponent.name), reply_markup=self.__base_keyboard(status=competitor.status) ) LogsSheet.glog(get_translation_for('gsheet_log_game_canceled').format(opponent.name, competitor.name)) return RET.OK, None, None, None
def main(): bot = TeleBot(TOKEN) redis_sub.subscribe(REPLY_COLL_NAME) while (True): reply_msg = redis_sub.get_message().get("data", None) if reply_msg: reply_msg_data = loads(reply_msg) bot.send_message(reply_msg_data.get("chat_id"), reply_msg_data.get("reply_msg"))
def end_sick_leave(self, message: Message, user: User, bot: TeleBot, competitor: Competitor): if competitor.status != COMPETITOR_STATUS.INJUIRY: return RET.OK, None, None, None competitor.change_status(competitor.previous_status) competitor.save() bot.send_message( message.chat.id, get_translation_for('menu_on_sick_leave_end_msg'), reply_markup=self.__base_keyboard(status=competitor.status) ) LogsSheet.glog(get_translation_for('gsheet_log_on_injuiry_ended').format(competitor.name)) return RET.OK, None, None, None
def req_num(bot: TeleBot, chat_id): lang = redis_cache.get_language(chat_id) if lang == 'uz': _req_num = req_num_uz req_num_but = req_num_but_uz else: _req_num = req_num_ru req_num_but = req_num_but_ru markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) button_contact = KeyboardButton(text=req_num_but, request_contact=True) markup.add(button_contact) bot.send_message(chat_id=chat_id, text=_req_num, reply_markup=markup)
class TestTelebot: def setup(self): self.app = TeleBot(__name__) def teardown(self): self.app = None def test_no_config(self): ''' Verify polling can't start without api_key set. ''' pytest.raises(ValueError, self.app.poll) def test_parrot_registered(self): ''' Verify route decorator registers within the update rules. ''' @self.app.route('(?!/).+') def parrot(message): return "testing {}".format(message) assert len(self.app.update_rules) == 1 assert self.app.update_rules[0]['rule'] == re.compile('(?!/).+') assert self.app.update_rules[0]['endpoint'] is None assert self.app.update_rules[0]['options'] == {} assert self.app.update_rules[0]['view_func']('it') == "testing it" @my_vcr.use_cassette('telegram.yaml') def test_start(self): self.app.config['api_key'] = '123:abc' self.app._start() assert self.app.whoami == { 'first_name': 'Test-Bot', 'id': 123, 'username': '******', } @my_vcr.use_cassette('telegram.yaml') def test_start_existing(self): ''' Make sure start doesn't override whoami when previously set. ''' self.app.config['api_key'] = '123:abc' self.app.whoami = {'id': 111} self.app._start() assert self.app.whoami == {'id': 111} @my_vcr.use_cassette('telegram.yaml') def test_parrot_app(self): test_messages = [] @self.app.route('/command ?(.*)') def example_command(message, cmd): chat_dest = message['chat']['id'] msg = "Command Received: {}".format(cmd) self.app.send_message(chat_dest, msg) test_messages.append([message, cmd, chat_dest, msg]) @self.app.route('(?!/).+') def parrot(message): chat_dest = message['chat']['id'] user_msg = message['text'] msg = "Parrot Says: {}".format(user_msg) self.app.send_message(chat_dest, msg) test_messages.append([message, chat_dest, msg]) self.app.config['api_key'] = '123:abc' pytest.raises(ValueError, self.app.poll, debug=True) assert test_messages == [ [ { 'chat': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'type': 'private', 'username': '******', }, 'date': 1462057648, 'from': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'username': '******', }, 'message_id': 73, 'text': 'Test 1', }, 8282, 'Parrot Says: Test 1', ], [ { 'chat': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'type': 'private', 'username': '******', }, 'date': 1462057662, 'entities': [ {'length': 8, 'offset': 0, 'type': 'bot_command'}, ], 'from': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'username': '******', }, 'message_id': 75, 'text': '/command test', }, 'test', 8282, 'Command Received: test', ], [ { 'chat': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'type': 'private', 'username': '******', }, 'date': 1462057676, 'from': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'username': '******', }, 'message_id': 77, 'text': 'End test', }, 8282, 'Parrot Says: End test' ], ]