Python Telegram Bot 让机器人响应消息



我目前正在使用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()

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

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

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

相关文档:

  • InlineQuery.user
  • User.send_message

最新更新