繁体   English   中英

获取 AttributeError: 'Update' object has no attribute 'send_message' 当我尝试使用 Telegram bot 发送消息时

[英]Getting an AttributeError: 'Update' object has no attribute 'send_message' when I try to send a message with Telegram bot

我收到 AttributeError: 'Update' object has no attribute 'send_message' 当我尝试发送消息时。 我知道“更新”class 没有“发送消息”属性,但我没有使用“更新”class。我使用的是“机器人”class,但我仍然收到完全相同的错误。

这是我的代码:

from telegram.ext import Updater, CommandHandler
from telegram import Bot

bot = Bot(token='TOKEN')

def start(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text="Hello")


updater = Updater(token='TOKEN')
dispatcher = updater.dispatcher
command_handler = CommandHandler('start', start)
dispatcher.add_handler(command_handler)

updater.start_polling()

这是错误;

bot.send_message(chat_id=update.message.chat_id, text="Hello")
AttributeError: 'Update' object has no attribute 'send_message'

尝试单独导入 Bot 库,但仍然没有任何效果。

可能会发生此错误,因为 send_message 方法在 Update 对象上不可用。 Update 对象是 python-telegram-bot 库提供的一个类,表示来自 Telegram API 的传入更新。 它没有 send_message 方法,因为它不负责发送消息——它仅用于表示从 API 收到的更新。

要使用 Telegram 机器人发送消息,您需要使用 python-telegram-bot 库提供的 Bot 对象。 Bot 对象有一个 send_message 方法,您可以使用它向用户或组发送消息。

以下是如何使用 send_message 方法的示例:

import telegram

bot = telegram.Bot(token='YOUR_BOT_TOKEN')

chat_id = 12345678  # Replace with the chat ID of the recipient
text = 'Hello, World!'

bot.send_message(chat_id=chat_id, text=text)

此代码将发送消息 Hello, World。 到 ID 为 12345678 的聊天室。

您需要从Telegram Botfather获取机器人令牌并将 YOUR_BOT_TOKEN 替换为您的实际机器人令牌才能使此代码正常工作。

我终于让它工作了! 您需要添加context参数而不是update参数

这是更新后的代码:

def start(bot, update):
bot.send_message(chat_id=update.message.chat_id, text="Hello")

start_handler = CommandHandler("start", start)
dispatcher.add_handler(start_handler)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM