async def test_with_context_types(self, ud, cd, bd, singlefile): cc = ContextTypes(user_data=ud, chat_data=cd, bot_data=bd) persistence = PicklePersistence("pickletest", single_file=singlefile, context_types=cc) assert isinstance(await persistence.get_bot_data(), bd) assert await persistence.get_bot_data() == 0 persistence.user_data = None persistence.chat_data = None await persistence.drop_user_data(123) await persistence.drop_chat_data(123) assert isinstance(await persistence.get_user_data(), dict) assert isinstance(await persistence.get_chat_data(), dict) persistence.user_data = None persistence.chat_data = None await persistence.update_user_data(1, ud(1)) await persistence.update_chat_data(1, cd(1)) await persistence.update_bot_data(bd(1)) assert (await persistence.get_user_data())[1] == 1 assert (await persistence.get_chat_data())[1] == 1 assert await persistence.get_bot_data() == 1 await persistence.flush() persistence = PicklePersistence("pickletest", single_file=singlefile, context_types=cc) assert isinstance((await persistence.get_user_data())[1], ud) assert (await persistence.get_user_data())[1] == 1 assert isinstance((await persistence.get_chat_data())[1], cd) assert (await persistence.get_chat_data())[1] == 1 assert isinstance(await persistence.get_bot_data(), bd) assert await persistence.get_bot_data() == 1
def main(): global updater # Read all prod/test environment-specific runtime variables into a global map set_env_vars_map() # Create persistence manager object persistence_manager = PicklePersistence(filename=get_persistence_filename_prefix(), store_user_data=False, store_chat_data=True, store_bot_data=True, single_file=False, on_flush=False) # Create the Updater and pass it your bot's token. updater = Updater(get_token(), persistence=persistence_manager, use_context=True) # Add status update handler for chat migrations updater.dispatcher.add_handler(CHAT_MIGRATION_HANDLER) # Add root handler for routing task commands updater.dispatcher.add_handler(ROUTER_HANDLER) # Start the Bot updater.start_polling() # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle() run_cleanup_jobs(persistence_manager)
def main(): my_persistence = PicklePersistence(filename='my_pickle', single_file=False, store_chat_data=False) updater = Updater(TOKEN, persistence=my_persistence) updater.dispatcher.add_handler(new_cargo_conversation_handler) updater.dispatcher.add_handler(registration_conversation_handler) updater.dispatcher.add_handler(changedataconversation_handler) updater.dispatcher.add_handler(message_handler) updater.dispatcher.add_handler(inline_keyboard_handler) updater.dispatcher.add_error_handler(error_handler) # updater.start_polling() # updater.idle() updater.start_webhook(listen='127.0.0.1', port=5002, url_path=TOKEN) updater.bot.set_webhook(url='https://cardel.ml/' + TOKEN) updater.idle()
def main() -> None: # Create the Updater and pass it your bot's token. persistence = PicklePersistence(filename='conversationbot') updater = Updater("133333378:AAxxxxxxxxxxxxxxxxxxnPU", persistence=persistence) updater.dispatcher.add_handler(CommandHandler('rain', rain)) updater.dispatcher.add_handler(CommandHandler('approve', approve)) updater.dispatcher.add_handler(CallbackQueryHandler(button)) updater.dispatcher.add_handler(CommandHandler('addhb', addhb)) updater.dispatcher.add_handler(CommandHandler('address', address)) # Start the Bot updater.start_polling() # Run the bot until you press 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 main(): # TODO: move data to XDG_CACHE_DIR(~/.cache) or XDG_DATA_DIR(~/.local/share) # get script's directory path script_dir = os.path.dirname(os.path.realpath(__file__)) persistence_file = PicklePersistence(filename=f'{script_dir}/data/bot_persistence') updater = Updater(token=TOKEN, use_context=True, persistence=persistence_file) # add command handlers updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_handler(CommandHandler('city', change_city)) updater.dispatcher.add_handler(CommandHandler('provider', change_provider)) updater.dispatcher.add_handler(CommandHandler('today', print_daily_forecast)) updater.dispatcher.add_handler(CommandHandler('tomorrow', print_tomorrow_forecast)) updater.dispatcher.add_handler(CommandHandler('week', print_weekly_forecast)) updater.dispatcher.add_handler(CommandHandler('help', display_help)) updater.dispatcher.add_handler(CallbackQueryHandler(query_handler)) # load data with open(f"{script_dir}/data/weather_data.json", "r") as f: updater.dispatcher.bot_data['forecast_data'] = json.loads(f.read()) with open(f"{script_dir}/data/city_data.json", "r") as f: data = json.loads(f.read()) updater.dispatcher.bot_data['cities'] = set(d['city'] for d in data) updater.dispatcher.bot_data['providers'] = set(d['provider'] for d in data) updater.start_polling() updater.idle()
def main(): ### adding persistence my_persistence = PicklePersistence(filename='test', store_bot_data=True) ### creating the updater and dispatcher from telegram.ext import Updater updater = Updater(token=token, persistence=my_persistence, use_context=True) dispatcher = updater.dispatcher ## storing list of letters and dictionary into the bot_data fn = 'meta_letters/Volume 1.txt' with open(fn, 'r') as fo: vol1 = fo.read() fn = 'meta_letters/Volume 2.txt' with open(fn, 'r') as fo: vol2 = fo.read() # fn = 'all_letters/dict_0to10.json' fn = 'all_letters/dict_all_letters.json' with open(fn, 'r') as fo: import json letters = json.load(fo) dispatcher.bot_data['vol 1'] = vol1 dispatcher.bot_data['vol 2'] = vol2 dispatcher.bot_data['letters'] = letters dispatcher.add_handler(start_handler) dispatcher.add_handler(read_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(list_handler) updater.start_polling() updater.idle()
def poll(): # monitoring prometheus_server(8080) # chat whitelist whitelist = None if os.getenv("TG_SINGLE_CHAT"): whitelist = Filters.chat(chat_id=int(os.getenv("TG_SINGLE_CHAT"))) persistence = PicklePersistence(filename="data.pkl") updater = Updater(os.getenv("TG_TOKEN"), persistence=persistence) dp = updater.dispatcher # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", start, filters=whitelist)) dp.add_handler(CommandHandler("stop", stop, filters=whitelist)) # on noncommand i.e message - check if it was correct dp.add_handler(MessageHandler(Filters.text, check)) # log all errors dp.add_error_handler(lambda update, context: logger.error( f"(on update {update}) {context.error}")) # start the bot updater.start_polling() updater.idle()
def main(): tst = not False if tst: pp = PicklePersistence(filename='conversationbot') updater = Updater( BOT_TOKEN, use_context=True, persistence=pp) updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_handler( CallbackQueryHandler(callback_query_handler)) updater.dispatcher.add_handler(CommandHandler('add', handle_reply)) conv_handler = ConversationHandler( entry_points=[CommandHandler('postjob', strt)], states={ TYPE: [MessageHandler(Filters.text, name)], DESC: [MessageHandler(Filters.text, desc), ], CMP: [MessageHandler(Filters.text, job_types)], JOBTYPES: [MessageHandler(Filters.regex('^(Remote|Permanent|Contractual|Hourly)$'), final)], # FINAL: [MessageHandler(Filters.text, end_response)] # BIO: [MessageHandler(Filters.text & ~Filters.command, bio)] }, fallbacks=[CommandHandler('cancel', cancel)] ) updater.dispatcher.add_handler(CommandHandler('cancel', cancel)) updater.dispatcher.add_handler(conv_handler) updater.start_polling() updater.idle() else: messageSender()
def init_persistance(): # if os.path.exists(pickle_logs): # os.remove(pickle_logs) # else: # print("Good!!! - The file does not exist!") # fei_persist = PicklePersistence( # filename=pickle_logs, # store_user_data=True, store_chat_data=True, # single_file=True) # fei_persist.flush() # userData = fei_persist.get_user_data() # chatData = fei_persist.get_chat_data() # userConv = fei_persist.get_conversations(CHATID) # uDataFile = open(r"log/userData.txt", "w") # cDataFile = open(r"log/chatData.txt", "w") # cnvDataFile = open(r"log/convData.txt", "w") # uDataFile.write(str(userData)) # uDataFile.close() # cDataFile.write(str(chatData)) # cDataFile.close() # cnvDataFile.write(str(userConv)) # cnvDataFile.close() return PicklePersistence(filename=pickle_logs, store_user_data=True, store_chat_data=True, store_bot_data=True, single_file=False)
def main(): persistence = PicklePersistence(filename=str(data / 'persistence.pickle')) updater = Updater(config["token"], use_context=True, persistence=persistence) # updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_error_handler(error) conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ ASKING: [MessageHandler(Filters.regex(f'^{config["buttons"]["ask"]}$'), ask), MessageHandler(Filters.regex(f'^{config["buttons"]["q_list"]}$'), q_list)], TYPING_NEW_QUESTION: [MessageHandler(Filters.regex(f'^({config["buttons"]["cancel_ask"]})$'), cancel_ask), MessageHandler(Filters.text, user_question)] }, fallbacks=[], name="ask_conversation", persistent=True ) updater.dispatcher.add_handler(conv_handler) # Запуск бота updater.start_polling() # Работать пока пользователь не нажмет Ctrl-C или процесс получит SIGINT, # SIGTERM or SIGABRT updater.idle()
def run(): mqbot = MQBot(token=BOT_TOKEN, request=Request(connect_timeout=10, con_pool_size=30)) updater = Updater( bot=mqbot, use_context=True, persistence=PicklePersistence( filename=Path(BASE_DIR, 'persistence', 'conversations'))) dp = updater.dispatcher add_bot.register(dp) revoke_token.register(dp) main.register(dp) if not IS_DEBUG: error.register(dp) updater.start_webhook( listen='0.0.0.0', port=BOT_PORT, url_path=BOT_TOKEN, key=SSL_KEY, cert=SSL_CERT, webhook_url=f"https://{BOT_IP}:{BOT_PORT}/{BOT_TOKEN}") else: updater.start_polling() updater.idle()
def main(): cpu_count = os.cpu_count() workers = cpu_count log.debug('System: CPU_COUNT=%s, WORKERS=%s', cpu_count, workers) log.debug('Start') persistence = PicklePersistence(filename='data.pickle') # Create the EventHandler and pass it your bot's token. updater = Updater(config.TOKEN, workers=workers, persistence=persistence, use_context=True) # Get the dispatcher to register handlers dp = updater.dispatcher dp.add_handler(CommandHandler('start', on_start)) dp.add_handler(MessageHandler(Filters.regex(r'(?i)^(set)\b'), on_set)) dp.add_handler(MessageHandler(Filters.regex(r'(?i)^get'), on_get)) dp.add_handler(MessageHandler(Filters.text, on_request)) # Handle all errors dp.add_error_handler(on_error) # Start the Bot updater.start_polling() # Run the bot until the you 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() log.debug('Finish')
def main(): pp = PicklePersistence(filename = 'conversationbot') updater = Updater(token = TOKEN, persistence = pp, use_context = True) dp = updater.dispatcher dp.add_handler(CommandHandler('start', start)) dp.add_handler(CommandHandler('help', help)) dp.add_handler(CommandHandler('sendsticker', send_sticker)) dp.add_handler(CommandHandler('getcurevent', get_cur_event)) dp.add_handler(CommandHandler('getnextevent', get_next_event)) dp.add_handler(CommandHandler('nextdeadline', next_deadline)) dp.add_handler(CommandHandler('listdeadlines', list_deadlines)) add_deadline_handler = ConversationHandler( entry_points = [CommandHandler('adddeadline', ad_start)], states = { DATE: [MessageHandler(Filters.text, ad_date)], NAME: [MessageHandler(Filters.text, ad_name)], DESCRIPTION: [MessageHandler(Filters.text, ad_description)] }, fallbacks = [ CommandHandler('cancel', cancel) ], name = "adddeadline", persistent = True ) dp.add_handler(add_deadline_handler) #dp.add_handler(CommandHandler('api', api)) dp.add_handler(MessageHandler(Filters.all, default)) dp.add_error_handler(error) updater.start_polling() updater.idle()
class TestClass: bot = Mockbot() ug = UserGenerator() cg = ChatGenerator() mg = MessageGenerator(bot) pp = PicklePersistence(filename='bbqreserve_test') updater = Updater(bot=bot, persistence=pp, use_context=True) @pytest.mark.parametrize("test_input, expected, userdata, delme", create_reserve_parameters) def test_create_reservation(self, test_input, expected, userdata, delme): user = self.ug.get_user(id=userdata['id'], first_name=userdata['first_name'], last_name=userdata['last_name']) chat = self.cg.get_chat(user=user) self.updater.dispatcher.add_handler(reserve.reserve_conv_handler) self.updater.start_polling() update = self.mg.get_message(user=user, chat=chat, text=test_input) self.bot.insertUpdate(update) sent = self.bot.sent_messages self.updater.stop() if delme: import os os.remove("bbqreserve_test") # check expected result with actual result assert sent[-1]['text'] == expected
def main(): # Read config with open('config.json', 'r') as f: config = json.load(f) # The updater primarily gets telegram updates from telegram servers cinnabot = Updater( token=config['telegram_bot_token'], persistence=PicklePersistence(config['persistence_file']), ) # The dispatcher routes updates to the first matching handler for feature in FEATURES: cinnabot.dispatcher.add_handler(feature.handler) # Store data for /help and /help <feature> in the bot cinnabot.dispatcher.bot_data['help_text'] = dict() cinnabot.dispatcher.bot_data['help_full'] = dict() for feature in FEATURES: cinnabot.dispatcher.bot_data['help_text'][ feature.command] = feature.help_text cinnabot.dispatcher.bot_data['help_full'][ feature.command] = feature.help_full # Run the bot! # cinnabot.start_webhook() # For deployment cinnabot.start_polling() cinnabot.idle()
def pickle_persistence_only_user(): return PicklePersistence(filename='pickletest', store_user_data=True, store_chat_data=False, store_bot_data=False, single_file=False, on_flush=False)
def main(self, tk): ''' Executes bot code and handles bot polling/lifecycle ''' my_persistence = PicklePersistence(filename='persistence') updater = Updater(tk, persistence=my_persistence, use_context=True) # for security purposes, everytime main will be called, the token # attribute will be erased from object memory del tk dp = updater.dispatcher jobQueue = updater.job_queue # commands start = Start(self, dp) start.registerToDispatcher() help = Help(self, dp) help.registerToDispatcher() info = Info(self, dp) info.registerToDispatcher() self.enableLogging() # start the bot updater.start_polling() updater.idle()
def main(): # updater = Updater(...) my_persistence = PicklePersistence(filename='data_storage') updater = Updater(token, persistence=my_persistence, use_context=True) job_queue = updater.job_queue # Periodically save jobs job_queue.run_repeating(save_jobs_job, timedelta(seconds=5)) try: load_jobs(job_queue) except FileNotFoundError: # First run pass job_queue.run_repeating(callback_daily, interval=10, first=0, context={'chat_id': 304640198}) updater.start_polling() updater.idle() # Run again after bot has been properly shutdown save_jobs(job_queue)
def main(): data_dir = os.getenv("CONFIG_PATH", "") if not data_dir: data_dir = Path.joinpath(Path.home(), ".config", "firefly-bot") data_dir.mkdir(parents=True, exist_ok=True) else: data_dir = Path(data_dir) bot_persistence = PicklePersistence(filename=str(data_dir / "bot-data")) bot_token = os.getenv("TELEGRAM_BOT_TOKEN") updater = Updater(bot_token, persistence=bot_persistence, use_context=True) conversation_handler = ConversationHandler( entry_points=[CommandHandler("start", start)], states={ FIREFLY_URL: [MessageHandler(Filters.text, get_firefly_token)], DEFAULT_WITHDRAW_ACCOUNT: [ MessageHandler(Filters.text, get_default_account), CallbackQueryHandler(store_default_account, pattern="^[0-9]*$") ] }, fallbacks=[CommandHandler("cancel", cancel)]) updater.dispatcher.add_handler(CommandHandler("help", help)) updater.dispatcher.add_handler(CommandHandler("about", about)) updater.dispatcher.add_handler( MessageHandler(filters=Filters.regex("^-?[0-9]+"), callback=spend)) updater.dispatcher.add_error_handler(error) updater.dispatcher.add_handler(conversation_handler) # Start the Bot updater.start_polling() # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle()
def handle(self, *args, **options): logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO) logging.getLogger('apscheduler').setLevel(logging.WARNING) logger = logging.getLogger(__name__) logger.info('Launching bot...') persistence = PicklePersistence('bot_persistence') updater = Updater( token=settings.BOT_TOKEN, use_context=True, persistence=persistence, ) logger.info('Registering handlers...') from ...handlers import load_all load_all(updater.dispatcher, updater.job_queue) logger.info('Starting polling...') updater.start_polling() BotCLI(persistence, updater.job_queue).cmdloop() logger.info('Stopping updater...') updater.stop() logger.info('Bye!')
def main() -> None: """Setup and run ONGAbot""" persistence = PicklePersistence( filename=os.getenv("DB_PATH", "ongabot.db")) updater = Updater(os.getenv("API_TOKEN"), persistence=persistence, use_context=True) # Register handlers dispatcher = updater.dispatcher dispatcher.add_handler(StartCommandHandler()) dispatcher.add_handler(HelpCommandHandler()) dispatcher.add_handler(OngaCommandHandler()) dispatcher.add_handler(NewEventCommandHandler()) dispatcher.add_handler(CancelEventCommandHandler()) dispatcher.add_handler(EventPollHandler()) dispatcher.add_handler(EventPollAnswerHandler()) dispatcher.add_error_handler(error) # Start the bot updater.start_polling() # Block until you press 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()
async def test_custom_pickler_unpickler_with_custom_objects( self, bot, pickle_persistence, good_pickle_files): dict_s = self.DictSub("private", "normal", bot) slot_s = self.SlotsSub("new_var", "private_var") regular = self.NormalClass(12) pickle_persistence.set_bot(bot) await pickle_persistence.update_user_data(1232, { "sub_dict": dict_s, "sub_slots": slot_s, "r": regular }) pp = PicklePersistence("pickletest", single_file=False, on_flush=False) pp.set_bot(bot) # Set the bot data = (await pp.get_user_data())[1232] sub_dict = data["sub_dict"] sub_slots = data["sub_slots"] sub_regular = data["r"] assert sub_dict._bot is bot assert sub_dict.normal == dict_s.normal assert sub_dict._private == dict_s._private assert sub_slots.new_var == slot_s.new_var assert sub_slots._private == slot_s._private assert sub_slots._bot is None # We didn't set the bot, so it shouldn't have it here. assert sub_regular.my_var == regular.my_var
def main(): data_keeper = DataKeeper() my_persistence = PicklePersistence(filename='bot_persistence.pickle') updater = Updater( token=TOKEN, persistence=my_persistence, use_context=True ) dispatcher = updater.dispatcher job_queue = updater.job_queue execute_notifications_job = job_queue.run_repeating( notify.execute_notifications, interval=55, first=1 ) conv_handler = conversation.create_coversation_handler(data_keeper) dispatcher.add_handler(conv_handler) dispatcher.add_error_handler(error) updater.start_polling() updater.idle()
def test_all_application_args_custom(self, builder, bot, monkeypatch): job_queue = JobQueue() persistence = PicklePersistence("file_path") update_queue = asyncio.Queue() context_types = ContextTypes() concurrent_updates = 123 async def post_init(app: Application) -> None: pass async def post_shutdown(app: Application) -> None: pass app = (builder.token(bot.token).job_queue(job_queue).persistence( persistence).update_queue(update_queue).context_types( context_types).concurrent_updates(concurrent_updates). post_init(post_init).post_shutdown(post_shutdown)).build() assert app.job_queue is job_queue assert app.job_queue.application is app assert app.persistence is persistence assert app.persistence.bot is app.bot assert app.update_queue is update_queue assert app.updater.update_queue is update_queue assert app.updater.bot is app.bot assert app.context_types is context_types assert app.concurrent_updates == concurrent_updates assert app.post_init is post_init assert app.post_shutdown is post_shutdown updater = Updater(bot=bot, update_queue=update_queue) app = ApplicationBuilder().updater(updater).build() assert app.updater is updater assert app.bot is updater.bot assert app.update_queue is updater.update_queue
def main(): cpu_count = os.cpu_count() workers = cpu_count log.debug(f'System: CPU_COUNT={cpu_count}, WORKERS={workers}') log.debug('Start') persistence = PicklePersistence(filename='data.pickle') # Create the EventHandler and pass it your bot's token. updater = Updater( config.TOKEN, workers=workers, persistence=persistence, defaults=Defaults(run_async=True), ) # Get the dispatcher to register handlers dp = updater.dispatcher dp.add_handler(CommandHandler('start', on_start)) dp.add_handler(MessageHandler(Filters.photo, on_photo)) dp.add_handler(MessageHandler(Filters.text(COMMANDS_DEEP_DREAM), on_deep_dream)) dp.add_handler(MessageHandler(Filters.text([COMMAND_RESET]), on_reset)) dp.add_handler(MessageHandler(Filters.all, on_request)) dp.add_error_handler(on_error) # Start the Bot updater.start_polling() # Run the bot until the you 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, token, *args, **kwargs): persistence_file = os.path.join(settings.MEDIA_ROOT, 'persistence_files/{}'.format(token)) persistence = PicklePersistence(filename=persistence_file) super(BotUpdater, self).__init__(token, persistence=persistence, use_context=True, *args, **kwargs) self.set_commands() self.reply_manager = TelegramReplyTemplate dp = self.dispatcher conv_handler = ConversationHandler( entry_points=[CommandHandler('start', self.start)], states={ self.MENU_STATE: self.get_main_menu_handlers(), self.FOOD_MENU: self.get_food_menu_handlers(), }, fallbacks=[CommandHandler('start', self.start)], persistent=True, name='client_conversation') dp.add_handler(conv_handler) dp.add_handler(MessageHandler(Filters.text, self.undefined_cmd_msg))
def main(): """ Init telegram bot, attach handlers and wait for incoming requests. """ # Init telegram bot bot = Updater(TELEGRAM_BOT_TOKEN, persistence=PicklePersistence(filename=session_data_path), use_context=True) dispatcher = bot.dispatcher dispatcher.job_queue.run_repeating(distribution_ready_check, interval=JOB_INTERVAL_IN_SECONDS) setup_existing_user(dispatcher) dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('distribute', distribute_handler)) # Add error handler dispatcher.add_error_handler(error) # Start the bot bot.start_polling() logger.info('LICX Distribute Bot is running...') # Run the bot until you press 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. bot.idle()
def main(): my_persistence = PicklePersistence(filename='zsd_pers') updater = Updater(token='your token', persistence=my_persistence, use_context=True) # Start the Bot updater.start_polling() my_persistence.get_user_data dispatcher = updater.dispatcher start_handler = CommandHandler('start', start) dispatcher.add_handler(start_handler) dispatcher.add_handler(CommandHandler('uname', setUname)) dispatcher.add_handler(CommandHandler('passwd', setPasswd)) dispatcher.add_handler(CommandHandler('mydata', getMyData)) incidents_handler = CommandHandler('incidents', incidents) dispatcher.add_handler(incidents_handler) # Run the bot until you press 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 main(): token = os.getenv('TELEGRAM_TOKEN', None) if not token: load_dotenv() token = os.getenv('TELEGRAM_TOKEN', None) pp = None if os.getenv('ENVIRONMENT', '') == 'DEV': pp = PicklePersistence(filename='storage/telegram/heywallet') if not token: logger.error("Is required TELEGRAM_TOKEN is generate from BotFather.") exit() updater = Updater(token, persistence=pp, use_context=True) # Get the dispatcher to register handlers dp = updater.dispatcher # set Workflow /start dp.add_handler(BaseHandler().handler()) # Start the Bot updater.start_polling() # Run the bot until you press 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 main(): # Create the Updater and pass it your bot's token. pp = PicklePersistence(filename='telelyricsbot') updater = Updater(BOT_TOKEN, persistence=pp) # Get the dispatcher to register handlers dp = updater.dispatcher # Add conversation handler with the states conv_handler = ConversationHandler( entry_points=[CommandHandler('lyrics', lyrics, pass_user_data=True)], states={ TYPING_URL: [MessageHandler(Filters.text, received_url, pass_user_data=True)] }, fallbacks=[], name="conversation", allow_reentry=True, persistent=True ) dp.add_handler(conv_handler) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() # Run the bot until you press 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()