Похожие чаты

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

44 просмотра

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.

Sergo [AFK]- Автор вопроса

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"

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

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

Добрый день. Хочу сделать отрисовку по команде на панели. Почему-то рисуется только при втором вызове. С чем может быть связано, не подскажете? procedure TForm1.FormDblClick(...
Kirill Filippenok
20
а зачем этот вопрос для удаления из чата?
Mёdkinson Medvezhkin
63
using next image component with s3 image: "url" parameter is valid but upstream response is invalid code: <Image fill src={s...
Fasil
3
Эх кто-то пришел и весь праздник испортил :( You need complex FBX scene importing setup to change things on import? good luck with that. You need navigation and pathfinding? g...
Serg Gini
5
Всем привет! Нужен совет от опытных. Переношу свой проект с Делфи 10.2 Токио на Лазарус 3.2 установленный через инсталлятор fpcupdeluxe-x86_64-win64. При импортировании проект...
Дмитрий Завгородний
2
Friends, how can I find my Wazirx wallet address?
Silm Silm
31
Всем привет! Подскажите. Я написал приложение на Delphi 10.2 Tokyo под Windows 10. И передо мной стал вопрос о том чтобы сделать это приложение кроссплатформенным (под Linux и...
Дмитрий Завгородний
24
Какого хера? /Sources/App/Modules/User/Models/UserLinkApple.swift:21:20: warning: stored property '_id' of 'Sendable'-conforming class 'UserLinkApple' is mutable @ID(...
Alexander Sherbakov
14
My 7 year old daughter recognizes the Bitcoin symbol and knows it's currency. What are the top ,3-5 most basic important concepts to convey to a kid about BCH? I started with ...
Big Hair
24
How the price of ANVL is decided? The buying pressure comes just from staking which is very slow, while the selling pressure might be huge. What are the benefits for those who...
MJ Javvaji @muralijavvaji
13
Карта сайта