Answer the question
In order to leave comments, you need to log in
How to make a loop inside async def aiogram?
Good day to all! I am writing a telegram bot (aiogram). It is necessary that the id of new users be added to the text.txt file.
Everything would be fine, but here I ran into a problem. I don't need users to "duplicate" so I added a check if there is already a user with the same id, but soon realized that loops don't work inside async def. Tell me, please, what to do, and how can everything be implemented without a cycle?
import random
import logging
from aiogram import Bot, Dispatcher, executor, types
logging.basicConfig(level=logging.INFO)
bot = Bot(token="...")
dp=Dispatcher(bot)
@dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
await message.reply("Hi!\nI'm EchoBot!\nPowered by aiogram.")
@dp.message_handler()
async def echo(message: types.Message):
f = open('users.txt', 'a+')
isuser = False
length = len(f.read())
f.seek(0)
user = types.User.get_current()
f.seek(0)
while (f.tell()<length):
if (f.read(len(str(user.id))+4)=='id: '+str(user.id)):
isuser = True
while (f.read(1)!='\n'):
print(f.read(1))
if (isuser ==False):
f.write('id: '+ str(user.id) +'; name: '+str (user.full_name) +'; username: ' +str(user.username)+';\n')
f.close()
await message.answer(message.text)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
Answer the question
In order to leave comments, you need to log in
Problem solved. Loops work great, just
(f.tell() < length)did not work correctly, so the cycle was skipped.
import random
import logging
from aiogram import Bot, Dispatcher, executor, types
logging.basicConfig(level=logging.INFO)
bot = Bot(token="...")
dp=Dispatcher(bot)
@dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
await message.reply("Hi!\nI'm EchoBot!\nPowered by aiogram.")
@dp.message_handler()
async def echo(message: types.Message):
f = open('users.txt', 'a+')
isuser = False
length = len(f.read())
f.seek(0)
user = types.User.get_current()
f.seek(0)
i=0
while (f.read(1)):
f.seek(f.tell()-1)
print(f.tell())
if (f.read(len(str(user.id))+4)=='id: '+str(user.id)):
isuser = True
break
while(f.read(1)!='\n'):
print('+' + str(f.tell()))
if (isuser == False):
f.write('id: '+ str(user.id) +'; name: '+str (user.full_name) +'; username: ' +str(user.username)+';\n')
f.close()
await message.answer(message.text)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question