Python telegram.ext.Filters.command() Examples

The following are 16 code examples of telegram.ext.Filters.command(). 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.Filters , or try the search function .
Example #1
Source File: telegram.py    From platypush with MIT License 7 votes vote down vote up
def run(self):
        # noinspection PyPackageRequirements
        from telegram.ext import MessageHandler, Filters

        super().run()
        telegram = self._plugin.get_telegram()
        dispatcher = telegram.dispatcher

        dispatcher.add_handler(MessageHandler(Filters.group, self._group_hook()))
        dispatcher.add_handler(MessageHandler(Filters.text, self._msg_hook(TextMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.photo, self._msg_hook(PhotoMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.video, self._msg_hook(VideoMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.contact, self._msg_hook(ContactMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.location, self._msg_hook(LocationMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.document, self._msg_hook(DocumentMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.command, self._command_hook()))

        self.logger.info('Initialized Telegram backend')
        telegram.start_polling()


# vim:sw=4:ts=4:et: 
Example #2
Source File: telegram.py    From platypush with MIT License 6 votes vote down vote up
def _command_hook(self):
        # noinspection PyUnusedLocal
        def hook(update, context):
            msg = update.effective_message
            m = re.match('\s*/([0-9a-zA-Z_-]+)\s*(.*)', msg.text)
            cmd = m.group(1).lower()
            args = [arg for arg in re.split('\s+', m.group(2)) if len(arg)]

            try:
                self._authorize(msg)
                self.bus.post(CommandMessageEvent(chat_id=update.effective_chat.id,
                                                  command=cmd,
                                                  cmdargs=args,
                                                  message=self._plugin.parse_msg(msg).output,
                                                  user=self._plugin.parse_user(update.effective_user).output))
            except PermissionError:
                pass

        return hook 
Example #3
Source File: maintenance.py    From NanoWalletBot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
	# Create the EventHandler and pass it your bot's token.
	if (proxy_url is None):
		updater = Updater(api_key, workers=64)
	else:
		updater = Updater(token=api_key, workers=64, request_kwargs={'proxy_url': proxy_url, 'urllib3_proxy_kwargs': {'username': proxy_user, 'password': proxy_pass}})

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

	# on noncommand i.e message - return not found
	dp.add_handler(MessageHandler(Filters.command, maintenance))
	dp.add_handler(MessageHandler(Filters.text, maintenance))
	
	# log all errors
	dp.add_error_handler(error)

	# Start the Bot
	#updater.start_polling()
	updater.start_webhook(listen='127.0.0.1', port=int(listen_port), url_path=api_key)
	updater.bot.setWebhook('https://{0}/{1}'.format(domain, api_key))
	# 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() 
Example #4
Source File: telegram_util.py    From bot with GNU General Public License v3.0 6 votes vote down vote up
def _unknown(self, update, context):
        """
        trap all others commands as unknown
        :return:
        """
        if self._check_authorized(update, context):
            context.bot.send_message(
                chat_id=update.message.chat_id,
                text="Sorry I don't understand that command",
            )
            context.bot.send_message(
                chat_id=update.message.chat_id,
                text=" Recognized actions are:\n"
                + "   - /start (initialize bot) \n"
                + "   - /report (a live report from the bot)\n"
                + "   - /stop (force stop the bot)\n",
            ) 
Example #5
Source File: locks.py    From SkittBot with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, command, callback, **kwargs):
        super().__init__(command, callback, **kwargs) 
Example #6
Source File: commands.py    From AmbroBot with GNU General Public License v3.0 5 votes vote down vote up
def default(bot, update):
    """If a user sends an unknown command, answer accordingly"""
    bot.send_message(
        chat_id=update.message.chat_id, text=random.choice(COMANDO_DESCONOCIDO)
    ) 
Example #7
Source File: commands.py    From AmbroBot with GNU General Public License v3.0 5 votes vote down vote up
def code(bot, update):
    """If a user sends an unknown command, answer accordingly"""
    REPO = 'https://github.com/Ambro17/AmbroBot'
    msg = (
        f"Here you can see my internals: {REPO}\n"
        "Don't forget to give it a ⭐️ if you like it!"
    )
    update.message.reply_text(msg, disable_web_page_preview=True) 
Example #8
Source File: cleaner.py    From EmiliaHikari with GNU General Public License v3.0 5 votes vote down vote up
def set_blue_text_must_click(update, context):
	chat = update.effective_chat  # type: Optional[Chat]
	user = update.effective_user  # type: Optional[User]
	message = update.effective_message  # type: Optional[Message]
	args = context.args

	conn = connected(context.bot, update, chat, user.id, need_admin=True)
	if conn:
		chat_id = conn
		chat_name = dispatcher.bot.getChat(conn).title
	else:
		if update.effective_message.chat.type == "private":
			send_message(update.effective_message, tl(update.effective_message, "Anda bisa lakukan command ini pada grup, bukan pada PM"))
			return ""
		chat_id = update.effective_chat.id
		chat_name = update.effective_message.chat.title

	if len(args) >= 1:
		val = args[0].lower()
		if val == "off" or val == "no":
			sql.set_cleanbt(chat_id, False)
			if conn:
				text = tl(update.effective_message, "Penghapus pesan biru telah di *non-aktifka*n di *{}*.").format(chat_name)
			else:
				text = tl(update.effective_message, "Penghapus pesan biru telah di *non-aktifkan*.")
			send_message(update.effective_message, text, parse_mode="markdown")

		elif val == "yes" or val == "ya" or val == "on":
			sql.set_cleanbt(chat_id, True)
			if conn:
				text = tl(update.effective_message, "Penghapus pesan biru telah di *aktifkan* di *{}*.").format(chat_name)
			else:
				text = tl(update.effective_message, "Penghapus pesan biru telah di *aktifkan*.")
			send_message(update.effective_message, text, parse_mode="markdown")

		else:
			send_message(update.effective_message, tl(update.effective_message, "Argumen tidak dikenal - harap gunakan 'yes', atau 'no'."))
	else:
		send_message(update.effective_message, tl(update.effective_message, "Pengaturan untuk penghapus pesan biru saat ini di {}: *{}*").format(chat_name, "Enabled" if sql.is_enable(chat_id) else "Disabled"), parse_mode="markdown") 
Example #9
Source File: bot.py    From vk-messages-bot with MIT License 5 votes vote down vote up
def __init__(self, tg_bot_token, vk_client_id):
        self.tg_bot_token = tg_bot_token
        self.poller = Poller()
        self.vk = Vk(vk_client_id)
        self.clients = Client.all_from_db()

        self.updater = Updater(token=tg_bot_token)
        dispatcher = self.updater.dispatcher

        start_command_handler = CommandHandler('start', self.start_command_callback)
        dispatcher.add_handler(start_command_handler)
        start_command_handler = CommandHandler('whoami', self.whoami_command_callback)
        dispatcher.add_handler(start_command_handler)
        start_command_handler = CommandHandler('pick', self.pick_command_callback)
        dispatcher.add_handler(start_command_handler)
        start_command_handler = CommandHandler('unpick', self.unpick_command_callback)
        dispatcher.add_handler(start_command_handler)
        start_command_handler = CommandHandler('details', self.details_command_callback)
        dispatcher.add_handler(start_command_handler)
        unknown_handler = MessageHandler(Filters.command, self.unknown_command_callback)
        dispatcher.add_handler(unknown_handler)
        message_handler = MessageHandler(Filters.text, self.message_callback)
        dispatcher.add_handler(message_handler)
        dispatcher.add_error_handler(self.error_callback)

        self.restore() 
Example #10
Source File: unknown_command.py    From tnt-village-bot with MIT License 5 votes vote down vote up
def on_unknown_command(update: Update, _):
    logger.info('%d: unknown command', update.effective_user.id)

    update.message.reply_html(Strings.UNKNOWN_COMMAND)


# this handler MUST be added to the bot after all other handlers has been added. Since
# plugins are loaded alphabetically, we are lucky this one is the last one right now 
Example #11
Source File: raiwalletbot.py    From NanoWalletBot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def restricted(func):
	@wraps(func)
	def wrapped(bot, update, *args, **kwargs):
		# extract user_id from arbitrary update
		try:
			user_id = update.message.from_user.id
		except (NameError, AttributeError):
			try:
				user_id = update.inline_query.from_user.id
			except (NameError, AttributeError):
				try:
					user_id = update.chosen_inline_result.from_user.id
				except (NameError, AttributeError):
					try:
						user_id = update.callback_query.from_user.id
					except (NameError, AttributeError):
						print("No user_id available in update.")
						return
		if user_id not in admin_list:
			print("Unauthorized access denied for {0}.".format(user_id))
			return
		return func(bot, update, *args, **kwargs)
	return wrapped


# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error. 
Example #12
Source File: locks.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, command, callback, **kwargs):
        super().__init__(command, callback, **kwargs) 
Example #13
Source File: main.py    From simple-forwarder-bot with MIT License 5 votes vote down vote up
def main():
    global dispatcher, updater, Token, Blacklist, admin
    load_config()
    updater = Updater(Token)
    dispatcher = updater.dispatcher
    fwd_text_handler = MessageHandler(Filters.all & (~Filters.command),
                                      read_text_message)
    ban_user_handler = CommandHandler('ban', ban_user)
    unban_user_handler = CommandHandler('unban', unban_user)
    callback_query_handler = CallbackQueryHandler(answer_session)
    dispatcher.add_handler(callback_query_handler)
    dispatcher.add_handler(fwd_text_handler)
    dispatcher.add_handler(ban_user_handler)
    dispatcher.add_handler(unban_user_handler)
    updater.start_polling() 
Example #14
Source File: locks.py    From tgbot with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, command, callback, **kwargs):
        super().__init__(command, callback, **kwargs) 
Example #15
Source File: rules_bot.py    From rules-bot with GNU Affero General Public License v3.0 4 votes vote down vote up
def main():
    config = configparser.ConfigParser()
    config.read('bot.ini')

    updater = Updater(token=config['KEYS']['bot_api'], use_context=True)
    dispatcher = updater.dispatcher

    global SELF_CHAT_ID
    SELF_CHAT_ID = f'@{updater.bot.get_me().username}'

    rate_limit_tracker_handler = MessageHandler(~Filters.command, rate_limit_tracker)

    start_handler = CommandHandler('start', start)
    rules_handler = CommandHandler('rules', rules)
    rules_handler_hashtag = MessageHandler(Filters.regex(r'.*#rules.*'), rules)
    docs_handler = CommandHandler('docs', docs)
    wiki_handler = CommandHandler('wiki', wiki)
    sandwich_handler = MessageHandler(Filters.regex(r'(?i)[\s\S]*?((sudo )?make me a sandwich)[\s\S]*?'),
                                      sandwich)
    off_on_topic_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...
    github_handler = MessageHandler(Filters.text, github)
    forward_faq_handler = MessageHandler(Filters.regex(r'(?i).*#faq.*'), forward_faq)

    dispatcher.add_handler(rate_limit_tracker_handler, group=-1)

    # Note: Order matters!
    taghints.register(dispatcher)
    dispatcher.add_handler(forward_faq_handler)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(rules_handler)
    dispatcher.add_handler(rules_handler_hashtag)
    dispatcher.add_handler(docs_handler)
    dispatcher.add_handler(wiki_handler)
    dispatcher.add_handler(sandwich_handler)
    dispatcher.add_handler(off_on_topic_handler)
    dispatcher.add_handler(github_handler)

    inlinequeries.register(dispatcher)
    dispatcher.add_error_handler(error)

    updater.start_polling()
    logger.info('Listening...')

    try:
        github_issues.set_auth(config['KEYS']['github_client_id'], config['KEYS']['github_client_secret'])
    except KeyError:
        logging.info('No github auth set. Rate-limit is 60 requests/hour without auth.')

    github_issues.init_issues(dispatcher.job_queue)

    updater.idle() 
Example #16
Source File: telegram_util.py    From bot with GNU General Public License v3.0 4 votes vote down vote up
def telegram_bot(self):
        """
        Funtion to initialize a telegram bot that you can talk to and control your InstaPy Bot
        :return:
        """
        if self.token == "":
            self.__logger.warning(
                "You need to set token for InstaPyTelegramBot to work"
            )
            return
        if self.telegram_username == "":
            self.__logger.warning(
                "You need to set telegram_username for InstaPyTelegramBot to work"
            )
            return
        if self.instapy_session is None:
            self.__logger.warning(
                "You need to set instapy_session for InstaPyTelegramBot to work"
            )
            return

        self._clean_web_hooks()

        if self.proxy is not None:
            updater = Updater(
                token=self.token,
                use_context=True,
                user_sig_handler=self.end,
                request_kwargs=self.proxy,
            )
        else:
            updater = Updater(
                token=self.token, use_context=True, user_sig_handler=self.end
            )
        self.__updater = updater

        dispatcher = updater.dispatcher
        self.__context = dispatcher
        dispatcher.add_error_handler(self._error_callback)
        start_handler = CommandHandler("start", self._start)
        dispatcher.add_handler(start_handler)
        report_handler = CommandHandler("report", self._report)
        dispatcher.add_handler(report_handler)
        report_handler = CommandHandler("stop", self._stop)
        dispatcher.add_handler(report_handler)
        unknown_handler = MessageHandler(Filters.command, self._unknown)
        dispatcher.add_handler(unknown_handler)
        updater.start_polling()
        if self.__chat_id is not None:
            # session was restored, send a message saying that instapy session is starting
            self.__context.bot.send_message(
                self.__chat_id, text="Telegram session restored, InstaPy starting\n"
            )