如何在同一会话中多次使用同一电视马拉松客户端

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

我有这个电视马拉松代码:

from telethon import TelegramClient
import asyncio

api_id = ""
api_hash = ""
session = "john"
username = 'Hello_World'   # For Example

async def main():
    client = TelegramClient(session, api_id, api_hash)
    await client.start()

    entity = await client.get_entity("https://t.me/ahsan_alhadeeth")
    search_user = await client.get_participants(entity, search=username)

    print(search_user)

def in_channel():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main())

in_channel()
in_channel()

当我对

in_channel()
使用一次调用时,它会正常运行直到完成。

但是当使用两个调用时,它会返回错误:

sqlite3.OperationalError: database is locked

我想知道如何多次使用同一个客户端而不进行多个会话。

请帮忙。

python asynchronous client python-asyncio telethon
4个回答
0
投票

我认为不可能同时多次执行同一任务。由于这是异步函数,因此您需要等待第一个 in_channel() 完成,然后再执行下一个 in_channel。数据库()可能被锁定,因为客户端已经在使用中。

当您说多次使用同一个客户端时,您的意思是多次运行 in_channel() 直到完成,还是您的目标是同时运行 in_channel() 多次?

我可能可以帮助你,但我需要更多答案:-)

(抱歉,这是一个“答案”。在我得到 50 分之前,我不允许发表评论。)


0
投票

更好的是,您可以循环同一会话,但在主函数末尾添加

client.disconnect()


0
投票

   client = TelegramClient(session, api_id, api_hash)

TelegramClient 使用 Telegram 创建会话,并代表您的机器人或客户端与 Telegram 的通信。只是为了确保,这不是您与任何特定用户(例如:John)的会话。您可以与任何您想要的用户进行交互,前提是有人发起了与您或与添加到相应频道/组的凭据(api_id、api_hash)关联的用户/机器人的对话。 您应该将此客户端视为一个连接,可以在其中创建多个实例来平衡多个调用的负载。

您的代码可以按如下方式修复:

from telethon import TelegramClient
import asyncio

class TClient:
    def __init__(self, session):
        api_id = ""
        api_hash = ""
        self.session = session

    async def init(self, username = 'Hello_World'):
        self.client = TelegramClient(session, api_id, api_hash)
        await self.client.start()

    async def main(self):
        entity = await client.get_entity("https://t.me/ahsan_alhadeeth")
        search_user = await client.get_participants(entity, search=username)

        print(search_user)

    def in_channel(self, callFn, args):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(callFn(args))

    in_channel()

if __name__ == '__main__':
    tc1 = TClient(session = "john1")
    tc1.in_channel(tc.init())
    tc1.in_channel(tc.main(username = 'Hello_World'))
    tc1.in_channel(tc.main(username = 'Hello_World2'))

    tc2 = TClient(session = "bot2")
    tc2.in_channel(tc.init(username = 'Hello_World'))))
    tc2.in_channel(tc.main(username = 'Hello_World2'))

上述内容使您能够为多个用户重复使用您的会话。我对上面做了2处修改。

  1. 我重构了代码,以便可以使用具有不同会话 ID 的 Telegram 客户端创建多个连接。
  2. 主函数可以针对不同的用户名多次调用

PS - 我还没有测试过上面的代码。


0
投票

对我来说,ISP 屏蔽了电报。所以不得不使用VPN

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