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

Python Pyrogram中如何让两个函数并行运行?线程实现报错求助

解决Pyrogram中两个函数同时运行的问题

错误原因

你遇到的RuntimeError: There is no current event loop in thread错误,是因为Pyrogram基于asyncio运行,新启动的线程默认没有初始化asyncio事件循环,而app.run()必须依赖当前线程的事件循环才能工作。

方案一:用asyncio并发(推荐)

Pyrogram本身是异步框架,直接用asyncio的任务并发是最合理的方式,无需额外创建线程。

重构代码示例

import asyncio
from pyrogram import Client
from random import choice

# 假设以下变量已提前定义
messages = ["消息内容1", "消息内容2", "消息内容3"]
chat = ...  # 你的目标chat对象
delay = 5   # 发送间隔时间

async def flud(account_name):
    member_n = 0
    while True:
        app = Client(name=account_name)
        text = choice(messages)
        async with app:
            await app.send_message(chat_id=chat.id, text=text)
        await asyncio.sleep(delay)  # 用asyncio.sleep替代time.sleep,避免阻塞事件循环

async def flud_1(account_name):
    member_n = 0
    while True:
        app = Client(name=account_name)
        text = choice(messages)
        async with app:
            await app.send_message(chat_id=chat.id, text=text)
        await asyncio.sleep(delay)

async def main():
    # 创建两个并发任务
    task1 = asyncio.create_task(flud("账号1标识"))
    task2 = asyncio.create_task(flud_1("账号2标识"))
    # 持续等待任务执行(因函数内是无限循环,会一直运行)
    await asyncio.gather(task1, task2)

if __name__ == "__main__":
    asyncio.run(main())

关键修改点

  • 将原同步函数改为异步函数,用async def定义
  • 替换time.sleep(delay)为await asyncio.sleep(delay),防止阻塞整个事件循环
  • 通过asyncio.create_task创建并发任务,asyncio.gather统一管理任务执行
  • 无需手动调用app.stop(),async with app会自动处理客户端的启动与关闭

方案二:修复线程方式的代码

如果一定要用线程,需在每个线程中手动创建并绑定asyncio事件循环:

修改后的线程代码示例

import threading
import asyncio
from pyrogram import Client
from random import choice
import time

# 假设以下变量已提前定义
messages = ["消息内容1", "消息内容2", "消息内容3"]
chat = ...  # 你的目标chat对象
delay = 5   # 发送间隔时间

def flud(account_name):
    # 为当前线程创建并设置事件循环
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    
    member_n = 0
    while True:
        app = Client(name=account_name)
        text = choice(messages)
        
        async def in_flud():
            async with app:
                await app.send_message(chat_id=chat.id, text=text)
        
        loop.run_until_complete(in_flud())
        time.sleep(delay)

def flud_1(account_name):
    # 为当前线程创建并设置事件循环
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    
    member_n = 0
    while True:
        app = Client(name=account_name)
        text = choice(messages)
        
        async def in_flud_1():
            async with app:
                await app.send_message(chat_id=chat.id, text=text)
        
        loop.run_until_complete(in_flud_1())
        time.sleep(delay)

if __name__ == "__main__":
    threading.Thread(target=flud, args=("账号1标识",)).start()
    threading.Thread(target=flud_1, args=("账号2标识",)).start()

关键修改点

  • 在每个线程函数开头,创建新的事件循环并设置为当前线程的默认循环
  • 用loop.run_until_complete()替代app.run()执行异步逻辑
  • 移除手动调用的app.stop(),依赖async with app自动关闭客户端

注意事项

  • 优先选择方案一,异步框架用asyncio并发比线程更高效,也更贴合Pyrogram的设计逻辑
  • 每个客户端的name参数需唯一,对应不同的会话存储文件
  • 控制消息发送频率,避免触发Telegram的反垃圾机制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:05:22