def end_poll_processor(user, bot, update, come_from=None): poll = polls_repo.find_one({'name': update.message.text, 'archived': False}) if come_from and come_from == 'start_rating_processor': button_list = [ KeyboardButton("Показать мои ответы"), KeyboardButton("Вернуться в главное меню") ] reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1)) bot.send_message(chat_id=update.message.chat_id, text="Вы вернулись в меню пройденного опроса", reply_markup=reply_markup) elif come_from and come_from == 'poll_processor': button_list = [ KeyboardButton("Показать мои ответы"), KeyboardButton("Вернуться в главное меню") ] reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1)) bot.send_message(chat_id=update.message.chat_id, text="Опрос пройден успешно!", reply_markup=reply_markup) elif update.message.text == 'Показать мои ответы': answers_record = answers_repo.find_one({'poll_id': str(user['current_poll']), 'user_id': str(user['_id'])}) message = 'Хэш транзакции: ' + answers_record['hash'] + '\n' for answer in answers_record['answers']: message += 'Вопрос: ' + answer['question_text'] + '\n' message += 'Ответ: ' + str(answer['answer']) + '\n' bot.send_message(chat_id=update.message.chat_id, text=message) elif update.message.text == 'Оценить ответы других участников': user['state'] = 'on_rating_start' user = users_repo.update(user) rating_start_processor(user, bot, update) return elif update.message.text == 'Вернуться в главное меню': user['state'] = 'on_polls_main_menu' user = users_repo.update(user) main_menu_processor(user, bot, update) elif poll: button_list = [ KeyboardButton("Показать мои ответы"), KeyboardButton("Вернуться в главное меню") ] reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1)) bot.send_message(chat_id=update.message.chat_id, text="Вы уже проходили данный опрос!", reply_markup=reply_markup) else: button_list = [ KeyboardButton("Показать мои ответы"), KeyboardButton("Вернуться в главное меню") ] reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1)) bot.send_message(chat_id=update.message.chat_id, text="Вы вернулись в меню пройденного опроса", reply_markup=reply_markup)
def post(self): print(self.args) chat_id = self.args["chat"]["chat_id"] if chat_id not in cache: cache[chat_id] = {"buttons": False} text = False if "message" in self.args and not self.args["file"]: text = self.args["message"]["text"] file_urls = [] if "file" in self.args: caption = False if "message" in self.args: caption = self.args["message"]["text"] for file_url in self.args["file"]: file_urls.append(file_url["payload"]) if self.args["buttons"]: if self.args["buttons_type"] == "inline": buttons = [] for button in self.args["buttons"]: buttons.append( InlineKeyboardButton(text=button["text"], callback_data=button["value"])) menu = InlineKeyboardMarkup(build_menu(buttons, 4)) else: cache[chat_id]["buttons"] = True buttons = [] for button in self.args["buttons"]: buttons.append(KeyboardButton(text=button["text"])) menu = ReplyKeyboardMarkup(build_menu(buttons, 2), resize_keyboard=True) else: menu = False if text: if menu: self.bot.send_message(chat_id=chat_id, text=text, reply_markup=menu) else: self.bot.send_message(chat_id=chat_id, text=text, reply_markup=ReplyKeyboardRemove()) if file_urls: for f_url in file_urls: if f_url in cache["file_ids"]: self.bot.send_photo(chat_id, cache["file_ids"][f_url], caption) else: message = self.bot.send_photo(chat_id, f_url, caption) cache["file_ids"][f_url] = message.photo[-1].file_id self.set_header('content-type', 'application/json')
def poll_start_processor(user, bot, update): poll = polls_repo.find_one({'_id': ObjectId(user['current_poll'])}) if poll.get('welcome_message'): bot.send_message(chat_id=update.message.chat_id, text=poll['welcome_message'], reply_markup={'hide_keyboard': True}) bot.send_message(chat_id=update.message.chat_id, text='Сейчас вам будут задаваться вопросы.', reply_markup={'hide_keyboard': True}) if poll.get('type') and poll['type'] == 'kompas': user['state'] = 'on_bounty' question = user['questions'][0] +\ ": напиши, за какие заслуги, ты премируешь его за прошедшую неделю" bot.send_message(chat_id=update.message.chat_id, text=question, reply_markup={'hide_keyboard': True}) else: user['state'] = 'on_poll' question = poll['questions'][0] if question['type'] == 'open': bot.send_message(chat_id=update.message.chat_id, text=question['text'], reply_markup={'hide_keyboard': True}) elif question['type'] in ['select', 'multiselect']: button_list = [] for option in question['options']: button_list.append(KeyboardButton(option)) reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1)) bot.send_message(chat_id=update.message.chat_id, text=question['text'], reply_markup=reply_markup) user = users_repo.update(user)
def archive_poll_menu_processor(user, bot, update): poll = polls_repo.find_one({'name': update.message.text, 'archived': True}) if poll: bot.send_message(chat_id=update.message.chat_id, text="Опрос в архиве") # user['state'] = 'on_archive_poll' # user = users_repo.update(user) elif update.message.text == 'Вернуться в главное меню': user['state'] = 'on_polls_main_menu' user = users_repo.update(user) main_menu_processor(user, bot, update) else: button_list = [] archive_polls = polls_repo.get_cursor({'archived': True}) for poll in archive_polls: if (not poll['participants']) or (poll['participants'] and user['username'] in poll['participants']): button_list.append(KeyboardButton(poll['name'])) button_list.append(KeyboardButton('Вернуться в главное меню')) reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1)) if len(button_list) > 1: bot.send_message(chat_id=update.message.chat_id, text="Эти опросы нельзя пройти", reply_markup=reply_markup) else: bot.send_message(chat_id=update.message.chat_id, text="Архивных опросов нет", reply_markup=reply_markup)
def coming(bot, update): start_time = datetime.datetime.now() user_name = update.message.from_user.username print( f"{datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}:用户 {user_name} 使用即将上映" ) movie_list, movie_id_list = data_funcs.coming() range_len_movie_list = range(len(movie_list)) button_list = list() for i in range_len_movie_list: button_list.append( InlineKeyboardButton(movie_list[i], callback_data=movie_id_list[i])) reply_markup = InlineKeyboardMarkup(utils.build_menu(button_list, n_cols=2)) bot.send_message(chat_id=update.message.chat_id, text="以下是即将上映的电影,请点击按钮查看详情", reply_markup=reply_markup) end_time = datetime.datetime.now() print("即将上映-执行时间:", end_time - start_time)
def news(bot, update): chat_id = update.message.chat_id bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING) url_source = 'https://newsapi.org/v1/sources?language=en' source_json = requests.get(url_source) source_object = json.loads(source_json.text) name_list = [ 'BBC News', 'Buzzfeed', 'CNN', 'Engadget', 'Google News', 'Hacker News', 'National Geographic', 'The Economist', 'The Telegraph', 'The Verge', 'The Washington Post', 'Time', 'USA Today' ] source_list = [] for item in source_object['sources']: if (item['name'] in name_list): source_list.append( telegram.InlineKeyboardButton(item['name'], callback_data='news/' + item['id'])) reply_markup = telegram.InlineKeyboardMarkup( utils.build_menu(source_list, n_cols=2)) bot.send_message(chat_id=chat_id, text="Please choose a news source", reply_markup=reply_markup).message_id
def actor_search(bot, update): start_time = datetime.datetime.now() user_name = update.message.from_user.username print( f"{datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S')} :用户 {user_name} 使用演员搜索" ) try: *_, actor_name = update.message.text.split(' ', 1) actor_list, actor_id_list = data_funcs.actor_search(actor_name) range_len_actor_list = range(len(actor_list)) button_list = list() for i in range_len_actor_list: button_list.append( InlineKeyboardButton(actor_list[i], callback_data=actor_id_list[i])) reply_markup = InlineKeyboardMarkup( utils.build_menu(button_list, n_cols=2)) bot.send_message(chat_id=update.message.chat_id, text="请选择以下演员查看详情", reply_markup=reply_markup) except ValueError: bot.send_message(chat_id=update.message.chat_id, text="请输入要搜索的演员\n" "搜索格式:演员搜索 演员名称(中间以空格分隔)\n" "例如:演员搜索 姜文") end_time = datetime.datetime.now() print("演员搜索-执行时间:", end_time - start_time)
def start(bot, update): start_time = datetime.datetime.now() user_name = update.message.from_user.username print( f"{datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S')} :用户 {user_name} 使用机器人" ) button_list = [ KeyboardButton(text="正在热映"), KeyboardButton(text="即将上映"), KeyboardButton(text="新片榜"), KeyboardButton(text="Top250"), KeyboardButton(text="快捷搜索"), KeyboardButton(text="其它搜索方式(旧接口,可能不准确)"), ] reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=2), resize_keyboard=True, one_time_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text="请根据下方按钮选择功能", reply_markup=reply_markup) end_time = datetime.datetime.now() print("入口-执行时间:", end_time - start_time)
def movie_keyboard(bot, update): start_time = datetime.datetime.now() bot.answer_callback_query(callback_query_id=update.callback_query.id, text="正在获取该电影的详细信息,请稍后") *_, id_ = update.callback_query.data.split() user_name = update.callback_query.from_user.username print( f"{datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}:用户 {user_name} 查询电影,ID:{id_}" ) msg_id = bot.send_message(chat_id=update.callback_query.message.chat_id, text="正在生成 Instant View 页面,请稍等").message_id url, score = data_funcs.movie_info(id_) bot.edit_message_text( chat_id=update.callback_query.message.chat_id, message_id=msg_id, text=url, reply_markup=InlineKeyboardMarkup( utils.build_menu([ InlineKeyboardButton("生成影评词云", callback_data=f'comment_wordcloud {id_}') ], n_cols=1)) if score != '暂无评分' else None) end_time = datetime.datetime.now() print("电影详情-执行时间:", end_time - start_time)
def top250_message(bot, update): start_time = datetime.datetime.now() user_name = update.message.from_user.username print( f"{datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}:用户 {user_name} 使用 Top250" ) footer_buttons = list() footer_buttons.append(InlineKeyboardButton('第1页', callback_data='Top250 1')) footer_buttons.append(InlineKeyboardButton('下一页', callback_data='Top250 2')) footer_buttons.append( InlineKeyboardButton('最后一页', callback_data='Top250 10')) movie_list, movie_id_list = data_funcs.top250(1) range_len_movie_list = range(len(movie_list)) button_list = list() for i in range_len_movie_list: button_list.append( InlineKeyboardButton(movie_list[i], callback_data=movie_id_list[i])) reply_markup = InlineKeyboardMarkup( utils.build_menu(button_list, n_cols=2, footer_buttons=footer_buttons)) bot.send_message(chat_id=update.message.chat_id, text="以下是电影Top250,请点击按钮查看详情", reply_markup=reply_markup) end_time = datetime.datetime.now() print("Top250-执行时间:", end_time - start_time)
def weather_menu(loc, time): button_list = [ InlineKeyboardButton("Yeah, gimme that sweet wall of text", callback_data=json.dumps({ 'time': time, 'loc': loc })) ] reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=1)) return reply_markup
def set_notifications(bot, update): button_list = [ KeyboardButton(timezone) for timezone in conf.PY_TIMEZONES_RU['timezones'] ] button_list.append(KeyboardButton('Меню')) reply_markup = ReplyKeyboardMarkup(build_menu(button_list, n_cols=3), resize_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text="Выберите часовой пояс", reply_markup=reply_markup)
def settings(update, context): user_id = update.effective_user.id groups = database.get_groups_admin(user_id) buttons = [ InlineKeyboardButton(group.title, callback_data=f"settings_{group.id}") for group in groups ] update.effective_message.reply_text(strings.SETTINGS_COMMAND, reply_markup=InlineKeyboardMarkup( build_menu(buttons, 4))) context.user_data["groups"] = groups
def send_question(update: Update, context: CallbackContext) -> int: send_string = conv_strings.send_question_type button_list = [create_inline_button(send_string.buttons, t, callback_data_name='send_question_type', callback_data_creator_payload=t.upper()) for t in send_string.buttons.keys()] reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=2)) context.bot.send_message(update.callback_query.message.chat_id, send_string.text, reply_markup=reply_markup) return TYPE
def person_search_menu(update, context): search = update.message.text.split('/person ')[1] movie = search_person(search) buttons = list() for m in movie: buttons.append( InlineKeyboardButton( f'{m.data.get("title")} - {m.data.get("year")}', callback_data=f'person,{m.movieID}')) reply_markup = InlineKeyboardMarkup(build_menu(buttons, n_cols=2)) update.message.reply_text('Which one do you mean?', reply_markup=reply_markup)
def movie_search_menu(bot, update): search = update.message.text.split('/movie ')[1] movie = movies.search(search) buttons = list() for m in movie: buttons.append( InlineKeyboardButton( f'{m.data.get("title")} - {m.data.get("year")}', callback_data=f'movie,{m.movieID}')) reply_markup = InlineKeyboardMarkup(build_menu(buttons, n_cols=2)) update.message.reply_text('Which one do you mean?', reply_markup=reply_markup, remove_keyboard=True)
def top250_keyboard(bot, update): start_time = datetime.datetime.now() bot.answer_callback_query(callback_query_id=update.callback_query.id, text='正在获取Top250电影列表,请稍后') try: *_, page_num = update.callback_query.data.split() page_num = int(page_num) except ValueError: page_num = 1 user_name = update.callback_query.from_user.username, print( f"{datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}:用户 {user_name} 使用 Top250" ) footer_buttons = list() if page_num != 1: footer_buttons.append( InlineKeyboardButton('最前一页', callback_data=f'Top250 1')) footer_buttons.append( InlineKeyboardButton('上一页', callback_data=f'Top250 {page_num - 1}')) footer_buttons.append( InlineKeyboardButton(f'第{page_num}页', callback_data=f'Top250 {page_num}')) if page_num != 10: footer_buttons.append( InlineKeyboardButton('下一页', callback_data=f'Top250 {page_num + 1}')) footer_buttons.append( InlineKeyboardButton('最后一页', callback_data=f'Top250 10')) movie_list, movie_id_list = data_funcs.top250(page_num) range_len_movie_list = range(len(movie_list)) button_list = list() for i in range_len_movie_list: button_list.append( InlineKeyboardButton(movie_list[i], callback_data=movie_id_list[i])) reply_markup = InlineKeyboardMarkup( utils.build_menu(button_list, n_cols=2, footer_buttons=footer_buttons)) bot.edit_message_text(chat_id=update.callback_query.message.chat_id, message_id=update.callback_query.message.message_id, text="以下是电影Top250,请点击按钮查看详情", reply_markup=reply_markup) end_time = datetime.datetime.now() print("Top250-执行时间:", end_time - start_time)
def back(update, context): user_id = update.effective_user.id groups = database.get_groups_admin(user_id) buttons = [ InlineKeyboardButton(group.title, callback_data=f"settings_{group.id}") for group in groups ] update.callback_query.edit_message_text( strings.SETTINGS_COMMAND, reply_markup=InlineKeyboardMarkup(build_menu(buttons, 2)), ) context.user_data["groups"] = groups if "group" in context.user_data: del context.user_data["group"] update.callback_query.answer()
def send_speech(bot, chat_id, speech_id): try: speech = DialogManager.get_speech(speech_id) except StopIteration: speech = DialogManager.get_first_speech() button_list = [ InlineKeyboardButton(option['text'], callback_data=str(option['reference'])) for option in speech['options'] ] reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=2)) bot.send_message(chat_id=chat_id, text=speech['text'], reply_markup=reply_markup)
def active_polls_menu_processor(user, bot, update): poll = polls_repo.find_one({'name': update.message.text, 'archived': False}) if poll: answer = answers_repo.find_one({'poll_id': str(poll['_id']), 'user_id': str(user['_id'])}) if answer: user['state'] = 'on_poll_end' user['current_poll'] = str(poll['_id']) user['current_questions_answers'] = [] user = users_repo.update(user) end_poll_processor(user, bot, update) else: if poll.get('type') and poll['type'] == 'kompas': for participant in poll['participants']: user['questions'].append(str(participant)) options_list = ['0%', '10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%', '90%', '100%'] user['questions'].append(options_list) user['sum'] = 0 user['state'] = 'on_poll_start' user['current_poll'] = str(poll['_id']) user['current_questions_answers'] = [] user = users_repo.update(user) poll_start_processor(user, bot, update) elif update.message.text == 'Вернуться в главное меню': user['state'] = 'on_polls_main_menu' user = users_repo.update(user) main_menu_processor(user, bot, update) else: button_list = [] active_polls = polls_repo.get_cursor({'archived': False}) for poll in active_polls: if (not poll['participants']) \ or (poll['participants'] and user['username'] in poll['participants']): button_list.append(KeyboardButton(poll['name'])) button_list.append(KeyboardButton('Вернуться в главное меню')) reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1)) if len(button_list) > 1: bot.send_message(chat_id=update.message.chat_id, text="Выберите опрос для прохождения", reply_markup=reply_markup) else: bot.send_message(chat_id=update.message.chat_id, text="Активных опросов нет", reply_markup=reply_markup)
def rating_processor(user, bot, update): current_ratings_record = next( record for record in user['ratings'] if record['poll_id'] == str(user['current_poll'])) if update.message.text == '+1': question_to_rate = next( question for question in current_ratings_record['questions'] if not question.get('rate')) question_to_rate['rate'] = 1 current_ratings_record['questions_rated'] += 1 users_repo.update(user) elif update.message.text == '-1': question_to_rate = next( question for question in current_ratings_record['questions'] if not question.get('rate')) question_to_rate['rate'] = -1 current_ratings_record['questions_rated'] += 1 users_repo.update(user) try: question_to_rate = next( question for question in current_ratings_record['questions'] if not question.get('rate')) button_list = [ KeyboardButton('+1'), KeyboardButton('-1') ] reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1)) bot.send_message(chat_id=update.message.chat_id, text='Вопрос: ' + question_to_rate['question'] + '\n' + 'Ответ: ' + question_to_rate['answer'], reply_markup=reply_markup) except StopIteration: for question in current_ratings_record['questions']: true_answer_record = answers_repo.find_one({'_id': ObjectId(question['answer_id'])}) answer = next( answer for answer in true_answer_record['answers'] if answer['question_text'] == question['question']) if question['rate'] == -1: answer['dislikes'] += 1 elif question['rate'] == 1: answer['likes'] += 1 answers_repo.update(true_answer_record) user['state'] = 'on_poll_end' user = users_repo.update(user) bot.send_message(chat_id=update.message.chat_id, text="Спасибо за участие в оценке ответов!\n\nПриглашаем стать участником" " сообщества по обсуждению вопросов регулирования" " технологий блокчейн, криптовалют и ICO:\n\n" "https://t.me/InnoExpert", reply_markup={'hide_keyboard': True}) end_poll_processor(user, bot, update)
def button(bot, update): """ Handler for inline keyboards provoked by /config command :param bot: :param update: :return: """ query = update.callback_query if query.data.startswith('bid'): configuration = { 'board': query.data[3:], 'chat_id': query.message.chat_id } database.save_config(configuration) bugs_board = client.get_board(query.data[3:]) lists = bugs_board.all_lists() button_list = [] for lst in lists: button_list.append( InlineKeyboardButton(lst.name, callback_data=f'lid{lst.id}')) reply_markup = InlineKeyboardMarkup( utils.build_menu(button_list, n_cols=2)) bot.edit_message_text(text='Now, please, choose a list', chat_id=query.message.chat_id, message_id=query.message.message_id, reply_markup=reply_markup) elif query.data.startswith('lid'): configuration = { 'list': query.data[3:], 'chat_id': query.message.chat_id } database.save_config(configuration) bot.send_message(chat_id=query.message.chat_id, text=f'Congrats! You are ready to report bugs!') else: bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=settings.WRONG)
def shortcut_search(bot, update): start_time = datetime.datetime.now() user_name = update.message.from_user.username print(f"{datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}:用户 {user_name} 使用快捷搜索") button_list = list() button_list.append(InlineKeyboardButton('开始搜索', switch_inline_query_current_chat='')) reply_markup = InlineKeyboardMarkup(utils.build_menu(button_list, n_cols=1)) bot.send_message(chat_id=update.message.chat_id, text="点击以下按钮,然后输入要搜索的电影、演员或导演", reply_markup=reply_markup) end_time = datetime.datetime.now() print("快捷搜索-执行时间:", end_time - start_time)
def settings(bot, update): status, reply_markup = None, None user = session.query(UserProfile).filter( UserProfile.chat_id == update.message.chat_id).one_or_none() if user.notify_timer: status = 'Расписание включено {0}\n' \ 'Часовой пояс \b{1}\b\n' \ 'Звук автоуведомлений отключен с {2} до {3}'\ .format( emojize(":white_check_mark:", use_aliases=True), user.timezone, user.time_notify_start, user.time_notify_stop ) button_list = [[ KeyboardButton("Выключить расписание"), KeyboardButton("Изменить настройки") ], [KeyboardButton("Меню")]] reply_markup = ReplyKeyboardMarkup(button_list, resize_keyboard=True) elif not user.notify_timer and not user.time_notify_start: status = 'Расписание не включено и не настроено' button_list = [ KeyboardButton("Настроить расписание"), KeyboardButton("Меню") ] reply_markup = ReplyKeyboardMarkup(build_menu(button_list, n_cols=2), resize_keyboard=True) elif not user.notify_timer: status = 'Раписание выключено {0} \n' \ 'Часовой пояс \b{1}\b\n' \ 'Звук автоуведомлений отключен с {2} до {3}'\ .format( emojize(':no_entry_sign:', use_aliases=True), user.timezone, user.time_notify_start, user.time_notify_stop ) button_list = [[ KeyboardButton("Включить расписание"), KeyboardButton("Изменить настройки") ], [KeyboardButton("Меню")]] reply_markup = ReplyKeyboardMarkup(button_list, resize_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text=status, reply_markup=reply_markup)
def beer_search_menu(bot, update): if update.message.text.startswith('/beer'): search = update.message.text.split('/beer ')[1] beers = beer.search_untappd(search) elif update.message.text.startswith('/homebrew'): search = update.message.text.split('/homebrew ')[1] beers = beer.search_untappd(search, homebrew=True) buttons = list() for b in beers: emoji = emojify(b['country']) buttons.append( InlineKeyboardButton( f'{emoji} {b["name"]} by {b["brewery"]} - ({b["checkin_count"]}) checkins', callback_data=f'beer,{b["bid"]}')) reply_markup = InlineKeyboardMarkup(build_menu(buttons, n_cols=1)) update.message.reply_text('Which one do you mean?', reply_markup=reply_markup, remove_keyboard=True)
def config(bot, update): """ /config telegram command. Needed to set up required Trello board and list :param bot: :param update: :return: """ boards = client.list_boards() button_list = [] for board in boards: button_list.append( InlineKeyboardButton(board.name, callback_data=f'bid{board.id}')) reply_markup = InlineKeyboardMarkup(utils.build_menu(button_list, n_cols=2)) bot.send_message(chat_id=update.message.chat_id, text="Please, choose a board", reply_markup=reply_markup)
def main_menu_processor(user, bot, update): if update.message.text == 'Показать активные опросы': user['state'] = 'on_active_polls' user = users_repo.update(user) active_polls_menu_processor(user, bot, update) elif update.message.text == 'Показать архив': user['state'] = 'on_archive_polls' user = users_repo.update(user) archive_poll_menu_processor(user, bot, update) else: button_list = [ KeyboardButton("Показать активные опросы"), KeyboardButton("Показать архив") ] reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1)) bot.send_message(chat_id=update.message.chat_id, text="Какие опросы вы хотите посмотреть?", reply_markup=reply_markup)
def create_buttons(game_id: str, link: str, buttons: Dict, is_attach_key: bool = True): payload = "{}".format(game_id) button_list = [ create_inline_button( buttons, t, callback_data_creator_payload=(payload + ';' + t) if is_attach_key else payload) for t in buttons.keys() ] reply_markup = InlineKeyboardMarkup( build_menu(button_list, n_cols=2, footer_buttons=[create_bot_link_button(link)])) return reply_markup
def post(bot, update): chat_id = update.message.chat_id bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING) source_list = [ telegram.InlineKeyboardButton('Yes!', callback_data='post/1'), telegram.InlineKeyboardButton('No', callback_data='post/0') ] reply_markup = telegram.InlineKeyboardMarkup( utils.build_menu(source_list, n_cols=2)) bot.send_message(chat_id=chat_id, text="Would you like to post it?", reply_markup=reply_markup, reply_to_message_id=update.message.message_id) file_object = open('message_meta.py', 'w') try: file_object.write(str(update.message)) finally: file_object.close()
def settings(bot, update): status, reply_markup = None, None user = session.query(UserProfile).filter(UserProfile.chat_id == update.message.chat_id).one_or_none() if user.notify_timer: status = 'Расписание включено {0}\n' \ 'Часовой пояс \b{1}\b\n' \ 'Звук автоуведомлений отключен с {2} до {3}'\ .format( emojize(":white_check_mark:", use_aliases=True), user.timezone, user.time_notify_start, user.time_notify_stop ) button_list = [ [KeyboardButton("Выключить расписание"), KeyboardButton("Изменить настройки")], [KeyboardButton("Меню")] ] reply_markup = ReplyKeyboardMarkup(button_list, resize_keyboard=True) elif not user.notify_timer and not user.time_notify_start: status = 'Расписание не включено и не настроено' button_list = [ KeyboardButton("Настроить расписание"), KeyboardButton("Меню") ] reply_markup = ReplyKeyboardMarkup(build_menu(button_list, n_cols=2), resize_keyboard=True) elif not user.notify_timer: status = 'Раписание выключено {0} \n' \ 'Часовой пояс \b{1}\b\n' \ 'Звук автоуведомлений отключен с {2} до {3}'\ .format( emojize(':no_entry_sign:', use_aliases=True), user.timezone, user.time_notify_start, user.time_notify_stop ) button_list = [ [KeyboardButton("Включить расписание"), KeyboardButton("Изменить настройки")], [KeyboardButton("Меню")] ] reply_markup = ReplyKeyboardMarkup(button_list, resize_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text=status, reply_markup=reply_markup)
def text(bot, update): """ Function for handling text-messages """ remove_special_keyboard = ReplyKeyboardRemove() if validate_request(update.message.text): amount, result, name, year, id_ = make_request_for_search( update.message.text) if amount == 0 or amount > 25: bot.send_message(chat_id=update.message.chat_id, text=result, reply_markup=remove_special_keyboard) elif amount == 1: bot.send_message( chat_id=update.message.chat_id, text=one_result_message % ('https://declarator.org/person/%s/' % id_, name, year), parse_mode=ParseMode.HTML, reply_markup=remove_special_keyboard) for message in result: bot.send_message(chat_id=update.message.chat_id, text=message, parse_mode=ParseMode.MARKDOWN, reply_markup=remove_special_keyboard) else: button_list = [] for person in result: button_list.append( InlineKeyboardButton(person['text'], callback_data=person['id'])) reply_markup = InlineKeyboardMarkup( build_menu(button_list, n_cols=1)) bot.send_message(chat_id=update.message.chat_id, text=many_results_message % update.message.text, reply_markup=reply_markup) else: bot.send_message(chat_id=update.message.chat_id, text='Неверный формат запроса.', reply_markup=remove_special_keyboard)
def set_notifications(bot, update): button_list = [KeyboardButton(timezone) for timezone in conf.PY_TIMEZONES_RU['timezones']] button_list.append(KeyboardButton('Меню')) reply_markup = ReplyKeyboardMarkup(build_menu(button_list, n_cols=3), resize_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text="Выберите часовой пояс", reply_markup=reply_markup)