简体   繁体   English

如何使用 Telegram 的 python bot API 编辑已发送的消息?

[英]How do I edit a sent message using Telegram's python bot API?

The documentation ( https://core.telegram.org/bots/api#editmessagetext ) says that I need to specify a message ID to edit, but I have no idea how to go about getting that message ID.文档 ( https://core.telegram.org/bots/api#editmessagetext ) 说我需要指定要编辑的消息 ID,但我不知道如何获取该消息 ID。

I've tried setting the ID as a variable:我试过将 ID 设置为变量:

import telepot
from telepot.namedTuple import InlineKeyboardMarkup, InlineKeyboardButton

messageEditID = bot.sendMessage(<location ID>, "Test", reply_markup=InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="Testing", callback_data="test"]]))['message_id']

because the POST data for such a message would be因为此类消息的 POST 数据将是

{"message_id":1140126,"chat":{"title":"<location name>","type":"supergroup","id":<location ID>},"date":1477960655,"from":{"username":"<bot username>","first_name":"<bot name>","id":<bot ID>},"text":"Test"}

and then calling it back based on the inline reply data然后根据内联回复数据回调

if msg['data'] == 'test':
    bot.editMessage(messageEditID, "Did it work?")

but it throws an Exception with the following message:但它会抛出一个带有以下消息的异常:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/telepot/__init__.py", line 738, in collector
    callback(item)
  File "testingStuff.py", line 150, in handle
    bot.editMessageText(messageEditID, "Does it work?")
  File "/usr/local/lib/python3.5/dist-packages/telepot/__init__.py", line 592, in editMessageText
    return self._api_request('editMessageText', _rectify(p))
  File "/usr/local/lib/python3.5/dist-packages/telepot/__init__.py", line 398, in _api_request
    return api.request((self._token, method, params, files), **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/telepot/api.py", line 131, in request
    return _parse(r)
  File "/usr/local/lib/python3.5/dist-packages/telepot/api.py", line 126, in _parse
    raise exception.TelegramError(description, error_code, data)
telepot.exception.TelegramError: ('Bad Request: Wrong inline message identifier specified', 400, {'description': 'Bad Request: Wrong inline message identifier specified', 'ok': False, 'error_code': 400})

It threw the same error when I tried to edit the message based on the response,当我尝试根据响应编辑消息时,它抛出了相同的错误,

if msg['data'] == 'test':
    msgID = msg['message']['message_id']
    bot.editMessageText(msgID, "OBOY")

since the data for an incoming Inline Reply is:因为传入的内联回复的数据是:

{'chat_instance': '112564336693044113',
 'data': 'test',
 'from': {'first_name': 'B(', 'id': <user ID>, 'username': '<username>'},
 'id': '852908411206280027',
 'message': {'chat': {'id': <chat ID>,
                      'title': 'We da bes',
                      'type': 'supergroup',
                      'username': '<chat username>'},
             'date': 1477961765,
             'from': {'first_name': 'Testing For James',
                      'id': <bot ID>,
                      'username': '<bot username>'},
             'message_id': 63180,
             'text': 'Test'}}

Can anyone help me figure out where I've gone wrong?谁能帮我弄清楚我哪里出错了?

Here is a simple example to edit a message without using telepot这是一个不使用telepot编辑消息的简单示例

Demo: Before edit After edited演示:编辑前 编辑

from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackContext
from telegram import Update
import logging

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)


def start(update: Update, context: CallbackContext) -> None:
    context.bot.send_message(chat_id=update.message.chat_id, text="hi")


def edit(update: Update, context: CallbackContext) -> None:
    context.bot.editMessageText(chat_id=update.message.chat_id,
                                message_id=update.message.reply_to_message.message_id, 
                                text="edited")


def main() -> None:
    updater = Updater("TOKEN")
    updater.dispatcher.add_handler(CommandHandler('start', start))
    updater.dispatcher.add_handler(CommandHandler('edit', edit))
    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()

Update: Telepot has a message_identifier method that you can call by setting the sendMessage method to a variable and then calling the message_identifier message更新: Telepot 有一个 message_identifier 方法,您可以通过将 sendMessage 方法设置为变量然后调用 message_identifier 消息来调用

sent = bot.sendMessage(9999999, "Testing")
edited = telepot.message_identifier(sent)
bot.editMessageText(edited, "Tested")

EDIT: In my answer i'm talking about python-telegram-bot and not about telepot so it's not relevant, sorry.编辑:在我的回答中,我说的是python-telegram-bot而不是telepot所以它不相关,抱歉。

You can only use the edit function if you are using messages with buttons (its called "InlineKeyboard").如果您使用带有按钮的消息(称为“InlineKeyboard”),则只能使用编辑功能。 Here is a example这是一个例子

暂无
暂无

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

相关问题 Python-telegram-bot:如何在电报 api 中通过机器人获取自定义编号的最新消息? - Python-telegram-bot: How can I get customized number latest message by bot in telegram api? 我可以使用 python 机器人删除我在电报上的 gc 中发送的每条消息吗? - Can I delete every message I've sent in a gc on telegram using a python bot? 如何使用带有 python selenium 的电报机器人发送消息 - How I can send message using telegram bot with python selenium 如何使用 python-telegram-bot API 在电报中查找第 th 条消息? - How to find the 𝘯th message in telegram with the python-telegram-bot API? 如何获取我通过 Python 使用 Telegram 机器人发送的消息的 ID? - How get id of the message I sent with my Telegram bot via Python? 如何使用电报Bot API使用python以编程方式创建垂直自定义键盘布局? - How do I programmatically create a vertical custom keyboard layout with python using the telegram bot api? 电报机器人。 如何在电报消息中打印 DataFrame? - Telegram bot. How do I print DataFrame in telegram message? Python-telegram-bot api &#39;update.message.date&#39; 返回错误的时间。 我该如何解决? - Python-telegram-bot api 'update.message.date' is returning the wrong time. how do i fix this? Telegram bot API编辑InlineKeyboard与python-telegram-bot无法正常工作 - Telegram bot API edit InlineKeyboard with python-telegram-bot not working Python Telegram Bot-如何更新我的机器人已发送的最后一条消息的文本 - Python Telegram Bot - How to update the text of the last message my bot has sent
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM