def test_pass_job_or_update_queue(self, dp, chat_member): handler = ChatMemberHandler(self.callback_queue_1, pass_job_queue=True) dp.add_handler(handler) dp.process_update(chat_member) assert self.test_flag dp.remove_handler(handler) handler = ChatMemberHandler(self.callback_queue_1, pass_update_queue=True) dp.add_handler(handler) self.test_flag = False dp.process_update(chat_member) assert self.test_flag dp.remove_handler(handler) handler = ChatMemberHandler(self.callback_queue_2, pass_job_queue=True, pass_update_queue=True) dp.add_handler(handler) self.test_flag = False dp.process_update(chat_member) assert self.test_flag
def main() -> None: """Start the bot.""" # Create the Updater and pass it your bot's token. updater = Updater("TOKEN") # Get the dispatcher to register handlers dispatcher = updater.dispatcher # Keep track of which chats the bot is in dispatcher.add_handler( ChatMemberHandler(track_chats, ChatMemberHandler.MY_CHAT_MEMBER)) dispatcher.add_handler(CommandHandler("show_chats", show_chats)) # Handle members joining/leaving chats. dispatcher.add_handler( ChatMemberHandler(greet_chat_members, ChatMemberHandler.CHAT_MEMBER)) # Start the Bot # We pass 'allowed_updates' to *only* handle updates with '(my_)chat_member' or 'message' # If you want to handle *all* updates, pass Update.ALL_TYPES updater.start_polling(allowed_updates=[ Update.MESSAGE, Update.CHAT_MEMBER, Update.MY_CHAT_MEMBER ]) # 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 test_basic(self, dp, chat_member): handler = ChatMemberHandler(self.callback_basic) dp.add_handler(handler) assert handler.check_update(chat_member) dp.process_update(chat_member) assert self.test_flag
def test_slot_behaviour(self, recwarn, mro_slots): action = ChatMemberHandler(self.callback_basic) for attr in action.__slots__: assert getattr(action, attr, 'err') != 'err', f"got extra slot '{attr}'" assert not action.__dict__, f"got missing slot(s): {action.__dict__}" assert len(mro_slots(action)) == len(set(mro_slots(action))), "duplicate slot" action.custom = 'should give warning' assert len(recwarn) == 1 and 'custom' in str(recwarn[0].message), recwarn.list
async def test_context(self, app, chat_member): handler = ChatMemberHandler(self.callback) app.add_handler(handler) async with app: await app.process_update(chat_member) assert self.test_flag
def test_slot_behaviour(self, mro_slots): action = ChatMemberHandler(self.callback) for attr in action.__slots__: assert getattr(action, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(action)) == len(set( mro_slots(action))), "duplicate slot"
def main() -> None: """Start the bot.""" # Create the Application and pass it your bot's token. application = Application.builder().token("TOKEN").build() # Keep track of which chats the bot is in application.add_handler( ChatMemberHandler(track_chats, ChatMemberHandler.MY_CHAT_MEMBER)) application.add_handler(CommandHandler("show_chats", show_chats)) # Handle members joining/leaving chats. application.add_handler( ChatMemberHandler(greet_chat_members, ChatMemberHandler.CHAT_MEMBER)) # Run the bot until the user presses Ctrl-C # We pass 'allowed_updates' handle *all* updates including `chat_member` updates # To reset this, simply pass `allowed_updates=[]` application.run_polling(allowed_updates=Update.ALL_TYPES)
def test_chat_member_types( self, dp, chat_member_updated, chat_member, expected, allowed_types ): result_1, result_2 = expected handler = ChatMemberHandler(self.callback_basic, chat_member_types=allowed_types) dp.add_handler(handler) assert handler.check_update(chat_member) == result_1 dp.process_update(chat_member) assert self.test_flag == result_1 self.test_flag = False chat_member.my_chat_member = None chat_member.chat_member = chat_member_updated assert handler.check_update(chat_member) == result_2 dp.process_update(chat_member) assert self.test_flag == result_2
async def test_chat_member_types(self, app, chat_member_updated, chat_member, expected, allowed_types): result_1, result_2 = expected handler = ChatMemberHandler(self.callback, chat_member_types=allowed_types) app.add_handler(handler) async with app: assert handler.check_update(chat_member) == result_1 await app.process_update(chat_member) assert self.test_flag == result_1 self.test_flag = False chat_member.my_chat_member = None chat_member.chat_member = chat_member_updated assert handler.check_update(chat_member) == result_2 await app.process_update(chat_member) assert self.test_flag == result_2
def test_pass_user_or_chat_data(self, dp, chat_member): handler = ChatMemberHandler(self.callback_data_1, pass_user_data=True) dp.add_handler(handler) dp.process_update(chat_member) assert self.test_flag dp.remove_handler(handler) handler = ChatMemberHandler(self.callback_data_1, pass_chat_data=True) dp.add_handler(handler) self.test_flag = False dp.process_update(chat_member) assert self.test_flag dp.remove_handler(handler) handler = ChatMemberHandler(self.callback_data_2, pass_chat_data=True, pass_user_data=True) dp.add_handler(handler) self.test_flag = False dp.process_update(chat_member) assert self.test_flag
def main() -> None: """Start the bot.""" # Create the Updater and pass it your bot's token. updater = Updater(BOT_TOKEN) # Get the dispatcher to register handlers dispatcher = updater.dispatcher # Keep track of which chats the bot is in dispatcher.add_handler(ChatMemberHandler(track_chats, ChatMemberHandler.MY_CHAT_MEMBER)) dispatcher.add_handler(CommandHandler("show_chats", show_chats)) # Handle members joining/leaving chats. dispatcher.add_handler(ChatMemberHandler(greet_chat_members, ChatMemberHandler.CHAT_MEMBER)) # Start the Bot # We pass 'allowed_updates' handle *all* updates including `chat_member` updates # To reset this, simply pass `allowed_updates=[]` updater.start_polling(allowed_updates=Update.ALL_TYPES) # 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 start_bot(): updater = Updater(settings.TELEGRAM_TOKEN) dispatcher = updater.dispatcher for command in commands: dispatcher.add_handler(CommandHandler(str(command), command)) updater.dispatcher.add_handler(CallbackQueryHandler(SetLanguageQuery())) dispatcher.add_handler(ChatMemberHandler(ChatMember())) dispatcher.add_handler(MessageHandler(~Filters.command, Forward())) commands_help_text = '\n'.join( [command.help_text for command in commands if command.help_text]) for admin_id in settings.TELEGRAM_ADMINS: updater.bot.send_message(chat_id=admin_id, text='\n{}'.format(commands_help_text)) updater.start_polling() updater.idle()
• /cleanservice <on/off*:* deletes telegrams welcome/left service messages. *Example:* user joined chat, user left chat. *Welcome markdown:* • /welcomehelp*:* view more formatting information for custom welcome/goodbye messages. 「 Rules Commands」 • /rules*:* get the rules for this chat. *Admins only:* • /setrules <your rules here>*:* set the rules for this chat. • /clearrules*:* clear the rules for this chat. """ NEW_MEM_HANDLER = ChatMemberHandler(new_member, ChatMemberHandler.CHAT_MEMBER, run_async=True) LEFT_MEM_HANDLER = MessageHandler(Filters.status_update.left_chat_member, left_member, run_async=True) WELC_PREF_HANDLER = CommandHandler("welcome", welcome, filters=Filters.chat_type.groups, run_async=True) GOODBYE_PREF_HANDLER = CommandHandler("goodbye", goodbye, filters=Filters.chat_type.groups, run_async=True) SET_WELCOME = CommandHandler("setwelcome", set_welcome, filters=Filters.chat_type.groups, run_async=True) SET_GOODBYE = CommandHandler("setgoodbye", set_goodbye, filters=Filters.chat_type.groups, run_async=True) RESET_WELCOME = CommandHandler("resetwelcome", reset_welcome, filters=Filters.chat_type.groups, run_async=True) RESET_GOODBYE = CommandHandler("resetgoodbye", reset_goodbye, filters=Filters.chat_type.groups, run_async=True) WELCOMEMUTE_HANDLER = CommandHandler("welcomemute", welcomemute, filters=Filters.chat_type.groups, run_async=True) CLEAN_SERVICE_HANDLER = CommandHandler("cleanservice", cleanservice, filters=Filters.chat_type.groups, run_async=True) CLEAN_WELCOME = CommandHandler("cleanwelcome", clean_welcome, filters=Filters.chat_type.groups, run_async=True) WELCOME_HELP = CommandHandler("welcomehelp", welcome_help, run_async=True) WELCOME_MUTE_HELP = CommandHandler("welcomemutehelp", welcome_mute_help, run_async=True) BUTTON_VERIFY_HANDLER = CallbackQueryHandler(user_button, pattern=r"user_join_", run_async=True) dispatcher.add_handler(NEW_MEM_HANDLER)
def test_context(self, cdp, chat_member): handler = ChatMemberHandler(self.callback_context) cdp.add_handler(handler) cdp.process_update(chat_member) assert self.test_flag
def test_other_update_types(self, false_update): handler = ChatMemberHandler(self.callback_basic) assert not handler.check_update(false_update) assert not handler.check_update(True)
def __chat_settings__(chat_id, user_id): welcome_pref = sql.get_welc_pref(chat_id)[0] goodbye_pref = sql.get_gdbye_pref(chat_id)[0] return ("This chat has it's welcome preference set to `{}`.\n" "It's goodbye preference is `{}`.".format(welcome_pref, goodbye_pref)) from tg_bot.modules.language import gs def get_help(chat): return gs(chat, "greetings_help") NEW_MEM_HANDLER = ChatMemberHandler(new_member, ChatMemberHandler.CHAT_MEMBER) LEFT_MEM_HANDLER = MessageHandler(Filters.status_update.left_chat_member, left_member, run_async=True) WELC_PREF_HANDLER = CommandHandler("welcome", welcome, filters=Filters.chat_type.groups, run_async=True) GOODBYE_PREF_HANDLER = CommandHandler("goodbye", goodbye, filters=Filters.chat_type.groups, run_async=True) SET_WELCOME = CommandHandler("setwelcome", set_welcome, filters=Filters.chat_type.groups, run_async=True)
def main() -> None: config = configparser.ConfigParser() config.read('bot.ini') defaults = Defaults(parse_mode=ParseMode.HTML, disable_web_page_preview=True) updater = Updater(token=config['KEYS']['bot_api'], defaults=defaults) dispatcher = updater.dispatcher update_rules_messages(updater.bot) dispatcher.add_handler(MessageHandler(~Filters.command, rate_limit_tracker), group=-1) # Note: Order matters! # Taghints - works with regex taghints.register(dispatcher) # Simple commands dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('rules', rules)) dispatcher.add_handler(MessageHandler(Filters.regex(r'.*#rules.*'), rules)) dispatcher.add_handler(CommandHandler('docs', docs)) dispatcher.add_handler(CommandHandler('wiki', wiki)) dispatcher.add_handler(CommandHandler('help', help_callback)) # Stuff that runs on every message with regex dispatcher.add_handler( MessageHandler( Filters.regex(r'(?i)[\s\S]*?((sudo )?make me a sandwich)[\s\S]*?'), sandwich)) dispatcher.add_handler( MessageHandler( Filters.regex(r'(?i)[\s\S]*?\b(?<!["\\])(off|on)[- _]?topic\b'), off_on_topic)) # We need several matches so Filters.regex is basically useless # therefore we catch everything and do regex ourselves # This should probably be in another dispatcher group # but I kept getting SystemErrors.. dispatcher.add_handler( MessageHandler( Filters.text & Filters.update.messages & ~Filters.command, github)) # Status updates dispatcher.add_handler( ChatMemberHandler(greet_new_chat_members, chat_member_types=ChatMemberHandler.CHAT_MEMBER)) dispatcher.add_handler( MessageHandler( Filters.chat(username=[ONTOPIC_USERNAME, OFFTOPIC_USERNAME]) & Filters.status_update.new_chat_members, delete_new_chat_members_message, ), group=1, ) # Inline Queries inlinequeries.register(dispatcher) # Error Handler dispatcher.add_error_handler(error_handler) updater.start_polling(allowed_updates=Update.ALL_TYPES) logger.info('Listening...') try: github_issues.set_auth(config['KEYS']['github_client_id'], config['KEYS']['github_client_secret']) except KeyError: logging.info( 'No github api token set. Rate-limit is 60 requests/hour without auth.' ) github_issues.init_ptb_contribs( dispatcher.job_queue) # type: ignore[arg-type] github_issues.init_issues(dispatcher.job_queue) # type: ignore[arg-type] # set commands updater.bot.set_my_commands([ ('docs', 'Send the link to the docs. Use in private chat with rools.'), ('wiki', 'Send the link to the wiki. Use in private chat with rools.'), ('hints', 'List available tag hints. Use in private chat with rools.'), ('help', 'Send the link to this bots README. Use in private chat with rools.'), ]) updater.idle()
def main() -> None: config = configparser.ConfigParser() config.read("bot.ini") defaults = Defaults(parse_mode=ParseMode.HTML, disable_web_page_preview=True) updater = Updater(token=config["KEYS"]["bot_api"], defaults=defaults) dispatcher = updater.dispatcher update_rules_messages(updater.bot) # Note: Order matters! dispatcher.add_handler(MessageHandler(~Filters.command, rate_limit_tracker), group=-1) dispatcher.add_handler( MessageHandler( Filters.sender_chat.channel & ~Filters.is_automatic_forward, ban_sender_channels)) # Simple commands # The first one also handles deep linking /start commands dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("rules", rules)) dispatcher.add_handler(CommandHandler("docs", docs)) dispatcher.add_handler(CommandHandler("wiki", wiki)) dispatcher.add_handler(CommandHandler("help", help_callback)) # Stuff that runs on every message with regex dispatcher.add_handler( MessageHandler( Filters.regex(r"(?i)[\s\S]*?((sudo )?make me a sandwich)[\s\S]*?"), sandwich)) dispatcher.add_handler( MessageHandler(Filters.regex("/(on|off)_topic"), off_on_topic)) # Tag hints - works with regex dispatcher.add_handler(MessageHandler(TagHintFilter(), tag_hint)) # We need several matches so Filters.regex is basically useless # therefore we catch everything and do regex ourselves dispatcher.add_handler( MessageHandler( Filters.text & Filters.update.messages & ~Filters.command, reply_search)) # Status updates dispatcher.add_handler( ChatMemberHandler(greet_new_chat_members, chat_member_types=ChatMemberHandler.CHAT_MEMBER)) dispatcher.add_handler( MessageHandler( Filters.chat(username=[ONTOPIC_USERNAME, OFFTOPIC_USERNAME]) & Filters.status_update.new_chat_members, delete_new_chat_members_message, ), group=1, ) # Inline Queries dispatcher.add_handler(InlineQueryHandler(inlinequeries.inline_query)) # Captcha for userbots dispatcher.add_handler( CommandHandler( "say_potato", say_potato_command, filters=Filters.chat( username=[ONTOPIC_USERNAME, OFFTOPIC_USERNAME]), )) dispatcher.add_handler( CallbackQueryHandler(say_potato_button, pattern="^POTATO")) # Error Handler dispatcher.add_error_handler(error_handler) updater.start_polling(allowed_updates=Update.ALL_TYPES) logger.info("Listening...") try: github_issues.set_auth(config["KEYS"]["github_client_id"], config["KEYS"]["github_client_secret"]) except KeyError: logging.info( "No github api token set. Rate-limit is 60 requests/hour without auth." ) github_issues.init_ptb_contribs( dispatcher.job_queue) # type: ignore[arg-type] github_issues.init_issues(dispatcher.job_queue) # type: ignore[arg-type] # set commands updater.bot.set_my_commands( build_command_list(private=True), scope=BotCommandScopeAllPrivateChats(), ) updater.bot.set_my_commands( build_command_list(private=False), scope=BotCommandScopeAllGroupChats(), ) for group_name in [ONTOPIC_CHAT_ID, OFFTOPIC_CHAT_ID]: updater.bot.set_my_commands( build_command_list(private=False, group_name=group_name), scope=BotCommandScopeChat(group_name), ) updater.bot.set_my_commands( build_command_list(private=False, group_name=group_name, admins=True), scope=BotCommandScopeChatAdministrators(group_name), ) updater.idle()
def main() -> NoReturn: """Run bot.""" persist = PicklePersistence(filename=f'{conf.PERSISTENCE_NAME}.pickle') # Create the Updater and pass it your bot's token. updater = Updater(f"{conf.API['telegram_bot_token']}", persistence=persist, use_context=True, workers=conf.WORKERS) # Get the dispatcher to register handlers dispatcher = updater.dispatcher # on different commands - answer in Telegram dispatcher.add_handler(CommandHandler('start', start, run_async=True)) dispatcher.add_handler(CommandHandler('help', help, run_async=True)) dispatcher.add_handler(CommandHandler('h', help, run_async=True)) dispatcher.add_handler( CommandHandler('help_admin', help_admin, run_async=True)) dispatcher.add_handler(CommandHandler('ha', help_admin, run_async=True)) dispatcher.add_handler( CommandHandler('show_chats', show_chats, run_async=True)) dispatcher.add_handler( CommandHandler('chat_data_reset', chat_data_reset, run_async=True)) dispatcher.add_handler( CommandHandler('acdr', chat_data_reset, run_async=True)) dispatcher.add_handler(CommandHandler('stonk_add', stonk_add)) dispatcher.add_handler(CommandHandler('sa', stonk_add)) dispatcher.add_handler(CommandHandler('stonk_del', stonk_del)) dispatcher.add_handler(CommandHandler('sd', stonk_del)) dispatcher.add_handler(CommandHandler('stonk_clear', stonk_clear)) dispatcher.add_handler(CommandHandler('sc', stonk_clear)) dispatcher.add_handler( CommandHandler('stonk_list', stonk_list, run_async=True)) dispatcher.add_handler(CommandHandler('sl', stonk_list, run_async=True)) dispatcher.add_handler( CommandHandler('list_price', list_price, run_async=True)) dispatcher.add_handler(CommandHandler('lp', list_price, run_async=True)) dispatcher.add_handler(CommandHandler('chart', chart, run_async=False)) dispatcher.add_handler(CommandHandler('c', chart, run_async=False)) dispatcher.add_handler( CommandHandler('discovery', discovery_websites, run_async=True)) dispatcher.add_handler( CommandHandler('di', discovery_websites, run_async=True)) dispatcher.add_handler( CommandHandler('sector_performance', sector_performance, run_async=True)) dispatcher.add_handler( CommandHandler('sp', sector_performance, run_async=True)) dispatcher.add_handler( CommandHandler('upcoming_earnings', upcoming_earnings, run_async=True)) dispatcher.add_handler( CommandHandler('ue', upcoming_earnings, run_async=True)) dispatcher.add_handler( CommandHandler('stonk_upcoming_earnings', stonk_upcoming_earnings, run_async=True)) dispatcher.add_handler( CommandHandler('sue', stonk_upcoming_earnings, run_async=True)) dispatcher.add_handler(CommandHandler('gainers', gainers, run_async=True)) dispatcher.add_handler(CommandHandler('g', gainers, run_async=True)) dispatcher.add_handler(CommandHandler('losers', losers, run_async=True)) dispatcher.add_handler(CommandHandler('l', losers, run_async=True)) dispatcher.add_handler(CommandHandler('orders', orders, run_async=True)) dispatcher.add_handler(CommandHandler('o', orders, run_async=True)) dispatcher.add_handler( CommandHandler('high_short', high_short, run_async=True)) dispatcher.add_handler(CommandHandler('hs', high_short, run_async=True)) dispatcher.add_handler( CommandHandler('low_float', low_float, run_async=True)) dispatcher.add_handler(CommandHandler('lf', low_float, run_async=True)) dispatcher.add_handler( CommandHandler('hot_penny', hot_penny, run_async=True)) dispatcher.add_handler(CommandHandler('hp', hot_penny, run_async=True)) dispatcher.add_handler( CommandHandler('underval_large', underval_large, run_async=True)) dispatcher.add_handler(CommandHandler('ul', underval_large, run_async=True)) dispatcher.add_handler( CommandHandler('underval_growth', underval_growth, run_async=True)) dispatcher.add_handler( CommandHandler('ug', underval_growth, run_async=True)) dispatcher.add_handler( CommandHandler('exec_job_check_rise_fall', exec_job_check_rise_fall)) dispatcher.add_handler(CommandHandler('ejcrf', exec_job_check_rise_fall)) dispatcher.add_handler(CommandHandler('all_stonk_clear', all_stonk_clear)) dispatcher.add_handler(CommandHandler('asc', all_stonk_clear)) dispatcher.add_handler( CommandHandler('bot_list_all_data', bot_list_all_data, run_async=True)) dispatcher.add_handler( CommandHandler('blad', bot_list_all_data, run_async=True)) dispatcher.add_handler( CommandHandler('wallstreetbets', wallstreetbets, run_async=True)) dispatcher.add_handler( CommandHandler('wsb', wallstreetbets, run_async=True)) dispatcher.add_handler( CommandHandler('mauerstrassenwetten', mauerstrassenwetten, run_async=True)) dispatcher.add_handler( CommandHandler('msw', mauerstrassenwetten, run_async=True)) dispatcher.add_handler( CommandHandler('investing', investing, run_async=True)) dispatcher.add_handler(CommandHandler('ri', investing, run_async=True)) dispatcher.add_handler(CommandHandler('rstocks', stocks, run_async=True)) dispatcher.add_handler(CommandHandler('rs', stocks, run_async=True)) dispatcher.add_handler(CommandHandler('gamestop', gamestop, run_async=True)) dispatcher.add_handler(CommandHandler('gme', gamestop, run_async=True)) dispatcher.add_handler( CommandHandler('spielstopp', spielstopp, run_async=True)) dispatcher.add_handler(CommandHandler('rss', spielstopp, run_async=True)) dispatcher.add_handler( CommandHandler('stockmarket', stockmarket, run_async=True)) dispatcher.add_handler(CommandHandler('rsm', stockmarket, run_async=True)) dispatcher.add_handler( CommandHandler('daytrading', daytrading, run_async=True)) dispatcher.add_handler(CommandHandler('rdt', daytrading, run_async=True)) dispatcher.add_handler( CommandHandler('pennystocks', pennystocks, run_async=True)) dispatcher.add_handler(CommandHandler('rps', pennystocks, run_async=True)) dispatcher.add_handler( CommandHandler('cryptomarkets', cryptomarkets, run_async=True)) dispatcher.add_handler(CommandHandler('rcm', cryptomarkets, run_async=True)) dispatcher.add_handler( CommandHandler('satoshistreetbets', satoshistreetbets, run_async=True)) dispatcher.add_handler( CommandHandler('ssb', satoshistreetbets, run_async=True)) dispatcher.add_handler( CommandHandler('popular_symbols', popular_symbols, run_async=True)) dispatcher.add_handler( CommandHandler('ps', popular_symbols, run_async=True)) dispatcher.add_handler(CommandHandler('bullbear', bullbear, run_async=True)) dispatcher.add_handler(CommandHandler('bb', bullbear, run_async=True)) dispatcher.add_handler( CommandHandler('stock_messages', stock_messages, run_async=True)) dispatcher.add_handler(CommandHandler('sm', stock_messages, run_async=True)) dispatcher.add_handler( CommandHandler('trending_symbols', trending_symbols, run_async=True)) dispatcher.add_handler( CommandHandler('ts', trending_symbols, run_async=True)) dispatcher.add_handler(CommandHandler('price', price, run_async=True)) dispatcher.add_handler(CommandHandler('p', price, run_async=True)) dispatcher.add_handler(CommandHandler('details', details, run_async=False)) dispatcher.add_handler(CommandHandler('d', details, run_async=False)) dispatcher.add_handler( CommandHandler('rsamoyedcoin', r_samoyed_coin, run_async=True)) dispatcher.add_handler( CommandHandler('rsc', r_samoyed_coin, run_async=True)) # ...and the error handler dispatcher.add_error_handler(error_handler, run_async=True) # Message handler # Keep track of which chats the bot is in dispatcher.add_handler( ChatMemberHandler(track_chats, ChatMemberHandler.MY_CHAT_MEMBER)) # Handle members joining/leaving chats. dispatcher.add_handler( ChatMemberHandler(greet_chat_members, ChatMemberHandler.CHAT_MEMBER)) # Unknown command. this handler must be added last. dispatcher.add_handler( MessageHandler(Filters.command, command_unknown, run_async=True)) # Job queue stuff job_queue = updater.job_queue job_queue.run_repeating(check_rise_fall_day, conf.JOBS['check_rise_fall_day']['interval_sec'], context=updater) bot_init(updater) # Start the Bot updater.start_polling(drop_pending_updates=True, allowed_updates=Update.ALL_TYPES) # 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()
def main(): updater = Updater( token=TELEGRAM, use_context=True, request_kwargs={ "read_timeout": 10, "connect_timeout": 10 }, ) dp = updater.dispatcher # group handlers dp.add_handler( ChatMemberHandler(group.chat_member_update, ChatMemberHandler.CHAT_MEMBER)) dp.add_handler( ChatMemberHandler(group.my_chat_member_update, ChatMemberHandler.MY_CHAT_MEMBER)) # thanks to https://t.me/dotvhs and https://t.me/twitface, both of them like regex (weird). # test: https://regex101.com/r/Amrm07/1 dp.add_handler( MessageHandler( Filters.regex(r"^/report\b|(^|\s)@admin[a-z_]{0,27}\b") & Filters.chat_type.groups, group.report, )) dp.add_handler( CommandHandler("reload_admins", group.reload_admins, Filters.chat_type.groups)) dp.add_handler( MessageHandler(Filters.status_update.new_chat_title, group.update_title)) dp.add_handler( MessageHandler(Filters.status_update.migrate, group.update_id)) # this is the administration mode where the bot can kick and restrict members dp.add_handler( CallbackQueryHandler(report_callback.ignore, pattern="report_ignore")) dp.add_handler( CallbackQueryHandler(report_callback.delete, pattern="report_del")) dp.add_handler( CallbackQueryHandler(report_callback.restrict, pattern="report_restrict")) dp.add_handler( CallbackQueryHandler(report_callback.ban, pattern="report_ban")) dp.add_error_handler(private.error_handler) # private handlers, basic setup dp.add_handler( CommandHandler("start", private.start, Filters.chat_type.private)) dp.add_handler( CommandHandler("settings", private.settings, Filters.chat_type.private)) dp.add_handler( CommandHandler("help", private.help_command, Filters.chat_type.private)) # private setting callbacks dp.add_handler( CallbackQueryHandler(private.select_group, pattern="settings")) dp.add_handler( CallbackQueryHandler(private.group_report, pattern="set_report")) dp.add_handler( CallbackQueryHandler(private.group_reply_confirmation, pattern="set_reply")) dp.add_handler( CallbackQueryHandler(private.group_mention, pattern="set_mention")) dp.add_handler( CallbackQueryHandler(private.group_administration, pattern="set_administration")) dp.add_handler( CallbackQueryHandler(private.group_link_back, pattern="set_linked_back")) dp.add_handler( CallbackQueryHandler(private.group_do_link, pattern="set_linked")) dp.add_handler(CallbackQueryHandler(private.group_link, pattern="set_link")) dp.add_handler(CallbackQueryHandler(private.back, pattern="set_back")) # private timeout/timeoff convs timeout_conv = ConversationHandler( entry_points=[ CommandHandler("timeout", private.timeout_command, Filters.chat_type.private), ], states={ private.TIMEOUT_REPLY: [ MessageHandler( Filters.text & (~Filters.command), private.timeout, ) ] }, fallbacks=[CommandHandler("cancel", private.cancel)], ) dp.add_handler(timeout_conv) timeoff_conv = ConversationHandler( entry_points=[ CommandHandler("timeoff", private.timeoff_command, Filters.chat_type.private) ], states={ private.TIMEOFF_REPLY: [ MessageHandler( Filters.text & (~Filters.command), private.timeoff, ) ] }, fallbacks=[CommandHandler("cancel", private.cancel)], ) dp.add_handler(timeoff_conv) dp.add_handler( CommandHandler("timeoff_del", private.timeoff_del, Filters.chat_type.private)) dp.add_handler( CommandHandler("cancel", private.cancel, Filters.chat_type.private)) # just for the sake of it (BLUE TEXT), do not use it in private dp.add_handler( CommandHandler("reload_admins", private.reload_admins, Filters.chat_type.private)) # registering to group member updates updater.start_polling(allowed_updates=[ Update.MESSAGE, Update.CHAT_MEMBER, Update.MY_CHAT_MEMBER, Update.CALLBACK_QUERY, ]) now = datetime.datetime.now() dt = ceil_dt(now, datetime.timedelta(minutes=30)) # temporary fix td = dt - now updater.job_queue.run_repeating( half_hourly, 60 * 30, first=td.total_seconds(), name="half-hourly", context={ "admins": {}, "date": now.strftime("%d.%m") }, ) updater.job_queue.run_daily(backup_job, datetime.time(12, 0, 0), name="Backup database") # set private commands dp.bot.set_my_commands( [ BotCommand("start", "Short greeting message"), BotCommand("settings", "change settings of administrated groups"), BotCommand("help", "Long help message"), BotCommand( "timeout", "set a timeout for some time between now and sometime in the next 24 hours", ), BotCommand( "timeoff", "Specifiy do not disturb times for each day of the week"), BotCommand("timeoff_del", "Delete yourself from the timeoff list"), BotCommand("cancel", "Cancel the current action"), ], scope=BotCommandScopeAllPrivateChats(), ) updater.idle()