Answer the question
In order to leave comments, you need to log in
How to check the existence of chat_id when sending messages to a telegram bot?
Hello! There is a telegram bot with n subscribers. The user's chat_id is written to the database when the bot is launched. It is required to send a message through the bot to all its subscribers. Sending is implemented through a loop in which the chat_id array is iterated over, sending is done through sendMessage(). If the array contains a chat_id whose user deleted this bot, then the loop is interrupted and the script stops working. Is it possible to check chat_id for binding to a bot, validity? Is it possible to intercept the event: bot deletion and delete the chat_id from the database accordingly?
Answer the question
In order to leave comments, you need to log in
When sending to such a chat, an exception occurs (the server returns an error), it must be caught and processed (delete this chat from the database, for example), then the script will not crash.
You can check the user for his presence in the bot only through the mailing list
count = 0
errors = 0
with sq.connect('base.db') as con:
cur = con.cursor()
cur.execute('''SELECT userid FROM users''')
AllUser = cur.fetchall()
start_time = time.time()
for s in range(len(AllUser)):
user_id = AllUser[count][0]
try:
bot.send_message(user_id, text='Текст для рассылки')
count += 1
except:
count += 1
errors += 1
with sq.connect('base.db') as con:
cur = con.cursor()
cur.execute('''DELETE FROM users WHERE userid=?''', (user_id,)) # поймали ошибку на айди юзера и удалили его из базы
allusers = int(len(dataid))
goodresult = allusers - errors
goodresult = str(goodresult)
errors = str(errors)
times = "Время выполнения: %s сек." % round((time.time() - start_time))
sms = 'Рассылка завершена!'+'\n'+ 'Успешных результатов: '+goodresult+'\n'+'Ошибок: '+errors+'\n'+str(times)
bot.send_message(твой_айди, sms)# сюда придет уведомление о результатах рассылки
Thanks to all! I have a php bot.
Added an empty handler
function myCustomErrorHandler(int $errNo, string $errMsg, string $file, int $line) {}
set_error_handler('myCustomErrorHandler');
foreach($arUsers as $user) {
try {
$bot->send($user['chat_id']);
} catch (Throwable $e) {
$bot->run(
"DELETE FROM `users` WHERE `chat_id` = :chat_id",
array('chat_id' => $user['chat_id']),
PDO::FETCH_ASSOC
);
continue;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question