def main(): if 'TELEGRAM_TOKEN' not in os.environ: logging.error('You need to set the environment variable "TELEGRAM_TOKEN"') return sys.exit(-1) updater = Updater(token=os.environ.get('TELEGRAM_TOKEN'), use_context=True) updater.bot.set_my_commands([ BotCommand('start', 'Returns a warming welcome message'), BotCommand('timezone', 'Changes the timezone of a group'), BotCommand('score', 'Prints the scores of everyone'), BotCommand('clock', 'Outputs the date of the received message'), BotCommand('my_id', 'Outputs your id which is internally used for score tracking'), ]) updater.dispatcher.add_handler(CommandHandler('timezone', handle_timezone_command)) updater.dispatcher.add_handler(CommandHandler('start', handle_start_command)) updater.dispatcher.add_handler(CommandHandler('score', handle_score_command)) updater.dispatcher.add_handler(CommandHandler('clock', handle_clock_command)) updater.dispatcher.add_handler(CommandHandler('my_id', handle_my_id_command)) updater.dispatcher.add_handler(CommandHandler('sprueche', handle_sprueche_command)) updater.dispatcher.add_handler(CommandHandler('sprueche_early', handle_sprueche_early_command)) updater.dispatcher.add_handler(CallbackQueryHandler(handle_inlinebutton_click)) updater.dispatcher.add_handler( MessageHandler(Filters.group & (Filters.text | Filters.sticker), handle_incoming_message)) updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, handle_added_to_group)) updater.dispatcher.add_handler(MessageHandler(Filters.status_update.left_chat_member, handle_removed_from_group)) updater.start_polling()
def test_de_json(self, bot): json_dict = {'command': self.command, 'description': self.description} bot_command = BotCommand.de_json(json_dict, bot) assert bot_command.command == self.command assert bot_command.description == self.description assert BotCommand.de_json(None, bot) is None
def test_build_available_commands_msg(): bot_commands = [ BotCommand("/command1", "Description1"), BotCommand("/command2", "Description2"), BotCommand("/command3", "Description3"), ] res = utils.build_available_commands_msg(bot_commands) assert res == ("Available commands:" "\n/command1 ➜ Description1" "\n/command2 ➜ Description2" "\n/command3 ➜ Description3")
def test_build_available_commands_msg(): bot_commands = [ BotCommand("/command1", "Description1"), BotCommand("/command2", "Description2"), BotCommand("/command3", "Description3"), ] res = utils.build_available_commands_msg(bot_commands) tc.assertEqual( res, "Available commands:" "\n/command1 ➜ Description1" "\n/command2 ➜ Description2" "\n/command3 ➜ Description3")
def add_commands(up: Updater): """Adds the list of commands with their description to the bot Args: up (Updater): supplyed Updater """ commands = [ BotCommand("start", "starts the bot"), BotCommand("help ", "help message and list of commands"), BotCommand("list ", "shows who the specified user is following"), BotCommand("count ", "shows how many users each user follows"), BotCommand("remove ", "removes all database records of the specified user"), ] up.bot.set_my_commands(commands=commands)
def test_equality(self, proximity_alert_triggered): a = proximity_alert_triggered b = ProximityAlertTriggered(User(1, "John", False), User(2, "Doe", False), 42) c = ProximityAlertTriggered(User(3, "John", False), User(2, "Doe", False), 42) d = ProximityAlertTriggered(User(1, "John", False), User(3, "Doe", False), 42) e = ProximityAlertTriggered(User(1, "John", False), User(2, "Doe", False), 43) f = BotCommand("start", "description") assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e) assert a != f assert hash(a) != hash(f)
def test_equality(self, proximity_alert_triggered): a = proximity_alert_triggered b = ProximityAlertTriggered(User(1, 'John', False), User(2, 'Doe', False), 42) c = ProximityAlertTriggered(User(3, 'John', False), User(2, 'Doe', False), 42) d = ProximityAlertTriggered(User(1, 'John', False), User(3, 'Doe', False), 42) e = ProximityAlertTriggered(User(1, 'John', False), User(2, 'Doe', False), 43) f = BotCommand('start', 'description') assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e) assert a != f assert hash(a) != hash(f)
def ready_poepbot(): poep_bot = Bot(token=Config.AUTH_TOKEN, defaults=Config.DEFAULTS, request=Config.REQUEST) updater = Updater(bot=poep_bot, use_context=True) commands = [] for command in command_handlers.no_param_handlers: this_chandler = CommandHandler(command=command.__name__, callback=command) this_prhandler = PrefixHandler('!', command=command.__name__, callback=command) updater.dispatcher.add_handler(this_prhandler) updater.dispatcher.add_handler(this_chandler) description = command_handlers.function_description_dict.get( command.__name__) commands.append( BotCommand(command=command.__name__, description=description)) updater.dispatcher.add_handler( conversation_handlers.input_conversation_handler()) poep_bot.set_my_commands(commands=commands) updater.start_polling()
def get_our_bot_commands(): bot_commands: List[BotCommand] = [] for command in AVAILABLE_COMMANDS: new_bot_command = BotCommand(command['name'], command['description']) bot_commands.append(new_bot_command) return bot_commands
def test_set_and_get_my_commands(self, bot): commands = [ BotCommand('cmd1', 'descr1'), BotCommand('cmd2', 'descr2'), ] bot.set_my_commands([]) assert bot.get_my_commands() == [] assert bot.commands == [] assert bot.set_my_commands(commands) for bc in [bot.get_my_commands(), bot.commands]: assert len(bc) == 2 assert bc[0].command == 'cmd1' assert bc[0].description == 'descr1' assert bc[1].command == 'cmd2' assert bc[1].description == 'descr2'
def _update_command_list(): """Updates the bot command list at the startup of the bot.""" commands_str = """ create_queue - <queue name> Creates a new queue delete_queue - <queue name> Deletes the queue add_me - <queue name> Adds you to the queue remove_me - <queue name> Removes you from the queue skip_me - <queue name> Moves you down in the queue next - <queue name> Notifies next person in the queue and moves queue down show_queues - Shows all created queues show_members - <queue name> Resends queue message notify_all - Enables\\disables pinning the queues help - Shows description about_me - Detailed info about the bot report - [Description] report an error to the developer """ command_name: str description: str commands_list = [ BotCommand(command_name.strip(), description.strip()) for command_str in commands_str.split('\n') if command_str.strip() for (command_name, description) in (command_str.split('-'), ) ] bot.set_my_commands(commands_list) logger.info('The commands list was updated.')
def get_command(): return [ BotCommand('pdbal', 'Check your bank account!'), ('pddaily', 'Claim your daily coins!'), ('pddaily', 'Collect your daily coins!'), ('pdinv', 'Check your current inventory!') ]
def get_command(): return [ BotCommand( 'pdwork', 'Submit your work. You will either get rewarded or punished depending on your work quality.' ) ]
def set_commands(self): bot = self.bot commands_raw = [{ 'command': 'start', 'description': 'Начать общение с ботом' }] bot.set_my_commands([BotCommand(**comm) for comm in commands_raw])
def add_handler(dp: Dispatcher): dp.add_handler(CommandHandler('gamestart24', start)) dp.add_handler(CommandHandler('gameq', question)) dp.add_handler(CommandHandler('gameend24', end)) dp.add_handler(CommandHandler('gamerules', rules)) dp.add_handler(CommandHandler('gamel', List_Lifetime_Stats)) dp.add_handler( MessageHandler( Filters.text & (~Filters.command) & Filters.chat_type.groups, proc_text)) return [ BotCommand('gamestart24', '开始一个24点游戏'), BotCommand('gameq', '查询当前进行中的24点游戏'), BotCommand('gameend24', '结束当前进行的游戏'), BotCommand('gamerules', '查询24点的游戏规则'), BotCommand('gamel', '查询总排行榜') ]
def add_commands(up: Updater): """Adds the list of commands with their description to the bot Args: up (Updater): supplyed Updater """ commands = [ BotCommand("start", "presentazione iniziale del bot"), BotCommand("create", "avvia il processo di creazione dell'immagine"), BotCommand("cancel ", "annulla la procedura in corso e resetta il bot"), BotCommand("help ", "funzionamento e scopo del bot"), BotCommand( "settings", "modifica vari parametri utilizzati nella creazione dell'immagine") ] up.bot.set_my_commands(commands=commands)
def test_equality(self): a = BotCommand('start', 'some description') b = BotCommand('start', 'some description') c = BotCommand('start', 'some other description') d = BotCommand('hepl', 'some description') e = Dice(4, 'emoji') assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
def test_equality(self): a = BotCommand("start", "some description") b = BotCommand("start", "some description") c = BotCommand("start", "some other description") d = BotCommand("hepl", "some description") e = Dice(4, "emoji") assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
def ready_hhpc_bot(): hhpc_bot = Bot(token=Config.HHPC_TOKEN, defaults=Config.DEFAULTS, request=Config.REQUEST) updater = Updater(bot=hhpc_bot, use_context=True) insultees = [member.strip() for member in Config.MEMBERS.split(',')] for name in insultees: updater.dispatcher.add_handler( CommandHandler(command=name, callback=command_handlers.send_insult)) updater.dispatcher.add_handler( CommandHandler(command='insult', callback=command_handlers.insult)) updater.dispatcher.add_handler( CommandHandler(command='adjekratje', callback=command_handlers.adje_kratje)) updater.dispatcher.add_handler( CommandHandler(command='kratjes', callback=command_handlers.kratjes)) commands = [] commands.append( BotCommand(command='voornaam', description='Beledig iemand, bv: /Adolf ')) commands.append( BotCommand( command='insult', description='Voeg een nieuwe belediging toe aan de database')) commands.append( BotCommand(command='kratjes', description='Overzicht van alle onzinnige weddenschappen')) commands.append( BotCommand( command='adjekratje', description= 'Voeg weddenschap toe, -s --stake "inzet", -b --better "de wedder", -d --date "tot wanneer in yyyy-mm-dd"\n' 'voorbeeld: /adjekratje rutte liegt 100 keer -b henk -s 1 kratje -d 2020-01-01' )) updater.dispatcher.add_handler( conversation_handlers.input_conversation_handler()) hhpc_bot.set_my_commands(commands=commands) updater.start_polling()
def add_dispatcher(dp: Dispatcher): guess_handler = CommandHandler('guess', guess_start) # 将所有guess_start开头的按钮处理交由guess_start_callback来进行 dp.add_handler( CallbackQueryHandler(guess_start_callback, pattern="^guess_start:[A-Za-z0-9_]*")) dp.add_handler( CallbackQueryHandler(guess_play_callback, pattern="^guess_play:[A-Za-z0-9_]*")) dp.add_handler(guess_handler) return [BotCommand('guess', '猜大小')]
def runTgBot(commands_dict): help_msg = "" def start(u, c): c.bot.send_message(chat_id=u.effective_chat.id, text=""" Welcome! Get started!""" + "\n\n" + help_msg) def unknown(u, c): c.bot.send_message(chat_id=u.effective_chat.id, text="_Unknown Command!_", parse_mode='Markdown') updater = Updater(token=API_KEY, persistence=my_persistence, use_context=True) dispatcher = updater.dispatcher commands_dict = [ { "cmd": "start", "func": start, "desc": "Shows the Instructions" }, { "cmd": "help", "func": start, "desc": "Shows the Instructions" }, ] + commands_dict descriptions = [] for cmd in commands_dict: handlers = CommandHandler(cmd['cmd'], cmd['func']) dispatcher.add_handler(handlers) descriptions.append(BotCommand(cmd['cmd'], cmd['desc'])) help_msg += f"/{cmd['cmd']}: {cmd['desc']}\n" echo_handler = MessageHandler(Filters.text & (~Filters.command), bridge) dispatcher.add_handler(MessageHandler(Filters.photo, image_handler)) dispatcher.add_handler(echo_handler) updater.dispatcher.add_handler(CallbackQueryHandler(button)) dispatcher.add_handler(MessageHandler(Filters.command, unknown)) updater.bot.set_my_commands(descriptions) aps_logger = logging.getLogger('apscheduler') aps_logger.setLevel(logging.ERROR) job_queue = updater.job_queue job_queue.run_repeating(fetch_irc_updates, timedelta(seconds=.1)) updater.start_polling() updater.idle()
def get_commands() -> List[BotCommand]: commands_path = Path(__file__).absolute().parent.with_name( "commands-botfather.md") commands_info = commands_path.read_text("utf8") commands = [] for line in commands_info.splitlines(): if line.strip().startswith("-"): line = re.sub(r"- \/([\w]+)", r"\1", line).replace("\\_", "_") command, description = re.split(" - ", line, maxsplit=1) commands.append(BotCommand(command, description)) return commands
def main(): if not updater.bot.can_read_all_group_messages: print("ERROR: the bot works only if \"privacy mode\" is disabled. This is to make sure the bot receives " "commands such as \"!kick\" or \"!kickme\" even when it's not an administrator " "(more info at https://core.telegram.org/bots#privacy-mode).\nPlease disable it from " "@BotFather using the /setprivacy command") return kick_re = re.compile(r"^!kick(?:$|\b).*", re.IGNORECASE) kickme_re = re.compile(r"^!kickme(?:$|\b).*", re.IGNORECASE) on_supergroups_deeplink_handler = CommandHandler("start", on_supergroups_deeplink, Filters.regex("supergroups")) on_start_command_handler = CommandHandler(["start", "help"], on_start_command, Filters.chat_type.private) on_kick_command_handler = MessageHandler(Filters.chat_type.groups & Filters.reply & Filters.regex(kick_re), on_kick_command) on_kickme_command_handler = MessageHandler(Filters.chat_type.groups & Filters.regex(kickme_re), on_kickme_command) on_new_chat_member_handler = MessageHandler(Filters.status_update.new_chat_members, on_new_chat_member) on_migrate_handler = MessageHandler(Filters.status_update.migrate, on_migrate) updater.dispatcher.add_handler(on_supergroups_deeplink_handler) # needs to be added before "on_start_command_handler" updater.dispatcher.add_handler(on_start_command_handler) updater.dispatcher.add_handler(on_kick_command_handler) updater.dispatcher.add_handler(on_kickme_command_handler) updater.dispatcher.add_handler(on_new_chat_member_handler) updater.dispatcher.add_handler(on_migrate_handler) updater.bot.set_my_commands([]) # make sure the bot doesn't have any command set... updater.bot.set_my_commands( # ...then set the scope for private chats [ BotCommand("start", "get the welcome message"), BotCommand("help", "get the help message") ], scope=BotCommandScopeAllPrivateChats() ) allowed_updates = ["message"] # https://core.telegram.org/bots/api#getupdates logger.info("running as @%s, allowed updates: %s", updater.bot.username, allowed_updates) updater.start_polling(drop_pending_updates=True, allowed_updates=allowed_updates)
def _setup_commands(self): # Set commands in the Bot commands = [ BotCommand('start', 'start bot interaction'), BotCommand('stop', 'stop interacting with the bot'), BotCommand('edit_event', 'update event settings') ] self._bot.set_my_commands(commands) # Register handler for each command handlers = { 'start': self._start, 'stop': self._stop, 'edit_event': self._edit_event_start } self._updater = Updater(self._token) dispatcher = self._updater.dispatcher for c in commands: dispatcher.add_handler( CommandHandler(c.command, handlers[c.command], filters=self._userfilter)) # Add handler for edit_event actions dispatcher.add_handler( CallbackQueryHandler(self._edit_event, pattern='^edit_event/.*$'))
def main() -> None: # initialise bot and set commands bot = Bot(token=TELEGRAM_BOT_TOKEN) bot.set_my_commands([ BotCommand(command='start', description='start the bot session'), BotCommand(command='alert', description='enable alerts on new slots'), BotCommand(command='help', description='provide help on how to use the bot'), BotCommand(command='resume', description='enable alerts on new slots'), BotCommand(command='pause', description='disable alerts on new slots'), BotCommand(command='pincode', description='change pincode'), BotCommand(command='age', description='change age preference'), ]) # connect and create tables db.connect() db.create_tables([User, ]) # create the required index # TODO: # User.add_index(User.enabled, User.pincode, # where=((User.enabled == True) & (User.pincode.is_null(False)))) # initialise the handler updater = Updater(TELEGRAM_BOT_TOKEN) # Add handlers updater.dispatcher.add_handler(CommandHandler("start", start)) updater.dispatcher.add_handler(CommandHandler("help", help_command)) updater.dispatcher.add_handler(CommandHandler("alert", setup_alert_command)) updater.dispatcher.add_handler(CommandHandler("resume", setup_alert_command)) updater.dispatcher.add_handler(CommandHandler("pause", disable_alert_command)) updater.dispatcher.add_handler(CommandHandler("age", age_command)) updater.dispatcher.add_handler(CommandHandler("pincode", pincode_command)) updater.dispatcher.add_handler(CommandHandler("delete", delete_cmd_handler)) updater.dispatcher.add_handler(CallbackQueryHandler(set_age_preference, pattern=AGE_BUTTON_REGEX)) updater.dispatcher.add_handler(CallbackQueryHandler(cmd_button_handler, pattern=CMD_BUTTON_REGEX)) updater.dispatcher.add_handler(MessageHandler(Filters.regex( re.compile(PINCODE_PREFIX_REGEX, re.IGNORECASE)), set_pincode)) updater.dispatcher.add_handler(MessageHandler(Filters.regex( re.compile(DISABLE_TEXT_REGEX, re.IGNORECASE)), disable_alert_command)) updater.dispatcher.add_handler(MessageHandler(~Filters.command, default)) updater.dispatcher.add_error_handler(error_handler) # launch two background threads, one for slow worker (age group 45+) and another for fast one (age group 18+) threading.Thread(target=frequent_background_worker).start() threading.Thread(target=periodic_background_worker).start() # Start the Bot updater.start_polling() # block it, baby updater.idle()
def main(): commands = [ BotCommand("start", "Start Bot"), BotCommand("list_hostgroup", "List all host groups"), BotCommand("list_hosts", "List all host in a group"), BotCommand("list_problems_by_host", "List problems by host"), BotCommand("detail_items_with_problem_id", "Detail items related to a problem"), BotCommand("detail_items_with_graph", "Send all graphs related to problem"), BotCommand("send_graph", "Get Graph by item ID") ] set_commands = bot.set_my_commands(commands=commands) return set_commands
def test_equality(self): a = Dice(3, '🎯') b = Dice(3, '🎯') c = Dice(3, '🎲') d = Dice(4, '🎯') e = BotCommand('start', 'description') assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
def test_equality(self): a = Dice(3, "🎯") b = Dice(3, "🎯") c = Dice(3, "🎲") d = Dice(4, "🎯") e = BotCommand("start", "description") assert a == b assert hash(a) == hash(b) assert a != c assert hash(a) != hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
def set_up_commands(bot_instance: Bot) -> None: langs_with_commands: Dict[str, Dict[str, str]] = { 'en': { 'start': 'Start django bot 🚀', 'stats': 'Statistics of bot 📊', 'admin': 'Show admin info ℹ️', 'ask_location': 'Send location 📍', 'broadcast': 'Broadcast message 📨', 'export_users': 'Export users.csv 👥', }, 'es': { 'start': 'Iniciar el bot de django 🚀', 'stats': 'Estadísticas de bot 📊', 'admin': 'Mostrar información de administrador ℹ️', 'ask_location': 'Enviar ubicación 📍', 'broadcast': 'Mensaje de difusión 📨', 'export_users': 'Exportar users.csv 👥', }, 'fr': { 'start': 'Démarrer le bot Django 🚀', 'stats': 'Statistiques du bot 📊', 'admin': "Afficher les informations d'administrateur ℹ️", 'ask_location': 'Envoyer emplacement 📍', 'broadcast': 'Message de diffusion 📨', "export_users": 'Exporter users.csv 👥', }, 'ru': { 'start': 'Запустить django бота 🚀', 'stats': 'Статистика бота 📊', 'admin': 'Показать информацию для админов ℹ️', 'broadcast': 'Отправить сообщение 📨', 'ask_location': 'Отправить локацию 📍', 'export_users': 'Экспорт users.csv 👥', } } bot_instance.delete_my_commands() for language_code in langs_with_commands: bot_instance.set_my_commands( language_code=language_code, commands=[ BotCommand(command, description) for command, description in langs_with_commands[language_code].items() ] )
def add_handler(dp: Dispatcher): dp.add_handler(CommandHandler('smw', start)) dp.add_handler(CommandHandler('smend', end)) dp.add_handler(CommandHandler('sminfo', info)) dp.add_handler(CommandHandler('smchoose', vac)) dp.add_handler(CommandHandler('smnew', new)) dp.add_handler(CommandHandler('smrules', gamerules)) dp.add_handler( CallbackQueryHandler(callback, pattern="^story:[A-Za-z0-9_:]*")) return [ BotCommand('smnew', '开始一个故事接龙的游戏'), BotCommand('sminfo', '查询一个故事接龙的游戏的信息'), BotCommand('smchoose', '选择下一个接龙的人'), BotCommand('smw', '继续接龙'), BotCommand('smend', '结束一个故事接龙的游戏'), BotCommand('smrules', '查询一个故事接龙的游戏的规则') ]