我一直在做一个机器人,我用filters=Filters.private
作为start_command,然后在MessageHandler
中使用它,它是代码:
dp.add_handler(CommandHandler('start',start_command,filter = Filters.private))
dp.add_handler(MessageHandler(Filters.private,start_keyboard_answers))
它工作得很好,但是问题是我需要在第二个过滤器内制作另一个过滤器,并且代码应该像这样:
dp.add_handler(CommandHandler('start',start_command,filter = Filters.private)) dp.add_handler(MessageHandler(Filters.private,start_keyboard_answers,filters = Filters.private)) dp.add_handler(MessageHandler(Filters.private,start_keyboard_answers))
但是这是不可能的,第二行有两个过滤器 我该如何处理? 如果您想知道我在做什么,我会在此处放下完整的项目(我想在第二个键盘之后寻找其他按钮,就像我对第一个和第二个按钮所做的一样):
from telegram.ext import Updater, Filters, CommandHandler, MessageHandler
from telegram import ReplyKeyboardMarkup
BOT_TOKEN = ''
def start_command(update, context):
chat_id = update.message.chat.id
context.bot.send_message(
chat_id=chat_id,
text='Hey, welcome to Chocolate Coffee!'
)
keyboard = [
['Make an Order']
]
context.bot.send_message(
chat_id=chat_id,
text='How can I help you?',
reply_markup=ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True)
)
def start_keyboard_answers(update, context):
message_text = str(update.message.text)
if message_text.lower() == 'make an order':
update.message.reply_text(
text='Okay :)',
quote=True
)
keyboard = [
['breakfast'],
['coffee'],
['milkshake'],
['colddrink'],
['food'],
['mocktail'],
['icecream'],
['organic'],
['smoothi'],
['glossy'],
['tea']
]
chat_id = update.message.chat.id
context.bot.sendMessage(chat_id,"ok, then?",reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True))
message_text = str(update.message.text)
import pdb; pdb.set_trace()
if message_text.lower() == 'breakfast':
update.message.reply_text(
text='Okay :)',
quote=True
)
def main():
updater = Updater(token=BOT_TOKEN, use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler('start', start_command, filters=Filters.private))
dp.add_handler(MessageHandler(Filters.private, start_keyboard_answers))
updater.start_polling()
print('Started!')
updater.idle()
if __name__ == "__main__":
main()
答案 0 :(得分:2)
MessageHandler
的第一个参数是filters
我们可以使用按位运算符(&
-AND,|
-OR,~
-NOT)将多个过滤器链接在一起,并将其作为第一个参数传递。像这样
MessageHandler(filters = Filters.private & Filters.chat([ADMINS ID here]), callbacks = who_do_you_wanna_call_here)
或者简单地
MessageHandler(Filters.private & Filters.command, start_cmd_ck)
尽管从代码中可以看出,您需要ConversationHandler
才能与用户进行逐步对话。在这里查看example