簡體   English   中英

如何在 Telethon Python 中運行多個任務

[英]How to run multiple task in Telethon Python

我有關於使用 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()

列出的代碼有幾個問題。

您的def Checker()不是async def 當你調用它時它會立即運行,而loop.create_task(Checker())根本不起作用。

您在不使用await的情況下調用poster ,這是一個async def 這意味着它根本不會運行。

您正在使用time.sleep ,它會阻塞整個線程,這意味着asyncio無法運行其循環,因此創建的任何任務也不會運行。

BOT.get_entity也是一個async def定義。 它應該被await -ed。

檢查器看起來像這樣:

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)

並且不要忘記await BOT.get_entity(chatId)


但我強烈建議在嘗試編寫更復雜的代碼之前asyncio文檔並熟悉asyncio

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM