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

如何使用Telethon检查指定用户是否订阅我的Telegram频道

使用Telethon检查特定用户的频道订阅状态
  • 核心思路:避开批量拉取用户列表的200个数量限制,直接用Telethon的GetParticipantRequest接口单独查询每个目标用户的订阅状态,这个接口不受批量列表的限制。

  • 代码实现示例:

from telethon import TelegramClient
from telethon.errors import UserNotParticipantError
from telethon.tl.functions.channels import GetParticipantRequest

# 替换成你的API信息和会话文件
api_id = 123456
api_hash = 'your_api_hash_here'
session_name = 'my_session'

# 替换成你的频道ID或用户名(比如 '@my_channel')
channel_entity = '@your_channel_username'

async def check_user_subscription(client, channel, user_id):
    try:
        # 查询用户在频道中的参与信息
        participant = await client(GetParticipantRequest(channel, user_id))
        return True, f"用户 {user_id} 已加入频道"
    except UserNotParticipantError:
        # 用户未加入时抛出该异常
        return False, f"用户 {user_id} 未加入频道"
    except Exception as e:
        # 处理其他错误(如权限不足、用户不存在等)
        return None, f"查询出错:{str(e)}"

async def main():
    async with TelegramClient(session_name, api_id, api_hash) as client:
        # 替换成你要检查的目标用户ID列表
        target_user_ids = [123456789, 987654321]
        for user_id in target_user_ids:
            status, msg = await check_user_subscription(client, channel_entity, user_id)
            print(msg)

if __name__ == '__main__':
    import asyncio
    asyncio.run(main())
  • 关键注意事项:
    • 你的账号必须是目标频道的管理员,否则会因权限不足无法执行查询。
    • user_id需为用户的真实Telegram数字ID,若只有用户名,可先用client.get_entity(username)转换为ID。
    • UserNotParticipantError是判断用户未加入的标准依据,其他异常需根据提示排查问题(如频道不存在、用户ID无效等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:15:34