R
R
Revs12021-10-26 13:23:40
Python
Revs1, 2021-10-26 13:23:40

How to bypass users who blocked the bot when mailing?

Hello!
I am writing a bot in which user IDs are written to a txt file at startup, but an error occurs when sending to users, since the file contains users who have blocked the bot.
How can I make sure that these users are deleted from the txt file, or at least ignored, and the mailing goes to the next id?

Here is the code with the id entry in the txt file and the mailing itself:

import telebot
from telebot import *

bot = telebot.TeleBot('token')

joinedFile = open("D:/тестбот/joined.txt",'r')
joinedUsers = set ()
for line in joinedFile:
  joinedUsers.add(line.strip())
joinedFile.close()  

@bot.message_handler(commands=['start'])
def startJoin(message):
  if not str(message.chat.id) in joinedUsers:
    joinedFile=open("D:/тестбот/joined.txt", 'a')
    joinedFile.write(str(message.chat.id) + "\n")
    joinedUsers.add(message.chat.id)
    bot.send_message(message.chat.id, 'Добро пожаловать!')
 

@bot.message_handler(commands=['special'])
def mess(message):
  for user in joinedUsers:
    bot.send_message(user,message.text[message.text.find(' '):],parse_mode='MarkdownV2')

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eggsy, 2021-10-26
@Eggsy

Maybe you should use exceptions in Python? ( https://yandex.ru/search/?text=try+except+python&l... )

A
Alexander Ananchenko, 2021-10-27
@Shurik24

I recommend moving away from txt files towards the database, create a users table and write TgID Block into it.
Normally, all new users have such an entry
100000 False (Telegram ID, Blocked?)
When sending a message to the user, use try except

try:
    send_message(my message)
except:
   db.set(update Block = True, where TgID = telegramid) #Это вообще вымышленная работа с бд ибо фиг знает какую будешь юзать

Well, when you send out messages again, you just take all the IDs that have Block = Flase
And if you don’t want to learn how to use databases (it’s a pity the thing is good: C) you can just do this
try:
   send_message(my message)
except:
   pass

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question