Похожие чаты

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 ответов

78 просмотров

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"

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

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

30500 за редактор? )
Владимир
47
any reference of this implementation?
BitBuddha
29
Ⓐrtto, [4/23/24 7:02 PM] Please explain more fully how it is not working exactly, and what are the steps you are taking, and what error messages come or what happens. Ⓐrtto, ...
Ezza Kezza
2
sounds like people have lost their kaspa on tradeogre... does this mean tradeogre not trustworthy?
Ezza Kezza
15
Страшнейшая правда про списки ЦБ. С первых дней жизни P2P сферы, молодые человеки, начитавшись законодательной базы и "внутренних" документов, решили, что им противостоит сер...
Foxcool
3
Недавно Google Project Zero нашёл багу в SQLite с помощью LLM, о чём достаточно было шумно в определённых интернетах, которые сопровождались рассказами, что скоро всех "ибешни...
Alex Sherbakov
5
So much speculation in the last week. So much volatility in price. This is because Hedera has a GC that isn't using the network it's governing. Why aren't people asking why a...
Summit Seeker R
8
Anyone else having this error when trying to make transactions?
Datzel
11
Question: How viable is it to use Anvil as the backend infrastructure for managing a TradFi portfolio, while integrating Flexa for instant liquidity and payment solutions? Cou...
Kevin
2
вы делали что-то подобное и как? может есть либы готовые? увидел картинку нокода, где всё линиями соединено и стало интересно попробовать то же в ddl на lua сделать. решил с ч...
Victor
8
Карта сайта