def __init__(self, app, bot): self.app = app self.bot = bot super().__init__(entry_points=[ CommandHandler("newop", self.command_newop), ], states={ self.WAIT_FOR_DATE: [ MessageHandler(Filters.text, self.handle_newop_date, pass_user_data=True) ], self.WAIT_FOR_CITY: [ MessageHandler(Filters.text, self.handle_newop_city, pass_user_data=True) ], self.CONFIRM_CITY: [ CallbackQueryHandler( self.handle_newop_city_confirmation, pattern="city_", pass_user_data=True) ], self.WHAT_TO_DO: [ MessageHandler(Filters.text, self.handle_next_action, pass_user_data=True) ], }, fallbacks=[ CommandHandler("cancel", self.command_cancel, pass_user_data=True) ])
def main(): updater = Updater(TOKEN, use_context=True) #get the dispatcher to register handler dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(MessageHandler(Filters.regex('^💼 Wallets$'),save_wallet)) dispatcher.add_handler(MessageHandler(Filters.regex('^🎁 Bonus$'),bonus)) my_conversation_handler = ConversationHandler(entry_points=[CallbackQueryHandler(button_wall, pattern='^' + str(TITLE) + '$')],states={TITLE: [MessageHandler(Filters.text & ~Filters.command, get_title)]},fallbacks=[CommandHandler("caaancel",cancel)]) #------Second Conversation my_conversation_handlor = ConversationHandler(entry_points=[MessageHandler(Filters.regex('^☎️ Help$'),supp)],states={TYPING: [MessageHandler(Filters.text,typ)]},fallbacks=[CommandHandler("caaancel",cancel)]) dispatcher.add_handler(my_conversation_handler) dispatcher.add_handler(my_conversation_handlor) dispatcher.add_handler(MessageHandler(Filters.text,joined)) updater.start_webhook(listen="0.0.0.0", port=int(PORT), url_path=TOKEN) updater.bot.setWebhook('https://working-bot-python.herokuapp.com/' + TOKEN) print('Running... [Press Ctrl+C to stop]') updater.idle() update.stop()
def bind(self, dp): dp.add_handler( MessageHandler(Filters.update.edited_message, self.ignoreEdit)) ####################### dp.add_handler(CommandHandler("help", self.help)) ####################### dp.add_handler( MessageHandler((Filters.text | Filters.command) & (~Filters.update.edited_message), self.process)) return True
def add_handlers(): _handlers = {} _handlers['start_handler'] = CommandHandler('start', start_handler) _handlers['help_handler'] = CommandHandler('help', help_handler) _handlers['next_handler'] = CommandHandler('next', next_handler) _handlers['whatLast'] = CommandHandler('last', last_handler) _handlers['unknown'] = MessageHandler(Filters.command, unknown) _handlers['question_handler'] = MessageHandler( Filters.text, question_handler) for name, _handler in _handlers.items(): print(f'Adding handler {name}') dispatcher.add_handler(_handler)
def main(): logging.info('covid19india_bot started') _initStateCodes('statecodes.json') updater = Updater(token=_readToken(_tokenFile), use_context=True) updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_handler(CommandHandler('help', help)) updater.dispatcher.add_handler(CommandHandler('covid19india', covid19india)) updater.dispatcher.add_handler(CommandHandler('statecodes', statecodes)) updater.dispatcher.add_handler(CommandHandler('mohfw', mohfw)) updater.dispatcher.add_handler(CommandHandler('comparemohfw', comparemohfw)) updater.dispatcher.add_handler(CommandHandler('ndma', ndma)) updater.dispatcher.add_handler(CommandHandler('comparendma', comparendma)) updater.dispatcher.add_handler(CommandHandler('recon', recon)) updater.dispatcher.add_handler(CommandHandler('advanced', advanced)) updater.dispatcher.add_handler(CommandHandler('request', request)) updater.dispatcher.add_handler(MessageHandler(Filters.regex('#request') | \ Filters.regex('#resources'), \ request)) updater.start_polling() updater.idle()
def __init__(self, config, bot=None, resources=None): self.config = config self.resources = resources if resources else Resources(config) # O parâmetro bot só possui valor nos casos de teste, nesse caso, # encerra o __init__ aqui para não haver conexão ao Telegram. if bot: self.bot = bot return # Conecta ao telegram com o token passado na configuração self.updater = Updater(token=config['telegram_token']) self.bot = self.updater.bot # Anexa uma função da API antiga para manter retrocompatibilidade self.bot.reply_to = lambda message, text, **kwargs: \ self.bot.send_message(chat_id=message.chat_id, text=text, reply_to_message_id=message.message_id, **kwargs) # Configura os comandos aceitos pelo bot dispatcher = self.updater.dispatcher for k, function in commands.functions.items(): name = k[1:] if k[0] == '/' else k dispatcher.add_handler( CommandHandler(name, adapt_callback(function, self))) # Configura as easter eggs easter_eggs = ( (find_ruby, self.love_ruby), (find_java, self.memory_java), (find_python, self.easter_python), ) for search, action in easter_eggs: dispatcher.add_handler( MessageHandler(FilterSearch(search), adapt_callback(action)))
def _start_bot(self): self._updater = Updater(token=self._token) self._bot = self._updater.bot self._updater.dispatcher.add_handler( CommandHandler('start', self._on_command_start)) self._updater.dispatcher.add_handler( MessageHandler([Filters.text], self._on_message)) self._updater.start_polling()
def start_bot_thread(): print("Start bot Thread started...") updater = Updater(main_bot_token) dispatcher = updater.dispatcher # logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) photo = MessageHandler(Filters.photo, photo_handler) video = MessageHandler(Filters.video, video_handler) audio = MessageHandler(Filters.audio, audio_handler) voice = MessageHandler(Filters.voice, voice_handler) document = MessageHandler(Filters.document, document_handler) view_q = CommandHandler('viewqueue', view_queue_handler) view_c = CommandHandler('viewchannel', view_target_channel) change_c = CommandHandler('changechannel', change_target_channel) empty_q = CommandHandler('emptyqueue', empty_queue_handler) delete_p = CommandHandler('deletepost', delete_post_handler, pass_args=True) send_p = CommandHandler('sendpost', manual_send_handler, pass_args=True) get_q = CommandHandler('getqueue', get_queue_handler) get_t = CommandHandler('gettasks', get_tasks_handler) get_t_z_d = CommandHandler('gettimediff', get_time_zone_diff_handler) set_t_z_d = CommandHandler('settimediff', set_time_zone_diff_handler, pass_args=True) dispatcher.add_handler(photo) dispatcher.add_handler(video) dispatcher.add_handler(audio) dispatcher.add_handler(voice) dispatcher.add_handler(document) dispatcher.add_handler(view_q) dispatcher.add_handler(view_c) dispatcher.add_handler(change_c) dispatcher.add_handler(empty_q) dispatcher.add_handler(delete_p) dispatcher.add_handler(send_p) dispatcher.add_handler(get_q) dispatcher.add_handler(get_t) dispatcher.add_handler(get_t_z_d) dispatcher.add_handler(set_t_z_d) updater.start_polling() print("Ending initialization of the bot...")
def run(): updater = Updater(BOT_TOKEN, request_kwargs={"proxy_url": PROXY}) dp = updater.dispatcher dp.add_handler(InlineQueryHandler(inlinequery)) dp.add_handler(CommandHandler("start", start)) dp.add_handler(MessageHandler(Filters.command, echo)) updater.start_polling() updater.idle()
def __init__(self, logger: Logger, db_service: DatabaseService, updater_service: UpdaterService) -> None: self.logger = logger self.database = db_service self.updater = updater_service.updater # Handlers message = MessageHandler(Filters.text, self.regex_message) # Dispatcher dispatcher = self.updater.dispatcher dispatcher.add_handler(message)
def main() -> None: updater = Updater(token=config.TOKEN, use_context=True) dispatcher = updater.dispatcher down_handler = ConversationHandler( entry_points=[CommandHandler('download', download)], states = { TYPE: [MessageHandler(Filters.regex('^('+'|'.join([i for i in config.ALLOWED_TYPES])+')$'), type)], MAGNET: [MessageHandler(Filters.regex('^magnet*'), magnet)], CONFIRM: [MessageHandler(Filters.regex('^OK$'), confirm)], }, fallbacks=[CommandHandler('cancel', cancel),], ) dispatcher.add_handler(down_handler) dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('status', status)) dispatcher.add_handler(CommandHandler('clear', clear)) dispatcher.add_handler(CommandHandler('help', help)) dispatcher.add_handler(MessageHandler(Filters.command, unknown)) updater.start_polling() updater.idle()
def init(): global tg_updater global tg_dispatcher timer_thread = threading.Thread(target=main_loop) timer_thread.start() cmd_thread = threading.Thread(target=cmd_loop) cmd_thread.start() start_handler = CommandHandler('start', start) tg_dispatcher.add_handler(start_handler) help_handler = CommandHandler('help', printHelp) tg_dispatcher.add_handler(help_handler) stop_handler = CommandHandler('stop', stopNotice) tg_dispatcher.add_handler(stop_handler) resume_handler = CommandHandler('resume', resumeNotice) tg_dispatcher.add_handler(resume_handler) inm_handler = CommandHandler('114514', RedTeaOnly) tg_dispatcher.add_handler(inm_handler) set_timezone_handler = ConversationHandler( entry_points=[CommandHandler('settimezone', set_timezone)], states={ SETTING_TZ: [MessageHandler(Filters.regex('^[+-][0-9]{1,2}:00.*'), set_timezone_done), MessageHandler(~Filters.command, set_timezone_wrong_format)], SETTING_TZ_RETRY: [MessageHandler(~Filters.command, set_timezone)] }, fallbacks=[CommandHandler('cancel', cancel_set_timezone)] ) tg_dispatcher.add_handler(set_timezone_handler) tg_updater.start_polling() #tg_updater.idle() pass
def __init__(self, logger: Logger, db_service: DatabaseService, updater_service: UpdaterService) -> None: self.logger = logger self.database = db_service self.updater = updater_service.updater # Handlers # List current alerts list_command = CommandHandler('list', self.list_alerts) # Conversation states entry_add_conversation = CommandHandler('create', self.asking_add_alert) entry_delete_conversation = CommandHandler('delete', self.asking_delete_alert) setting_add_conversation = MessageHandler(Filters.text, self.create_alert) setting_delete_conversation = MessageHandler(Filters.text, self.delete_alert) # Conversation handlers create_command = ConversationHandler( entry_points=[entry_add_conversation], states={self.SETTING_VALUE: [setting_add_conversation]}, fallbacks=[], conversation_timeout=60) delete_command = ConversationHandler( entry_points=[entry_delete_conversation], states={self.SETTING_VALUE: [setting_delete_conversation]}, fallbacks=[], conversation_timeout=60) # Dispatcher dispatcher = self.updater.dispatcher dispatcher.add_handler(list_command) dispatcher.add_handler(create_command) dispatcher.add_handler(delete_command)
def __init__(self, app): self.app = app super().__init__(entry_points=[ RegexHandler("/order_(\d+)", self.command_order, pass_groups=True, pass_user_data=True), ], states={ self.WAIT_FOR_ORDER_TEXT: [ MessageHandler(Filters.text, self.handle_neworder_text, pass_user_data=True) ] }, fallbacks=[])
def __init__(self, app): self.app = app super().__init__(entry_points=[ CommandHandler("start", self.command_start, pass_user_data=True), CommandHandler("help", self.command_start, pass_user_data=True), CommandHandler("changehometown", self.command_changehometown) ], states={ self.WAIT_FOR_HOMETOWN: [ MessageHandler(Filters.text | Filters.location, self.handle_hometown, pass_user_data=True), ], }, fallbacks=[])
def main() -> None: updater = Updater(TOKEN, use_context=True) # Get the dispatcher to register handlers dispatcher = updater.dispatcher # Add conversation handler to ask for user's stock portfolio/watchlist conv_handler = ConversationHandler( entry_points=[ MessageHandler( Filters.regex( '^(Add to stock portfolio|Add to watchlist|Remove from watchlist|Remove from stock portfolio)$' ), update_user) ], states={ UPDATED: [ MessageHandler( Filters.text & ~(Filters.command | Filters.regex('^Done$')), received_information, ) ] }, fallbacks=[MessageHandler(Filters.regex('^Done$'), done)], name="updates", allow_reentry=True, ) dispatcher.add_handler(conv_handler) dispatcher.add_handler( MessageHandler( Filters.regex('^(Portfolio updates|Watchlist updates)$'), provide_updates)) dispatcher.add_handler( MessageHandler( Filters.regex('^Subscribe/Unsubscribe to daily updates$'), toggle_subscription)) dispatcher.add_handler(MessageHandler(Filters.regex('^Done'), done)) dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("get_px_change", get_px_change)) dispatcher.add_handler(CommandHandler("default", get_default_port)) # Start the Bot # `start_polling` for local dev; webhook for production # updater.start_polling() updater.start_webhook(listen="0.0.0.0", port=int(PORT), url_path=TOKEN) updater.bot.setWebhook("https://telegram-stockm.herokuapp.com/" + TOKEN) # Block until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle()
def __init__(self): self.config = {"api_token": os.getenv("API_TOKEN")} self.db = load_db() updater = Updater(self.config["api_token"]) dp = updater.dispatcher # type: Dispatcher dp.add_handler(WelcomeConversationHandler(self)) dp.add_handler(NewOpConversationHandler(self, updater.bot)) dp.add_handler(OrderConversationHandler(self)) dp.add_handler(CommandHandler("myorders", self.command_myorders)) dp.add_handler(ListOpportunitiesConversationHandler(self)) # Todo: /notify (marudor-only) (Benachrichtigt alle Nutzer in einer Stadt) dp.add_handler(MessageHandler(Filters.text, self.handle_fetch_op)) dp.add_error_handler(self.handle_error) updater.start_polling() updater.idle()
dl = Downloader(music_src) context.bot.send_audio(chat_id=update.effective_chat.id, audio=open(dl.song, 'rb'), performer=dl.author, title=dl.title, caption="@invisiblemusicbot") except Exception as e: context.bot.send_message( chat_id=update.effective_chat.id, text= str(e), parse_mode=ParseMode.HTML, ) dispatcher.add_handler(CommandHandler("music", music)) dispatcher.add_handler(MessageHandler(Filters.private,send_msg)) updater.start_polling() #
from telegram.ext.commandhandler import CommandHandler from telegram.ext.messagehandler import MessageHandler from telegram.ext.filters import Filters from bot_admin import commands command_handlers = { '/start': CommandHandler('start', commands.start_command), '/help': CommandHandler('help', commands.help_command), '/chuck': CommandHandler('chuck', commands.chuck_command) } message_handlers = {'caps': MessageHandler(Filters.text, commands.caps)}
# set commands dispatcher.add_handler(CommandHandler('start', cmd_start)) dispatcher.add_handler(CommandHandler('help', cmd_help)) dispatcher.add_handler(CommandHandler('ping', cmd_ping)) dispatcher.add_handler(CommandHandler('sub', cmd_sub, pass_args=True)) dispatcher.add_handler( CommandHandler('subChan', cmd_subChan, pass_args=True)) dispatcher.add_handler(CommandHandler('unsub', cmd_unsub, pass_args=True)) dispatcher.add_handler(CommandHandler('unChan', cmd_unChan, pass_args=True)) dispatcher.add_handler(CommandHandler('list', cmd_list)) dispatcher.add_handler(CommandHandler('export', cmd_export)) dispatcher.add_handler(CommandHandler('all', cmd_all)) dispatcher.add_handler(CommandHandler('wipe', cmd_wipe)) dispatcher.add_handler(CommandHandler('source', cmd_source)) dispatcher.add_handler(CommandHandler('auth', cmd_get_auth_url)) dispatcher.add_handler(CommandHandler('verify', cmd_verify, pass_args=True)) dispatcher.add_handler(CommandHandler('export_friends', cmd_export_friends)) dispatcher.add_handler( CommandHandler('set_timezone', cmd_set_timezone, pass_args=True)) dispatcher.add_handler(MessageHandler([Filters.text], handle_chat)) # put job queue = updater.job_queue queue.put(FetchAndSendTweetsJob(), next_t=0) # poll updater.start_polling()
""" method to handle /remove command to remove the keyboard and return back to text reply """ # making a reply markup to remove keyboard # documentation: https://python-telegram-bot.readthedocs.io/en/stable/telegram.replykeyboardremove.html reply_markup = ReplyKeyboardRemove() # sending the reply so as to remove the keyboard update.message.reply_text(text="I'm back.", reply_markup=reply_markup) pass def echo(update: Update, context: CallbackContext): """ message to handle any "Option [0-9]" Regrex. """ # sending the reply message with the selected option update.message.reply_text("You just clicked on '%s'" % update.message.text) pass updater.dispatcher.add_handler(CommandHandler("start", start)) updater.dispatcher.add_handler(CommandHandler("remove", remove)) # adding the message handler with filter to handle the Option [0-9] regex input # documentation for MessageHandler: https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.messagehandler.html # documentation for Filter: https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.filters.html#telegram.ext.filters.Filters updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"Option [0-9]"), echo)) updater.start_polling()
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.WARNING) logging.getLogger(AmazonBot.__name__).setLevel(logging.DEBUG) #logging.getLogger(FetchAndSendTweetsJob.__name__).setLevel(logging.DEBUG) # initialize telegram API token = '285896652:AAEjzg55_oFFRyEN-sQi1V7aLqHdGWqKSZE' updater = Updater(token=token) dispatcher = updater.dispatcher # set commands dispatcher.add_handler(CommandHandler('start', cmd_start)) dispatcher.add_handler(CommandHandler('help', cmd_help)) dispatcher.add_handler(CommandHandler('ping', cmd_ping)) dispatcher.add_handler(MessageHandler(Filters.text, echo)) dispatcher.add_handler(CommandHandler('caps', caps, pass_args=True)) dispatcher.add_handler(CommandHandler('add', addTracking, pass_args=True)) dispatcher.add_handler(CommandHandler('list', listTracking)) dispatcher.add_handler(CommandHandler('remove', removeTracking)) dispatcher.add_handler( CallbackQueryHandler(callbackHandler, pass_chat_data=True)) dispatcher.add_handler(MessageHandler(Filters.command, unknown)) # put job #updater.job_queue #myqueue._queue(CrawlerJob(), next_t=0) # poll updater.start_polling() updater.idle()
state_processor.bounty_processor(user, bot, update) def receive_contact(bot, update): user = users_repo.find_one({'telegram_id': update.message.chat_id}) if not user: raise RuntimeError('user should be created') if user.get('state') == 'not_approved': all_states_handler(user, bot, update) def handle_message(bot, update): user = users_repo.find_one({'telegram_id': update.message.chat_id}) if not user: raise RuntimeError('user should be created') all_states_handler(user, bot, update) contact_handler = MessageHandler(Filters.contact, receive_contact) text_msg_handler = MessageHandler(Filters.text, handle_message, pass_job_queue=True) start_handler = CommandHandler('start', start, pass_job_queue=True) dispatcher.add_handler(start_handler) dispatcher.add_handler(contact_handler) dispatcher.add_handler(text_msg_handler) if __name__ == '__main__': updater.start_polling()
""" message to handle any "Option [0-9]" Regrex. """ update.message.reply_text("For Future Implementations...") # sending the reply message with the selected option #update.message.reply_text("You just clicked on '%s'" % update.message.text) pass updater.dispatcher.add_handler(CommandHandler("start", start)) updater.dispatcher.add_handler(CommandHandler("remove", remove)) updater.dispatcher.add_handler(CommandHandler("help", help)) updater.dispatcher.add_handler(CommandHandler("getstatus", getstatus)) updater.dispatcher.add_handler(CommandHandler("execquery", execquery)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"TD Specific"), TDSpecific)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"TD Adhoc"), TDAdhoc)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"TD Extract"), TDExtract)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"<<<<>>>>"), TDExtras)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"J01_STEP"), TDSpecificSheet)) updater.dispatcher.add_handler( MessageHandler(Filters.regex(r"J01_UPDXL"), TDSpecificUpdExcel)) print( 'TD RegressionBot Started..... Please Check with Murali Before Closing This....' )
def cancel(bot, update): user = update.message.from_user log.info("User %s canceled the conversation." % user.first_name) bot.sendMessage(update.message.chat_id, text='Operation canceled') return ConversationHandler.END show_movies_cnv_handler = RegexHandler('\w', show_movies) add_movie_cnv_handler = ConversationHandler( entry_points=[RegexHandler('\w', add_movies)], states={ MOVIE_NAME: [MessageHandler([Filters.text], movie_name)], MOVIE_YEAR: [ RegexHandler(r'[\d]{4}', movie_year), CommandHandler('skip', skip_movie_year) ] }, fallbacks=[CommandHandler('cancel', cancel)]) movie_list_handler = ConversationHandler( entry_points=[CommandHandler('movie_list', main_menu)], states={ ACTION_SELECTOR: [MessageHandler([Filters.text], action_selection)], LIST_MOVIES: [show_movies_cnv_handler], ADD_MOVIES: [add_movie_cnv_handler] }, fallbacks=[CommandHandler('cancel', cancel)])
from telegram.ext.callbackcontext import CallbackContext from telegram.ext.filters import Filters from telegram.ext.messagehandler import MessageHandler from telegram.update import Update from app.storage.telegram.bot import updater # Run this file with bot in channel as admin to get channel_id use in CID enviroment variable def cid(update: Update, context: CallbackContext): id = update.channel_post.chat.id text = update.channel_post.text if text == 'cid': update.channel_post.reply_text(id) if __name__ == '__main__': print('Add your bot with privacy mode disabled as admin in your channel') print( 'Text in your channel cid to get channel id and setup CID enviroment variable' ) dp = updater.dispatcher dp.add_handler(MessageHandler(Filters.text, cid)) updater.start_polling() updater.idle()
return crud(update, context) def add_place(update: Updater, context: CallbackContext): place = static.search_place(update, context) if (place): try: user_transactions.track_place(update.message.from_user.id, place.id) update.message.reply_text(f'Guardado lugar con id {place.id}', reply_markup=ReplyKeyboardRemove()) except: update.message.reply_text(f'Error guardando lugar {place.id}', reply_markup=ReplyKeyboardRemove()) return crud(update, context) def fallback(update: Updater, context: CallbackContext): update.message.reply_text('Lo siento, no entendà eso :(') conv_handler = ConversationHandler( entry_points=[CommandHandler('places', crud)], states={ State.CHOOSING: [MessageHandler(Filters.text, choose_option)], State.ADD_PLACE: [MessageHandler(Filters.text, add_place)], State.REMOVE_PLACE: [MessageHandler(Filters.text, remove_place)] }, fallbacks=[MessageHandler(Filters.all, fallback)])
from telegram.forcereply import ForceReply from telegram.ext.filters import Filters from telegram.ext.updater import Updater from telegram.ext.messagehandler import MessageHandler from telegram.ext.callbackcontext import CallbackContext from telegram.update import Update updater = Updater("API KEY", use_context=True) def echo(update: Update, context: CallbackContext): # sending the force reply to the user # documentation: https://python-telegram-bot.readthedocs.io/en/stable/telegram.forcereply.html update.message.reply_text(reply_markup=ForceReply(selective=True), text="Reply to this message") pass updater.dispatcher.add_handler(MessageHandler(Filters.text, echo)) updater.start_polling()
logger.info("User %s canceled the conversation.", user.first_name) update.message.reply_text( '¿Te vas pronto? Puedes volver a iniciar esta conversación con /start. Si tuviste algun problema con el bot, no dudes en contactar a @Dyotson ' '(Max Militzer) para arreglarlo', reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END def send_to_json(context): thread = Thread(target=write_json, args=(context.user_data, )) thread.start() conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ GENDER: [MessageHandler(Filters.regex('^(El|Ella|Elle)$'), gender)], PHOTO: [ MessageHandler(Filters.photo, photo), CommandHandler('skip', skip_photo) ], LOCATION: [ MessageHandler(Filters.text, location), CommandHandler('skip', skip_location), ], BIO: [MessageHandler(Filters.text & ~Filters.command, bio)], }, fallbacks=[CommandHandler('cancel', cancel)], )
text = COVER + str(style) if arg == 'ready' and name == 'ready': next_state = ConversationHandler.END text = '<b>Настройки сохранены.</b>\n\n' + str(style) msg.delete() msg.reply_text(text, reply_markup=start.reply_markup, parse_mode=ParseMode.HTML) elif msg.text != text: msg.edit_text(text, reply_markup=InlineKeyboardMarkup(keyboard)) return next_state def on_fallback(bot, update: Update): msg: Message = update.message msg.reply_text('Вы всё ещё в диалоге настройки стиля. ' 'Если вам надоело, щёлкните кнопку "Готово"', reply_markup=InlineKeyboardMarkup(ready_keyboard)) return State.choice conv_handler = ConversationHandler( entry_points=[CommandHandler('style', on_style, Filters.private, pass_user_data=True)], states={ State.choice: [CallbackQueryHandler(on_choose, pass_user_data=True)], }, fallbacks=[MessageHandler(Filters.all, on_fallback)] )