# InlineKeyboardButton("row 2", callback_data=...) # ] reply_keyboard = [['/address', '/phone'], ['/help', '/close']] markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=False) button_list = [ InlineKeyboardButton('address', callback_data=0), InlineKeyboardButton('phone', callback_data=1), InlineKeyboardButton('help', callback_data=2), InlineKeyboardButton('close', callback_data=3) ] reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=4)) some_strings = ["col1", "col2", "row2"] button_list = [[KeyboardButton(ss)] for ss in some_strings] # сборка клавиатуры из кнопок `KeyboardButton` reply_markup1 = ReplyKeyboardMarkup(build_menu(button_list, n_cols=2)) # отправка клавиатуры в чат def echo(update, context): txt = update.message.text if txt.lower() in ['привет', 'здаров']: txt = "И тебе привет человек!" update.message.reply_text(txt) def start(update, context): update.message.reply_text( "Привет! Я эхо-бот. Напишите мне что-нибудь, и я пришлю это назад!",
def to_address(bot, update, user_data): command2 = update.message.text cancel_button = KeyboardButton('Выход') start_price = KeyboardButton('Я заплачу...') reply_markup = ReplyKeyboardMarkup([[start_price], [cancel_button]], resize_keyboard=True, one_time_keyboard=True) text = 'Ты можешь решить, за сколько хочешь поехать и мы постараемся поискать, когда цена станет подходящей(нажми кнопку "Я заплачу...") или ты можешь сразу перейти в приложение.' # try-except - обработчик ошибок. Если ошибки обнаруженны - остается только кнопка "Выход". try: if update.message.location is None: command2 = command2.replace(',', '').split() info = location.get_location(command2) locat = info['response']['GeoObjectCollection']['featureMember'] for loc in locat: loc_name = loc['GeoObject']['Point']['pos'] loc_name = loc_name.split(' ') add2 = arg(loc_name) to_long = add2[0] to_lat = add2[1] from_long = user_data['from_long'] from_lat = user_data['from_lat'] user_data['to_lat'] = to_lat user_data['to_long'] = to_long price_yandex = ya_price.price(from_long, from_lat, to_long, to_lat) price_city = city.get_est_cost(from_lat, from_long, to_lat, to_long) user_data['price_yandex'] = price_yandex user_data['price_city'] = price_city if from_long == to_long and from_lat == to_lat: update.message.reply_text( 'Здесь ты мог бы и пешком пройтись. Нажми "Выход" и подумай над своим маршрутом.') elif price_city < price_yandex: update.message.reply_text( 'Цена в Яндекс.Такси: {}. Цена в Ситимобил: {}. [Перейди в приложение Ситимобил](http://onelink.to/5m3naz)'.format( price_yandex, float(price_city)), parse_mode='Markdown', reply_markup=reply_markup) update.message.reply_text(text) else: update.message.reply_text( 'Цена в Яндекс.Такси: {}. Цена в Ситимобил: {}. [Перейди в приложение Яндекс.Такси](https://3.redirect.appmetrica.yandex.com/route?utm_source=serp&utm_medium=org&start-lat={}&start-lon={}&end-lat={}&end-lon={}&ref=402d5282d269410b9468ae538389260b&appmetrica_tracking_id=1178268795219780156)'.format( price_yandex, float(price_city), from_lat, from_long, to_lat, to_long), parse_mode='Markdown', reply_markup=reply_markup) update.message.reply_text(text) else: command = update.message.location to_long_location = command['longitude'] to_lat_location = command['latitude'] from_long_location = user_data['from_long'] from_lat_location = user_data['from_lat'] user_data['to_lat'] = to_lat_location user_data['to_long'] = to_long_location price_yandex = ya_price.price(from_long_location, from_lat_location, to_long_location, to_lat_location) price_city = city.get_est_cost(from_lat_location, from_long_location, to_lat_location, to_long_location) user_data['price_yandex'] = price_yandex user_data['price_city'] = price_city if from_long_location == to_long_location and from_lat_location == to_lat_location: update.message.reply_text( 'Здесь ты мог бы и пешком пройтись. Нажми "Выход" и подумай над своим маршрутом.') if price_city < price_yandex: update.message.reply_text( 'Цена в Яндекс.Такси: {}. Цена в Ситимобил: {}. [Перейди в приложение Ситимобил](http://onelink.to/5m3naz)'.format( price_yandex, float(price_city)), parse_mode='Markdown', reply_markup=reply_markup) update.message.reply_text(text) else: update.message.reply_text( 'Цена в Яндекс.Такси: {}. Цена в Ситимобил: {}. [Перейди в приложение Яндекс.Такси](https://3.redirect.appmetrica.yandex.com/route?utm_source=serp&utm_medium=org&start-lat={}&start-lon={}&end-lat={}&end-lon={}&ref=402d5282d269410b9468ae538389260b&appmetrica_tracking_id=1178268795219780156)'.format( price_yandex, float(price_city), from_lat_location, from_long_location, to_lat_location, to_long_location), parse_mode='Markdown', reply_markup=reply_markup) update.message.reply_text(text) return SELECT except Exception as ex: cancel_button = KeyboardButton('Выход') reply_markup = ReplyKeyboardMarkup([[cancel_button]], resize_keyboard=True, one_time_keyboard=True) logging.exception(ex) update.message.reply_text( 'Кажется, что-то пошло не так... Нажми "Выход" и начни все сначала.', reply_markup=reply_markup)
def main_keyboard(): return ReplyKeyboardMarkup([[ 'Прислать котика', KeyboardButton('Мои координаты', request_location=True) ]])
def button(bot, update) -> None: query = bot.callback_query.data global statusDict datas = str(query).split(';') if "Ozan_approve" in query: status = statusDict[0] headers = {'Accept': '*/*', 'Content-Type': 'application/json'} requests.put(url="http://localhost:9090/chageStatus/" + datas[1], json=status, headers=headers) update.bot.sendMessage( chat_id=datas[1], text="Your request approved. You can use other commands") cacheUserLists() elif "Ozan_decline" in query: status = statusDict[2] headers = {'Accept': '*/*', 'Content-Type': 'application/json'} requests.put(url="http://localhost:9090/chageStatus/" + datas[1], json=status, headers=headers) update.bot.sendMessage( chat_id=datas[1], text="Your request rejected. You are Blacklisted") cacheUserLists() elif "WhiteList" in query: status = statusDict[0] headers = {'Accept': '*/*', 'Content-Type': 'application/json'} requests.put(url="http://localhost:9090/chageStatus/" + datas[1], json=status, headers=headers) update.bot.sendMessage(chat_id=datas[1], text="Your status changed to WhiteListed") cacheUserLists() elif "WaitingList" in query: status = statusDict[1] headers = {'Accept': '*/*', 'Content-Type': 'application/json'} requests.put(url="http://localhost:9090/chageStatus/" + datas[1], json=status, headers=headers) update.bot.sendMessage(chat_id=datas[1], text="Your status changed to WaitingListed") cacheUserLists() elif "BlackList" in query: status = statusDict[2] headers = {'Accept': '*/*', 'Content-Type': 'application/json'} requests.put(url="http://localhost:9090/chageStatus/" + datas[1], json=status, headers=headers) update.bot.sendMessage(chat_id=datas[1], text="Your status changed to BlackListed") cacheUserLists() elif "Admin" in query: status = statusDict[3] headers = {'Accept': '*/*', 'Content-Type': 'application/json'} requests.put(url="http://localhost:9090/chageStatus/" + datas[1], json=status, headers=headers) update.bot.sendMessage(chat_id=datas[1], text="Your status changed to Admin") cacheUserLists() elif "Location_Information" in query: keyboard = [] row = [] row.append( InlineKeyboardButton("Send Location", callback_data="LocationApprove;" + str(datas[1]) + ";" + str(datas[3]))) row.append( InlineKeyboardButton("Cancel request", callback_data="CancelRequest;" + str(datas[1]) + ";" + str(datas[3]))) keyboard.append(row) row = [] row.append( InlineKeyboardButton( "Block user for sending another Location Request", callback_data="LocationBlock;" + str(datas[1]))) keyboard.append(row) reply_markup = InlineKeyboardMarkup(keyboard) update.bot.sendMessage( chat_id=datas[1], text="Your Location information is requested by " + str(datas[2]), reply_markup=reply_markup) elif "Contact_Information" in query: keyboard = [] row = [] row.append( InlineKeyboardButton("Send Contract", callback_data="ContractApprove;" + str(datas[1]))) row.append( InlineKeyboardButton("Cancel request", callback_data="CancelRequest;" + str(datas[1]) + ";" + str(datas[3]))) keyboard.append(row) row = [] row.append( InlineKeyboardButton( "Block user for sending another Contract Request", callback_data="ContractBlock;" + str(datas[1]))) keyboard.append(row) reply_markup = InlineKeyboardMarkup(keyboard) update.bot.sendMessage( chat_id=datas[1], text="Your Contract information is requested by " + str(datas[2]), reply_markup=reply_markup) elif "CancelRequest" in query: update.bot.sendMessage(chat_id=datas[1], text="Request Canceled") update.bot.sendMessage( chat_id=datas[2], text="Your request canceled by the requested user") elif "LocationApprove" in query: keyboard = [[ KeyboardButton(text="Approve Location Share", request_location=True), KeyboardButton(text="Cancel Share", request_location=False) ]] keyboardMarkup = ReplyKeyboardMarkup(keyboard=keyboard, one_time_keyboard=True, resize_keyboard=True) update.bot.sendMessage(chat_id=str(datas[1]), text="SharedLocationTo;" + datas[2], reply_markup=keyboardMarkup)
max_score = score max_disease = current_disease if score < 0.1: score *= 5 if score > 0.8: score = 0.75 return score, max_disease ### print('Ready') HOW_IT_WORKS = emojize(':mag: Как это работает', use_aliases=True) ABOUT_US = emojize(':rocket: О нас', use_aliases=True) RANDOM_DRUG = emojize(':crying_cat_face: Пример жалобы', use_aliases=True) MAIN_MENU_BUTTON = emojize(':seat: Главное меню', use_aliases=True) main_menu_keyboard = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text=RANDOM_DRUG)], [KeyboardButton(text=HOW_IT_WORKS), KeyboardButton(text=ABOUT_US)]], resize_keyboard=True) back_to_menu_keyboard = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text=MAIN_MENU_BUTTON)]],resize_keyboard=True) def all_work(bot, update, jaloba_mine): bot.send_chat_action(chat_id=update.message.chat_id, action=ChatAction.TYPING) try: msg = 'Подождите, пожалуйста, сейчас информация обрабатывается' bot.send_message(chat_id=update.message.chat_id, text=msg) jaloba_mine = noraml_elem_of_diseases(jaloba_mine) score, result = what_disease(link_table, jaloba_mine) current_tabel = link_table[link_table['disease'] == result]
ch.setFormatter(formatter) log.addHandler(fh) log.addHandler(ch) return log log = get_logger() # Хранилище цитат башорга, из которого будут браться цитаты, и посылаться в телеграм. # Когда этот список будет пустым, оно будет заполнено с сайта. QUOTES_LIST = list() REPLY_KEYBOARD_MARKUP = ReplyKeyboardMarkup([[KeyboardButton('Хочу цитату!')]], resize_keyboard=True) def get_random_quotes_list(): log.debug('get_random_quotes_list') quotes = list() try: with urlopen(Request(config.URL, headers={'User-Agent': config.USER_AGENT})) as f: root = etree.HTML(f.read()) for quote_el in root.xpath('//*[@class="quote"]'): try: url = urljoin(config.URL, quote_el.xpath('*[@class="actions"]/*[@class="id"]')[0].attrib['href'])
from hvr import * from math import ceil import locale hvr = None user_config = {} # Enable logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) custom_keyboard = [[ KeyboardButton('/fill'), KeyboardButton('/charge'), KeyboardButton('/balance') ]] yes_no_keyboard = [[KeyboardButton('/no'), KeyboardButton('/yes')]] reply_markup = ReplyKeyboardMarkup(custom_keyboard) yes_no_markup = ReplyKeyboardMarkup(yes_no_keyboard) remove_markup = ReplyKeyboardRemove() waiting_for_charge_amount = False waiting_for_fill_amount = False waiting_for_confirmation = False charge_amount = 0 CARD_CHARGE_SUCCESS_MESSAGE = "הטעינה הושלמה בהצלחה"
def message_settingstype(self): """ Called when user sends the type of settings he wants to change """ if self.message.text == '️🧍 Personal Information': self.bot.sendMessage( self.message.user.chatID, "Here are the Information about you that you can change:", reply_markup=ReplyKeyboardMarkup( [[KeyboardButton('🗣 Name')], [KeyboardButton('🚅 Address')], [KeyboardButton('🏫 Course')], [KeyboardButton('⏪ Back')]], resize_keyboard=True, one_time_keyboard=True)) self.message.user.expectedMessageType = 'settingspersonalinfo' elif self.message.text == '📲 Subscription-Settings': # Fetch the user's subscriptions to show them the current status options = [] if self.message.user.pauseAllNotifications: options.append( [KeyboardButton('🔔 Unpause all Push Notifications')]) else: options.append( [KeyboardButton('🔕 Pause all Push Notifications')]) if self.message.user.wantsMenu: options.append([KeyboardButton('❌ Unsubscribe the Menu Push')]) else: options.append([KeyboardButton('✅ Subscribe the Menu Push')]) if self.message.user.wantsLecturePlan: options.append( [KeyboardButton('❌ Unsubscribe the Lecture Plan Push')]) else: options.append( [KeyboardButton('✅ Subscribe the Lecture Plan Push')]) if self.message.user.wantsExamWarning: options.append( [KeyboardButton('❌ Unsubscribe the Exam Warning Push')]) else: options.append( [KeyboardButton('✅ Subscribe the Exam Warning Push')]) if self.message.user.wantsTransportInfo: options.append([ KeyboardButton('❌ Unsubscribe the Public Transport Info') ]) else: options.append( [KeyboardButton('✅ Subscribe the Public Transport Info')]) if self.message.user.wantsToRateMeals: options.append( [KeyboardButton('❌ Opt-out of the Meal Rating')]) else: options.append([KeyboardButton('✅ Opt-in to the Meal Rating')]) options.append([KeyboardButton('⏪ Back')]) self.bot.sendMessage(self.message.user.chatID, "Here are your Subscriptions:", reply_markup=ReplyKeyboardMarkup( options, resize_keyboard=True, one_time_keyboard=True)) self.message.user.expectedMessageType = 'settingssubscriptions' elif self.message.text == '⏰ Push Time Settings': menuPushTime = self.message.user.pushTimes['menu'] lecturePushTime = self.message.user.pushTimes['lecture'] self.bot.sendMessage( self.message.user.chatID, "What push notification should come on another time? ", reply_markup=ReplyKeyboardMarkup( [[ KeyboardButton( ('🍜 Menu Push (currently ' + menuPushTime + ')')) ], [ KeyboardButton(('🕒 Lecture Plan Push (currently ' + lecturePushTime + ')')) ], [KeyboardButton('⏪ Back')]], resize_keyboard=True, one_time_keyboard=True)) self.message.user.expectedMessageType = 'settingstimes' elif self.message.text == '🧨 Cancel': self.bot.sendMessage(self.message.user.chatID, "ALLES BLEIBT HIER WIE ES IST.") self.message.user.expectedMessageType = '' else: self.bot.sendMessage( self.message.user.chatID, "Wrong input. Please try again:", reply_markup=ReplyKeyboardMarkup( [[KeyboardButton('️🧍 Personal Information')], [KeyboardButton('📲 Subscription-Settings')], [KeyboardButton('⏰ Push Time Settings')], [KeyboardButton('🧨 Cancel')]], resize_keyboard=True, one_time_keyboard=True))
def message_settingssubscriptions(self): """ Called when user sends the information that he wants to change his subscription settings """ if self.message.text == '🔔 Unpause all Push Notifications': self.message.user.pauseAllNotifications = False self.bot.sendMessage( self.message.user.chatID, "Unpaused the Push Notifications. Just for you.") self.message.user.expectedMessageType = '' elif self.message.text == '🔕 Pause all Push Notifications': self.message.user.pauseAllNotifications = True self.bot.sendMessage( self.message.user.chatID, "Paused all Push Notifications. Just for you.") self.message.user.expectedMessageType = '' elif self.message.text == '❌ Unsubscribe the Menu Push': self.message.user.wantsMenu = False self.bot.sendMessage(self.message.user.chatID, "💔 Unsubscribed you from the menu push") self.message.user.expectedMessageType = '' elif self.message.text == '✅ Subscribe the Menu Push': self.message.user.wantsMenu = True self.bot.sendMessage(self.message.user.chatID, "❤️ Subscribed you to the menu push") self.message.user.expectedMessageType = '' elif self.message.text == '❌ Unsubscribe the Lecture Plan Push': self.message.user.wantsLecturePlan = False self.bot.sendMessage( self.message.user.chatID, "💔 Unsubscribed you from the lecture plan push") self.message.user.expectedMessageType = '' elif self.message.text == '✅ Subscribe the Lecture Plan Push': self.message.user.wantsLecturePlan = True self.bot.sendMessage(self.message.user.chatID, "❤️ Subscribed you to the lecture plan push") # Check if the user has already entered his course if self.message.user.course == '' or self.message.user.course is None: self.bot.sendMessage( self.message.user.chatID, ("‼️ You have not entered your course yet. " + "Please do that via /settings -> Personal Information."), reply_markup=ReplyKeyboardMarkup( [[KeyboardButton('/settings')]], resize_keyboard=True, one_time_keyboard=True)) self.message.user.expectedMessageType = '' elif self.message.text == '❌ Unsubscribe the Exam Warning Push': self.message.user.wantsExamWarning = False self.bot.sendMessage( self.message.user.chatID, "💔 Unsubscribed you from the exam warning push") self.message.user.expectedMessageType = '' elif self.message.text == '✅ Subscribe the Exam Warning Push': self.message.user.wantsExamWarning = True self.bot.sendMessage(self.message.user.chatID, "❤️ Subscribed you to the exam warning push") # Check if the user has already entered his course if self.message.user.course == '' or self.message.user.course is None: self.bot.sendMessage( self.message.user.chatID, ("‼️ You have not entered your course yet. " + "Please do that via /settings -> Personal Information."), reply_markup=ReplyKeyboardMarkup( [[KeyboardButton('/settings')]], resize_keyboard=True, one_time_keyboard=True)) self.message.user.expectedMessageType = '' elif self.message.text == '❌ Unsubscribe the Public Transport Info': self.message.user.wantsTransportInfo = False self.bot.sendMessage( self.message.user.chatID, "💔 Unsubscribed you from the public transport info") self.message.user.expectedMessageType = '' elif self.message.text == '✅ Subscribe the Public Transport Info': self.message.user.wantsTransportInfo = True self.bot.sendMessage( self.message.user.chatID, "❤️ Subscribed you to the public transport info") # Check if the user has already entered his address if self.message.user.address == '' or self.message.user.address is None: self.bot.sendMessage( self.message.user.chatID, ("‼️ You have not entered your address yet. " + "Please do that via /settings -> Personal Information"), reply_markup=ReplyKeyboardMarkup( [[KeyboardButton('/settings')]], resize_keyboard=True, one_time_keyboard=True)) self.message.user.expectedMessageType = '' elif self.message.text == '❌ Opt-out of the Meal Rating': self.message.user.wantsToRateMeals = False self.bot.sendMessage(self.message.user.chatID, "💔 Opted you out of the meal rating system") self.message.user.expectedMessageType = '' elif self.message.text == '✅ Opt-in to the Meal Rating': self.message.user.wantsToRateMeals = True self.bot.sendMessage(self.message.user.chatID, "❤️ Opted you in to the meal rating system") self.message.user.expectedMessageType = '' elif self.message.text == '⏪ Back': self.bot.sendMessage( self.message.user.chatID, 'What do you want to change?', reply_markup=ReplyKeyboardMarkup( [[KeyboardButton('️🧍 Personal Information')], [KeyboardButton('📲 Subscription-Settings')], [KeyboardButton('⏰ Push Time Settings')], [KeyboardButton('🧨 Cancel')]], resize_keyboard=True, one_time_keyboard=True)) self.message.user.expectedMessageType = 'settingstype' else: # Fetch the user's subscriptions to show them the current status options = [] if self.message.user.pauseAllNotifications: options.append( [KeyboardButton('🔔 Unpause all Push Notifications')]) else: options.append( [KeyboardButton('🔕 Pause all Push Notifications')]) if self.message.user.wantsMenu: options.append([KeyboardButton('❌ Unsubscribe the Menu Push')]) else: options.append([KeyboardButton('✅ Subscribe the Menu Push')]) if self.message.user.wantsLecturePlan: options.append( [KeyboardButton('❌ Unsubscribe the Lecture Plan Push')]) else: options.append( [KeyboardButton('✅ Subscribe the Lecture Plan Push')]) if self.message.user.wantsExamWarning: options.append( [KeyboardButton('❌ Unsubscribe the Exam Warning Push')]) else: options.append( [KeyboardButton('✅ Subscribe the Exam Warning Push')]) if self.message.user.wantsTransportInfo: options.append([ KeyboardButton('❌ Unsubscribe the Public Transport Info') ]) else: options.append( [KeyboardButton('✅ Subscribe the Public Transport Info')]) if self.message.user.wantsToRateMeals: options.append( [KeyboardButton('❌ Opt-out of the Meal Rating')]) else: options.append([KeyboardButton('✅ Opt-in to the Meal Rating')]) options.append([KeyboardButton('⏪ Back')]) self.bot.sendMessage(self.message.user.chatID, "Wrong input. Please try again:", reply_markup=ReplyKeyboardMarkup( options, resize_keyboard=True, one_time_keyboard=True))
], # [InlineKeyboardButton("на 3 дня", callback_data='Погода_3'), # InlineKeyboardButton("Погода на неделю", callback_data='Погода_7')], [ InlineKeyboardButton("Изменить местоположение", callback_data="Изменить местоположение") ], [ InlineKeyboardButton(KEYBOARD_TEXT_MAIN_MENU, callback_data=KEYBOARD_CALLBACK_MAIN_MENU) ] ]) CHANGE_LOCATION = ReplyKeyboardMarkup([[ KeyboardButton(text="Изменить локацию для погоды", resize_markup=True, request_location=True) ]], resize_keyboard=True, one_time_keyboard=True) KEYBOARD_FLOWER_CALLBACK_WATER_ALL = "полить всё" KEYBOARD_FLOWER_CALLBACK_SHOW_FLOWER_LIST_BALCONY = "Балкон-1_список" KEYBOARD_FLOWER_CALLBACK_WATER_BALCONY = "балкон-1_полив" """ KEYBOARD_FLOWER_ROOM_LIST = InlineKeyboardMarkup([ [ InlineKeyboardButton(KEYBOARD_ROOM_BALCONY1, callback_data=KEYBOARD_FLOWER_CALLBACK_SHOW_FLOWER_LIST_BALCONY), ], [ InlineKeyboardButton("Полить все", callback_data=KEYBOARD_FLOWER_CALLBACK_WATER_ALL)
def message_mealrating(self): """ Called when user sends the rating for his meal """ rating = self.message.text dishes = self.message.user.tempParams['ratingMealset'] rated_dish = self.message.user.tempParams['ratedMeal'] try: rating = int(rating[:1]) except: self.bot.sendMessage(self.message.user.chatID, "Wrong input. Try again.", reply_markup=ReplyKeyboardMarkup( [[ KeyboardButton('0 ⭐'), KeyboardButton('1 ⭐'), KeyboardButton('2 ⭐'), KeyboardButton('3 ⭐'), KeyboardButton('4 ⭐'), KeyboardButton('5 ⭐') ]], resize_keyboard=True, one_time_keyboard=True)) return if rating in (0, 1, 2, 3, 4, 5): rated_dish_id = dishes[rated_dish]['dish_id'] MenuUtilities.add_rating_to_dish(self.conn, rated_dish_id, self.message.user.userID, rating) self.bot.sendMessage(self.message.user.chatID, "Thank you for rating! 😁") self.message.user.tempParams['ratingMealset'] = '' self.message.user.tempParams['ratedMeal'] = '' self.message.user.expectedMessageType = '' else: self.bot.sendMessage(self.message.user.chatID, "Wrong input. Try again.", reply_markup=ReplyKeyboardMarkup( [[ KeyboardButton('0 ⭐'), KeyboardButton('1 ⭐'), KeyboardButton('2 ⭐'), KeyboardButton('3 ⭐'), KeyboardButton('4 ⭐'), KeyboardButton('5 ⭐') ]], resize_keyboard=True, one_time_keyboard=True))
def anketa_get_name(bot, update): update.user_data['name'] = bot.message.text # временно сохраняем ответ location_button = KeyboardButton('Отправить геопозицию', request_location=True) bot.message.reply_text("Отправьте локацию", reply_markup=ReplyKeyboardMarkup( [[location_button]], resize_keyboard=True)) return "user_location" # ключ для определения следующего шага
logger = logging.getLogger(__name__) db = setoran_beneran() # STATES START, START_PROCESS, LIHAT, TAMBAH, TAMBAH_NAMA_SANTRI, PERSETUJUAN_SAVE_SANTRI, CARI_NAMA_SANTRI, PROCESS_END, PROCESS_JENIS, PROCESS_LULUS, PROCESS_PERSETUJUAN_SETORAN, PROCESS_START, PROCESS_LIHAT, BELUM = range( 14) # CONSTANS ADMIN_IDS = admin_ids TG_TOKEN = tg_token CONTEXT = dict() # CUSTOM KEYBOARDS reply_start = [[KeyboardButton("👀 Lihat"), KeyboardButton("➕ Tambah")]] reply_tambah = [[KeyboardButton("Santri"), KeyboardButton("Setoran")]] reply_persetujuan = [[KeyboardButton("✔ Simpan"), KeyboardButton("✖ Jangan")]] reply_jenis = [[KeyboardButton("➕ Tambah Baru"), KeyboardButton("♻ Murojaah")]] reply_lulus = [[KeyboardButton("👍 Lulus"), KeyboardButton("👎 Ulang Lagi")]] reply_lihat = [[ KeyboardButton("📃 Daftar Santri"), KeyboardButton("📚 Daftar Surat") ], [KeyboardButton("👏 Free"), KeyboardButton("⛔ Belum")]] reply_belum = [[KeyboardButton("Setoran")], [KeyboardButton("♻ Murojaah"), KeyboardButton("➕ Tambah Baru")], [KeyboardButton("Murojaah sudah, harus ulang")], [KeyboardButton("Tambah sudah, harus ulang")]]
from telegram.ext import (Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters, ConversationHandler, CallbackContext) # Enable logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) # GENDER, PHOTO, LOCATION, BIO = range(4) JNAME, JDESC, JCMP, JTYPE = range(4) BOT_TOKEN = "1346826306:AAEBRd8TbKAl4t52gqZGginATw91dTWea38" kb = [[KeyboardButton('📝 Add new job'), KeyboardButton('🧳 Your Job offers')], [KeyboardButton('⚙️ Settings')]] kb_markup = ReplyKeyboardMarkup(kb, resize_keyboard=True) def start(update, context): update.message.reply_text( 'Hi! My name is Professor Bot. I will hold a conversation with you. ' 'Send /cancel to stop talking to me.\n\n') # handles job name def entryTxt(update, context): command = update.message.text
# -*- coding: utf-8 -*- __author__ = 'ipetrash' import os import time # pip install python-telegram-bot from telegram import Update, ReplyKeyboardMarkup, KeyboardButton from telegram.ext import Updater, MessageHandler, CommandHandler, Filters, CallbackContext from telegram.ext.dispatcher import run_async import config from common import get_logger, log_func, reply_error contact_keyboard = KeyboardButton('Send contact', request_contact=True) location_keyboard = KeyboardButton('Send location', request_location=True) custom_keyboard = [[contact_keyboard, location_keyboard]] REPLY_KEYBOARD_MARKUP = ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True) log = get_logger(__file__) @run_async @log_func(log) def on_start(update: Update, context: CallbackContext): update.message.reply_text('Введите что-нибудь', reply_markup=REPLY_KEYBOARD_MARKUP)
from telegram import KeyboardButton, ReplyKeyboardMarkup SMILE = ['😊', '😀', '😇', '🤠', '😎', '🤓'] CALLBACK_BUTTON_PICTURE = "Картинка 🏞" CALLBACK_BUTTON_PEN = "Заполнить анкету 🖌" CALLBACK_BUTTON_START = "Начать 🎰" CALLBACK_BUTTON_JOKE = "Анекдот 🎭" back_but = KeyboardButton('Назад🔙') def get_keyboard(): contact_but = KeyboardButton('Отправить контакт', request_contact=True) local_but = KeyboardButton('Узнать свою локацию', request_location=True) my_keyboard = ReplyKeyboardMarkup( [['Начать'], [local_but], ['Рестораны 🍷☕'], ['Отели 🏩🛎'], ['Клубы 🍹🍸'], ['ТРЦ 🛍🛒'], ['Религиозные места ☮']], resize_keyboard=True) return my_keyboard
from telegram import ReplyKeyboardMarkup, KeyboardButton KEYBOARDS = dict( REGISTER_1=ReplyKeyboardMarkup( [[KeyboardButton('mr'), KeyboardButton('mrs')]], one_time_keyboard=True), REGISTER_2=ReplyKeyboardMarkup( [[KeyboardButton('1'), KeyboardButton('2')]], one_time_keyboard=True), REGISTER_3=ReplyKeyboardMarkup([[ KeyboardButton('a little'), KeyboardButton('normal'), KeyboardButton('a lot') ]], one_time_keyboard=True)) MESSAGES_EN = dict( START_HELLO_MESSAGE="Hi, <description and some disclaimer>", REGISTER_1="What is your title?", REGISTER_2="What is your age?", REGISTER_3="How much would you like us to keep in touch?", REGISTER_3_EXIT="Thanks! We'll be in touch. Don't hesitate to message us.", SETTINGS_MENU= "*Settings*\nChange settings below, or go /back\n- /subscription Change how often we contact you\n- /title Change your title\n- /delete Delete your data", SETTINGS_DELETE= "*Danger zone*\nDo you want to delete your data?\nThis will delete all your data from our system, it cannot be undone.\n\nYou can go /back\n\nOr proceed by writing\n*/*yesimsuredelete" ) MESSAGES_SE = dict( START_HELLO_MESSAGE_SE="Hej. Jag kanner en bot", REGISTER_1="Vad ar din tittel?", REGISTER_2="Vad ar din alder?",
import messages import config.base as base_config import mongo_queries as mq logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) # Menus objects MAIN_MENU, SETTINGS_MENU, ALERTS_MENU, SET_INTERVAL, SET_THRESHOLD, ADD_RM_COINS, ADD_RM_EX, BLACK_HOLE = range( 8) # Keyboards objects kb_main = ReplyKeyboardMarkup( [[KeyboardButton('🤖Settings'), KeyboardButton('🔬FAQ')], [KeyboardButton('👾About'), KeyboardButton('📱Contacts')]], resize_keyboard=True) kb_settings = ReplyKeyboardMarkup( [[KeyboardButton('⏱Set interval'), KeyboardButton('🎚Set threshold')], [ KeyboardButton('🎛Alerts settings'), KeyboardButton('🔊Turn off/on notification') ], [KeyboardButton('⬅Back')]], resize_keyboard=True) kb_alerts = ReplyKeyboardMarkup([[
import json from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, RegexHandler from telegram import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove from functools import wraps from hvr import * hvr = None user_config = {} # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) custom_keyboard = [[KeyboardButton('/charge'), KeyboardButton('/balance')]] yes_no_keyboard = [[KeyboardButton('/no'), KeyboardButton('/yes')]] reply_markup = ReplyKeyboardMarkup(custom_keyboard) yes_no_markup = ReplyKeyboardMarkup(yes_no_keyboard) remove_markup = ReplyKeyboardRemove() waiting_for_amount = False wating_for_confirmation = False charge_amount = 0 def restricted(func): @wraps(func) def wrapped(update, context, *args, **kwargs): chat_id = update.message.chat.id if str(chat_id) != user_config['telegram_chat_id']: print("Unauthorized access denied for chat {}.".format(user_id))
from telegram import KeyboardButton, ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup # Predefine Main menu keyboard mainMenu = [[KeyboardButton("New Expense")], [KeyboardButton("Expenses Report"), KeyboardButton("Budget")], [ KeyboardButton("Search Expenses"), KeyboardButton("List Expenses") ]] newExpense = [[KeyboardButton("Timestamp"), KeyboardButton("Description")], [KeyboardButton("Proof"), KeyboardButton("Category")], [KeyboardButton("Amount"), KeyboardButton("Submit")], [KeyboardButton("Main Menu")]] newExpenseNoTs = [[ KeyboardButton("Description"), KeyboardButton("Proof"), KeyboardButton("Category") ], [ KeyboardButton("Amount"), KeyboardButton("Submit"), KeyboardButton("Main Menu") ]] newExpenseNoDescr = [[ KeyboardButton("Timestamp"),
from telegram import ReplyKeyboardMarkup, KeyboardButton main_keyboard = ReplyKeyboardMarkup([[KeyboardButton("Create new line ➕")], [KeyboardButton("My lines 📋")]], resize_keyboard=True, one_time_keyboard=True)
def menu(type="main"): reboot = KeyboardButton("reboot") disarm = KeyboardButton("disarm") arm = KeyboardButton("arm") prev = KeyboardButton("<") next = KeyboardButton(">") back = KeyboardButton("..") empty = KeyboardButton(" ") commandsSub = KeyboardButton("commands") getImage = KeyboardButton("images") getDistance = KeyboardButton("distance") selfCheck = KeyboardButton("selfcheck") preflightSub = KeyboardButton("preflight") systemSub = KeyboardButton("system") calibrateSub = KeyboardButton("calibrate") testflySub = KeyboardButton("navigate") profilesSub = KeyboardButton("profiles") getTelemetry = KeyboardButton("get telemetry") getTopicHZ = KeyboardButton("get topic hz") takeoff = KeyboardButton("com takeoff") land = KeyboardButton("com land") status = KeyboardButton("com status") ekf2 = KeyboardButton("ekf2 status") sensors = KeyboardButton("sensors status") check = KeyboardButton("com check") px4io = KeyboardButton("px4io status") mavlink = KeyboardButton("mavlink status") fmu = KeyboardButton("fmu status") level = KeyboardButton("calibrate level") gyro = KeyboardButton("calibrate gyro") accel = KeyboardButton("calibrate accel") mag = KeyboardButton("calibrate mag") loadProfile0 = KeyboardButton("upload profile 0") loadProfile1 = KeyboardButton("upload profile 1") loadProfile2 = KeyboardButton("upload profile 2") saveProfile0 = KeyboardButton("save profile 0") saveProfile1 = KeyboardButton("save profile 1") saveProfile2 = KeyboardButton("save profile 2") diffProfile0 = KeyboardButton("diff profile 0") diffProfile1 = KeyboardButton("diff profile 1") diffProfile2 = KeyboardButton("diff profile 2") if type == 'main': keyboard = [[empty, reboot, disarm, arm, empty], [commandsSub, systemSub, calibrateSub], [getDistance, getImage, profilesSub], [preflightSub, selfCheck, testflySub]] return ReplyKeyboardMarkup(keyboard) if type == 'commands': #keyboard = [[ back, reboot, disarm, arm, back ], [takeoff, land, status], [ekf2, sensors, check], [px4io, mavlink, fmu] ] keyboard = [[back, reboot, disarm, arm, back], [takeoff, land, empty], [empty, empty, empty], [empty, empty, empty]] return ReplyKeyboardMarkup(keyboard) if type == 'calibrate': keyboard = [[back, reboot, disarm, arm, back], [level, gyro], [accel, mag], [empty, empty, empty]] return ReplyKeyboardMarkup(keyboard) if type == 'profiles': keyboard = [[back, reboot, disarm, arm, back], [loadProfile0, loadProfile1, loadProfile2], [diffProfile0, diffProfile1, diffProfile2], [saveProfile0, saveProfile1, saveProfile2]] return ReplyKeyboardMarkup(keyboard) if type == 'preflight': keyboard = [[back, reboot, disarm, arm, back], [getTelemetry, getTopicHZ, status], [ekf2, sensors, check], [px4io, mavlink, fmu]] return ReplyKeyboardMarkup(keyboard) if type == 'distance': topics = getTopicsMenu() keyboard = [[back, reboot, disarm, arm, back]] keyboard.extend(topics) return ReplyKeyboardMarkup(keyboard) if type == 'system': topics = getFilesMenu(3, "system") keyboard = [[back, reboot, disarm, arm, back]] keyboard.extend(topics) return ReplyKeyboardMarkup(keyboard) if type == 'navigate': topics = getFilesMenu(3, "navigate") keyboard = [[back, reboot, disarm, arm, back]] keyboard.extend(topics) return ReplyKeyboardMarkup(keyboard)
def start(update: Update, context: CallbackContext): message: Message = update.message button = KeyboardButton(patterns.START_CONV_TEXT, callback_data=patterns.START_CONV_TEXT) message.reply_text('Press GO to start.', reply_markup=ReplyKeyboardMarkup([[button]]))
def start(update, context): global Current kb = [[ KeyboardButton('c'), KeyboardButton('()'), KeyboardButton('÷'), KeyboardButton('del') ], [ KeyboardButton('7'), KeyboardButton('8'), KeyboardButton('9'), KeyboardButton('×') ], [ KeyboardButton('4'), KeyboardButton('5'), KeyboardButton('6'), KeyboardButton('-') ], [ KeyboardButton('1'), KeyboardButton('2'), KeyboardButton('3'), KeyboardButton('+') ], [ KeyboardButton(' '), KeyboardButton('0'), KeyboardButton('.'), KeyboardButton('=') ]] kb_markup = ReplyKeyboardMarkup(kb, True) Current = "0" context.bot.send_message(chat_id=update.message.chat_id, text="Let's do this!", reply_markup=kb_markup)
def my_keyboard(text=texts['b_next']) -> ReplyKeyboardMarkup: keyboard = ReplyKeyboardMarkup([[KeyboardButton(text)]], resize_keyboard=True) return keyboard
def getLocation(chat_id): location_keyboard = KeyboardButton(text="Send location", request_location=True) custom_keyboard = [[location_keyboard]] reply_markup = ReplyKeyboardMarkup(custom_keyboard)
from telegram import ReplyKeyboardMarkup, KeyboardButton from telegram import InlineKeyboardMarkup, InlineKeyboardButton import logging import userManagement as users import orderManagement as orders logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO, ) main_keyboard = ReplyKeyboardMarkup([ [ KeyboardButton(text='Gallery'), KeyboardButton(text='About'), ], ], resize_keyboard=True) def is_admin(user_id): if user_id == getEnvVar('ADMIN_ID'): return True else: return False # Reading token from external file def getEnvVar(varName):
from telegram.ext import Updater, CommandHandler,\ CallbackQueryHandler, Filters, MessageHandler import logging import redis # initialize parameters logging.basicConfig(format='%(asctime)s -' ' %(name)s -' ' %(levelname)s -' ' %(message)s ', level=logging.INFO) server_r = redis.Redis() isadmin = 0 keyboard_main2 = ReplyKeyboardMarkup([[ KeyboardButton(text=u'\U00002795' + 'افزودن محصول'), KeyboardButton(text=u'\U0000274E' + 'حذف محصول'), KeyboardButton(text=u'\U0001F4DD' + 'تغییر محصول'), KeyboardButton(text=u'\U000025C0' + 'برگشت'), ]], resize_keyboard=True) # data product_women = [{ "id": "1", "name": "lamour", "cost": "از دویست هزار تومان تا چهار صد و پنجاه هزار تومان", "description":
def start_msg() -> (list, str): root_nodes = NeedHelp.objects.root_nodes() btn_text = [i.user_input for i in root_nodes if not i.is_default] btn_to_send = [[KeyboardButton(text=i)] for i in btn_text] text_out = StartMessage.objects.get(hello_text=True).text return btn_to_send, text_out
def first_markup(): first_conv = KeyboardButton('Конвертировать🔄') first_course = KeyboardButton('Курс📈') first_close = KeyboardButton('Закрыть') base_markup = ReplyKeyboardMarkup([[first_conv, first_course], [first_close]], resize_keyboard=True) return base_markup