如何通过 Python Telethon 让一个机器人持续工作,而另一个机器人 10 秒后工作?

问题描述 投票:0回答:1

我有 2 个电报机器人,它们应该在聊天中收到新消息。一开始,当一条消息出现时,两个机器人都必须记住该消息,然后第一个机器人不断记住该消息,第二个机器人在一段时间(例如 10 秒)后记住该消息,而第一个机器人则不断工作。

我尝试实现此方法,但它不起作用,有人对如何修复此代码有任何想法吗?另外,有谁知道当聊天模式很慢时使用 teleton 的方法吗?谢谢大家,希望能帮到你

from telethon import TelegramClient, sync, events, utils, functions, types
bot1 = TelegramClient()
bot2 = TelegramClient()

@bot1.on(events.NewMessage(chats=[channel_chat]))
async def handler(event):
    print("bot 1")
    

@bot2.on(events.NewMessage(chats=[channel_chat]))
async def handler(event):
    print("bot 2")
    await asyncio.sleep(10)


def main():
    bot1.start()
    bot2.start()
    loop = asyncio.get_event_loop()
    tasks = [
        loop.create_task(bot1.run_until_disconnected()),
        loop.create_task(bot2.run_until_disconnected())
    ]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()

if __name__ == '__main__':
    main()

python-asyncio telegram telethon
1个回答
0
投票

我希望您按照以下步骤使其发挥作用:

为每个机器人使用单独的手柄。

正确启动两个机器人并确保它们处于异步循环中。

在不终止第一个机器人循环的情况下处理第二个机器人的延迟。

您可以通过以下方式使用 telethon 库:

import asyncio
from telethon import TelegramClient, events

# Fill in your API_ID, API_HASH, and BOT_TOKEN
api_id = 'your_api_id'
api_hash = 'your_api_hash'
bot1_token = 'your_bot1_token'
bot2_token = 'your_bot2_token'

# Create Telegram clients for both bots
bot1 = TelegramClient('bot1', api_id, api_hash).start(bot_token=bot1_token)
bot2 = TelegramClient('bot2', api_id, api_hash).start(bot_token=bot2_token)

channel_chat = 'your_channel_chat_id_or_username'

# Handler for bot1 to process messages continuously
@bot1.on(events.NewMessage(chats=[channel_chat]))
async def handler_bot1(event):
    print("bot 1 received a message:", event.message.text)

# Handler for bot2 to process messages with a delay
@bot2.on(events.NewMessage(chats=[channel_chat]))
async def handler_bot2(event):
    print("bot 2 received a message, will process after delay:", event.message.text)
    await asyncio.sleep(10)
    print("bot 2 processed the message:", event.message.text)

async def main():
    await asyncio.gather(
        bot1.run_until_disconnected(),
        bot2.run_until_disconnected()
    )

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

要点:

单独的句柄,await asyncio,sleep(10)通过建立延迟而不终止第一个机器人循环来确保这一点,并且 asyncio.gather 用于以并发方式运行两个机器人。

为 TelegramClient 正确使用机器人令牌。事件处理程序管理非常重要。 ayncio.run(main()) 运行两个机器人直到断开连接。

© www.soinside.com 2019 - 2024. All rights reserved.