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.
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
. It's going to run immediately when you call it, and loop.create_task(Checker())
won't work at all.
You are calling poster
, which is an async def
, without using await
. 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.
BOT.get_entity
is also an async def
. It should be 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)
.
But I strongly recommend reading through the asyncio
documentation and being more comfortable with asyncio
before attempting to write more complex code.