电报内联Bot -按钮卡住加载



我正在制作一个嵌入式电报机器人。

bot应该通过任何聊天调用,所以我使用内联方法,但是bot现在使用一个会话流,需要通过使用/start命令启动会话,这不是我想要的。

用命令调用bot后,我设置用户应该看到消息1,然后点击一个按钮,将显示一个新的按钮选择和另一个消息。

我的问题是,现在机器人显示初始消息和2个按钮,但当我点击按钮什么都没有发生。我相信这是由于ConversationHandler状态和它的设置方式

conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', inlinequery)],
states={
FIRST: [
CallbackQueryHandler(one, pattern='^' + str(ONE) + '$'),
CallbackQueryHandler(two, pattern='^' + str(TWO) + '$'),
CallbackQueryHandler(three, pattern='^' + str(THREE) + '$'),
],
SECOND: [
CallbackQueryHandler(start_over, pattern='^' + str(ONE) + '$'),
CallbackQueryHandler(end, pattern='^' + str(TWO) + '$'),
],
},
fallbacks=[CommandHandler('start', inlinequery)],

基于此,它正在等待/start命令启动conv_handler。我希望它在用户发送任何聊天@botusername <命令时启动。它写在函数inlinequery中>

代码:

from datetime import datetime
from uuid import uuid4
import logging
import emojihash
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import (
Updater,
CommandHandler,
CallbackQueryHandler,
ConversationHandler,
CallbackContext,
)
from telegram.ext import InlineQueryHandler, CommandHandler, CallbackContext
from telegram.utils.helpers import escape_markdown
from telegram import InlineQueryResultArticle, ParseMode, InputTextMessageContent, Update
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)

TransactionDateTime: str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
TransactionNumber: int = 1
TotalTransactions:int = 1
EmojiCode: str = emojihash.eh1("unique password" , 5) #TODO: make more complex
Emojihash: str =emojihash.eh1("unique code",5)

FIRST, SECOND = range(2)
ONE, TWO, THREE, FOUR = range(4)
verified_message_2="message 2"
verified_message_1 = "Message 1 "
def inlinequery(update: Update, context: CallbackContext) -> None:
print("Inline hit!")
# print the inline query from the update.
query = update.inline_query.query
print("len(query):" + str(len(query)))
if len(query) > 0:
print("query[-1] == " "?: " + str(query[-1] == "?"))
print("query[-1] == " + query[-1])
#  len(query) > 1 and query[-1] == " "
if len(query) == 0 or query[-1] != ".":
print("Empty query, showing message to seller to type username of buyer")
results = [
InlineQueryResultArticle(
id="Noop",
title="title",
input_message_content=InputTextMessageContent("I don't know how to use this bot yet. I was supposed to type the username but clicked this button anyway. Give me a second to figure this out."),

)
]
update.inline_query.answer(results)
# else if the query ends with a period character:
elif len(query) > 1 and query[-1] == ".":
buyer_username = query
SellerUserName: str = update.inline_query.from_user.username
print("buyer_username:" + buyer_username)
EmojiCode: str = emojihash.eh1("unique password" + SellerUserName + str(update.inline_query.from_user.id), 5)
keyboard = [
[
InlineKeyboardButton(EmojiCode, callback_data=str(ONE)),
],
[
InlineKeyboardButton(Emojihash, callback_data=str(TWO)),
],
]
reply_markup = InlineKeyboardMarkup(keyboard)
context.bot.send_message(chat_id=update.inline_query.from_user.id,text=verified_message_1, reply_markup=reply_markup)

return FIRST
def start_over(update: Update, context: CallbackContext) -> int:
query = update.callback_query
logger.info("User clicked on button %s", query.data)
SellerUserName: str = update.inline_query.from_user.username
buyer_username = query
print("buyer_username:" + buyer_username)
EmojiCode: str = emojihash.eh1("unique password" + SellerUserName + str(update.inline_query.from_user.id), 5)
SellerUserName: str = update.inline_query.from_user.username
verified_message_1 = f"""message 1 """
query.answer()
keyboard = [
[
InlineKeyboardButton(EmojiCode, callback_data=str(ONE)),
],
[
InlineKeyboardButton(Emojihash, callback_data=str(TWO)),
],
]
reply_markup = InlineKeyboardMarkup(keyboard)
context.bot.send_message(chat_id=update.inline_query.from_user.id,text=verified_message_1, reply_markup=reply_markup)
return FIRST

