def req(bot, update, user_data): text = update.message.text result = search(text, 1, 5) for idx, model in enumerate(result): keyboard = [[ telegram.InlineKeyboardButton(model['title']['compact'], callback_data=str(model['_id'])) ]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text(str(idx) + ') ' + model['title']['fa'], reply_markup=reply_markup) user_data.pop('query', None) if 'state' in user_data: state = user_data['state'] del user_data['state'] return state return REQ
def handle_inline_query(update: tg.Update, context: tg_ext.CallbackContext): from bot.inline import CallbackCommands query = update.inline_query.query results = [ tg.InlineQueryResultArticle( id=uuid.uuid4(), title="Send", input_message_content=tg.InputTextMessageContent( message_text='Spoiler'), reply_markup=tg.InlineKeyboardMarkup(inline_keyboard=[[ tg.InlineKeyboardButton( text='Show', callback_data=json.dumps( [CallbackCommands.DISPLAY_SPOILER, query])) ]])) ] update.inline_query.answer(results=results)
def visualRecognition(bot, update): user = update.message.from_user photo_file = bot.get_file(update.message.photo[-1].file_id) name = str(update.message.chat_id) + ".jpg" photo_file.download(name) keyboard = [[ telegram.InlineKeyboardButton("Reconocimiento facial", callback_data='1') ], [ telegram.InlineKeyboardButton("Reconocimiento de objetos", callback_data='2') ]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( 'Elige el tipo de reconocimiento que quieres aplicar a la imagen', reply_markup=reply_markup)
def callback_response(update, context): meow = re.match("(c___).*", update.callback_query.data) if meow is not None and meow.string == update.callback_query.data: return choose_card(update, context) goth = re.match("(d___).*", update.callback_query.data) if goth is not None and goth.string == update.callback_query.data: return delete_card(update, context) if update.callback_query.data == "Cards": context.bot.deleteMessage( chat_id=update.callback_query.message.chat_id, message_id=update.callback_query.message.message_id, ) return set_cards_keyboard(update, context) if update.callback_query.data == "View": return send_card_view(update, context) if update.callback_query.data == "next": return send_row(update, context) if update.callback_query.data == "translate": if "translate" not in context.user_data: context.bot.send_message( chat_id=update.callback_query.message.chat_id, text="Something went wrong, try again") return custom_keyboard = [ [telegram.InlineKeyboardButton("Next", callback_data="next")], [ telegram.InlineKeyboardButton("↙️ Cards", callback_data="Cards"), telegram.InlineKeyboardButton("🥐 View", callback_data="View") ] ] reply_markup = telegram.InlineKeyboardMarkup(custom_keyboard) context.bot.edit_message_text( chat_id=update.callback_query.message.chat_id, message_id=update.callback_query.message.message_id, text=context.user_data["translate"], reply_markup=reply_markup)
def build_link_action_message(self, chat: ETMChatType, tg_chat_id: TelegramChatID, tg_msg_id: TelegramMessageID): chat_display_name = chat.full_name self.msg_storage[(tg_chat_id, tg_msg_id)].chats = [chat] txt = self._("You've selected chat {0}.").format( html.escape(chat_display_name)) if chat.linked: txt += self._("\nThis chat has already linked to Telegram.") txt += self._( "\nWhat would you like to do?\n\n" "<i>* If the link button doesn't work for you, please try to link manually.</i>" ) link_url = f"https://telegram.me/{self.bot.me.username}?" \ f"startgroup={urllib.parse.quote(utils.b64en(utils.message_id_to_str(tg_chat_id, tg_msg_id)))}" self.logger.debug("Telegram start trigger for linking chat: %s", link_url) if chat.linked: btn_list = [ telegram.InlineKeyboardButton(self._("Relink"), url=link_url), telegram.InlineKeyboardButton(self._("Restore"), callback_data="unlink 0") ] else: btn_list = [ telegram.InlineKeyboardButton(self._("Link"), url=link_url) ] btn_list.append( telegram.InlineKeyboardButton( self._("Manual {link_or_relink}").format( link_or_relink=btn_list[0].text), callback_data="manual_link 0")) buttons = [ btn_list, [ telegram.InlineKeyboardButton( self._("Cancel"), callback_data=Flags.CANCEL_PROCESS) ] ] self.bot.edit_message_text( text=txt, chat_id=tg_chat_id, message_id=tg_msg_id, reply_markup=telegram.InlineKeyboardMarkup(buttons), parse_mode='HTML')
def __init__(self, creator, amount, reason): self.creator = creator self.amount = amount self.reason = reason self.approved = [] self.disapproved = [] self.message = None prefix = "pay " + str(creator['id']) self.message_markup = telegram.InlineKeyboardMarkup([ [ telegram.InlineKeyboardButton("APPROVE", callback_data=prefix + " approve"), ], [ telegram.InlineKeyboardButton("DISAPPROVE", callback_data=prefix + " disapprove"), ], ])
def selectCampus(self, bot, update): keyboard = [[ telegram.InlineKeyboardButton('Cantina Chapecó', callback_data='canteen-chapeco'), ], [ telegram.InlineKeyboardButton( '← Menu principal', callback_data='main-menu') ]] replyMarkup = telegram.InlineKeyboardMarkup(keyboard) bot.editMessageText( message_id=update.callback_query.message.message_id, chat_id=update.callback_query.message.chat.id, text='Selecione o campus:', parse_mode='HTML', reply_markup=replyMarkup)
def submit_results(bot, update): query = get_query(bot, update) kb = [] text_run = "🏃 Беговые" run = telegram.InlineKeyboardButton( text=text_run, url="https://traininginparks.typeform.com/to/aocZvF") text_weight = "🏋️ Силовые" weight = telegram.InlineKeyboardButton( text=text_weight, url="https://traininginparks.typeform.com/to/LzjVO3") kb.append([run]) kb.append([weight]) kb_markup = telegram.InlineKeyboardMarkup(kb) bot.sendMessage( text= "Что за результаты у тебя?\n(твои результаты появятся в течение 10 минут после занесения)", chat_id=query.message.chat.id, reply_markup=kb_markup)
def build_result_keyboard(cur_page, product, products_num): back_button = telegram.InlineKeyboardButton( "⏮ Back", callback_data="producthunt-previous-entry") next_button = telegram.InlineKeyboardButton( "Next ⏭", callback_data="producthunt-next-entry") url_button = telegram.InlineKeyboardButton("Get it ❤️", url=product['redirect_url']) discussion_button = telegram.InlineKeyboardButton( 'Join discussion 💬', url=product['discussion_url']) keyboard = [[], [url_button, discussion_button]] if cur_page != 0: keyboard[0].append(back_button) if cur_page != products_num - 1: keyboard[0].append(next_button) return telegram.InlineKeyboardMarkup(keyboard)
def add_reward_handler(update, context): user = update.message.from_user reward = update.message.text quest_id = context.user_data["current_quest"] chat_id = update.message.chat_id if not check_profile_existence(user.id): send_message(chat_id, "You don't have a sidequest board yet! Make one using /am.") return ConversationHandler.END sidequest_database["sidequests"][user.id][quest_id][2] = reward update.message.reply_text("Thanks! You're all done!") text = "%s has added a new sidequest:" % get_name_from_database(user.id) title = sidequest_database["sidequests"][user.id][quest_id][0] buttons = [] buttons.append( [ # Callback data for show is: # [SHOW (header), Sidequest Giver Telegram ID, Sidequest ID] telegram.InlineKeyboardButton(text=title if title != "" else "[NO TITLE]", callback_data="SHOW,%s,%s" % (user.id, quest_id)) ] ) buttons.append( [ # Callback data for listing the accepters is: # [LIST (header), Sidequest Owner Telegram ID, Sidequest ID] telegram.InlineKeyboardButton(text="≡ (0)", callback_data="LIST,%s,%s" % (user.id, quest_id)), # Callback data for toggle is: # [TOGGLE (header), Sidequest Giver Telegram ID, Sidequest ID] telegram.InlineKeyboardButton(text="⬜", callback_data="TOGGLE,%s,%s" % (user.id, quest_id)) ] ) for id, name in sidequest_database["users"]: if id != user.id: bot.send_message(chat_id=id, text=text, reply_markup=telegram.InlineKeyboardMarkup(buttons), parse_mode=telegram.ParseMode.HTML) return ConversationHandler.END
def start_cmd(bot, update): tg_user = update.message.from_user app_user = models.User.query.get(tg_user.id) if not app_user: is_admin = tg_user.username in config.admin_username_list app_user = models.User(id=tg_user.id, first_name=tg_user.first_name, last_name=tg_user.last_name, username=tg_user.username, is_admin=is_admin) models.db.session.add(app_user) models.db.session.commit() reply_markup = tg.InlineKeyboardMarkup( [[tg.InlineKeyboardButton('Оставить отзыв', callback_data='feedback')]]) update.message.reply_text('Добро пожаловать!', reply_markup=reply_markup)
def train_details(bot, update, train): if check_username(bot, update) == False: return query = get_query(bot, update) kb = [] try: if "attendee" in train and query.message.chat.username in train[ "attendee"]: text_sign = "❌ Не смогу прийти" signup = telegram.InlineKeyboardButton(text=text_sign, callback_data="101;" + str(train["id"])) else: text_sign = "✅ Записаться" signup = telegram.InlineKeyboardButton(text=text_sign, callback_data="102;" + str(train["id"])) except Exception as exc: logging.exception(exc) text_attendees = "🙏 Участники" attendees = telegram.InlineKeyboardButton(text=text_attendees, callback_data="105;{};".format( str(train["id"]))) kb.append([signup, attendees]) text_loc = "🗺 Где это?" location = telegram.InlineKeyboardButton(text=text_loc, callback_data="103;" + str(train["id"])) # text_cal = "🗓 Добавить" # cal = telegram.InlineKeyboardButton(text=text_cal, url=train["htmlLink"] + # "&action=TEMPLATE" + # "&text=" + train["summary"] + # "&dates=" + train["start"]["dateTime"] + "/" + train["end"]["dateTime"] + # Проблема с конвертацией даты # "&trp=false" + # "&sprop=" + # "&sprop=name:" + # "&pprop=HowCreated:QUICKADD&scp=ONE") # logging.critical(cal) # kb.append([location, cal]) kb.append([location]) kb_markup = telegram.InlineKeyboardMarkup(kb) bot.sendMessage(text="Детали по событию: {} - {}".format( train["start"]["date"], train["summary"]), chat_id=query.message.chat.id, reply_markup=kb_markup)
def get_service(bot, update, user_id, token=None): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ creds = None if redis_client.hexists(user_id, "credentials"): creds = pickle.loads(redis_pickle_client.hget(user_id, "credentials")) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( "credentials.json", SCOPES) # Setup authorization URL flow.redirect_uri = InstalledAppFlow._OOB_REDIRECT_URI auth_url, _ = flow.authorization_url() if not token: instructions = """Please follow the instructions to setup a Google Sheet: 1. Click on the authorization URL 2. Copy the authentication code 3. Use '/setup_sheet <authentication_code>' to finish!""" keyboard = [[ telegram.InlineKeyboardButton("Open URL", url=auth_url) ]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text(instructions, reply_markup=reply_markup) # Fetch access token if args present flow.fetch_token(code=token) creds = flow.credentials # Save the credentials for the next run redis_pickle_client.hset(user_id, "credentials", pickle.dumps(creds)) service = build("sheets", "v4", credentials=creds) return service
def send_keyboard(self, title, menu_options, options=None): """Send an inline keyboard with commands. This will edit the last-sent keyboard if it's the most recent message in the chat, otherwise it will delete the previous keyboard and send a new one. """ # format keyboard text = "{}:".format(title) keyboard = _grouper(options, 3) keyboard.append([option for option in menu_options]) # convert to inline keyboard buttons = [[ telegram.InlineKeyboardButton(col, callback_data=col) for col in row ] for row in keyboard] reply_markup = telegram.InlineKeyboardMarkup(buttons) # ignore keyboards sent too long ago to edit or delete if self.info.keyboard_id: keyboard_age = datetime.utcnow() - self.info.keyboard_date if keyboard_age > KEYBOARD_LIFETIME: self.info.keyboard_id = None # remove stale keyboard if self.info.keyboard_id and self.info.keyboard_stale: time.sleep(KEYBOARD_DELAY_SECONDS) self.bot.delete_message(chat_id=self.chat_id(), message_id=self.info.keyboard_id) self.info.keyboard_id = None # send if not self.info.keyboard_id: message = self.bot.send_message(chat_id=self.chat_id(), text=text, reply_markup=reply_markup) self.info.keyboard_id = message.message_id self.info.keyboard_date = datetime.utcnow() self.info.keyboard_stale = False return # edit try: self.bot.edit_message_text(chat_id=self.chat_id(), message_id=self.info.keyboard_id, text=text, reply_markup=reply_markup) except telegram.error.BadRequest as ex: if "Message is not modified" not in str(ex): raise
def send_portfolio(bot, user_id): # run project main on <user_id>.json filename = '{}.json'.format(user_id) if os.path.isfile(filename): ret = subprocess.check_output( ['./report', '-s', '-o', 'value', '-d', '{}.json'.format(user_id)], universal_newlines=True) ret = "```\n{:s}\n```".format(ret) btn = telegram.InlineKeyboardButton('Refresh', callback_data='{}'.format(user_id)) kb = telegram.InlineKeyboardMarkup([[btn]]) bot.send_message(user_id, text=ret, parse_mode='markdown', reply_markup=kb) else: ret = 'You are not registrated. This bot will not help you.' bot.send_message(user_id, text=ret, parse_mode='markdown')
def __send(bot: telegram.Bot, chat_id, reply_to_message_id, date, button_data) -> None: def link(chat_id, msg_id, text): prefix = '-100' cid_str = str(chat_id) if not cid_str.startswith(prefix): return text cid_without_100 = cid_str[len(prefix):] return f'<a href="https://t.me/c/{cid_without_100}/{msg_id}">{text}</a>' keyboard = [ [telegram.InlineKeyboardButton("Показать оригинал", callback_data=(get_callback_data(button_data)))] ] reply_markup = telegram.InlineKeyboardMarkup(keyboard) orig_photo: Photo = button_data['orig_photo'] orig_msg_id = orig_photo.message_id msg = f'Баян! Уже было {link(chat_id, orig_msg_id, relative_date(date))}' bot.send_message(chat_id, msg, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup, parse_mode='HTML')
def _evaluation_end_cmd(self, bot, update): self._log_user('_evaluation_end_cmd', update) self._evaluation[update.effective_user.id]['is_running'] = False update.message.reply_text("Evaluation mode is off!") keyboard = [ [ telegram.InlineKeyboardButton("Bad", callback_data='overall_bad'), telegram.InlineKeyboardButton("Neutral", callback_data='overall_neutral'), telegram.InlineKeyboardButton("Good", callback_data='overall_good') ], ] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text( '"Evaluate overall dialogue quality, please: "', reply_markup=reply_markup)
def start(self, bot, update): row1 = [ telegram.InlineKeyboardButton(text="button1", callback_data="button1"), telegram.InlineKeyboardButton(text="button2", url="https://google.com") ] #row2 = [telegram.InlineKeyboardButton(text="button3"),telegram.InlineKeyboardButton(text="button4")] list_buttons = [row1] self.buttons = telegram.InlineKeyboardMarkup(list_buttons) self.status = bot.send_message(chat_id=update.message.chat_id, parse_mode=telegram.ParseMode.MARKDOWN, text="hola", reply_markup=self.buttons)
def check_username(bot, update): query = get_query(bot, update) if not query.message.chat.username or query.message.chat.username == "": kb = [] button = telegram.InlineKeyboardButton(text="Инструкции", callback_data="000") kb.append([button]) kb_markup = telegram.InlineKeyboardMarkup(kb) kb_start = [[telegram.KeyboardButton('/start')]] kb_markup_start = telegram.ReplyKeyboardMarkup(kb_start, resize_keyboard=False) bot.sendMessage( text="Привет!\n\nК сожалению Вы не установили username для своего telegram-аккаунта, и поэтому бот не сможет корректно для Вас работать.", chat_id=query.message.chat.id, reply_markup=kb_markup_start) bot.sendMessage(text="Хочешь посмотреть на инструкции, как это быстро и легко сделать?", chat_id=query.message.chat.id, reply_markup=kb_markup) return False else: return True
def startagain(update, context): text2 = f"Hai {update.message.from_user['first_name']}! \nSudah tahu mau liburan kemana? Chavel punya rekomendasi nih special buat kamu." kboard = [[ tl.InlineKeyboardButton('Bali', callback_data='BALI'), tl.InlineKeyboardButton('Danau Toba', callback_data='DNTOBA'), tl.InlineKeyboardButton('Yogyakarta', callback_data='YGY') ], [ tl.InlineKeyboardButton('Labuan Bajo', callback_data='LABBJO'), tl.InlineKeyboardButton('Likupang', callback_data='LKP'), tl.InlineKeyboardButton('Mandalika', callback_data='MDL') ]] reply_markup = tl.InlineKeyboardMarkup(kboard, resize_keyboard=True) update.message.reply_text('<b>Welcome back to ChavellBot</b>', parse_mode=tl.ParseMode.HTML) update.message.reply_text(text2, reply_markup=reply_markup) return WELCOME2
def setUp(self): self.id = 'id' self.type = 'audio' self.audio_file_id = 'audio file id' self.caption = 'caption' self.input_message_content = telegram.InputTextMessageContent( 'input_message_content') self.reply_markup = telegram.InlineKeyboardMarkup( [[telegram.InlineKeyboardButton('reply_markup')]]) self.json_dict = { 'type': self.type, 'id': self.id, 'audio_file_id': self.audio_file_id, 'caption': self.caption, 'input_message_content': self.input_message_content.to_dict(), 'reply_markup': self.reply_markup.to_dict(), }
def near_cat(bot, update): global near_cat_loc global near_loc near_loc = False near_cat_loc = True kb = [ [telegram.InlineKeyboardButton("Еда",callback_data="food")], [telegram.InlineKeyboardButton("Спорт",callback_data="sport")], [telegram.InlineKeyboardButton("Проживание",callback_data="hotels")], [telegram.InlineKeyboardButton("Развлечения",callback_data="entertainment")], [telegram.InlineKeyboardButton("Красота",callback_data="beauty")], [telegram.InlineKeyboardButton("Магазины",callback_data="market")], [telegram.InlineKeyboardButton("Медицина",callback_data="medicine")], [telegram.InlineKeyboardButton("Другое",callback_data="other")] ] markup = telegram.InlineKeyboardMarkup(kb) bot.send_message(chat_id=update.message.chat_id, text="Выберите категорию: ", reply_markup = markup)
def send_message(self, chat_id, text, choices): if isinstance(choices, list): self.handle_choice(chat_id, choices) self.bot.send_message(chat_id=chat_id, text=text) if isinstance(choices, dict): if choices['action'] in ['kinopoisk', 'select_torrent']: self.handle_choice(chat_id, choices['data'], choices['action']) self.bot.send_message(chat_id=chat_id, text=text) elif choices['action'] == 'download_callback': row_buttons = [ telegram.InlineKeyboardButton( text='Прогресс скачивания.', callback_data=self.save_callback_data(choices['data'])) ] keyboard = telegram.InlineKeyboardMarkup([row_buttons]) self.bot.send_message(chat_id=chat_id, text=text, reply_markup=keyboard)
def send(self, transport): review_id_hash = hashlib.md5( self.review['id'].encode('ascii')).hexdigest() transport.sendMessage( self.chat_id, text='Review is ready: %s %s' % (self.review['revision'][:7], self.review['subject']), reply_markup=telegram.InlineKeyboardMarkup([[ telegram.InlineKeyboardButton('Approve', callback_data='approve %s' % review_id_hash), telegram.InlineKeyboardButton('Reject', callback_data='reject %s' % review_id_hash), telegram.InlineKeyboardButton('Ignore', callback_data='ignore %s' % review_id_hash) ]]))
def register_suggestions(self, update: telegram.Update, candidates: List[str], chat_id: int, message_id: int): storage_id = (chat_id, message_id) self.msg_storage[storage_id] = ChatListStorage([]) self.msg_storage[storage_id].set_chat_suggestion(update, candidates) legends, buttons = self.channel.chat_binding.slave_chats_pagination( storage_id, 0, source_chats=candidates) self.bot.edit_message_text( text=self._("Error: No recipient specified.\n" "Please reply to a previous message, " "or choose a recipient:\n\nLegend:\n") + "\n".join(legends), chat_id=chat_id, message_id=message_id, reply_markup=telegram.InlineKeyboardMarkup(buttons)) self.suggestion_handler.conversations[ storage_id] = Flags.SUGGEST_RECIPIENT
def confirmation(bot, updater): time.sleep(random.uniform(0, 0.7)) players = wr.read_results() if str(updater.message.chat.id) in players: bot.send_message(chat_id=updater.message.chat.id, text='Йо, ты уже в системе. Просто используй команды.') show_menu(bot, updater) else: btnlist = [ telegram.InlineKeyboardButton('Согласен.', callback_data='agree'), telegram.InlineKeyboardButton('Не согласен.', callback_data='disagree'), ] markup = telegram.InlineKeyboardMarkup(wr.build_menu(btnlist, n_cols=2)) bot.send_message(chat_id=updater.message.chat.id, text='Для начала необходимо согласиться с Согласием на обработку персональный данных.') bot.send_message(chat_id=updater.message.chat.id, text='Я даю своё согласие на обработку и публикацию моих персональных данных, таких как: результат участия в Экономической Карусели и никнейм в телеграмм.', reply_markup=markup)
def _cmd_district_heating_on(self, update: Update, context: CallbackContext) -> None: if self._is_modifying_heating: self._safe_send(chat_id(update), _('Someone else is currently modifying the system configuration. Please try again later.')) return # Set flag to prevent other users from concurrently modifying heating self._is_modifying_heating = True # See helheimr_heating.district_heating for values supported by the CMI supported_temperatures = [55, 60, 65] temperature_buttons = [telegram.InlineKeyboardButton(f'{t:d}\u200a°C', callback_data=CALLBACK_TELE_TURN_ON_CONFIRM + CALLBACK_DELIMITER + f'{t:d}') for t in supported_temperatures] # We'll display a two-row keyboard (top: temperature selection, bottom: cancel button) keyboard = [temperature_buttons, [telegram.InlineKeyboardButton(_('Cancel'), callback_data=CALLBACK_TELE_CANCEL)]] # Set flag only if we could display the keyboard: self._is_modifying_heating = self._safe_message_reply(update, _('Select supply temperature:'), reply_markup=telegram.InlineKeyboardMarkup(keyboard))
def station_type(bot, update): myLat = update.message.location.latitude myLong = update.message.location.longitude callBike = 'bike {0} {1}'.format(myLat, myLong) callTrain = 'train {0} {1}'.format(myLat, myLong) keyboard = [[ telegram.InlineKeyboardButton("Dart Station", callback_data=callTrain), telegram.InlineKeyboardButton("Bike Station", callback_data=callBike) ]] reply_markup = telegram.InlineKeyboardMarkup(keyboard) update.message.reply_text('Which type of station are you looking for?', reply_markup=reply_markup) print(myLat, myLong)
def change_verbosity(self, update, context): """ Defines the handler for /changeVerbosity command """ chat_id = update.message.chat_id bot = context.bot if self.context.config["configure-by-telegram"]: if chat_id in self.context.verified_chats: self.context.button_mode = MODE_CHANGE_VERBOSITY_1 inline_keyboard = [] projects = [ project for project in self.context.config["gitlab-projects"] if (project["token"] in self.context.table and chat_id in self.context.table[project["token"]]) ] if len(projects) > 0: for project in projects: inline_keyboard.append([ telegram.InlineKeyboardButton( text=project["name"], callback_data=project["token"]) ]) replyKeyboard = telegram.InlineKeyboardMarkup( inline_keyboard=inline_keyboard) bot.send_message( chat_id=chat_id, reply_markup=replyKeyboard, text= "Choose the project from which you want to change verbosity.", ) else: bot.send_message( chat_id=chat_id, text="No project configured on this chat.") else: bot.send_message(chat_id=chat_id, text="This chat is no verified.") else: bot.send_message( chat_id=chat_id, text= "If you want to configure the bot with telegram, please set the 'configure-by-telegram' option to true in the settings.", )
def f(respond, chat_id, delete_me): a = Client(chat_id, catalogue) text = 'Hier dein Fortschritt:\n\n' for section in catalogue.get_all_sections(): progress = a.get_section_score(section) text += '{emoji} {perc:<.3}% {sn}\n'.format( emoji=progress_to_machine_emoji(progress), perc=float(progress * 100), sn=section.name) text += '\n\nDurchläufe:\n' runs = a.get_run_scorediffs() if not runs: text += 'Es scheint noch keine vollständigen Durchläufe zu geben.' for run in runs: section_details = '' if run.section: section_details = '({name} {diff:<.3}%)'.format( name=run.section.name, diff=run.section_scorediff * 100, ) run_text = '{date} {chart_emoji} {scorediff:<.3}% {mode} {section_details}\n'.format( date=datetime.fromtimestamp( run.timestamp + run.duration).strftime('%Y/%m/%d %H:%M'), chart_emoji='', scorediff=run.scorediff * 100, mode=MODUS_TABLE[run.mode][0], section_details=section_details, ) text += run_text text += ( '\n\nDer Fortschritt einer Lektion ist die ' 'durchschnittliche Confidence der enthaltenen Fragen.\n' 'Die Confidence einer Frage berechnet sich aus deinen letzten 6 Antworten.\n' 'Für mehr Infos einfach fragen.') reply_markup = telegram.InlineKeyboardMarkup([[ telegram.InlineKeyboardButton( 'Zurück', callback_data='back_to_intro_{}'.format(catalogue.id)) ]]) r = respond(text, reply_markup=reply_markup) delete_me.append(r.message_id) return ConversationHandler.END