You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telegram Bot开发:如何实现标记消息为已读功能?

解决Telegram Bot标记消息为已读的问题

你的代码无法显示已读标记,核心问题是调用read_chat_history时传入了用户名,但这个方法需要的是聊天ID(整数类型)。Telegram API不支持用用户名作为该方法的参数,而且部分用户可能未设置用户名,会导致调用失败。

修改后的代码

app = Client(session_name, api_id, api_hash)

@app.on_message()
async def my_handler(client, message):
    await app.send_message(message.chat.id, "ok boss")
    # 使用聊天ID而非用户名调用read_chat_history
    await app.read_chat_history(message.chat.id)

app.run()

关键改动说明

  • 替换message.from_user.username为message.chat.id:message.chat.id是当前对话的唯一标识,不管是私人聊天还是群组都能正确识别,比用户名更可靠。
  • 如果仅针对私人聊天场景,也可以用message.from_user.id,但message.chat.id的兼容性更强。

修改后,机器人发送消息后会正确标记对话中的未读消息为已读,你就能看到已读对勾了。

内容的提问来源于stack exchange,提问作者Михаил Петров

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 14:20:22