Похожие чаты

Hello Who could to explain how to add message hander in

multi thread bot?

i have this code, and he is working
accounts = tuple(TelegramClient(StringSession(x.strip()), api_id, api_hash) for x in sessions_strings)

async def work(client):
async with client:
me = await client.get_me()
await client.send_message("@Gumbl4", me.first_name)
starttime = time.time()
# while True:
# print('Working with', me.first_name)
# delay = 0.1
# time.sleep(delay - ((time.time() - starttime) % delay))

def main(client):
asyncio.run(work(client))


thread_list = []
for acc in accounts:
thread_list.append(Thread(target=main, args=(acc,)))
for t in thread_list:
t.start()
for t in thread_list:
t.join()


but this is not working already
async def work(client):
async with client:
me = await client.get_me()
while True:
@events.register(events.NewMessage('(?i)hello'))
async def handler(event):
client = event.client
await event.respond('Hey!')
await client.send_message('me', 'I said hello to someone')
await client.send_message("@Gumbl4", me.first_name)
starttime = time.time()
# while True:
# print('Working with', me.first_name)
# delay = 0.1
# time.sleep(delay - ((time.time() - starttime) % delay))

def main(client):
asyncio.run(work(client))


thread_list = []
for acc in accounts:
thread_list.append(Thread(target=main, args=(acc,)))
for t in thread_list:
t.start()
for t in thread_list:
t.join()

10 ответов

81 просмотр

Just don't use threads, asyncio tasks will do

Sergo [AFK]- Автор вопроса
Sergo [AFK]
How, if i need to use 2+ accounts?

it isn't your main issue, but still, using asyncio is more fitting for async library. so same way as now, just replace running parts async def work(client): .... same stuff, but at last line add await client.run_until_disconnected() async def main(client): await asyncio.gather(*[work(client) for client in accounts]) asyncio.run(main()) and replace any time.sleep with await asyncio.sleep, and why do you have while True in second one? remove that too

Sergo [AFK]- Автор вопроса
⎞ .·. ⎝ ⎝
it isn't your main issue, but still, using asyncio...

logging.info('Reading sessions...!') sessions_strings = open("string_sessions.txt", "r").readlines() accounts = tuple(TelegramClient(StringSession(x.strip()), api_id, api_hash) for x in sessions_strings) async def work(client): async with client: me = await client.get_me() @events.register(events.NewMessage('(?i)hello')) async def handler(event): client = event.client await event.respond('Hey!') await client.send_message('me', 'I said hello to someone') await client.send_message("@Gumbl4", me.first_name) await client.run_until_disconnected() async def main(client): #asyncio.run(work(client)) await asyncio.gather(*[work(client) for client in accounts]) asyncio.run(main()) Intresting, but TypeError: main() missing 1 required positional argument: 'client' why, if i give it him?

Sergo [AFK]
logging.info('Reading sessions...!') sessions_stri...

yeah, remove that too async def main(client): -> async def main():

Sergo [AFK]- Автор вопроса
⎞ .·. ⎝ ⎝
yeah, remove that too async def main(client): ->...

ok, i fixed it with ur advice or self with add arg. But handler message dont work, and online hold approximately 10-20 seconds and accounts going get offline status

Sergo [AFK]
ok, i fixed it with ur advice or self with add arg...

which sort of "offline status" also why are you using @events.register() without add_event_handler, make that @client.on(events.NewMessage('(?i)hello')) if this is all of the code.

That's normal, status setting needs to be done by a seperate request manually. fix your @events.register() first if the command isn't working

Sergo [AFK]- Автор вопроса
⎞ .·. ⎝ ⎝
That's normal, status setting needs to be done by ...

hmmm... Get ValueError: Cannot find any entity corresponding to "(?i)hello"

Похожие вопросы

Обсуждают сегодня

Господа, а что сейчас вообще с рынком труда на делфи происходит? Какова ситуация?
Rꙮman Yankꙮvsky
29
А вообще, что может смущать в самой Julia - бы сказал, что нет единого стандартного подхода по многим моментам, поэтому многое выглядит как "хаки" и произвол. Короче говоря, с...
Viktor G.
2
@Benzenoid can you tell me the easiest, and safest way to bu.y HEX now?
Živa Žena
20
This is a question from my wife who make a fortune with memes 😂😂 About the Migration and Tokens: 1. How will the old tokens be migrated to the new $LGCYX network? What is th...
🍿 °anton°
2
30500 за редактор? )
Владимир
47
а через ESC-код ?
Alexey Kulakov
29
What is the Dex situation? Agora team started with the Pnetwork for their dex which helped them both with integration. It’s completed but as you can see from the Pnetwork ann...
Ben
1
Гайс, вопрос для разносторонее развитых: читаю стрим с юарта, нада выделять с него фреймы с определенной структурой, если ли чо готовое, или долбаться с ринг буффером? нада у...
Vitaly
9
Anyone knows where there are some instructions or discort about failed bridge transactions ?
Jochem
21
@lozuk how do I get my phex copies of my ehex from a atomic wallet, to move to my rabby?
Justfrontin 👀
11
Карта сайта