Python telegram.ext.CommandHandler() Examples

The following are 30 code examples of telegram.ext.CommandHandler(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module telegram.ext , or try the search function .
Example #1
Source File: herokubotcp.py    From ptb-heroku-skeleton with MIT License 8 votes vote down vote up
def __init__(self, TOKEN, NAME):
        super(BotComm, self).__init__()
        self.TOKEN = TOKEN
        self.NAME=NAME
        self.bot = telegram.Bot(self.TOKEN)
        try:
            self.bot.setWebhook("https://{}.herokuapp.com/{}".format(self.NAME, self.TOKEN))
        except:
            raise RuntimeError("Failed to set the webhook")

        self.update_queue = Queue()
        self.dp = Dispatcher(self.bot, self.update_queue)

        self.dp.add_handler(CommandHandler("start", self._start))
        self.dp.add_handler(MessageHandler(Filters.text, self._echo))
        self.dp.add_error_handler(self._error) 
Example #2
Source File: Server.py    From CineMonster with Apache License 2.0 7 votes vote down vote up
def __init__(self):
        self.config_instance = self.config_init()
        updater = Updater(self.config_instance.TELEGRAM_BOT_KEY)
        dp = updater.dispatcher

        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            filename=self.config_instance.LOG_FILE
        )

        dp.add_handler(MessageHandler(
            [Filters.text], self.command_check_resps))
        dp.add_handler(CommandHandler("start", self.command_start))
        dp.add_handler(CommandHandler(
            "roll", self.command_roll, pass_args=True))
        dp.add_handler(CommandHandler("leaderboard", self.command_leaderboard))
        dp.add_error_handler(self.error)

        jq = updater.job_queue
        jq.put(self.update_all_timers, 1)

        self.logger.info("Started... ")

        updater.start_polling()
        updater.idle() 
Example #3
Source File: start.py    From server_monitor_bot with MIT License 6 votes vote down vote up
def main():
    logging_location = log_location + log_name
    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level= logging.INFO, filename= logging_location)
    logging.info("Bot server started")
    print(token_val)
    try:
        if token_val == "":
            raise ValueError("Not found")
        command_filter = CommandFilter()
        updater = Updater(token= token_val, use_context= True)
        dispatcher = updater.dispatcher
        start_handler = CommandHandler('start',start)
        command_message_handler = MessageHandler(command_filter, exec_command)
        dispatcher.add_handler(start_handler)
        dispatcher.add_handler(command_message_handler)
        logging.info("Successfully initialized handlers")
    except ValueError as ex:
        print('It seems your token is empty!')
        return
    except Exception as e:
        logging.warning("Error intializing handlers")
        logging.error(str(e))
    updater.start_polling() 
Example #4
Source File: ques_of_the_day.py    From superCodingBot with MIT License 6 votes vote down vote up
def __init__(self, mount_point, fallback):
        self.mount_point = mount_point
        self.conv_handler = ConversationHandler(
            entry_points=[CommandHandler('subscribe', self.subscribe)],
            allow_reentry=True,
            states={
                SUBSEL: [CallbackQueryHandler(self.subsel, pattern=r'\w*sub3\b', pass_user_data=True)],
                SUB: [CallbackQueryHandler(self.sub, pattern=r'\w*sub2\b', pass_user_data=True)]
            },
            fallbacks=[fallback]
        )
        self.conv_handler1 = ConversationHandler(
            entry_points=[CommandHandler('unsubscribe', self.unsubsel)],
            allow_reentry=True,
            states={
                UNSUB: [CallbackQueryHandler(self.unsub, pattern=r'\w*unsub4\b')]
            },
            fallbacks=[fallback]
        ) 
Example #5
Source File: update_rank_list.py    From superCodingBot with MIT License 6 votes vote down vote up
def __init__(self, mount_point, fallback):
        self.mount_point = mount_point
        self.fallback = fallback
        self.rating_obj = ratings.Rating()
        self.utility = Utility(mount_point)
        self.conv_handler = ConversationHandler(
            entry_points=[CommandHandler('update', self.updatesel)],
            allow_reentry=True,
            states={
                UPDA: [CallbackQueryHandler(self.updasel, pattern=r'\w*upd5\b')]
            },
            fallbacks=[fallback]
        ) 
