B
B
bakin20042019-09-29 10:16:18
Python
bakin2004, 2019-09-29 10:16:18

How to make it so that if the conditions are not met, the bot stops further work?

There is the following code, which checks if the user has an id in the list. If it is not present, then a message is displayed.

import telebot
bot = telebot.TeleBot('мой токен') 

users = [id1,id2,id3]

@bot.message_handler(func=lambda message: message.chat.id not in users)
def CheckUser(message):
    bot.send_message(message.chat.id, "Извини, но ты не можешь работать с ботом")

bot.polling(none_stop=True, interval=0)

How to make it so that the user who is on the list can execute bot commands, and the user who is not there cannot?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Forevka69, 2019-10-04
@Forevka69

as an option to raise an error.

class DontNeedToDo(Exception):
    pass

@bot.message_handler(func=lambda message: message.chat.id not in users)
def CheckUser(message):
    bot.send_message(message.chat.id, "Извини, но ты не можешь работать с ботом")
    raise DontNeedToDo()

In this case, after sending the SMS, an error will be raised and the code will stop running.
Just check if the polling will not fall because of this

D
Danil K., 2019-10-30
@Danya_Violet

# Ограничение доступа к боту по ID
@bot.message_handler(func=lambda message: message.chat.id not in users)
def some(message):
    bot.send_message(message.chat.id, 'Не дозволено общаться с незнакомцами')


# Ограничение выполнение команды start
@bot.message_handler(func=lambda message: message.chat.id not in users, commands=['start'])
def some(message):
    bot.send_message(message.chat.id, 'Не дозволено')


# Ограничение выполнение команд
@bot.message_handler(func=lambda message: message.chat.id not in users_command,
                     commands=['command1', 'command2', 'command3', 'command4'])
def some(message):
    bot.send_message(message.chat.id, 'Не дозволено')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question