def esami(update: Update, context: CallbackContext): check_log(update, context, "esami") if 'esami' in context.user_data: context.user_data['esami'].clear( ) #ripulisce il dict dell'user relativo al comando /esami da eventuali dati presenti else: context.user_data['esami'] = { } #crea il dict che conterrà i dati del comando /esami all'interno della key ['esami'] di user data user_id = update.message.from_user.id chat_id = update.message.chat_id if chat_id != user_id: # forza ad eseguire il comando in una chat privata, anche per evitare di inondare un gruppo con i risultati context.bot.sendMessage( chat_id=chat_id, text="Questo comando è utilizzabile solo in privato") context.bot.sendMessage( chat_id=user_id, text="Dal comando esami che hai eseguito in un gruppo") message_text, inline_keyboard = get_esami_text_InlineKeyboard(context) context.bot.sendMessage(chat_id=user_id, text=message_text, reply_markup=inline_keyboard)
def vertical_handler(update: Update, context: CallbackContext): context.user_data[NICHE] = update.callback_query.data.split('_')[1] logger.info('user_data: %s', context.user_data) inline_buttons = InlineKeyboardMarkup(inline_keyboard=[ [ InlineKeyboardButton(text=name, callback_data='q5_' + name) for name in question5['answers'][:2] ], [ InlineKeyboardButton(text=name, callback_data='q5_' + name) for name in question5['answers'][2:4] ], [ InlineKeyboardButton(text=name, callback_data='q5_' + name) for name in question5['answers'][4:] ], ], ) update.callback_query.edit_message_text( text=question5['title'], reply_markup=inline_buttons, ) return GEO
def email_question_handler(update: Update, context: CallbackContext): logger.info(f'user_data: {update}') selected, date = telegramcalendar.process_calendar_selection( update, context) context.user_data['NEXT_STAGE_CALLBACK'] = 'reg' if selected: date_choise = date.strftime("%d/%m/%Y") p = Profile.objects.get(external_id=update.callback_query.from_user.id) p.date_ready = date p.save() inline_buttons = InlineKeyboardMarkup(inline_keyboard=[[ InlineKeyboardButton(text='Да', callback_data='email'), InlineKeyboardButton(text='Нет', callback_data='success_registration') ]], ) update.callback_query.edit_message_text( text=f'Вы выбрали {date.strftime("%d/%m/%Y")}\n\n' f'Предоставить адрес электронной почты?', reply_markup=inline_buttons, ) return ConversationHandler.END else: return CALENDAR
def get_source_code_state_handler(update: Update, context: CallbackContext, model): lang = context.user_data["lang"] if update.message.document: path = update.message.document.get_file().download() try: with open(path, 'r') as f: text = f.read() os.remove(path) except UnicodeDecodeError: update.message.reply_text( model.lang.data[lang]["PASTE_GET_SOURCE_CODE_FILE_ERROR"]) return GET_SOURCE_CODE else: text = update.message.text context.user_data["source_code"] = text escaped_text = f"<code>{html.escape(text)}</code>" if len(escaped_text) > 4096: escaped_text = f"<code>{html.escape(text[:2040]+chr(10)+'...'+chr(10)+text[-2040:])}</code>" update.message.reply_text(escaped_text, parse_mode="HTML").reply_text( model.lang.data[lang]["PASTE_GET_SOURCE_CODE_CONFIRM"], reply_markup=model.programming_languages_keyboard) return GET_LANG
def date_of_birth(update: Update, context: CallbackContext) -> int: update.message.reply_text("Thank you so much.") if len(update.message.text.strip()) != 10: update.message.reply_text( 'You entered wrong format of your date of birth, please enter correctly.' ) return get_date_of_birth(update, context) telegram_id = update.message.from_user.id logger.info(f"{telegram_id}: Check if user exist in Database.") user_info = create_telegram_user(telegram_id=update.message.from_user.id, username=context.user_data['username'], date_of_birth=update.message.text.strip(), key=context.user_data['failure']) if user_info and type(user_info) == dict and 'id' in user_info: logger.info(f"{telegram_id}: User exist in Database.") return get_group(update, context) elif user_info == INVALID_USER: context.user_data['failure'] = 1 return get_date_of_birth(update, context) logger.info(f"{telegram_id}: User is not exist in Database.") messages = context.user_data['messages'] update.message.reply_text(messages.NOTFOUND) return get_student_id(update, context)
def roll_command(update: Update, context: CallbackContext): # update.message.reply_text(args) args = context.args if len(args) == 0: builder = DiceRollerBuilder() context.chat_data["builder"] = builder context.bot.send_message( chat_id=update.message.chat_id, text=builder.reply_text(), reply_markup=builder.button_gen(), ) for arg in args: try: no_of_dice, no_dice_sides, modifier = parse_command(arg) except ValueError as err: update.message.reply_markdown( f"‼️ Your input '{arg}' was invalid: {err}‼️\n\n💣 Roll dice in the format '1d20+5' for example; no spaces 💣 " ) continue roll = roll_dice(no_of_dice, no_dice_sides, modifier) update.message.reply_markdown(create_roll_response(roll))
def block_user_cb(update: Update, context: CallbackContext): """Block the user for the incoming callback query.""" update.callback_query.answer() database = context.bot_data["database"] message = update.callback_query.message user_id, _ = database.get_user_message_id_from_users(message.message_id) msg_id = block_user(user_id, context) membership = get_membership(user_id, context) username, full_name, blocked = database.get_user(user_id) edit_text = Message.USER_CONNECTED.format( FULL_NAME=full_name, USER_ID=user_id, USERNAME=username, MEMBERSHIP=membership, BLOCKED=blocked, ) text = Message.BLOCKED_USER.format(USER_ID=user_id, FULL_NAME=full_name) markup = InlineKeyboardMarkup.from_row([Button.UNBLOCK, Button.CONNECT]) message.edit_text(text=edit_text, reply_markup=markup) message = message.reply_html(text) database.add_admin_message(0, user_id, msg_id) database.add_user_message(1, user_id, message.message_id) context.bot_data["lastUserId"] = Literal.ADMINS_GROUP_ID
def atlz_portfolio_B(update: Update, context: tg.CallbackContext): user = update.message.chat_id message_id = update.message.message_id context.bot.sendChatAction(chat_id=user, action='typing') msg = update.message.text opts = [ 'Aumentar o valor', 'Subtrair do valor', 'Zerar', 'Substituir o portfolio' ] if msg in opts: context.user_data['selection'] = opts.index(msg) if msg == opts[2]: fc.func_port(None, 2, user, dbname) response = 'O portfolio foi zerado com sucesso!' wrapped_msg[len(wrapped_msg) + 1] = [user, response, message_id, RKR] return tg.ConversationHandler.END else: response = 'Digite agora o valor ou clique em /cancelar:' wrapped_msg[len(wrapped_msg) + 1] = [user, response, message_id, RKR] return PORTFOLIO_C
def category(update: Update, context: CallbackContext): categories = [] chat_ID = update.message.chat_id # get the categories try: context.bot.sendChatAction(chat_id=chat_ID, action='Typing') r = requests.get(env.get("URL_CATEGORIES"), params={'chat_id': chat_ID}) response = r.json() if response['Success'] is not True: # some error text = ("Failed!" + "\nComment: " + response['Comment'] + "\nError: " + response['Error'] + ".") else: # no errors # append the categories to the reply markup list # for category in response['Data']: # categories.append([KeyboardButton(category['Category'])]) categories = [[KeyboardButton(category['Category'])] for category in response['Data']] reply_markup = ReplyKeyboardMarkup(categories, resize_keyboard=True) text = ( "Select a category from below or type in the category. Or /cancel to return to choose other options." + "\nOr /home to return to Main Menu") except Exception as e: text = ("Something went wrong." + "\n" + "\nNo connection to the db server." + "\n" + "Type in the category. Or /cancel to choose other options." + "\nOr /home to return to Main Menu") utils.logger.error("failed to select category with error: " + repr(e)) reply_markup = ReplyKeyboardRemove() context.user_data[ 'currentExpCat'] = "Category" #update the check for most recently updated field context.bot.send_message(chat_id=chat_ID, text=text, reply_markup=reply_markup) return TYPING_REPLY
def image_crop_callback(update: Update, context: CallbackContext) -> int: """Handles the image crop callback Modifies the cropping parameters The conversation remains in the "crop" state or is put in the "end" state Args: update (Update): update event context (CallbackContext): context passed by the handler Returns: int: new state of the conversation """ info = get_callback_info(update, context) operation = info["query_data"][11:] if operation == 'reset': context.user_data['background_offset'] = {'x': 0, 'y': 0} elif operation == 'finish': sender_id = info['sender_id'] info['bot'].edit_message_reply_markup(chat_id=info['chat_id'], message_id=info['message_id'], reply_markup=None) if os.path.exists(build_bg_path(sender_id)): os.remove(build_bg_path(sender_id)) os.remove(build_photo_path(sender_id)) return STATE['end'] else: offset_value = OFFSET_VALUES[operation] context.user_data['background_offset']['x'] += offset_value['x'] context.user_data['background_offset']['y'] += offset_value['y'] generate_photo(info=info, user_data=context.user_data, delete_message=True) return STATE['crop']
def ticket_get_name(update: Update, context: CallbackContext) -> str: user_full_name = update.message.text if len(user_full_name.split(' ')) != 2: update.message.reply_text( 'Введите Имя и Фамилию через пробел.', reply_markup=CANCEL, ) return 'name' else: context.user_data['full_name'] = user_full_name chat_id = update.message.chat_id context.bot.send_message( chat_id=chat_id, text='Введите номер своего подразделения:\n' '1. Колл-Центр\n' '2. Офис\n' '3. Офис(Одесская)\n' '4. Игнатова\n' '5. Казбекская\n' '6. Котлярова\n' '7. Красная\n' '8. Красная площадь\n' '9. Лофт\n' '10. Мега\n' '11. Новороссийск Молодежная\n' '12. Новроссийск Серебрякова\n' '13. Покрышкина\n' '14. СБС\n' '15. Ставропольская\n' '16. Туапсе\n' '17. Тюляева\n' '18. Чекистов\n' '19. Российская\n' '20. Сочи\n', reply_markup=CANCEL, ) return 'department'
def begin_debate(update: Update, context: CallbackContext): moderator = context.chat_data.get('moderator') phase = context.chat_data.get('phase', 0) if not phase: update.effective_chat.send_message('No debate ongoing to begin.') return if moderator: if update.effective_user.username != moderator.username: update.effective_chat.send_message( 'Only the moderator can send the /begin command.') return context.chat_data['phase'] = DEBATE update.effective_chat.unpin_all_messages() update.effective_chat.send_message(parse_mode=ParseMode.HTML, text=(f""" <b>Debate:</b> {context.chat_data.get('debate_prop')} <b>Moderator:</b> {moderator.full_name} <b>Phase:</b> Debate <b><u>RULES</u></b> - Debators are only allowed to send messages with one of 6 commands: /meta, /conclude, /poi, /for, /against, /lf or /cancel - The moderator is not allowed to pick sides or contribute to the debate other than ensuring everyone follows the rules - The moderator is required to ensure that all debators follow the rules - The moderator is required to encourage is required to notify debators if their argument uses a logical fallacy and encourage the debator to update their argument - If debators have no more arguments to present, they may /conclude their debate. The debate will officially /conclude when a majority of debators /conclude. - The debate will officially /conclude when the moderator sends the /conclude command - Only use the /cancel command to ungracefully end the debate """)).pin() _send_survey(update, context, 'PRE-DEBATE')
def greet_new_chat_members(update: Update, context: CallbackContext): group_user_name = update.effective_chat.username # Get saved users user_lists = context.chat_data.setdefault('new_chat_members', {}) users = user_lists.setdefault(group_user_name, []) # save new users new_chat_members = update.message.new_chat_members for user in new_chat_members: users.append(user.mention_html()) # check rate limit last_message_date = context.chat_data.setdefault( 'new_chat_members_timeout', dtm.datetime.now() - dtm.timedelta(minutes=NEW_CHAT_MEMBERS_LIMIT_SPACING + 1)) if dtm.datetime.now() < last_message_date + dtm.timedelta( minutes=NEW_CHAT_MEMBERS_LIMIT_SPACING): logging.debug('Waiting a bit longer before greeting new members.') return # save new timestamp context.chat_data['new_chat_members_timeout'] = dtm.datetime.now() link = ONTOPIC_RULES_MESSAGE_LINK if group_user_name == ONTOPIC_USERNAME else OFFTOPIC_RULES_MESSAGE_LINK text = ( f'Welcome {", ".join(users)}! Please read and follow the rules of this ' f'group. You can find them <a href="{link}">here 🔗</a>.') # Clear users list users.clear() # send message update.message.reply_text(text, disable_web_page_preview=True, quote=False, parse_mode=ParseMode.HTML)
def select_card(update: Update, context: CallbackContext) -> int: db = next(get_db()) telegram_id = update.effective_chat.username card_name = update.message.text cards_name_list = list_card_names(db, telegram_id) if card_name in cards_name_list: update.message.reply_text(f"Карточка с именем {card_name}:") context.user_data['card_name'] = card_name card_questions_list = list_card_questions(db, telegram_id, card_name) context.user_data['question_list'] = card_questions_list context.user_data['question_number'] = 0 context.user_data['correct_answers'] = 0 context.user_data['error_question_list'] = list() context.user_data['error_answer_list'] = list() context.user_data['correct_answer_list'] = list() return question_endpoint(update, context) else: update.message.reply_text(f"Карточки с именем {card_name} нет!") cards_name_list = list_card_names(db, telegram_id) return waiting_select_card_endpoint(update, context, cards_name_list)
def get_random_quote(update: Update, context: CallbackContext) -> Optional[db.Quote]: user = db.User.get_from(update.effective_user) if 'quotes' not in context.user_data: context.user_data['quotes'] = [] quotes = context.user_data['quotes'] log.debug(f'get_random_quote (quotes: {len(quotes)})') # Заполняем список новыми цитатами, если он пустой if not quotes: log.debug('Quotes is empty, filling from database.') years_of_quotes = user.get_years_of_quotes() filter_quote_by_max_length_text = user.get_filter_quote_by_max_length_text( ) update_cache(user, years_of_quotes, filter_quote_by_max_length_text, log, update, context) if quotes: return quotes.pop() return
def show_marked_talks(update: Update, context: CallbackContext): user = update.message.from_user logger.info("User %s %s username:%s: show_marked_talks", user.first_name, user.last_name, user.username) context.user_data['type'] = 'marked' marked_list = context.user_data['marked_list'] if find_time_intersections(context): reply_keyboard = keyboards.conflicts_to_begin_keyboard(context) else: reply_keyboard = keyboards.to_begin_keyboard(context) for marked_talk in marked_list: if context.user_data['lang'] == 'ru': reply_message = marked_talk.str_ru() else: reply_message = marked_talk.str_en() update.message.reply_text( reply_message, parse_mode=telegram.ParseMode.HTML, # this is needed for bold text reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True), ) if not marked_list: update.message.reply_text( context.user_data['localisation']['NOMARKED'], parse_mode=telegram.ParseMode.HTML, # this is needed for bold text reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True, resize_keyboard=True), ) return dk.MARKED
def setup_new_member_id_conv_handler(update: Update, context: CallbackContext): text = update.effective_message.text if text != 'Отменить': try: context.user_data['New_member_id'] = int(text) except ValueError: context.bot.send_message( chat_id=update.effective_message.chat_id, text='Неверное id, попробуйте снова!', ) return NEW_MEMBER_ID set_user_info(user_id=context.user_data['New_member_id'], member_name=context.user_data['New_member_name'], role=context.user_data['New_member_role']) context.bot.send_message( chat_id=update.effective_message.chat_id, text='Новый участник успешно добавлен в базу данных!', reply_markup=get_base_reply_keyboard(member_role=context.user_data['Role']) ) return ConversationHandler.END
def offer_help(update: Update, context: CallbackContext): query = update.callback_query help_request_id = query.data.split(':')[1] try: help_request = HelpRequest.objects.get(pk=help_request_id) except HelpRequest.DoesNotExist: query.answer() return user = TelegramUser.objects.get(pk=query.from_user.id) help_request.hidden = True help_request.save() owner = help_request.user context.user_data['user'] = user reaction = HelpRequestReaction.objects.create(help_request=help_request, helper_id=user.id) owner_timer = Timer(60, send_reaction_to_owner, (context, reaction, owner, user)) helper_timer = Timer(60, send_reaction_to_helper, (context, reaction, owner, user)) owner_notification = strings.from_helper_request_owner_notification(help_request, user, owner.language) context.bot.send_message(chat_id=owner.id, text=owner_notification, parse_mode=ParseMode.HTML) notification_sent = strings.notification_sent_message(owner, user.language) notification_sent = query.message.text_html + notification_sent query.edit_message_text(text=notification_sent, parse_mode=ParseMode.HTML) owner_timer.start() helper_timer.start() query.answer()
def date_handler(update: Update, context: CallbackContext): if not hasattr(update, "message"): return if not hasattr(update.message, "text"): return try: date = process_date(update.message.text) except ValueError as exception: error_message = "".join(exception.args) context.bot.send_message( chat_id=update.message.chat_id, text=f"Looks like there is an error in date: {error_message}.\ \nTry again or hit /cancel to cancel.", ) return DATE context.user_data["date"] = date data = context.user_data.copy() context.user_data.clear() context.bot.send_message( chat_id=update.message.chat_id, text=f"Date registered..\ \nDon't miss me, I'll be back soon with updates.:)", ) kwargs = { "user_data": data, "queue_collection": queue_collection, "bot": context.bot, } th = threading.Thread( target=validate_queue_and_inform_user, kwargs=kwargs, ) th.start() return ConversationHandler.END
def check_phone_2(update: Update, context: CallbackContext): query = update.callback_query datas = query.data.split('_') if datas[0] == 'category': cat_id = int(datas[1]) context.user_data['user_district'] = cat_id tg_user = query.from_user try: user = User.objects.get(tg_id=tg_user.id) except Exception: user = None try: user_region = UserRegion( user_id=user.id, region_id=context.user_data['user_region'], district_id=context.user_data['user_district']) user_region.save() except Exception: pass if user.phone: return last(update, context) else: return get_phone_number_2(update, context)
def photo_handler(update: Update, context: CallbackContext): photo = update.message.photo[-1] photo_id = photo.file_id photo_meta = bot.get_file(photo_id) photo_meta.download('image.jpg') fen = photo_to_fen('./image.jpg') context.user_data["fen"] = fen fen_parts = [None] * 6 fen_parts[0] = fen[:-1] board = Board(fen_parts) boardGrid = board.board boardImg = DrawImage(boardGrid, 'png', './', 'result') boardImg.create() boardImg.to_image() stockfish_engine.set_fen_position(fen) chat_id = update.message.chat.id bot.send_photo(chat_id, photo=open('result.png', 'rb'), caption="Here is detected chessboard configuration")
def restaurant_notifications(update: Update, context: CallbackContext): """ Restaurants notifications menu :param update: :param context: :return: """ context.user_data["notify"] = { "chat_id": update.message.chat_id, "time": "", "restaurant": "", "status": "", } buttons = [[ InlineKeyboardButton( "материк", callback_data=f'restaurant_{restaurants["MATERIK"]}'), InlineKeyboardButton( "вангог", callback_data=f'restaurant_{restaurants["VANGOG"]}'), InlineKeyboardButton( "пиццарони", callback_data=f'restaurant_{restaurants["PIZZARONI"]}'), ]] reply_markup = InlineKeyboardMarkup(buttons) update.message.reply_text("Выберите заведение", reply_markup=reply_markup)
def on_text_receive(update: Update, context: CallbackContext): logger.info('user sent a text message while we were waiting for a sticker') logger.debug('user_data: %s', context.user_data) status_to_return = Status.WAITING_STATIC_STICKERS if context.user_data['pack']['animated']: status_to_return = Status.WAITING_ANIMATED_STICKERS emojis = utils.get_emojis(update.message.text, as_list=True) if not emojis: update.message.reply_text(Strings.ADD_STICKER_NO_EMOJI_IN_TEXT) return status_to_return elif len(emojis) > 10: update.message.reply_text(Strings.ADD_STICKER_TOO_MANY_EMOJIS) return status_to_return context.user_data['pack']['emojis'] = emojis update.message.reply_text(Strings.ADD_STICKER_EMOJIS_SAVED.format( len(emojis), ''.join(emojis) )) return status_to_return
def get_personal_account(update: Update, context: CallbackContext): """ Запос на запись лицевого счёта. Входной параметр - строка из цифр. """ try: with db.atomic(): user = User.get( User.username == update.message.from_user['username']) if user.agent is None: context.user_data["status"] = "getting_account" context.bot.send_message( chat_id=update.effective_chat.id, text= "Укажите ваш лицевой счёт, чтобы я сохранил его в базе данных." ) else: context.bot.send_message( chat_id=update.effective_chat.id, text="Для этого аккаунта уже указан лицевой счёт. " "Если вы хотите сменить лицевой счёт, воспользуйтесь командой /change_account" ) except Exception as ex: logger = logging.getLogger("root") logger.error(f"DataBaseError: {ex}")
def _send_admins(context: CallbackContext): database = context.bot_data["database"] message = context.job.context user_id = message.from_user.id quote = context.bot_data.get("lastUserId", 0) != user_id reply = message.reply_to_message reply_to = None if reply: if reply.from_user.id == user_id: reply_to = database.get_dest_message_id_from_users( user_id, reply.message_id ) else: reply_to = database.get_message_id_from_admins(user_id, reply.message_id) dest_msgs = send_message( context.bot, message, Literal.ADMINS_GROUP_ID, reply_to, False, quote ) for dest_msg_id in dest_msgs: database.add_user_message(message.message_id, user_id, dest_msg_id) context.bot_data["lastUserId"] = user_id
def on_photo(update: Update, context: CallbackContext): message = update.effective_message chat_id = update.effective_chat.id user_id = update.effective_user.id msg = 'Downloading a picture ...' log.debug(msg) progress_message = message.reply_text(msg + '\n⬜⬜⬜⬜⬜') context.bot.send_chat_action(chat_id=chat_id, action=ChatAction.TYPING) url = message.photo[-1].get_file().file_path rs = requests.get(url) progress_message.edit_text(msg + '\n⬛⬛⬛⬜⬜') file_name = get_file_name_image(user_id) with open(file_name, 'wb') as f: f.write(rs.content) reset_img(user_id) msg = 'Picture downloaded!' log.debug(msg) progress_message.edit_text(msg + '\n⬛⬛⬛⬛⬛') progress_message.delete() # Reset context.user_data['elapsed_secs'] = -1 finish_progress(context) message.reply_text( 'Deep dream are now available', reply_markup=get_reply_keyboard_markup() )
def finish_handler(update: Update, context: CallbackContext): # Получить возраст age = validate_age(text=update.message.text) if age is None: update.message.reply_text('Пожалуйста, введите корректный возраст!') return AGE context.user_data[AGE] = age # logger.info('user_data: %s', context.user_data) # TODO: вот тут запись в базу финала # TODO 2: очистить `user_data` # Завершить диалог update.message.reply_text(f''' Все данные успешно сохранены! Мероприятие: {context.user_data[EVENT]}, Вы: {context.user_data[NAME]}, пол: {gender_hru(context.user_data[GENDER])}, возраст: {context.user_data[AGE]}, группа: {context.user_data[GROUP]}, ваш номер: {context.user_data[PHONE]} и почта {context.user_data[MAIL]} ''') from firebase import firebase event = context.user_data[EVENT] token = '/hackaton-9de63/' + event firebase = firebase.FirebaseApplication( "https://hackaton-9de63.firebaseio.com/") data = { 'Name': context.user_data[NAME], 'Age': context.user_data[AGE], 'Gender': gender_hru(context.user_data[GENDER]), 'Group': context.user_data[GROUP], 'Phone number': context.user_data[PHONE], 'Email': context.user_data[MAIL], } result = firebase.post(token, data) print(result) return ConversationHandler.END
def resposta_errada(update: Update, context: CallbackContext) -> None: query = update.callback_query query.answer() context.chat_data["erro"] = True pergunta = context.chat_data["proxima_pergunta"] - 1 resposta_certa = PERGUNTAS[pergunta]['resposta'] retornar_proxima_ou_resultado = "0" if context.chat_data["proxima_pergunta"] == 7 else context.chat_data["proxima_pergunta"] finalizar_ou_bora = "Finalizar" if context.chat_data["proxima_pergunta"] == 7 else "Borá pra próxima" # Cria lista com as opções para escolher opcoes = [ [ InlineKeyboardButton(finalizar_ou_bora, callback_data=retornar_proxima_ou_resultado), ], ] # Monta o teclado com as opçoes teclado_com_opcoes = InlineKeyboardMarkup(opcoes) query.edit_message_text( text=f""" Ah não 😫! Resposta errada. A resposta correta era: <u><b>{resposta_certa}</b></u>. Mas não desanime! """, parse_mode=ParseMode.HTML, reply_markup=teclado_com_opcoes ) return TESTE if context.chat_data["proxima_pergunta"] < 7 else RESULTADO
def notify_time(update: Update, context: CallbackContext): """ Set user's notification time :param update: :param context: :return: """ time = re.compile(r"[\.:\s+,]").split(update.message.text.strip()) hours, minutes = list(filter(None, time)) if int(hours) > 24 or int(minutes) > 59: update.message.reply_text( "Вы, видимо, ошиблись при вводе времени. Начните заново.", reply_markup=ReplyKeyboardMarkup(kb_restaurants, resize_keyboard=True), ) if "notify" in context.user_data: context.user_data["notify"]["time"] = f"{hours}:{minutes}" notify_info = set_user_notification(context.user_data["notify"]) update.message.reply_text( f'уведомления {notify_info["status"]} для заведения {notify_info["restaurant"]}', reply_markup=ReplyKeyboardMarkup(kb_restaurants, resize_keyboard=True), ) del context.user_data["notify"]
def ask_font(update: Update, context: CallbackContext): message = update.effective_message message.reply_chat_action(ChatAction.TYPING) _ = set_lang(update, context) text = message.text if text == _(CANCEL): return cancel(update, context) context.user_data[TEXT] = text reply_markup = ReplyKeyboardMarkup([[_(SKIP)]], resize_keyboard=True, one_time_keyboard=True) message.reply_text( _("Send me the font that you'll like to use for the PDF file or " "skip to use the default font\n\nSee here for the list of supported fonts:" ) + ' <a href="https://fonts.google.com/">Google Fonts</a>', parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=reply_markup, ) return WAIT_FONT