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

如何获取Telegram聊天的chat_id?基于Pyrogram的技术咨询

获取Pyrogram可用的Telegram聊天ID方法

你遇到的问题是因为网页版控制台拿到的peer id和Pyrogram所需的原始整数ID格式不匹配,下面是几种可靠的获取方式:

方法1:通过Pyrogram的get_chat()直接获取

你可以通过聊天的用户名、公开链接或者已知昵称,调用get_chat()方法拿到完整的Chat对象,从中提取正确的ID:

from pyrogram import Client

# 替换成你的账号配置
app = Client(
    "my_session",
    api_id=123456,
    api_hash="your_api_hash"
)

async def fetch_chat_id():
    async with app:
        # 替换成目标聊天的用户名、群组链接(如https://t.me/mygroup)或频道名
        chat = await app.get_chat("my_group_username")
        print(f"正确的聊天ID: {chat.id}")

app.run(fetch_chat_id())

方法2:监听消息自动获取ID

运行一个简单的监听脚本,当你在目标聊天发消息时,脚本会自动打印当前聊天的ID:

from pyrogram import Client, filters

app = Client(
    "my_session",
    api_id=123456,
    api_hash="your_api_hash"
)

@app.on_message(filters.all)
async def log_chat_id(client, message):
    print(f"当前聊天ID: {message.chat.id}")
    # 打印一次后自动停止脚本,避免持续监听
    await app.stop()

app.run()

为什么网页版的peer id不能用?

Telegram网页版控制台返回的peer id是经过网页端处理后的格式,比如群聊的原始ID是负数(以-开头),但网页版可能显示为正数或带前缀的字符串,和Pyrogram要求的原始整数ID不兼容,直接使用就会触发ValueError: Peer id invalid错误。


内容的提问来源于stack exchange,提问作者Максим Юрченко

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 08:30:57