The problem is that the database does not have time to be processed and there is a call on the second circle.
How to make the database processing happen and the cycle goes on. asynchronously
async def send_mes_to_users(client):
async with client:
user = 'userrrrrrrrr'
try:
if db.check_invited(name_table=table, user_name=user) != "TRUE":
await client.send_message(entity=user, message=message)
db.add_invited(name_table=table, user=user) #??????????
print(f'Sent: @{user}')
except errors.BadRequestError as e:
print(f'Error: {e}')
async def main():
await asyncio.gather(
send_mes_to_users(TelegramClient('user1', api_id, api_hash)),
send_mes_to_users(TelegramClient('user2', api_id, api_hash)),
)
asyncio.run(main())
2
Answers
You are running two tasks at the same time (with
gather
). You’re likely to run into a race condition. If you need to synchronize a "critical section", consider using anasyncio.Lock
:you want the second Task to not send do userrrrr as its marked as invited?
then you need to update database before awaiting send_message, as this passes control to the second task, which then checks for already invited userrrrr, and it´s not as it´s awaiting sending.