Pyrogram调用GetMessageReactionsList出现400 MSG_ID_INVALID错误排查
Pyrogram调用GetMessageReactionsList触发MSG_ID_INVALID错误的解决方法
问题描述
使用Pyrogram编写数据采集脚本时,部分消息触发400 MSG_ID_INVALID错误,未发现明确触发规律,怀疑和异步编程相关,但app.get_messages(chat_id, message.id)始终能正常获取对应消息。
原代码
from pyrogram import Client from pyrogram.raw.functions.messages import GetMessageReactionsList # configuration with open('config.txt', 'r') as f: api_id = f.readline().strip() api_hash = f.readline().strip() chat_id = int(f.readline().strip()) app = Client( "my_account", api_id=api_id, api_hash=api_hash ) async def collect_messages(): async with app: chat = await app.resolve_peer(peer_id=chat_id) async for message in app.get_chat_history(chat_id=chat_id, limit=1): message_id = message.id # always works fine print(await app.get_messages(chat_id, message.id)) # 400 MSG_ID_INVALID for some messages reactions = await app.invoke(GetMessageReactionsList(peer=chat, id=message.id, limit=10)) if __name__ == "__main__": app.run(collect_messages())
错误信息
pyrogram.errors.exceptions.bad_request_400.MsgIdInvalid: Telegram says: [400 MSG_ID_INVALID] - The message ID used in the peer was invalid (caused by "messages.GetMessageReactionsList")
问题原因
GetMessageReactionsList是Telegram底层Raw API,对参数兼容性要求更高:
- 手动提前调用
resolve_peer获取的peer对象,可能和当前消息所属的peer类型/格式不匹配(比如超级群、频道的peer结构差异); - 部分场景下(如转发消息、跨对话消息),
message.id是当前对话的显示ID,而非Raw API需要的原始消息ID; - 高层API
app.get_messages内部会自动处理消息ID与peer的映射、格式转换,而Raw API需要手动确保参数完全匹配。
解决方法
方法1:改用Pyrogram高层API(推荐)
Pyrogram的Message对象内置get_reactions()方法,已封装底层Raw API调用,自动处理参数兼容问题,无需手动处理peer和ID:
修改后的代码:
from pyrogram import Client # configuration with open('config.txt', 'r') as f: api_id = f.readline().strip() api_hash = f.readline().strip() chat_id = int(f.readline().strip()) app = Client( "my_account", api_id=api_id, api_hash=api_hash ) async def collect_messages(): async with app: async for message in app.get_chat_history(chat_id=chat_id, limit=1): # always works fine print(await app.get_messages(chat_id, message.id)) # 使用高层API获取反应,避免Raw API的兼容问题 reactions = await message.get_reactions(limit=10) print(reactions) if __name__ == "__main__": app.run(collect_messages())
方法2:兼容Raw API的调用方式
如果必须使用Raw API,需确保peer和消息ID完全匹配:
- 从当前
message对象中获取对应的peer,而非提前单独resolve; - 必要时使用
message.raw.id获取底层原始消息ID:
修改后的Raw API调用部分:
async for message in app.get_chat_history(chat_id=chat_id, limit=1): message_id = message.id print(await app.get_messages(chat_id, message.id)) # 从当前消息的chat获取正确的peer chat = await app.resolve_peer(message.chat.id) # 或直接使用message.raw.id尝试原始ID reactions = await app.invoke(GetMessageReactionsList(peer=chat, id=message.id, limit=10))
内容的提问来源于stack exchange,提问作者Milena
相关产品推荐
相关产品推荐

