Python Telegram API 在尝试编辑消息媒体时引发无用的错误

Python Telegram API raises unhelpful error when trying to edit message media

我正在 python 中编写一个电报机器人程序,根据命令,每隔几秒就开始将我计算机上 window 的照片发送到聊天室。当然,我不希望聊天中充斥着照片,所以我想返回并编辑我使用 edit_media.

发送的第一条消息

目前我对命令的回调函数如下所示:

def callback(update: Update, context: CallbackContext):
    first = True
    while True:
        image = screenshot('Snake')     # Gets a screenshot of the window
        bytesio = io.BytesIO()
        image.save(bytesio, format='PNG')
        bytes_image = bytes(bytesio.getvalue())     # Convert to bytes object
        if first:       # First time send a full message 
            context.bot.send_photo(update.message.chat_id, bytes_image)
            first = False
        else:       
            update.message.edit_media(media=InputMediaPhoto(media=bytes_image)) # Edit the message with the next photo
        time.sleep(2)

当此函数运行时,第一条消息发送成功,但尝试编辑消息时出现错误: telegram.error.BadRequest: Message can't be edited

如何解决这个问题才能成功编辑图片?

错误的完整回溯是:

Traceback (most recent call last):
  File "C:\Users\...\telegram\ext\dispatcher.py", line 555, in process_update
    handler.handle_update(update, self, check, context)
  File "C:\Users\...\telegram\ext\handler.py", line 198, in handle_update
    return self.callback(update, context)
  File "C:\Users\...\TelegramGameHub\main.py", line 56, in snake
    update.message.edit_media(media=InputMediaPhoto(media=bytes_image))
  File "C:\Users\...\telegram\message.py", line 2016, in edit_media
    return self.bot.edit_message_media(
  File "C:\Users\...\telegram\bot.py", line 130, in decorator
    result = func(*args, **kwargs)
  File "C:\Users\...\telegram\bot.py", line 2723, in edit_message_media
    return self._message(
  File "C:\Users\...\telegram\ext\extbot.py", line 199, in _message
    result = super()._message(
  File "C:\Users\...\telegram\bot.py", line 332, in _message
    result = self._post(endpoint, data, timeout=timeout, api_kwargs=api_kwargs)
  File "C:\Users\...\telegram\bot.py", line 295, in _post
    return self.request.post(
  File "C:\Users\...\telegram\utils\request.py", line 354, in post
    result = self._request_wrapper('POST', url, fields=data, **urlopen_kwargs)
  File "C:\Users\...\telegram\utils\request.py", line 279, in _request_wrapper
    raise BadRequest(message)

问题是你的线路

update.message.edit_media(media=InputMediaPhoto(media=bytes_image))

不会编辑您发送的照片消息。它反而会尝试编辑最初触发回调的消息。

要保留您发送的消息,您需要执行类似

的操作
message = context.bot.send_photo(update.message.chat_id, bytes_image)

请注意,PTB 为这类事情提供了快捷方式。所以你可以将其缩写为

message = update.message.reply_photo(bytes_image)

这(几乎)等价。

现在您可以调用 message.edit_media(...) 来更新照片了。

另一件需要注意的事情是你的循环

while True:
   ...
   time.sleep(2)

正在阻塞。这意味着在输入函数 callback 后,您的机器人将不会处理任何其他更新。 (旁注,如果你知道 run_async 的作用:即使你 运行 这个回调是异步的,它也会阻塞一个工作线程,一旦足够的更新触发了这个回调,所有的工作线程被阻止,您的机器人将不再处理任何更新)

我强烈建议使用内置的 JobQueue for such things. See also the wiki page and the example


免责声明:我目前是 python-telegram-bot.

的维护者