我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用telegram.ReplyKeyboardMarkup()。
def nearest_stations(bot, update, count=5): with open('allstations.csv', newline='', encoding='utf-8') as infile: csv_reader = csv.reader(infile, delimiter=';') stations = [(int(row[0]), float(row[1]), float(row[2]), row[3]) for row in csv_reader] # distance sorting based on http://stackoverflow.com/a/28368926 by Sergey Ivanov coord = (float(update.message.location.latitude), float(update.message.location.longitude)) pts = [geopy.Point(p[1], p[2], p[0]) for p in stations] sts = [p[3] for p in stations] onept = geopy.Point(coord[0], coord[1]) alldist = [(p, geopy.distance.distance(p, onept).m) for p in pts] nearest = sorted(alldist, key=lambda x: (x[1]))[:count] nearest_points = [n[0] for n in nearest] nearest_distances = [n[1] for n in nearest] nearest_sts = [sts[int(n.altitude)] for n in nearest_points] msg = 'Nächstgelegene Stationen:' for s, d, p in zip(nearest_sts, nearest_distances, nearest_points): msg += '\n{} (<a href="https://www.google.de/maps?q={},{}">{:.0f}m</a>)'.format(s, p.latitude, p.longitude, d) reply_keyboard = [[telegram.KeyboardButton(text='/Abfahrten {}'.format(n))] for n in nearest_sts] bot.sendMessage(chat_id=update.message.chat_id, text=msg, parse_mode='HTML', reply_markup=telegram.ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))
def recover(bot, update, db, users_state): user_id = update.message.from_user.id users_state[user_id] = dict() users_state[user_id]['channels'] = dict() keyboard = [] keyboard_row = [] for channel in db.query(DisabledChannel).filter(DisabledChannel.owner_id == str(user_id)).order_by(DisabledChannel.created_at.desc()): title = '{} ({})'.format(channel.vk_group_id, channel.channel_id) users_state[user_id]['channels'][title] = channel.channel_id keyboard_row.append(title) if len(keyboard_row) == 2: keyboard.append(keyboard_row) keyboard_row = [] if len(keyboard_row) != 0: keyboard.append(keyboard_row) if len(keyboard) == 0: update.message.reply_text('??? ???????, ??????? ????? ????????????') del_state(update, users_state) return ConversationHandler.END else: update.message.reply_text('???????? ?????', reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)) return ASKED_CHANNEL_ID_IN_RECOVER
def show_settings(bot, update): chat = update.message.chat if update.message.chat.type != 'private': send_async(bot, chat.id, text=_("Please edit your settings in a private chat with " "the bot.")) return us = UserSetting.get(id=update.message.from_user.id) if not us: us = UserSetting(id=update.message.from_user.id) if not us.stats: stats = '??' + ' ' + _("Enable statistics") else: stats = '?' + ' ' + _("Delete all statistics") kb = [[stats], ['??' + ' ' + _("Language")]] send_async(bot, chat.id, text='??' + ' ' + _("Settings"), reply_markup=ReplyKeyboardMarkup(keyboard=kb, one_time_keyboard=True))
def kb_select(bot, update, groups): chat = update.message.chat user = update.message.from_user option = groups[0] if option == '??': us = UserSetting.get(id=user.id) us.stats = True send_async(bot, chat.id, text=_("Enabled statistics!")) elif option == '??': kb = [[locale + ' - ' + descr] for locale, descr in sorted(available_locales.items())] send_async(bot, chat.id, text=_("Select locale"), reply_markup=ReplyKeyboardMarkup(keyboard=kb, one_time_keyboard=True)) elif option == '?': us = UserSetting.get(id=user.id) us.stats = False us.first_places = 0 us.games_played = 0 us.cards_played = 0 send_async(bot, chat.id, text=_("Deleted and disabled statistics!"))
def cmd_vote(bot: telegram.Bot, update: telegram.Update): cid = update.message.chat_id uid = update.message.from_user.id polls = get_polls(uid, bot) if update.message.chat.type != "private": bot.sendMessage(cid, text_private_chat_only) return ConversationHandler.END if len(polls) == 0: bot.sendMessage(cid, "You aren't eligible to vote in any polls.") else: keyboard_choices = [p["tag"] + ": " + p["title"] for p in polls] # keyboard array is a list of lists # because each list represents a new row # and we want each button on a separate row keyboard_array = [[k, ] for k in keyboard_choices] keyboard = ReplyKeyboardMarkup(keyboard_array, one_time_keyboard=True) bot.sendMessage(cid, "Click the button for the poll you would like to vote in.", reply_markup=keyboard) return state_vote_1
def execute(self, chat_id, bot: Bot, update: Update): handled = False if update.message.text in self._buildings_dict: handled = True building_identifier = self._buildings_dict[update.message.text] classrooms = self.get_classroom_source().get_classrooms_in_building(building_identifier) keyboard_button = [] counter = 0 row = -1 for classroom in classrooms: if counter == 0: keyboard_button.append([]) row += 1 keyboard_button[row].append(KeyboardButton("/"+classroom.get_name().lower())) counter += 1 if counter == 3: counter = 0 keyboard_button.append(["/buildings"]) reply_keyboard = ReplyKeyboardMarkup(keyboard_button) bot.send_message(chat_id=chat_id, text="Available classrooms", reply_markup=reply_keyboard) return handled
def services(bot, update): reply_keyboard = [["Agregar Saldo"], ["Ver saldo"], ["Retirar"], ["Mis retiros"], ["Transferir"], ["Mis transferencias"], ["Recargar"],["Mis recargas"], ["Menu Principal"]] response = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=False) update.message.reply_text("¿Que quieres hacer?", reply_markup=response) if response == "Ver saldo": return GET_BALANCE elif response == "Retirar": return WITHDRAW elif response == "Cuenta": return ACCOUNT_INFO elif response == "Transferir": return TRANSFERIR elif response == "Mis transferencias": return SHOW_TRANSFERS elif response == "Mis retiros": return SHOW_WITHDRAWS elif response == "Recargar": return RECARGAR elif response == "Mis recargas": return SHOW_RECHARGES elif response == "Menu Principal": return RETURN return ADD_BALANCE
def trade_cmd(bot, update): reply_msg = "Buy or sell?" buttons = [ KeyboardButton(KeyboardEnum.BUY.clean()), KeyboardButton(KeyboardEnum.SELL.clean()) ] cancel_btn = [ KeyboardButton(KeyboardEnum.CANCEL.clean()) ] reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2, footer_buttons=cancel_btn)) update.message.reply_text(reply_msg, reply_markup=reply_mrk) return WorkflowEnum.TRADE_BUY_SELL # Save if BUY or SELL order and choose the currency to trade
def trade_buy_sell(bot, update, chat_data): chat_data["buysell"] = update.message.text reply_msg = "Choose currency" cancel_btn = [ KeyboardButton(KeyboardEnum.CANCEL.clean()) ] # If SELL chosen, then include button 'ALL' to sell everything if chat_data["buysell"].upper() == KeyboardEnum.SELL.clean(): cancel_btn.insert(0, KeyboardButton(KeyboardEnum.ALL.clean())) reply_mrk = ReplyKeyboardMarkup(build_menu(coin_buttons(), n_cols=3, footer_buttons=cancel_btn)) update.message.reply_text(reply_msg, reply_markup=reply_mrk) return WorkflowEnum.TRADE_CURRENCY # Show confirmation to sell all assets
def trade_price(bot, update, chat_data): chat_data["price"] = update.message.text reply_msg = "How to enter the volume?" buttons = [ KeyboardButton(config["trade_to_currency"].upper()), KeyboardButton(KeyboardEnum.VOLUME.clean()) ] cancel_btn = [ KeyboardButton(KeyboardEnum.ALL.clean()), KeyboardButton(KeyboardEnum.CANCEL.clean()) ] reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2, footer_buttons=cancel_btn)) update.message.reply_text(reply_msg, reply_markup=reply_mrk) return WorkflowEnum.TRADE_VOL_TYPE # Save volume type decision and enter volume
def orders_choose_order(bot, update): buttons = list() # Go through all open orders and create a button if orders: for order in orders: order_id = next(iter(order), None) buttons.append(KeyboardButton(order_id)) else: update.message.reply_text("No open orders") return ConversationHandler.END msg = "Which order to close?" close_btn = [ KeyboardButton(KeyboardEnum.CANCEL.clean()) ] reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=1, footer_buttons=close_btn)) update.message.reply_text(msg, reply_markup=reply_mrk) return WorkflowEnum.ORDERS_CLOSE_ORDER # Close all open orders
def bot_cmd(bot, update): reply_msg = "What do you want to do?" buttons = [ KeyboardButton(KeyboardEnum.UPDATE_CHECK.clean()), KeyboardButton(KeyboardEnum.UPDATE.clean()), KeyboardButton(KeyboardEnum.RESTART.clean()), KeyboardButton(KeyboardEnum.SHUTDOWN.clean()), KeyboardButton(KeyboardEnum.SETTINGS.clean()), KeyboardButton(KeyboardEnum.CANCEL.clean()) ] reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2)) update.message.reply_text(reply_msg, reply_markup=reply_mrk) return WorkflowEnum.BOT_SUB_CMD # Execute chosen sub-cmd of 'bot' cmd
def chart_cmd(bot, update): reply_msg = "Choose currency" buttons = list() for coin, url in config["coin_charts"].items(): buttons.append(KeyboardButton(coin)) cancel_btn = [ KeyboardButton(KeyboardEnum.CANCEL.clean()) ] reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=3, footer_buttons=cancel_btn)) update.message.reply_text(reply_msg, reply_markup=reply_mrk) return WorkflowEnum.CHART_CURRENCY # Get chart URL for every coin in config
def settings_cmd(bot, update): settings = str() buttons = list() # Go through all settings in config file for key, value in config.items(): settings += key + " = " + str(value) + "\n\n" buttons.append(KeyboardButton(key.upper())) # Send message with all current settings (key & value) update.message.reply_text(settings) cancel_btn = [ KeyboardButton(KeyboardEnum.CANCEL.clean()) ] msg = "Choose key to change value" reply_mrk = ReplyKeyboardMarkup(build_menu(buttons, n_cols=2, footer_buttons=cancel_btn)) update.message.reply_text(msg, reply_markup=reply_mrk) return WorkflowEnum.SETTINGS_CHANGE # Change setting
def keyboard_cmds(): command_buttons = [ KeyboardButton("/trade"), KeyboardButton("/orders"), KeyboardButton("/balance"), KeyboardButton("/price"), KeyboardButton("/value"), KeyboardButton("/chart"), KeyboardButton("/history"), KeyboardButton("/funding"), KeyboardButton("/bot") ] return ReplyKeyboardMarkup(build_menu(command_buttons, n_cols=3)) # Generic custom keyboard that shows YES and NO
def eventSelectEditing(self, bot, update, user_data): user_data[user_data['editing_choice']] = update.message.text reply_text = "" if user_data['editing_choice'] == 'Time' and not isTimeString(update.message.text): reply_text = "Your time string is not formatted correctly, please try again.\n\n" user_data['Time'] = None elif user_data['editing_choice'] == 'Date' and not isDateString(update.message.text): reply_text = 'You Date string is not formatted correctly (m/d/20xx), please try again.\n\n' user_data['Date'] = None reply_keyboard = [['Name', 'Time', 'Date'], ['Group','Place'], ['Description']] if all (key in user_data for key in ['Name','Time','Date','Description','Place','Group']): reply_keyboard.append(['Cancel','Done']) else: reply_keyboard.append(['Cancel']) markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) reply_text += "Please select which you would like to edit, once you've entered something for all of these, you will be able to create the event." update.message.reply_text(reply_text, reply_markup=markup) return EVENTSELECT
def start(bot, update): """ Shows an welcome message and help info about the available commands. """ me = bot.get_me() # Welcome message msg = _("Hello!\n") msg += _("I'm {0} and I came here to help you.\n").format(me.first_name) msg += _("What would you like to do?\n\n") msg += _("/support - Opens a new support ticket\n") msg += _("/settings - Settings of your account\n\n") # Commands menu main_menu_keyboard = [[telegram.KeyboardButton('/support')], [telegram.KeyboardButton('/settings')]] reply_kb_markup = telegram.ReplyKeyboardMarkup(main_menu_keyboard, resize_keyboard=True, one_time_keyboard=True) # Send the message with menu bot.send_message(chat_id=update.message.chat_id, text=msg, reply_markup=reply_kb_markup)
def settings(bot, update): """ Configure the messages language using a custom keyboard. """ # Languages message msg = _("Please, choose a language:\n") msg += "en_US - English (US)\n" msg += "pt_BR - Português (Brasil)\n" # Languages menu languages_keyboard = [ [telegram.KeyboardButton('en_US - English (US)')], [telegram.KeyboardButton('pt_BR - Português (Brasil)')] ] reply_kb_markup = telegram.ReplyKeyboardMarkup(languages_keyboard, resize_keyboard=True, one_time_keyboard=True) # Sends message with languages menu bot.send_message(chat_id=update.message.chat_id, text=msg, reply_markup=reply_kb_markup)
def traffic(bot, update, args): """ Get Traffic Updates """ if len(args) == 0: final_string = 'Please enter either traffic Woodlands or traffic Tuas' custom_keyboard = [['/traffic Tuas', '/traffic Woodlands']] reply_markup = ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True, selective=True) bot.sendMessage(update.message.chat_id, final_string, reply_markup=reply_markup) else: bot.sendMessage(update.message.chat_id, text='I go turn on my spycam, please wait', parse_mode='HTML') bot.sendChatAction(update.message.chat_id, action=ChatAction.TYPING) final_string = gov.traffic_get(args[0]) bot.sendMessage(update.message.chat_id, text=final_string, parse_mode='HTML') botan_track(update.message.from_user.id, update.message, update.message.text)
def __init__(self, token, host, port, cert, cert_key, working_dir): self.token = token self.host = host self.port = port self.cert = cert self.cert_key = cert_key self.bot = telegram.Bot(self.token) self.app = Flask(__name__) self.context = (self.cert, self.cert_key) self.working_dir = working_dir self.kb = [[telegram.KeyboardButton('Offer me a coffee'), telegram.KeyboardButton('Source Code'), telegram.KeyboardButton('Vote Me')]] self.kb_markup = telegram.ReplyKeyboardMarkup(self.kb, resize_keyboard=True)
def custom_keyboard(bot, chat_id, buttons, text): reply_markup = ReplyKeyboardMarkup(buttons, resize_keyboard = True) try: bot.sendMessage(chat_id=chat_id, text=text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=reply_markup) except BadRequest: bot.sendMessage(chat_id=chat_id, text=replace_unsafe(text), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=reply_markup) except RetryAfter: sleep(240) bot.sendMessage(chat_id=chat_id, text=text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=reply_markup) except TimedOut: sleep(10) bot.sendMessage(chat_id=chat_id, text=text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=reply_markup) except: sleep(1) bot.sendMessage(chat_id=chat_id, text=text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=reply_markup)
def reply_to_start_command(bot, update): reply_keyboard = [['???????? ??????', '?????? ??????', '????????? ??????']] update.message.reply_text( "??????! ? ???, ??????? ??????? ????????? ??????? ??????.", reply_markup=ReplyKeyboardMarkup(reply_keyboard) )
def get_name(bot, update, user_data): user_name = update.message.text if len(user_name.split(" ")) < 2: update.message.reply_text("??????????, ???????? ??? ? ???????") return "name" else: user_data["name"] = user_name reply_keyboard = [["1", "2", "3", "4", "5"]] update.message.reply_text( "?????????? ?? ??? ????? ??????? ?? ????? ?? 1 ?? 5", reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) ) return "attitude"
def attitude(bot, update, user_data): user_data["attitude"] = update.message.text reply_keyboard = [["1", "2", "3", "4", "5"]] update.message.reply_text( "??? ?? ???? ???????? ??????? ?? ????? ?? 1 ?? 5", reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) ) return "understanding"
def comment(bot, update, user_data): user_data["comment"] = update.message.text reply_keyboard = [['???????? ??????', '?????? ??????']] update.message.reply_text("??????? ?? ??? ???????????!", reply_markup=ReplyKeyboardMarkup(reply_keyboard)) return ConversationHandler.END
def reply_to_start_command(bot, update, user_data): first_name = update.effective_user.first_name last_name = update.effective_user.last_name avatar = get_avatar(user_data) text = "??????, {} {}! ? ???, ??????? ???????? ??????? /start".format(first_name, avatar) logging.info("???????????? {} {} ????? {}".format(first_name, last_name, "/start")) update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup(get_keyboard(), resize_keyboard=True))
def change_avatar_step1(bot, update, user_data): reply_keyboard = [] for index, ava in enumerate(avatars): button = "/avatar {} {}".format(index, ava) button = emojize(button, use_aliases=True) reply_keyboard.append(button) text = '?????? ???????? {}'.format(get_avatar(user_data)) update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup([reply_keyboard], resize_keyboard=True))
def change_avatar_step2(bot, update, args, user_data): try: ava = avatars[int(args[0])] user_data['avatar'] = emojize(ava, use_aliases=True) update.message.reply_text('???????? ????????', reply_markup=ReplyKeyboardMarkup(get_keyboard(), resize_keyboard=True)) except(IndexError, ValueError): update.message.reply_text('?????????? ??? ???')
def reply_to_start_command(bot, update, user_data): user = get_user(update.effective_user, user_data) text = "??????, {} {}! ? ???, ??????? ???????? ??????? /start".format(user.first_name, user.avatar) logging.info("???????????? {} {} ????? {}".format(user.first_name, user.last_name, "/start")) update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup(get_keyboard(), resize_keyboard=True))
def change_avatar_step1(bot, update, user_data): user = get_user(update.effective_user, user_data) reply_keyboard = [] for index, ava in enumerate(avatars): button = "/avatar {} {}".format(index, ava) button = emojize(button, use_aliases=True) reply_keyboard.append(button) text = '?????? ???????? {}'.format(get_avatar(user_data)) update.message.reply_text(text, reply_markup=ReplyKeyboardMarkup([reply_keyboard], resize_keyboard=True))
def start(bot, update): hiKey = KeyboardButton("Hi", callback_data="Bonjour") howRU = KeyboardButton("How are you?") bye = KeyboardButton("Bye") introduce = KeyboardButton("I'm Gutsy") keyboard = [ [hiKey, howRU], [bye, introduce] ] reply_markup = ReplyKeyboardMarkup(keyboard) update.message.reply_text('Please choose:', reply_markup=reply_markup)
def start(self, bot, update): keyboardStr = [ ["-", "?", "+"], ["?", " ", "?"], ["?", "?", "?"], ["STOP"], ] headKeyboard = [ [" ", "?", " "], ["?", " ", "?"], [" ", "?", " "], ["Paparazzi"], ] gripperKeyboard = [ ["Open Left", "Open Right"], ["Close Half Left", "Close Half Right"], ["Close Left", "Close Right"] ] keyboard = self.createKeyboard(keyboardStr) reply_markup = ReplyKeyboardMarkup(keyboard) update.message.reply_text( 'Tap the arrows to move the PR2:', reply_markup=reply_markup)
def new_in_state_asked_vk_group_link(bot, update, users_state): vk_url = update.message.text vk_domain = vk_url.split('/')[-1] users_state[update.message.from_user.id] = dict() users_state[update.message.from_user.id]['vk_domain'] = vk_domain update.message.reply_text('???????! ??????:') update.message.reply_text('1. ???????? ????? ?????. ????? ???????????? ????????????') keyboard = [['? ??????']] update.message.reply_text('2. ???????? ????? ???? (@vk_channelify_bot) ? ?????????????? ??????', reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)) return ASKED_CHANNEL_ACCESS_IN_NEW
def filter_by_hashtag(bot, update, db, users_state): user_id = update.message.from_user.id users_state[user_id] = dict() users_state[user_id]['channels'] = dict() keyboard = [] keyboard_row = [] for channel in db.query(Channel).filter(Channel.owner_id == str(user_id)).order_by(Channel.created_at.desc()): try: channel_chat = bot.get_chat(chat_id=channel.channel_id) users_state[user_id]['channels'][channel_chat.title] = channel.channel_id keyboard_row.append(channel_chat.title) if len(keyboard_row) == 2: keyboard.append(keyboard_row) keyboard_row = [] except telegram.TelegramError: logger.warning('filter_by_hashtag: cannot get title of channel {}'.format(channel.channel_id)) traceback.print_exc() if len(keyboard_row) != 0: keyboard.append(keyboard_row) update.message.reply_text('???????? ?????', reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)) return ASKED_CHANNEL_ID_IN_FILTER_BY_HASHTAG
def discab_keyboard(bot, update): """ Command that shows keyboard of sections for: discab_news, discabon and discaboff """ keys = [['News del Dipartimento'], ['Area Biotecnologie'], ['Area Medica'], ['Area Scienze Motorie'], ['Area Psicologia'], ['Chiudi']] bot.sendMessage(update.message.chat_id, 'Scegli la sezione:', reply_markup=telegram.ReplyKeyboardMarkup( keys, one_time_keyboard=True)) return "discab"
def mesva_keyboard(bot, update): """ Command that shows keyboard of sections for: mesva_news, mesvaon and mesvaoff """ keys = [['In Evidenza'], ['Area Medicina'], ['Area Scienze Ambientali'], ['Area Scienze Biologiche'], ['Chiudi']] bot.sendMessage(update.message.chat_id, 'Scegli la sezione:', reply_markup=telegram.ReplyKeyboardMarkup( keys, one_time_keyboard=True)) return "mesva"
def univaq(bot, update): """ Command that shows keyboard of sections for: inevidenza, ultimissime, univaqon, univaqoff """ keys = [['In Evidenza'], ['Ultimissime'], ['Chiudi']] bot.sendMessage(update.message.chat_id, 'Scegli la sezione:', reply_markup=telegram.ReplyKeyboardMarkup( keys, one_time_keyboard=True)) return "univaq"
def section_keyboard(bot, update): """ Command that shows keyboard of departments for: news, newson and newsoff """ keys = [['Univaq'], ['Disim'], ['Mesva'], ['Discab'], ['Chiudi']] bot.sendMessage(update.message.chat_id, 'Scegli il dipartimento:', reply_markup=telegram.ReplyKeyboardMarkup( keys, one_time_keyboard=True)) return "department"
def feedback_command(bot, update): """Defining the command to ask for user's feedback""" keys = [['Lascia un messaggio agli sviluppatori'], ['Chiudi']] bot.sendMessage(update.message.chat_id, 'Cosa desideri fare?', reply_markup=telegram.ReplyKeyboardMarkup( keys, one_time_keyboard=True)) return "send_feedback"
def _convert_answer_part(self, answer_part): if isinstance(answer_part, str): return Message(answer_part) if isinstance(answer_part, (collections.abc.Iterable, Keyboard)): # ??????????? resize_keyboard = False one_time_keyboard = True if isinstance(answer_part, collections.abc.Iterable): answer_part = list(answer_part) else: one_time_keyboard = answer_part.one_time_keyboard resize_keyboard = answer_part.resize_keyboard answer_part = answer_part.markup if isinstance(answer_part[0], str): # ???! ????????? ??? ?????????????? ??? ??????. # ??????, ??? ???? ?????????? ??????????? -- ??? ???? ??????. return ReplyKeyboardMarkup([answer_part], one_time_keyboard=one_time_keyboard, resize_keyboard=resize_keyboard) elif isinstance(answer_part[0], collections.abc.Iterable): # ????????? ??????????? answer_part = list(map(list, answer_part)) if isinstance(answer_part[0][0], str): # ???! return ReplyKeyboardMarkup(answer_part, one_time_keyboard=one_time_keyboard, resize_keyboard=resize_keyboard) if isinstance(answer_part, Inline): return answer_part.convert() return answer_part
def new_alarm(self, bot, update): keyboard = [[InlineKeyboardButton("Daily"), InlineKeyboardButton("Weekday Only")], [InlineKeyboardButton("Close")]] reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True) update.message.reply_text('Select type of alarm, or /cancel to cancel:', reply_markup=reply_markup) return self.ALARM_TYPE
def set_timezone(self, bot, update): keyboard = [] for continent in sorted(get_timezones().keys()): keyboard.append([InlineKeyboardButton(continent)]) reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True) update.message.reply_text('Please select a continent, or /cancel to cancel:', reply_markup=reply_markup) return self.TIMEZONE_CONTINENT
def timezone_continent(self, bot, update): reply = handle_cancel(update) if reply is None: keyboard = [] self.selected_continent = update.message.text for continent in sorted(get_timezones()[self.selected_continent]): keyboard.append([InlineKeyboardButton(continent)]) reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True) update.message.reply_text('Please select a timezone, or /cancel to cancel:', reply_markup=reply_markup) return self.TIMEZONE_TIME return ConversationHandler.END
def chat(bot, update): user = update.message.from_user logger.info('chat - %s' % user) update.message.reply_text( "Sobre que quieres hablar?", reply_markup=ReplyKeyboardMarkup( GENRE_KEYBOARD, one_time_keyboard=True, resize_keyboard=True ) ) return GENRE_SELECTOR
def search_song(bot, update): user = update.message.from_user song_name = update.message.text logger.info('search_song for user %s and song name %s' % (user, song_name)) url = '{}/song/{}' resp = requests.get( url=url.format(API_SERVER, song_name) ) if resp.status_code != 200 or not resp.json(): update.message.reply_text('Lo siento pero lo que estás buscando es demasiado raro incluso para Spotify') return ConversationHandler.END else: song_list = json.loads(resp.content) update.message.reply_text( u"""{} (Popularidad% {})\nActividad: {}\nAlbum: {}\nArtistas: {}\n{}\n{}""".format( song_list[0]['track_name'], song_list[0]['track_popularity'], song_list[0]['activity'], song_list[0]['track_album_name'], ','.join(a['name'] for a in song_list[0]['artists']), song_list[0]['thumb'], song_list[0]['external_url'], ), reply_markup=ReplyKeyboardMarkup( SONG_KEYBOARD, one_time_keyboard=True, resize_keyboard=True ) ) bot.song_cache = song_list[0] return SONG_ACTION
def choose_activity(bot, update): user = update.message.from_user logger.info('choose_activity - %s' % user) update.message.reply_text( "Que tipo de playlist quieres?", reply_markup=ReplyKeyboardMarkup( ACTIVITY_KEYBOARD, one_time_keyboard=True, resize_keyboard=True ) ) return ACTIVITY_SELECTOR
def train(bot, update): user = update.message.from_user logger.info('show_song_to_clasify %s' % user) resp = requests.get( url='{}/user_info/{}/'.format(API_SERVER, user.id) ) if not resp.json(): update.message.reply_text( 'Sorry {}, but I can\'t do that. Please, use "connect" command'.format(user['first_name']) ) else: resp = requests.get( url='{}/train/{}/'.format(API_SERVER, user.id) ) song = resp.json()['song'] if 'song' in resp.json() else None if song: bot.song_cache = song update.message.reply_text( u""" Choose one activity for this song:\n\n Title: {}\n Artist: {}\n Album: {}\n """.format(song[1], song[4], song[2]), reply_markup=ReplyKeyboardMarkup(ACTIVITY_KEYBOARD, one_time_keyboard=True, resize_keyboard=True) ) else: update.message.reply_text("Server error. %s" % resp.json()) return SAVE_SONG
def save_classification(bot, update): user = update.message.from_user logger.info('save_classification(%s) %s - %s' % (user, bot.song_cache, update.message.text)) resp = requests.get( url='{}/user_info/{}/'.format(API_SERVER, user.id) ) if not resp.json(): update.message.reply_text( 'Sorry {}, but I can\'t do that. Please, use "connect" command'.format(user['first_name']) ) else: resp = requests.get( url='{}/classify/{}/{}'.format( API_SERVER, bot.song_cache[0], ACTIVITY_KEYBOARD[0].index(update.message.text) ) ) result = resp.json() resp = requests.get( url='{}/stats/{}/'.format( API_SERVER, user.id ) ) result['total'] = resp.json()['total'] result['classified'] = resp.json()['classified'] update.message.reply_text( 'Result: %s \n\n Statistics:\n %s' % (result, resp.json()), reply_markup=ReplyKeyboardMarkup([[NAVIGATION_KEYBOARD[1]]], one_time_keyboard=True, resize_keyboard=True) ) return SAVE_SONG
def key_ben(bot, update,chat_id): keyboard = [ ['While downloading','Other...'] ] reply_markup = ReplyKeyboardMarkup( keyboard = keyboard, resize_keyboard=True, one_time_keyboard=True) bot.sendMessage(chat_id=chat_id, text="_When are you having your error?_ *(use the keyboard that appears just below)*", parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=reply_markup)