我正在尝试使用python-telegram-bot库开发自己的机器人。
我在使用ConversationHandler时遇到问题,可能是由于我不太了解如何使用它。
我想在机器人上放一个/ settings命令,当它被调用时,它会触发一个ConversationHandler。
这是一段代码片段,灵感来自其官方示例,该代码片段使ConversationHandler可以使用/ settings命令。
CHOOSING = range(1)
reply_keyboard = [['? Breaking News', '? News'], ['✅ Done']]
markup = ReplyKeyboardMarkup(reply_keyboard,one_time_keyboard=True)
settings_handler = ConversationHandler(
entry_points = [CommandHandler('settings', settings)],
states = {
CHOOSING: [MessageHandler(Filters.regex('^(? Breaking News)$'), modificaBreakingNews),
MessageHandler(Filters.regex('^(? News)$'),modificaLatestNews)]
},
fallbacks = [MessageHandler(Filters.regex('^✅ Done$'), save)]
)
然后,用户将获得几个设置选项并选择一个设置选项。
def modificaBreakingNews(update, context):
locale = update.message.from_user.language_code
keyboard = [
[InlineKeyboardButton("✅ Attiva", callback_data="modBreakingNews - True"),
InlineKeyboardButton("❌ Disattiva", callback_data="modBreakingNews - False")
]
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(translation['opzioniBreakingNews']['it'] if locale == 'it' else translation['opzioniBreakingNews']['en'], reply_markup=reply_markup)
def modificaLatestNews(update, coontext):
locale = update.message.from_user.language_code
keyboard = [
[InlineKeyboardButton("?? " + translation['primaSquadra']['it'] if locale == 'it' else translation['primaSquadra']['en'], callback_data="modLatestNews - First Team"),
InlineKeyboardButton("? " + translation['settGiovanile']['it'] if locale == 'it' else translation['settGiovanile']['en'], callback_data="modLatestNews - Youngsters"),
InlineKeyboardButton("?? " + translation['tutteNews']['it'] if locale == 'it' else translation['tutteNews']['en'] , callback_data="modLatestNews - All")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(translation['opzioniLatestNews']['it'] if locale == 'it' else translation['opzioniLatestNews']['en'], reply_markup=reply_markup)
def save(update,context):
locale = update.effective_user.language_code
update.effective_message.reply_text(translation['modificheOK']['it'] if locale == 'it' else translation['modificheOK']['en'])
return ConversationHandler.END
def gestore_callback(update, context):
data = update.callback_query.data.split(" - ")
dataToSend = {"idTelegram":update.effective_user.id, "intent":"", "confidenza": 0, "command": True}
print(dataToSend)
if data[0] == "modBreakingNews":
dataToSend["newPreference"] = data[1] == 'True'
print(dataToSend)
result = requests.post("http://localhost:8000/user/preferences/breaking", data=dataToSend)
elif data[0] == "modLatestNews":
dataToSend["newPreference"] = data[1]
result = requests.post("http://localhost:8000/user/preferences/news", data=dataToSend)
return save(update,context)
此后,修改后的设置将保存在我的后端,并且理想情况下,我希望ReplyKeyboard消失,直到再次触发/ setting命令为止。 这不会发生,因为当我想再次召唤/ settings时,不再触发该命令
我想念什么?当然,ConversationHandler和callbackhandler都已初始化并分配给调度程序对象。