简体   繁体   English

如何在 Telethon Python 中运行多个任务

[英]How to run multiple task in Telethon Python

I have issue about run multiple function using Telethon for example I want to using bot management command and tracker function both same time so I know I should multithread but here is my script I am trying to run both of them but never run at the same time.我有关于使用 Telethon 运行多个 function 的问题例如我想同时使用机器人管理命令和跟踪器 function 所以我知道我应该多线程但这是我的脚本我试图同时运行它们但从不同时运行.

def Checker():
    print('I am Running')
    while True:
        if isStart:
            for i in SpesificDictionary:
                Element = SpesificDictionary[i]
                poster(Element,i)
        time.sleep(10)

async def poster(Element,chatId): 
    text = Element.API.getText()   
    if text != None:
        luckyNews = await randomAds()
        if(luckyNews != None):
            print(f"Sending to {luckyNews[0]} with {luckyNews[1]}")
            text += f"\n\n <b>🚀 Ad's:</b> '<a href='{luckyNews[0]}'><b>{luckyNews[1]}</b></a>'"
        else:
            text += f"\n\n <b>🚀 Ad's:</b> <b>Ads your project📞</b>"
        
        if(len(SpesificButtonAdvertise) != 0):
            keyboard = [[Button.url(str(SpesificButtonAdvertise[1]),str(SpesificButtonAdvertise[0]))]]
        else:
            keyboard = [[Button.url('Advertise your project here 📞', "https://t.me/contractchecker")]]

        
        # chat = BOT.get_entity(-1001639775918)  #-1001639775918 test       # main -1001799563725  # sohbet : -1001648583714

        chat = BOT.get_entity(chatId) 
        await BOT.send_file(chat, 'giphy.gif', caption= text, buttons= keyboard, parse_mode = 'HTML')
    else:
        print("Waiting for the next update")


def main():
    BOT.start(bot_token=BOT_TOKEN)
    loop = asyncio.get_event_loop()
    tasks = [loop.create_task(Checker()),
             loop.create_task(BOT.run_until_disconnected())]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()

There are several problems with the listed code.列出的代码有几个问题。

Your def Checker() is not an async def .您的def Checker()不是async def It's going to run immediately when you call it, and loop.create_task(Checker()) won't work at all.当你调用它时它会立即运行,而loop.create_task(Checker())根本不起作用。

You are calling poster , which is an async def , without using await .您在不使用await的情况下调用poster ,这是一个async def This means it won't run at all.这意味着它根本不会运行。

You are using time.sleep , which blocks the entire thread, meaning asyncio cannot run its loop, and therefore any tasks created won't run either.您正在使用time.sleep ,它会阻塞整个线程,这意味着asyncio无法运行其循环,因此创建的任何任务也不会运行。

BOT.get_entity is also an async def . BOT.get_entity也是一个async def定义。 It should be await -ed.它应该被await -ed。

Checker would look like this:检查器看起来像这样:

async def Checker():
    print('I am Running')
    while True:
        if isStart:
            for i in SpesificDictionary:
                Element = SpesificDictionary[i]
                await poster(Element,i)
        await asyncio.sleep(10)

And don't forget to await BOT.get_entity(chatId) .并且不要忘记await BOT.get_entity(chatId)


But I strongly recommend reading through the asyncio documentation and being more comfortable with asyncio before attempting to write more complex code.但我强烈建议在尝试编写更复杂的代码之前asyncio文档并熟悉asyncio

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM