首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >电报内嵌机器人按钮被卡住加载

电报内嵌机器人按钮被卡住加载
EN

Stack Overflow用户
提问于 2022-12-04 01:49:17
回答 1查看 11关注 0票数 0

我在做一个在线电报机器人。

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

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

我的问题是,现在机器人显示了inital消息和2个按钮,但是当我单击该按钮时,什么都不会发生。我相信这要归功于ConversationHandler州和它是如何设置

代码语言:javascript
运行
复制
 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。我希望当用户发送在inlinequery函数中写入的任何chat @botusername时启动它。

守则:

代码语言:javascript
运行
复制
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,但没有给出任何结果

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-12-04 10:01:49

这需要使用/start命令启动会话,这不是我想要的。

情况并非如此--您可以使用任何处理程序作为入口点。

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

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74672289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档