Example #6
Source File: bot.py    From gdrivemirror_bot with GNU General Public License v3.0 6 votes vote down vote up
def main():
	updater = Updater(token=TOKEN, workers = 8)
	dispatcher = updater.dispatcher
	start_cmd = CommandHandler("start" , start)
	help_cmd = CommandHandler("help" , help)
	donate_cmd = CommandHandler("donate" , donate)
	dispatcher.add_handler(start_cmd)
	dispatcher.add_handler(help_cmd)
	dispatcher.add_handler(donate_cmd)
	if ADMIN_MODULE:
		extras.add_extra_commands(dispatcher)
	else:
		print("ADMIN_MODULE not found. (Won't effect the bot though.)")
		start_handler = MessageHandler((Filters.all) , start_bot)
		dispatcher.add_handler(start_handler)
	updater.start_polling() 
Example #7
Source File: codeforces.py    From superCodingBot with MIT License 6 votes vote down vote up
def __init__(self, mount_point, fallback):
        if not os.path.exists(mount_point + 'codeforces.json'):
            shutil.copy('codeforces.json', mount_point + 'codeforces.json')
        with open(mount_point + 'codeforces.json', 'r') as codeforces:
            self.qcf = json.load(codeforces)
        self.conv_handler10 = ConversationHandler(
            entry_points=[CommandHandler('randomcf', self.randomcf)],
            allow_reentry=True,
            states={
                QSELCF: [CallbackQueryHandler(self.qselcf, pattern=r'\w*cf1\b')]
            },
            fallbacks=[fallback]
        )

    # START OF CONVERSATION HANDLER FOR GETTING RANDOM QUESTION FROM CODEFORCES
    # FUNCTION TO GET INPUT ABOUT THE TYPE OF QUESTION FROM USER 
Example #8
Source File: telegram_main.py    From convai-bot-1337 with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, token):
        self._bot = telegram.Bot(token)
        self._updater = Updater(bot=self._bot)

        dp = self._updater.dispatcher
        dp.add_handler(CommandHandler("start", self._start_cmd))
        dp.add_handler(CommandHandler("reset", self._reset_cmd))
        dp.add_handler(CommandHandler("stop", self._reset_cmd))
        dp.add_handler(CommandHandler("help", self._help_cmd))
        dp.add_handler(CommandHandler("text", self._text_cmd))
        dp.add_handler(CommandHandler("evaluation_start", self._evaluation_start_cmd))
        dp.add_handler(CommandHandler("evaluation_end", self._evaluation_end_cmd))

        dp.add_handler(MessageHandler(Filters.text, self._echo_cmd))

        dp.add_handler(CallbackQueryHandler(self._eval_keyboard))
        dp.add_error_handler(self._error)

        self._users_fsm = {}
        self._users = {}
        self._text_and_qas = load_text_and_qas('data/squad-25-qas.json')
        self._text_ind = 0
        self._evaluation = {}
        self._eval_suggestions = None 
Example #9
Source File: competitions.py    From superCodingBot with MIT License 6 votes vote down vote up
def __init__(self, clist_user_name, clist_api_key, mount_point, bot, fallback):
        self.clist_user_name = clist_user_name
        self.clist_api_key = clist_api_key
        self.bot = bot
        self.ong = None
        self.upc = None
        self.mount_point = mount_point
        self.utility = ContestUtility(mount_point)
        self.jobstores = {
            'default': SQLAlchemyJobStore(url='sqlite:///' + mount_point + 'coders1.db')
        }
        self.schedule = BackgroundScheduler(jobstores=self.jobstores)
        self.schedule.start()
        self.conv_handler = ConversationHandler(
            entry_points=[CommandHandler('upcoming', self.upcoming)],
            allow_reentry=True,
            states={
                SCHED: [CallbackQueryHandler(self.remind, pattern=r"^[0-9]*$")]
            },
            fallbacks=[fallback]
        )
        self.conv_handler1 = ConversationHandler(
            entry_points=[CommandHandler('dontRemindMe', self.removeRemind)],
            allow_reentry=True,
            states={
                REMNOTI: [CallbackQueryHandler(self.remnoti, pattern=r'^.*notiplz.*$')]
            },

            fallbacks=[fallback]
        ) 
Example #10
Source File: admin.py    From superCodingBot with MIT License 6 votes vote down vote up
def __init__(self, mount_point, admin_list, fallback):
        self.admin_list = admin_list
        self.mount_point = mount_point
        self.utility = Utility(mount_point)
        self.conv_handler1 = ConversationHandler(
            entry_points=[CommandHandler('broadcast', self.broadcast)],
            allow_reentry=True,
            states={
                BDC: [MessageHandler(Filters.text, self.broadcast_message)]
            },
            fallbacks=[fallback]
        )
        self.conv_handler2 = ConversationHandler(
            entry_points=[CommandHandler('senddb', self.getDb)],
            allow_reentry=True,
            states={
                DB: [MessageHandler(Filters.document, self.db)]
            },
            fallbacks=[fallback]
        )

    # START OF ADMIN CONVERSATION HANDLER TO BROADCAST MESSAGE 
