N
N
Novichek20002020-04-01 17:48:25
Layout
Novichek2000, 2020-04-01 17:48:25

Python Telegram Bot. How to remove the user's user ID from a text file when encountering a 403 error (bot in chs)?

import telebot
import time
import schedule
import threading
from telebot import apihelper


This is how my user IDs get into the text file ids.txt :

@bot.message_handler(commands=['start'])
def welcome(message):
  # База данных
  user_id = message.from_user.id
  print(user_id)
  def add_id(filename: str, client_id: str) -> None:
    ids = set()
    try:
      with open(filename, "r") as f_read:
        ids.update([id_n.strip() for id_n in f_read.readlines()])
    except FileNotFoundError:
      pass

    ids.update([client_id])

    with open(filename, "w") as f_write:
      f_write.writelines([new_id + "\n" for new_id in ids])

  def check_id(filename: str, client_id: str) -> bool:
    try:
      with open(filename, "r") as f_read:
        return client_id in [id_n.strip() for id_n in f_read.readlines()]
    except FileNotFoundError:
      return False

  add_id("ids.txt", str(user_id))

def get_all_ids(filename: str) -> bool:
  try:
    with open(filename, "r") as f_read:
      return [id_n.strip() for id_n in f_read.readlines()]
  except FileNotFoundError:
    return False


This is how it sends scheduled messages:

def thread(my_func):
    def wrapper(*args, **kwargs):
        my_thread = threading.Thread(target=my_func, args=args, kwargs=kwargs)
        my_thread.start()
    return wrapper

def job_utro():
  for client_id in get_all_ids("ids.txt"):
    try:
      bot.send_message(int(client_id), "Доброе утро!")
    except Exception as e:
      print(repr(e))
      print("Неудачка_утро\nПользователь добавил бота в Черный Список...\n")

@thread
def vremya_utro():
  schedule.every().day.at("08:00").do(job_utro)

vremya_utro()


And when the bot sends scheduled messages, it often stumbles upon a 403 error (the bot was added to the emergency).
And here is the question: How to make it so that when the bot encounters a 403 error, it deletes the user who added the bot to the chs from the ids.txt text document and continues to write scheduled messages?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor, 2020-04-01
@adnim

In the try block, immediately after send_message, write the ID to a new file,
after sending, write the resulting file to the original one

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question