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

使用Telethon批量加Telegram群时如何规避Flood Wait限制?

优化Telethon批量加群的限流规避方案

问题背景

使用单个Telegram账号,基于Telethon编写批量加群脚本时频繁触发限流。将加群间隔延长至5分钟后,完成全部加群操作仍需17天甚至更久,急需更高效的限流规避方法。测试用脚本如下:

from opentele.tl import TelegramClient
from opentele.api import API
from telethon.errors import FloodWaitError
from telethon.tl.functions.messages import ImportChatInviteRequest
import time
import asyncio

# Replace these with your own session name and phone number
session_name = 'your_session_name'  # e.g., 'account1'
phone_number = 'PHONE NUMBER'        # Your phone number, including country code

# Load group invite links from a file
with open('groups.txt', 'r') as file:
    group_invite_links = [line.strip() for line in file if line.strip()]

async def join_groups():
    api = API.TelegramDesktop  # Use Telegram Desktop's official API
    client = TelegramClient(session_name, api=api)
    
    # Start the client and log in
    await client.start(phone=phone_number)
    
    for invite_link in group_invite_links:
        try:
            # Extract the invite hash from the invite link
            if 'joinchat' in invite_link:
                invite_hash = invite_link.split('/')[-1]
            else:
                # Handle t.me/+inviteHash format
                invite_hash = invite_link.split('/')[-1].lstrip('+')
            
            await client(ImportChatInviteRequest(invite_hash))
            print(f"Joined group: {invite_link}")
            
            # Add a delay to avoid triggering flood wait
            time.sleep(2)  # Adjust the delay as needed

        except FloodWaitError as e:
            print(f"Flood wait for {e.seconds} seconds")
            time.sleep(e.seconds)  # Wait out the flood wait time

        except Exception as e:
            print(f"Error joining group {invite_link}: {e}")

    await client.disconnect()

# Run the async function
asyncio.run(join_groups())

优化方案

1. 修复异步函数中的阻塞问题

原脚本在异步函数中使用time.sleep()会阻塞整个事件循环,导致额外时间浪费。应替换为asyncio.sleep(),让事件循环在等待时可正常调度其他任务:

# 替换原time.sleep语句为
await asyncio.sleep(300)  # 5分钟异步等待,避免阻塞事件循环

2. 利用Telethon内置自动限流处理

Telethon提供了智能的限流处理机制,无需手动捕获FloodWaitError。通过设置客户端的flood_sleep_threshold,让库自动处理限流等待:

async def join_groups():
    api = API.TelegramDesktop
    client = TelegramClient(session_name, api=api)
    
    await client.start(phone=phone_number)
    
    # 设置自动处理所有限流等待
    client.flood_sleep_threshold = 1000
    
    for invite_link in group_invite_links:
        try:
            if 'joinchat' in invite_link:
                invite_hash = invite_link.split('/')[-1]
            else:
                invite_hash = invite_link.split('/')[-1].lstrip('+')
            
            await client(ImportChatInviteRequest(invite_hash))
            print(f"Joined group: {invite_link}")
            
            await asyncio.sleep(300)

        except Exception as e:
            print(f"Error joining group {invite_link}: {e}")

    await client.disconnect()

3. 分时段动态调整加群间隔

Telegram限流阈值随时段变化,非高峰时段(如凌晨1点至上午10点)限制更宽松,可缩短间隔;高峰时段(晚8点至凌晨1点)则延长间隔:

import datetime

def get_dynamic_delay():
    current_hour = datetime.datetime.now().hour
    # 非高峰:3分钟间隔
    if 1 <= current_hour < 10:
        return 180
    # 平峰:5分钟间隔
    elif 10 <= current_hour < 20:
        return 300
    # 高峰:8分钟间隔
    else:
        return 480

# 在加群循环中使用动态间隔
await asyncio.sleep(get_dynamic_delay())

4. 提升账号权重降低限流概率

新账号或低活跃账号的限流阈值远低于老账号,可通过以下方式提升权重:

  • 提前养号:每天正常发送消息、参与群组互动,持续1-2周
  • 绑定手机号并启用两步验证,提升账号信任度
  • 保持自然使用节奏,避免短时间内集中操作

5. 提前过滤无效链接

提前验证邀请链接有效性,避免无效请求消耗限流配额:

async def validate_invite_link(client, invite_link):
    try:
        if 'joinchat' in invite_link:
            invite_hash = invite_link.split('/')[-1]
        else:
            invite_hash = invite_link.split('/')[-1].lstrip('+')
        # 验证链接有效性
        await client(ImportChatInviteRequest(invite_hash))
        return True
    except Exception as e:
        print(f"Invalid link {invite_link}: {e}")
        return False

# 过滤有效链接后再批量加群
valid_links = []
for link in group_invite_links:
    if await validate_invite_link(client, link):
        valid_links.append(link)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 21:20:04