Example #11
Source File: telegrambot.py    From django-telegrambot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    logger.info("Loading handlers for telegram bot")
    
    # Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS)
    dp = DjangoTelegramBot.dispatcher
    # To get Dispatcher related to a specific bot
    # dp = DjangoTelegramBot.getDispatcher('BOT_n_token')     #get by bot token
    # dp = DjangoTelegramBot.getDispatcher('BOT_n_username')  #get by bot username
    
    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler([Filters.text], echo))

    # log all errors
    dp.add_error_handler(error)

    # log all errors
    dp.addErrorHandler(error) 
Example #12
Source File: daysandbox_bot.py    From daysandbox_bot with MIT License 6 votes vote down vote up
def register_handlers(dispatcher, mode):
    assert mode in ('production', 'test')

    dispatcher.add_handler(MessageHandler(
        Filters.status_update.new_chat_members, handle_new_chat_members
    ))
    dispatcher.add_handler(CommandHandler(
        ['start', 'help'], handle_start_help
    ))
    dispatcher.add_handler(CommandHandler('stat', handle_stat))
    dispatcher.add_handler(CommandHandler(
        ['daysandbox_set', 'daysandbox_get'], handle_set_get
    ))
    dispatcher.add_handler(RegexHandler(
        r'^/setlogformat ', handle_setlogformat, channel_post_updates=True
    ))
    dispatcher.add_handler(CommandHandler('setlog', handle_setlog))
    dispatcher.add_handler(CommandHandler('unsetlog', handle_unsetlog))
    dispatcher.add_handler(MessageHandler(
        Filters.all, partial(handle_any_message, mode), edited_updates=True
    )) 
Example #13
Source File: telegrambot.py    From django-telegrambot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    logger.info("Loading handlers for telegram bot")

    # Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS)
    dp = DjangoTelegramBot.dispatcher
    # To get Dispatcher related to a specific bot
    # dp = DjangoTelegramBot.getDispatcher('BOT_n_token')     #get by bot token
    # dp = DjangoTelegramBot.getDispatcher('BOT_n_username')  #get by bot username

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))

    dp.add_handler(CommandHandler("startgroup", startgroup))
    dp.add_handler(CommandHandler("me", me))
    dp.add_handler(CommandHandler("chat", chat))
    dp.add_handler(MessageHandler(Filters.forwarded , forwarded))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error) 
Example #14
Source File: bot.py    From welcomebot with GNU General Public License v2.0 6 votes vote down vote up
def main():
    # Create the Updater and pass it your bot's token.
    updater = Updater(TOKEN, workers=10, use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    dp.add_handler(CommandHandler("start", help))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("welcome", set_welcome))
    dp.add_handler(CommandHandler("goodbye", set_goodbye))
    dp.add_handler(CommandHandler("disable_goodbye", disable_goodbye))
    dp.add_handler(CommandHandler("lock", lock))
    dp.add_handler(CommandHandler("unlock", unlock))
    dp.add_handler(CommandHandler("quiet", quiet))
    dp.add_handler(CommandHandler("unquiet", unquiet))

    dp.add_handler(MessageHandler(Filters.status_update, empty_message))

    dp.add_error_handler(error)

    updater.start_polling(timeout=30, clean=True)
    updater.idle() 
Example #15
Source File: telegramrss.py    From RSS-to-Telegram-Bot with GNU General Public License v3.0 6 votes vote down vote up
def main():
    updater = Updater(token=Token)
    job_queue = updater.job_queue
    dp = updater.dispatcher

    dp.add_handler(CommandHandler("add", cmd_rss_add, pass_args=True))
    dp.add_handler(CommandHandler("help", cmd_help))
    dp.add_handler(CommandHandler("test", cmd_test, pass_args=True))
    dp.add_handler(CommandHandler("list", cmd_rss_list))
    dp.add_handler(CommandHandler("remove", cmd_rss_remove, pass_args=True))

    # try to create a database if missing
    try:
        init_sqlite()
    except sqlite3.OperationalError:
        pass
    rss_load()

    job_queue.run_repeating(rss_monitor, delay)

    updater.start_polling()
    updater.idle()
    conn.close() 
