本文整理匯總了Python中telegram.ext.Filters.command方法的典型用法代碼示例。如果您正苦於以下問題:Python Filters.command方法的具體用法?Python Filters.command怎麽用?Python Filters.command使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類telegram.ext.Filters
的用法示例。
在下文中一共展示了Filters.command方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _command_hook
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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
示例2: run
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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:
示例3: main
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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()
示例4: _unknown
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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",
)
示例5: __init__
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
def __init__(self, command, callback, **kwargs):
super().__init__(command, callback, **kwargs)
示例6: default
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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)
)
示例7: code
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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)
示例8: set_blue_text_must_click
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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")
示例9: __init__
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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()
示例10: on_unknown_command
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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
示例11: restricted
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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.
示例12: main
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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()
示例13: main
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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()
示例14: telegram_bot
# 需要導入模塊: from telegram.ext import Filters [as 別名]
# 或者: from telegram.ext.Filters import command [as 別名]
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"
)