V
V
Vinogradov2021-10-06 22:23:25
Python
Vinogradov, 2021-10-06 22:23:25

How to write a function to clean up users who have blocked a bot in Telegram?

In general, the problem was described in the comments. I want to rewrite this code in such a way that I have a user cleanup function that adds users to the array through this error, then removes them from the database through a loop, and thus the mailing function works without bugs.

How to address this error directly so that the loop goes through the broken IDs?

@bot.message_handler(commands=['secretwords'])
def mess(message):
  
  # при вызове в боте команды /secretwords "какой-то текст"
  # происходит рассылка по всем пользователям

    
  try:

    # айди пользователей содержатся в базе данных
    # которая проходит через цикл
    # но при например 3-ем пользователе который заблокировал бота
    # цикл завершается и 4-ый пользователь не получается рассылку
    # получают только 1-ый и 2-ой

    sqlite_connection = sqlite3.connect('users.db')
    cursor = sqlite_connection.cursor()
    sqlite_select_query = """SELECT * from login_id"""
    cursor.execute(sqlite_select_query)
    records = cursor.fetchall()
    records = [i[0] for i in records]

    for user in records:
      a =[]
  
      #user = int(user)
      bot.send_message(user, message.text[message.text.find(' '):])
      
      a.append(user)
      print('norm',a)
      
  except telebot.apihelper.ApiException as e:

    if e.result.status_code == 403 or e.result.status_code == 400:
      b =[]
      b.append(user)
      print(b)
      
      n = 0

      connect = sqlite3.connect('users.db')
      cursor = connect.cursor()
      del_id = b[0]
      n+=1
      cursor.execute(f"DELETE FROM login_id WHERE id={del_id}")
      connect.commit()
      bot.send_message(message.from_user.id,f'пользователей удалено {n}')

    cursor.close()
  bot.send_message(message.from_user.id,f'пользователей всего {len(records)}')

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-10-06
@Vindicar

Move the try-except inside the for loop so that only the bot.send_message() call is inside the try-except, and that's it.
And why are you once again connecting to the database inside except, you already have a connection?

I
InternetMaster, 2021-10-06
@InternetMaster

It is necessary to make a mass mailing to all users with instant deletion of the sent message. Implement try-except. In except register deletion from the database.
Do you need ready-made code?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question