【问题标题】:Python Telegram Bot get the bot to respond to messagePython Telegram Bot 让机器人响应消息
【发布时间】:2020-02-09 22:06:14
【问题描述】:

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

由于某种原因,我无法让它工作。我尝试了下面的代码,但它不起作用...我还发布了来自 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()

【问题讨论】:

    标签: python telegram telegram-bot python-telegram-bot


    【解决方案1】:

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

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

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

    相关文档:

    【讨论】:

      猜你喜欢
      • 2018-05-17
      • 1970-01-01
      • 2018-10-05
      • 2021-07-19
      • 2021-03-22
      • 2019-11-23
      • 2016-10-01
      • 2018-10-17
      • 2020-10-04
      相关资源
      最近更新 更多