Example #16
Source File: telegramRSSbot.py    From RSS-to-Telegram-Bot with GNU General Public License v3.0 6 votes vote down vote up
def main():
    updater = Updater(token=Token)
    job_queue = updater.job_queue
    dp = updater.dispatcher

    dp.add_handler(CommandHandler("add", cmd_rss_add, pass_args=True))
    dp.add_handler(CommandHandler("help", cmd_help))
    dp.add_handler(CommandHandler("test", cmd_test, pass_args=True))
    dp.add_handler(CommandHandler("list", cmd_rss_list))
    dp.add_handler(CommandHandler("remove", cmd_rss_remove, pass_args=True))

    # try to create a database if missing
    try:
        init_sqlite()
    except sqlite3.OperationalError:
        pass
    rss_load()

    job_queue.run_repeating(rss_monitor, delay)

    updater.start_polling()
    updater.idle()
    conn.close() 
Example #17
Source File: bot.py    From ConvAI-baseline with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        self.history = {}

        self.updater = Updater(TOKEN)
        self.name = str(self).split(' ')[-1][:-1]

        self.dp = self.updater.dispatcher

        self.dp.add_handler(CommandHandler("start", start))
        self.dp.add_handler(CommandHandler("help", help))

        self.dp.add_handler(MessageHandler([Filters.text], echo))

        self.dp.add_error_handler(error)
        self.stories = StoriesHandler()
        logger.info('I\'m alive!') 
Example #18
Source File: bot.py    From bot-telegram-comentarios-xvideos with GNU General Public License v3.0 6 votes vote down vote up
def main():
    logging.basicConfig(
        filename='/var/log/bot-telegram-xvideos.log',
        level=logging.INFO,
        format='%(asctime)s %(levelname)s: %(message)s',
        datefmt='%m-%d-%Y %H:%M:%S')

    try:
        updater = Updater(os.environ['BOT_TELEGRAM_XVIDEOS_TOKEN'])
        dispatcher = updater.dispatcher

        dispatcher.add_handler(CommandHandler('start', start))
        dispatcher.add_handler(CommandHandler('comment', comment))

        updater.start_polling()

        print('Running!')

        updater.idle()

        print()
    except Exception as ex:
        logging.critical(f'{ex}') 
Example #19
Source File: __main__.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def main():
    test_handler = CommandHandler("test", test)
    start_handler = CommandHandler("start", start, pass_args=True)

    help_handler = CommandHandler("help", get_help)
    help_callback_handler = CallbackQueryHandler(help_button, pattern=r"help_")

    settings_handler = CommandHandler("settings", get_settings)
    settings_callback_handler = CallbackQueryHandler(settings_button, pattern=r"stngs_")

    donate_handler = CommandHandler("donate", donate)
    migrate_handler = MessageHandler(Filters.status_update.migrate, migrate_chats)

    # dispatcher.add_handler(test_handler)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(settings_handler)
    dispatcher.add_handler(help_callback_handler)
    dispatcher.add_handler(settings_callback_handler)
    dispatcher.add_handler(migrate_handler)
    dispatcher.add_handler(donate_handler)

    # dispatcher.add_error_handler(error_callback)

    if WEBHOOK:
        LOGGER.info("Using webhooks.")
        updater.start_webhook(listen="0.0.0.0",
                              port=PORT,
                              url_path=TOKEN)

        if CERT_PATH:
            updater.bot.set_webhook(url=URL + TOKEN,
                                    certificate=open(CERT_PATH, 'rb'))
        else:
            updater.bot.set_webhook(url=URL + TOKEN)

    else:
        LOGGER.info("Using long polling.")
        updater.start_polling(timeout=15, read_latency=4)

    updater.idle() 
Example #20
Source File: bot.py    From music-bot with GNU General Public License v3.0 5 votes vote down vote up
def main():
    u = Updater('YOUR-TOKEN')
    dp = u.dispatcher

    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(MessageHandler(Filters.text, music))

    u.start_polling()
    u.idle() 
