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

如何用Python判断Telegram用户名属用户/群组?求高效无限速方案

高效解决Telegram用户名类型判断与群组标题获取(规避限速)

核心优化思路

Telethon本身内置了针对Telegram API的速率控制逻辑,之前手动加sleep反而可能打乱其动态调整机制,导致处理变慢或仍触发限速。以下是更高效的解决方案:


1. 正确配置Telethon客户端

不要手动添加固定休眠时间,而是依赖Telethon的内置限流与自动重连:

  • 初始化客户端时开启auto_reconnect=True,让客户端自动处理临时限速的重试
  • 复用同一个客户端会话,避免频繁创建新连接增加服务器负载

2. 异步批量处理+并发控制

通过异步批量请求配合信号量控制并发数,既保证效率,又不会触发API限速:

from telethon import TelegramClient, types
import asyncio

# 替换为你的API信息
API_ID = 12345
API_HASH = 'your_api_hash'
SESSION_NAME = 'telegram_session'

async def check_single_username(client, username):
    try:
        # 用轻量的get_entity请求,足够获取类型与标题信息
        entity = await client.get_entity(username)
        if isinstance(entity, types.User):
            return {"username": username, "type": "用户", "标题": None}
        elif isinstance(entity, (types.Chat, types.Channel)):
            return {"username": username, "type": "群组/频道", "标题": entity.title}
    except Exception as e:
        return {"username": username, "type": "无效", "错误信息": str(e)}

async def batch_check_usernames(target_usernames, max_concurrent=8):
    async with TelegramClient(SESSION_NAME, API_ID, API_HASH, auto_reconnect=True) as client:
        # 信号量控制并发数,可根据实际情况调整(建议5-10)
        semaphore = asyncio.Semaphore(max_concurrent)
        
        async def bounded_check(username):
            async with semaphore:
                return await check_single_username(client, username)
        
        # 批量创建任务并执行
        tasks = [bounded_check(uname) for uname in target_usernames]
        results = await asyncio.gather(*tasks)
        return results

# 测试使用
if __name__ == '__main__':
    test_usernames = ["user123", "test_group", "invalid_name_123"]
    final_results = asyncio.run(batch_check_usernames(test_usernames))
    for res in final_results:
        print(res)

3. 关键注意事项

  • 务必使用官方申请的API ID和HASH,第三方共享的ID更容易被限制
  • 若仍遇到限速,可适当降低max_concurrent的值(比如调到5)
  • 避免一次性处理超大规模的用户名列表(比如上万条),可分批次处理,每批次间隔1-2分钟

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:02:42