def custom_keyboard(bot, update): buttonrow1 = telegram.KeyboardButton('phone') buttonrow2 = [ telegram.KeyboardButton('deleted'), telegram.KeyboardButton('recurring') ] buttonrow3 = [ telegram.KeyboardButton('waiting'), telegram.KeyboardButton('completed') ] keyboard = [[buttonrow1], buttonrow2, buttonrow3] kb = telegram.ReplyKeyboardMarkup(keyboard) kb.resize_keyboard bot.sendMessage(chat_id=update.message.chat_id, text="You enabled the custom keyboard", reply_markup=kb)
def selsubatd(self, update, context): ''' Asks user for the status of the given subject ''' self.subdic[update.effective_chat.id] = (update.message.text).upper() text = [["Present", "Absent"], ["Go to Menu"]] context.bot.send_message( chat_id=update.effective_chat.id, text='''Select the status of {}\n '''.format( (update.message.text).upper()), reply_markup=telegram.ReplyKeyboardMarkup(text)) context.bot.send_message( chat_id=update.effective_chat.id, text= '''If you want to enter \nthe pnt and ttl class \nseperatly then enter\nThem in this pattern - \n *pp:tt* \n(ex: 05:10)-\n5 out of 10 classes attended''', parse_mode='Markdown')
def setkeyboard(*args, chat_id=chat_id, message="Prova", is_exit=True, hide=False): # *arg must be an array if not hide: keyboard = [] for arg in args: keyboard.append(arg) if is_exit: keyboard.append(["Exit"]) reply_markup = telegram.ReplyKeyboardMarkup(keyboard) else: reply_markup = telegram.ReplyKeyboardHide() bot.sendMessage(chat_id=chat_id, text=message, reply_markup=reply_markup)
def forex_whoisbrokers_handler(bot, update): chat_id = update.message.chat_id lang = update.message.from_user.language_code button_whythese = telegram.KeyboardButton( text=_t("Почему именно на этих брокерах?", lang)) button_davinci = telegram.KeyboardButton( text=_t("Подробнее про робота DaVinci", lang)) button_contact_human = telegram.KeyboardButton( text=_t("Хочу поговорить с человеком", lang)) reply_markup = telegram.ReplyKeyboardMarkup([[button_whythese], [button_davinci], [button_contact_human]]) bot.send_message(chat_id=chat_id, text=_t("Брокер - это ...", lang), reply_markup=reply_markup)
def programasLuke(bot, update): btnProgramasLuke = [[telegram.KeyboardButton('/SocialCircleBlueprint2')], [telegram.KeyboardButton('/SocialCircleBlueprint')], [telegram.KeyboardButton('/Luke')]] reply_kb_markup = telegram.ReplyKeyboardMarkup(btnProgramasLuke, resize_keyboard=True, one_time_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text='Estes são os programs do Luke', reply_markup=reply_kb_markup)
def on_add_expense__add_category(self, update, context): context.user_data['last_cmd'] = 'add_expense__category' user = db.get_user(update.effective_user.name) api_key = user[1] categories = finance_requests.get_categories(api_key)['categories'] categories = map(lambda cat: cat['type'], categories) menu_keyboard = [categories] menu_markup = telegram.ReplyKeyboardMarkup(menu_keyboard, one_time_keyboard=True, resize_keyboard=True) self.updater.bot.sendMessage( chat_id=update.message.chat_id, text="Pick a category:", reply_markup=menu_markup, )
def geo(self, bot, update): # TODO - переделать по обычную клавиатуру # TODO №2 - вынести генерацию кнопок в класс butt_generator, а действие в функцию request_geopoint # TODO №3 - добавить кнопку на прогноз погоды в текущем месте (собрать несколько источников и выдать красивую сводку) try: kbutts = [telegram.KeyboardButton('Где я?', request_location=True)] reply_markup = telegram.ReplyKeyboardMarkup(self.build_menu( kbutts, n_cols=1), resize_keyboard=True, one_time_keyboard=True) bot.send_message(update.message.chat_id, "Выберите действие", reply_markup=reply_markup) except Exception as e: print(e) bot.sendMessage(chat_id=update.message.chat_id, text='Ошибка!')
def programasMadison(bot, update): btnProgramasMadison = [[telegram.KeyboardButton('/MadisonBootcampAtHome')], [telegram.KeyboardButton('/Boss')], [telegram.KeyboardButton('/Madison')]] reply_kb_markup = telegram.ReplyKeyboardMarkup(btnProgramasMadison, resize_keyboard=True, one_time_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text='Estes são os programs do Madison', reply_markup=reply_kb_markup)
def support(bot, update): msg="Как Вы хотите связаться с техподдержкой? Есть два варианта:\n1)/number - прислать Вам номер телефона специалиста\n2)/link - скидываем сюда ссылку на телеграм канал техподдержки\n!" kb_markup = telegram.ReplyKeyboardMarkup([ [telegram.KeyboardButton('/number', reply_msg='/number')], [telegram.KeyboardButton('/link', reply_msg='/link')] ], resize_keyboard=True, one_time_keyboard=True) # print(update.user_id) bot.sendMessage(chat_id=update.message.chat_id, text=msg, reply_markup=kb_markup)
def start_order(self, bot, update): username = update.message.from_user.username text = u"בסיום אימות הפרטים עם הבוט יש לחכות להודעת אישור בדיקת הפרטים ושליחת ההזמנה מנציג שירות אנושי, תהליך זה עשוי לקחת מספר דקות בשעות הפעילות." + "\n" #text += u"על מנת להתחיל את ההזמנה אנא שלח/י תמונת סלפי כשאת/ה מחזיק/ה תעודת זהות/רישיון נהיגה/דרכון. נא לשים לב שהתמונה ברורה." text += u"על מנת להתחיל את ההזמנה אנא בחר כמות להזמנה: " + "\n" kb = [[telegram.KeyboardButton(self.cancel_text)]] for key, val in sorted(self.orders.items()): if self.users_states[username]["service"] == "delivery": text += val[0] + " gram: " + str(val[1] +50) +"\n" else: text += val[0] + " gram: " + str(val[1]) +"\n" kb.append([telegram.KeyboardButton(val[0])]) kb_markup = telegram.ReplyKeyboardMarkup(kb, resize_keyboard=True, one_time_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text=text, reply_markup=kb_markup)
def period_CCPC(update,context): ''' Function to send KeyBoard of Periods to the user in Teacher_Announcements/Create_Class path ''' context.user_data['CR8ClsSub'] = (update.message.text) availableperlst = list() grade = (db.chkusr(update.effective_chat.id)).split('U')[0] stdperiodlst = [i[0] for i in db.getStdtt(grade ,context.user_data['stdCR8Day'])] for i in cs.datajson['periodlst']: if (i not in stdperiodlst): availableperlst.append(i) context.user_data['availableperlst'] = availableperlst update.message.reply_text(text='''Which period of {} do you want to create class ?'''.format((update.message.text)), reply_markup=telegram.ReplyKeyboardMarkup(cs.build_menu(context.user_data['availableperlst']+['Back']))) return CR8CLS_PERD_KEY
def help(bot, update): msg="Для Вас, у нас есть несколько команд, результаты которых, надеемся помогут Вам.\n1)/helpme - помогаем мы \n2)/support - по Вашему выбору скидываем в этот чат ссылку на телеграм канал (техподдержки) или телефон квалифицированного специалиста техподдержки" kb_markup = telegram.ReplyKeyboardMarkup([ [telegram.KeyboardButton('/helpme', reply_msg='/helpme')], [telegram.KeyboardButton('/support', reply_msg='/support')] ], resize_keyboard=True, one_time_keyboard=True) # print(update.user_id) bot.sendMessage(chat_id=update.message.chat_id, text=msg, reply_markup=kb_markup)
def choose_number(bot, update): uid = str(update.message.from_user.id) with open(queue_file, 'r') as f: used = [i.split('^')[0] for i in f.readlines()] if any([uid == i for i in used]): update.message.reply_text("Вы уже в очереди.") return digits_keyboard = [['1', '2', '3', '4', '5'], ['6', '7', '8', '9', '10'], ['11', '12', '13', '14', '<-']] reply_markup = telegram.ReplyKeyboardMarkup(digits_keyboard) bot.send_message(chat_id=update.message.chat_id, text="Какой номер в очереди хотите?", reply_markup=reply_markup)
def devgetCRRoll(update, context): ''' Function to Ask Roll no of CR ''' text = '' roll_no = db.getCR() for i in roll_no: text = text + '\n {} - {}'.format(roll_no.split('U')[0], roll_no) update.message.reply_text( text= '''List of CR Roll No :{}\nPlease Enter The Roll no of the CR.\nIf the roll no is already in the above list then \ I will delete it else i will add it\nNote : one grade can have only one CR''' .format(text), reply_markup=telegram.ReplyKeyboardMarkup([['Back']])) return DEV_MNG_CR_KEY
def dev_msg_usr(update, context): ''' Function to contact the Developer ''' context.user_data['DevUsrOpt'] = update.message.text update.message.reply_text( text="Send me the message that you want me to pass to {}".format( update.message.text), reply_markup=telegram.ReplyKeyboardMarkup( [['Back'], [ telegram.KeyboardButton( text='Send Poll', request_poll=telegram.KeyboardButtonPollType(type=None)) ]])) return DEV_MSG_KEY
def start(chat_id): button_list = [ [ telegram.KeyboardButton("latest activity"), telegram.KeyboardButton("latest creations"), # telegram.InlineKeyboardButton("artworks by artist", callback_data="artworks by artist"), ], [ telegram.KeyboardButton("feeling lucky (high price)"), telegram.KeyboardButton("feeling lucky (low price)"), # telegram.KeyboardButton("all artists"), ], ] # reply_markup = telegram.InlineKeyboardMarkup(button_list) reply_markup = telegram.ReplyKeyboardMarkup(button_list, resize_keyboard=True) bot.sendMessage(chat_id=chat_id, text="Choose option:", reply_markup=reply_markup)
def one(bot,update): msg="Какое Вы лицо:Физическое или Юридическое?" kb_markup = telegram.ReplyKeyboardMarkup([ [telegram.KeyboardButton('/Физическое', reply_msg='/Физическое')], [telegram.KeyboardButton('/Юридическое', reply_msg='/Юридическое')] ], resize_keyboard=True, one_time_keyboard=True) # print(update.user_id) bot.sendMessage(chat_id=update.message.chat_id, text=msg, reply_markup=kb_markup)
def next_step_prompt(suggestion): location_restaurant_button = telegram.KeyboardButton( text=f"Suggest a restaurant in {suggestion}") location_button = telegram.KeyboardButton( text="Suggest another location") all_location_button = telegram.KeyboardButton(text="See all locations") custom_keyboard = [[location_restaurant_button], [location_button], [all_location_button]] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True, resize_keyboard=True) bot.send_message( chat_id=update.message.chat_id, text= "Do you want me to suggest a restaurant in this location? Suggest another location? You can also choose to see all locations!", reply_markup=reply_markup)
def programasMax(bot, update): btnProgramasMax = [[telegram.KeyboardButton('/Fearless')], [telegram.KeyboardButton('/TheNatural')], [telegram.KeyboardButton('/Maximilian')]] reply_kb_markup = telegram.ReplyKeyboardMarkup(btnProgramasMax, resize_keyboard=True, one_time_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text='Estes são os programs do Max', reply_markup=reply_kb_markup)
def start(self, bot, update): username = update.message.from_user.username self.check_admin(update) self.users_states[username] = {} self.users_states[username]["state"] = 1 text = u"שלום " + username + "\n" text += u"הגעת לבוט ההזמנות האוטומטי של פוגיזז" + "\n" text += u"האם תרצה איסוף עצמי או משלוח?" + "\n" text += u"עלות משלוח היא 50 שח" kb = [[telegram.KeyboardButton(self.picup)], [telegram.KeyboardButton(self.delivery)]] kb_markup = telegram.ReplyKeyboardMarkup(kb, resize_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text=text, reply_markup=kb_markup)
def SendDelOrder(bot, update): orders = db.orders.find({'status': True}) for x in orders: bot.send_message(chat_id=update.message.chat_id, text=x['name'] + '\n' + x['area'], reply_markup=telegram.InlineKeyboardMarkup([[ telegram.InlineKeyboardButton( text='Удалить', callback_data=x['order_id'] + '$$DEL') ]])) bot.send_message(chat_id=update.message.chat_id, text='Доступные товары', reply_markup=telegram.ReplyKeyboardMarkup( [[telegram.KeyboardButton('🔙 Вернуться в меню')]], resize_keyboard=True))
def graph_start(update, context): update.message.reply_text( 'Подготавливаю список стран, ожидайте' ) # вопрос и убираем основную клавиатуру , reply_markup=ReplyKeyboardRemove() global g_df g_df = get_dataframe() # получаем свежий датафрейм, делаем его глобальным top_countr = g_df.iloc[:, [1, len(g_df.columns) - 1]].nlargest( NUM_COUNTRIES_IN_SET, [list(g_df.columns)[-1]], keep='all' ) # только NUM_COUNTRIES_IN_SET максимальных по последней колонке list_of_top10_countries = top_countr.iloc[:, 0].tolist( ) # передаем топ 10 стран из датафрейма в список global regex_string regex_string = list_of_top10_countries[0] + '|' + \ list_of_top10_countries[1] + '|' + \ list_of_top10_countries[2] + '|' + \ list_of_top10_countries[3] + '|' + \ list_of_top10_countries[4] + '|' + \ list_of_top10_countries[5] + '|' + \ list_of_top10_countries[6] + '|' + \ list_of_top10_countries[7] + '|' + \ list_of_top10_countries[8] + '|' + \ list_of_top10_countries[9] reply_keyboard = [[ list_of_top10_countries[0], list_of_top10_countries[1], list_of_top10_countries[2] ], [ list_of_top10_countries[3], list_of_top10_countries[4], list_of_top10_countries[5] ], [ list_of_top10_countries[6], list_of_top10_countries[7], list_of_top10_countries[8] ], [list_of_top10_countries[9], "Назад"]] update.message.reply_text( "Для какой страны из Top10 составить график?", reply_markup=telegram.ReplyKeyboardMarkup( reply_keyboard, resize_keyboard=True)) # , one_time_keyboard=True return "country_choise" # ключ для определения следующего шага
def common_message(update, context): """General response handler""" msg = update.message user = msg.from_user debug(f'Message received from {user.id} @{user.username}: {msg.text}') if AUTHORIZED_USERS and user.username not in AUTHORIZED_USERS: return if 'quiz' not in context.user_data: info(f'Quiz started by {user.id} @{user.username}') context.user_data['quiz'] = {} context.user_data['quiz']['answers'] = {} starttime = datetime.now() context.user_data['quiz']['starttime'] = starttime msg.bot.send_message(msg.chat_id, text=f'Тест начат в {starttime}', reply_markup=telegram.ReplyKeyboardRemove()) else: # save response context.user_data['quiz']['answers'][context.user_data['quiz']['current_qid']] = msg.text # ask the question questions_left = set(QUESTIONS) - set(context.user_data['quiz']['answers']) if len(questions_left) > 0: question = QUESTIONS[random.sample(questions_left, 1)[0]] msg.bot.send_message(msg.chat_id, text=f'{question.text}\n' + \ '\n'.join(f'{aid}. {text}' for aid, text in sorted(question.answers.items())), reply_markup=telegram.ReplyKeyboardMarkup([[aid for aid in sorted(question.answers)]])) context.user_data['quiz']['current_qid'] = question.qid else: msg.bot.send_message(msg.chat_id, text=f'Тест пройден!', reply_markup=telegram.ReplyKeyboardRemove()) context.user_data['quiz']['current_qid'] = None
def command_start(self, update): """Telegram command /start """ try: # if update.effective_user.id != self.telegram_master: # return self.wake(update) self.skill = None self.send_message( text='Чем я могу помочь?', reply_markup=telegram.ReplyKeyboardMarkup([[s.title] for s in self.skills])) self.sleep() except: self.chatid = update['message']['chat']['id'] f = io.StringIO() traceback.print_exc(file=f) self.send_message(text=f.getvalue())
def ema_happiness(update, context): user = update.message.from_user #Logs: username, chat id, datetime of original message, question, datetime of reply, reply info logger.info("%s, %s, %s, Happiness, %s, %s", user.username, update.message.chat_id, update.message.forward_date, update.message.date, update.message.text) #Custom keyboard layout kb = [['1', '2', '3', '4', '5'], ['6', '7', '8', '9', '10']] kb_markup = telegram.ReplyKeyboardMarkup(kb, one_time_keyboard=True) update.message.reply_text( "How energetic do you feel right now, where 1 = Very Tired and 10 = Very Energetic?", reply_markup=kb_markup) return ENERGY
def name_select(bot, update, user_data): seasons = [] for serie in Serie.get_series_list(): if serie.name == update.message.text: seasons = serie.get_seasons() user_data['serie'] = serie break if seasons is []: update.message.reply_text('No he encontrado nada :(', reply_markup=ReplyKeyboardRemove()) return restart(update, user_data) reply_markup = telegram.ReplyKeyboardMarkup([seasons, ['/cancelar']]) update.message.reply_text('Qué temporada?', reply_markup=reply_markup) save_data() return SEASON
def keyboard_Internazionale(update, context): # Custom keyboard custom_keyboard = [ # main commands ['/world Italy'], ['/world USA'], ['/world Germany'], ['/world China'], ['/world Russia'], ['/world UK'], ['/world Japan'], # leaving ['/start', '/keyboards', '/colore_regioni', '/help'], ] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True) update.message.reply_text(text=MESSAGE_KEYBOARD, reply_markup=reply_markup)
def bot_menu(self, bot, update): message_id = update._effective_message.message_id userid = update.message.from_user.id if (userid not in self.admins) and (userid not in self.admins): return False custom_keyboard = [] for entry in self.menu_reg: custom_keyboard.append([entry]) reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, selective=True, one_time_keyboard=True) self.dispatcher.bot.sendMessage(chat_id=self.chat_id, reply_markup=reply_markup, text="Menu", reply_to_message_id=message_id)
def askYesNo(self, message): custom_keyboar = [['yes', 'no']] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboar, resize_keyboard=True, one_time_keyboard=True) self.question_lock.acquire() message = self.question_tmpl.format(message=message) message = self.bot.sendMessage(chat_id=self.chat_id, text=message, parse_mode="Markdown", reply_markup=reply_markup) self.last_question_id = message.message_id self.question_lock.release() value = self.queue.get() self.last_question_id = None return value
def calc_me(bot, update): custom_keyboard = [['1', '2', '3', '*'], ['4', '5', '6', '/'], ['7', '8', '9', '-'], ['0', '.', '=', '+']] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) # bot.sendMessage(chat_id=update.message.chat_id, text = "Custom Keyboard Test", reply_markup = reply_markup) text = update.message.text numbers = {"один": "1", "два": "2", "три": "3", "четыре": "4", "пять": "5", "шесть": "6", "семь": "7", "восемь": "8", "девять": "9"} # digits = dict([(v, k) for k, v in numbers.items()]) ВЖУХ! И словарь наоборот text = text.strip('=')[6:] # if ' ' in text: # bot.sendMessage(update.message.chat_id, "избавься от пробелов!") # return text = text.split try: print(text) if 'плюс' in text: # elems = text.split("+") result = float(numbers[text[0]]) + float(numbers[text[2]]) elif 'минус' in text: # elems = text.split("-") result = float(numbers[text[0]]) - float(numbers[text[2]]) elif 'умножить' in text: # elems = text.split("*") result = float(numbers[text[0]]) * float(numbers[text[2]]) elif 'делить' in text: # elems = text.split("/") try: result = float(numbers[text[0]]) / float(numbers[text[2]]) except ZeroDivisionError: bot.sendMessage(update.message.chat_id, "деление на ноль!") return except ValueError: bot.sendMessage(update.message.chat_id, "кривая запись!") return bot.sendMessage(update.message.chat_id, result)