M
M
MIKHAN_GO2021-06-29 11:11:36
Python
MIKHAN_GO, 2021-06-29 11:11:36

Why does telebot function fire twice?

def check(message):
    if client.get_chat_member(channel_chat_id,  message.chat.id).status in need_status:
        return True
    else:
        client.send_message(message.chat.id, subscribe_error_msg)
        return False

@client.message_handler(commands = ['start'], func=check)
def hello(message):
    with sqlite3.connect("users.db") as con:
        cur = con.cursor()
        info = cur.execute('SELECT * FROM users WHERE userid=?', (int(message.chat.id), ))
        if info.fetchone() is None:
            user_info = (int(message.chat.id), message.from_user.first_name, message.from_user.last_name, undefined_status)
            cur.execute(f"""INSERT INTO users VALUES(?, ?, ?, ?);""", user_info)
            con.commit()
    sti = open('static/welcome.webp', 'rb')
    client.send_sticker(message.chat.id, sti)

    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    item1 = types.KeyboardButton(register)

    markup.add(item1)

    client.send_message(message.chat.id, hello_message.format(message.from_user, client.get_me()), parse_mode='html', reply_markup=markup)

For some reason, if you are not in the channel, it displays 2 messages with the text "you are not subscribed to the channel."
If the user is subscribed to the channel, then everything is OK

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Krostelev, 2021-06-29
@MIKHAN_GO

Apparently, the situation is as follows:
you have several handlers, each of which checks for the presence of a user in the chat.

@client.message_handler(commands = ['start'], func=check)

@client.message_handler(content_type= ['text'], func=check)

etc.
The user sends a message. The check in the first handler is triggered. During this check, it is determined that the user is not in a chat, a message is sent to the user, and False is returned.
Due to the fact that the first handler did not work, the check in the next one works. And the situation repeats itself.
Alternatively, you can do the following:
As far as I understand, the bot should not do anything if the user is not in the chat.
Make a separate handler with a check that the user is NOT in the chat.
def check(message):
    if client.get_chat_member(channel_chat_id,  message.chat.id).status in need_status:
        return False
    else:
        return True

@client.message_handler(content_types=['text'], func=check)
def access_denied(message):
    client.send_message(message.chat.id, subscribe_error_msg)

And this handler must be placed above all the others, then it will catch all messages in general the very first. If the user is not in the desired chat, it works, it says that the check was not passed and that's it, other handlers will not work.
I think the point is clear.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question