Example #21
Source File: __main__.py    From python-aria-mirror-bot with GNU General Public License v3.0 5 votes vote down vote up
def main():
    fs_utils.start_cleanup()
    # Check if the bot is restarting
    if path.exists('restart.pickle'):
        with open('restart.pickle', 'rb') as status:
            restart_message = pickle.load(status)
        restart_message.edit_text("Restarted Successfully!")
        remove('restart.pickle')

    start_handler = CommandHandler(BotCommands.StartCommand, start,
                                   filters=CustomFilters.authorized_chat | CustomFilters.authorized_user)
    ping_handler = CommandHandler(BotCommands.PingCommand, ping,
                                  filters=CustomFilters.authorized_chat | CustomFilters.authorized_user)
    restart_handler = CommandHandler(BotCommands.RestartCommand, restart,
                                     filters=CustomFilters.owner_filter)
    help_handler = CommandHandler(BotCommands.HelpCommand,
                                  bot_help, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user)
    stats_handler = CommandHandler(BotCommands.StatsCommand,
                                   stats, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user)
    log_handler = CommandHandler(BotCommands.LogCommand, log, filters=CustomFilters.owner_filter)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(ping_handler)
    dispatcher.add_handler(restart_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(stats_handler)
    dispatcher.add_handler(log_handler)
    updater.start_polling()
    LOGGER.info("Bot Started!")
    signal.signal(signal.SIGINT, fs_utils.exit_clean_up) 
Example #22
Source File: bot.py    From Crypto_trading_robot with MIT License 5 votes vote down vote up
def handle(self, cmd, callback):
        self.__updater.dispatcher.add_handler(CommandHandler(cmd, callback))
        return self 
Example #23
Source File: banme.py    From vldc-bot with MIT License 5 votes vote down vote up
def add_banme(upd: Updater, handlers_group: int):
    logger.info("registering banme handlers")
    dp = upd.dispatcher
    dp.add_handler(CommandHandler("banme", banme), handlers_group) 
Example #24
Source File: core.py    From vldc-bot with MIT License 5 votes vote down vote up
def add_core(upd: Updater, core_handlers_group: int):
    logger.info("register smile-mode handlers")
    dp = upd.dispatcher
    dp.add_handler(CommandHandler("start", start), core_handlers_group)
    dp.add_handler(CommandHandler("help", help_), core_handlers_group) 
Example #25
Source File: tree.py    From vldc-bot with MIT License 5 votes vote down vote up
def add_tree(upd: Updater, handlers_group: int):
    logger.info("registering tree handlers")
    dp = upd.dispatcher
    dp.add_handler(CommandHandler("tree", tree), handlers_group) 
Example #26
Source File: __init__.py    From vldc-bot with MIT License 5 votes vote down vote up
def _add_version(upd: Updater, version_handlers_group: int):
    logger.info("register version handlers")
    dp = upd.dispatcher
    dp.add_handler(CommandHandler("version", _version,
                                  filters=admin_filter), version_handlers_group) 
Example #27
Source File: telegram.py    From macaw with MIT License 5 votes vote down vote up
def __init__(self, params):
        """
        A Telegram bot interface for Macaw.

        Args:
            params(dict): A dict of parameters. The params 'logger' and 'bot_token' are mandatory.
        """
        super().__init__(params)
        self.logger = self.params['logger']

        self.MAX_MSG_LEN = 1000  # maximum number of characters in each response message.
        self.MAX_OPTION_LEN = 30  # maximum number of characters in each clickable option text.

        # Starting the bot by creating the Updater.
        # Make sure to set use_context=True to use the new context based callbacks
        # If you don't have a bot_token, add 'botfather' to your personal Telegram account and follow the instructions
        # to get a token for your bot.
        self.updater = Updater(self.params['bot_token'], use_context=True)
        self.dp = self.updater.dispatcher

        # Telegram command handlers (e.g., /start)
        self.dp.add_handler(CommandHandler('start', self.start))
        self.dp.add_handler(CommandHandler('help', self.help))

        # Telegram message handlers
        self.dp.add_handler(MessageHandler(Filters.text, self.request_handler))
        self.dp.add_handler(MessageHandler(Filters.voice, self.voice_request_handler))
        self.dp.add_handler(CallbackQueryHandler(self.button_click_handler))

        # logging all errors
        self.dp.add_error_handler(self.error) 
Example #28
Source File: simple_commands.py    From mau_mau_bot with GNU Affero General Public License v3.0 5 votes vote down vote up
def register():
    dispatcher.add_handler(CommandHandler('help', help_handler))
    dispatcher.add_handler(CommandHandler('source', source))
    dispatcher.add_handler(CommandHandler('news', news))
    dispatcher.add_handler(CommandHandler('stats', stats))
    dispatcher.add_handler(CommandHandler('modes', modes)) 
Example #29
Source File: pr.py    From vldc-bot with MIT License 5 votes vote down vote up
def add_pr(upd: Updater, handlers_group: int):
    logger.info("registering PR handler")
    dp: Dispatcher = upd.dispatcher
    dp.add_handler(CommandHandler("pr", _pr), handlers_group) 
Example #30
Source File: since_mode.py    From vldc-bot with MIT License 5 votes vote down vote up
def add_since_mode(upd: Updater, handlers_group: int):
    logger.info("register since-mode handlers")
    dp = upd.dispatcher
    dp.add_handler(CommandHandler("since", since_callback), handlers_group)
    dp.add_handler(CommandHandler("since_list", since_list_callback), handlers_group)