def one(update: Update, context: CallbackContext) -> int:
query = update.callback_query
logger.info("User  clicked on button %s", query.data)


query.answer()
keyboard = [
[
InlineKeyboardButton(EmojiCode, callback_data=str(THREE)),
],
[
InlineKeyboardButton(Emojihash, callback_data=str(TWO)),
],
]
reply_markup = InlineKeyboardMarkup(keyboard)
query.edit_message_text(
text=verified_message_2, reply_markup=reply_markup
)

return FIRST

def two(update: Update, context: CallbackContext) -> int:
query = update.callback_query
logger.info("User clicked on button %s", query.data)
query.answer()
keyboard = [
[
InlineKeyboardButton("Yes", callback_data=str(ONE)),
],
[
InlineKeyboardButton("No", callback_data=str(TWO)),
],
]
reply_markup = InlineKeyboardMarkup(keyboard)
query.edit_message_text(
text="You clicked on the wrong code. Do you want to try again?", reply_markup=reply_markup
)
return SECOND

def three(update: Update, context: CallbackContext) -> int:
query = update.callback_query
logger.info("User clicked on button %s", query.data)
buyer_username = query
SellerUserName: str = update.inline_query.from_user.username
print("buyer_username:" + buyer_username)
SellerUserName: str = update.inline_query.from_user.username
query.answer()
keyboard = [
[
InlineKeyboardButton(text='Yes', url=f'https://t.me/{SellerUserName}'),
],
[
InlineKeyboardButton("No", callback_data=str(TWO)),
],
[            InlineKeyboardButton("Read Again", callback_data=str(ONE)),
],
]
reply_markup = InlineKeyboardMarkup(keyboard)
query.edit_message_text(
text=f"""With this you have confirmed you read the messages above.
Go back to chat with seller?""", reply_markup=reply_markup
)
return SECOND

def end(update: Update, context: CallbackContext) -> int:
query = update.callback_query
logger.info("User clicked on button %s", query.data)
query.answer()
query.edit_message_text(text="Process stopped")
return ConversationHandler.END
def main() -> None:
"""Run the bot."""
updater = Updater("TOKEN")

dispatcher = updater.dispatcher

conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', inlinequery)],
states={
FIRST: [
CallbackQueryHandler(one, pattern='^' + str(ONE) + '$'),
CallbackQueryHandler(two, pattern='^' + str(TWO) + '$'),
CallbackQueryHandler(three, pattern='^' + str(THREE) + '$'),
],
SECOND: [
CallbackQueryHandler(start_over, pattern='^' + str(ONE) + '$'),
CallbackQueryHandler(end, pattern='^' + str(TWO) + '$'),
],
},
fallbacks=[CommandHandler('start', inlinequery)],
)
# Add ConversationHandler to dispatcher that will be used for handling updates
dispatcher.add_handler(conv_handler)
dispatcher.add_handler(InlineQueryHandler(inlinequery))
# Start the Bot
updater.start_polling()
# Run the bot until you press 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()

if __name__ == '__main__':
main()

我尝试切换命令处理程序为InlineQueryHandler,但没有给出任何结果

要求通过使用/start命令开始对话,这不是我想要的。

事实并非如此——你可以使用任何处理程序作为入口点。

我尝试切换命令处理程序为InlineQueryHandler,但没有给出任何结果

这里有一个警告:ConversationHandlerper_chat设置默认为True,但InlineQuery没有链接到chat_id。如果您设置了per_chat=False,那么使用InlineQueryHandler作为入口点应该可以正常工作。有关per_*设置的更多信息,请参阅此处。


免责声明:我目前是python-telegram-bot的维护者。

最新更新