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

如何通过Pyrogram的compose让多个账号执行同一操作?

用Pyrogram的compose方法实现多账号批量执行相同操作

要让多个Pyrogram账号通过compose方法执行相同操作,核心是定义通用操作逻辑,让所有账号实例调用该逻辑,结合异步工具实现并行执行或持续监听任务。

场景1:一次性批量执行操作(如发送消息、查询信息)

适合需要一次性完成的任务,操作结束后可关闭账号连接:

import asyncio
from pyrogram import Client, compose

# 定义所有账号要执行的通用操作
async def common_task(client):
    # 替换为你的具体操作,比如给自己发消息
    await client.send_message("me", f"[{client.name}] 已完成指定操作")
    # 示例:获取账号基本信息并打印
    account_info = await client.get_me()
    print(f"账号 {account_info.username} 操作完成")

async def main():
    # 初始化多个账号客户端
    apps = [
        Client("account1"),
        Client("account2"),
        Client("account3")
    ]

    # 启动所有客户端连接
    await compose(apps)
    try:
        # 并行执行所有账号的任务
        await asyncio.gather(*[common_task(app) for app in apps])
    finally:
        # 操作完成后关闭所有客户端
        for app in apps:
            await app.stop()

asyncio.run(main())

场景2:持续监听并处理事件(如自动回复消息)

适合需要长期运行的任务,比如监听特定消息并自动回复:

import asyncio
from pyrogram import Client, compose, filters

# 定义通用的消息处理逻辑
async def auto_reply(client, message):
    # 监听私聊中的/start命令并回复
    if message.chat.type == "private" and message.text == "/start":
        await message.reply(f"你好!我是账号 {client.name}")

async def main():
    apps = [
        Client("account1"),
        Client("account2"),
        Client("account3")
    ]

    # 给每个账号添加相同的事件处理器
    for app in apps:
        app.add_handler(filters.text & filters.command("start")(auto_reply))

    # 启动所有客户端并保持运行(直到手动终止程序)
    await compose(apps)

asyncio.run(main())

关键说明

  • compose(apps):负责同时启动所有Client实例,建立与Telegram服务器的连接。
  • asyncio.gather:用于并行执行多个异步任务,确保所有账号同时处理操作。
  • 事件处理器:通过add_handler给每个账号绑定相同的逻辑,实现统一的事件响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:50:50