首页 > 解决方案 > Python Telegram Bot 让机器人响应消息

问题描述

我目前正在使用python-telegram-bot库来制作电报机器人。我的问题是我试图让我的机器人在使用内联命令时做出响应。因此,当用户发送 bot 时@botname 'text',我希望将其存储'text'为 a string,然后让我的 bot 使用该变量发回一些东西。

出于某种原因,我无法让它工作。我尝试了下面的代码,但它不起作用......我还发布了来自 github 的示例,该示例有效但不是我想要的方式。

我的代码

def inlinequery(update, context):

"""Handle the inline query."""
 query = update.inline_query.query
 text = query.message_text
 print(text)
 update.message.reply_text(text)

示例代码

#Sends message when @botname is used
def inlinequery(update, context):

"""Handle the inline query."""
query = update.inline_query.query
results = [
    InlineQueryResultArticle(
        id=uuid4(),
        title="Caps",
        input_message_content=InputTextMessageContent(
            query.upper())),
    InlineQueryResultArticle(
        id=uuid4(),
        title="Bold",
        input_message_content=InputTextMessageContent(
            "*{}*".format(escape_markdown(query)),
            parse_mode=ParseMode.MARKDOWN)),
    InlineQueryResultArticle(
        id=uuid4(),
        title="Italic",
        input_message_content=InputTextMessageContent(
            "_{}_".format(escape_markdown(query)),
            parse_mode=ParseMode.MARKDOWN))]

update.inline_query.answer(results)


def main():
    # Get the dispatcher to register handlers
dp = updater.dispatcher
dp.add_handler(InlineQueryHandler(inlinequery))

# Start the Bot
updater.start_polling()

if __name__ == '__main__':
main()

标签: pythontelegramtelegram-botpython-telegram-bot

解决方案


您可以使用User内联查询的对象向他们发送消息。请记住,用户必须先与机器人开始私人聊天,然后机器人才能向他们发送消息。

我修改了你的尝试。它应该可以工作,但我还没有测试过:

def inlinequery(update, context):
    """Handle the inline query."""
    query = update.inline_query
    text = query.query
    print(text)
    query.from_user.send_message(text)

相关文档:


推荐阅读