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

Telethon脚本获取Telegram用户邀请关联报错求助与修复

问题排查与修复方案

错误原因分析

触发struct.error的核心原因是**GetExportedChatInvitesRequest的chat参数类型错误**:该参数要求传入整数类型的频道ID,或者PeerChannel对象,若直接传入频道的@用户名字符串,底层序列化时会因类型不匹配抛出"参数需为整数"的错误。

另外,仅调用GetExportedChatInvitesRequest只能获取频道已导出的邀请链接列表,无法直接关联到具体用户——要实现用户ID与加入邀请链接的绑定,需要结合参与者列表的邀请来源数据。

修复后的完整代码

from telethon import TelegramClient, types
from telethon.sessions import StringSession
import csv

# 替换为你的API信息与目标频道
API_ID = 123456
API_HASH = "your_api_hash_here"
SESSION_STRING = "your_session_string_here"
CHANNEL_TARGET = "@your_channel_username"  # 也可直接传入频道整数ID

async def export_user_invite_association():
    async with TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH) as client:
        # 将频道标识转换为合法Peer对象,自动处理用户名转ID
        channel = await client.get_entity(CHANNEL_TARGET)
        
        # 遍历所有频道参与者,提取用户ID与对应邀请链接
        user_invite_data = []
        async for participant in client.iter_participants(channel, aggressive=True):
            user_id = participant.id
            # 提取加入时使用的邀请链接(无则标记为直接加入)
            invite_link = participant.invite.link if (hasattr(participant, 'invite') and participant.invite) else "无邀请链接/直接加入"
            user_invite_data.append({"user_id": user_id, "invite_link": invite_link})
        
        # 导出数据到CSV文件
        with open("channel_user_invites.csv", "w", newline="", encoding="utf-8") as file:
            writer = csv.DictWriter(file, fieldnames=["user_id", "invite_link"])
            writer.writeheader()
            writer.writerows(user_invite_data)
        
        print(f"导出完成,共采集{len(user_invite_data)}条用户关联数据")

if __name__ == "__main__":
    import asyncio
    asyncio.run(export_user_invite_association())

关键细节说明

  • 参数类型修正:通过client.get_entity()将频道用户名/ID转换为PeerChannel对象,彻底避免类型不匹配问题。
  • 用户-邀请链接关联:iter_participants()返回的参与者对象中,invite字段包含该用户加入频道时使用的邀请链接信息,直接提取即可完成关联。
  • 批量处理适配:aggressive=True会自动分页拉取所有参与者,适配大频道的数据采集需求。

权限与环境要求

  • 你的Telegram账号必须是目标频道的管理员,否则无法获取参与者的邀请来源信息。
  • 确保已完成Telethon的环境配置(安装依赖、获取API密钥与会话字符串)。

内容的提问来源于stack exchange,提问作者Volodymyr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:25:13