tgbot-cpp icon indicating copy to clipboard operation
tgbot-cpp copied to clipboard

How to skip the "Forbidden: bot was blocked by the user" error?

Open Amirhan-Taipovjan-Greatest-I opened this issue 2 years ago • 2 comments

The case: User sent a command and then blocked the bot when bot was switched off.

I can't make any solution for this problem. try-catch, if-else... they didn't help Me. The program sends the error and stops ownself...

you may write a recursive script, in which on specific error like blocked by user, script starts again like: int main() {try {} catch(exception &e) {if (e == "something") {main()}}}

miannoodle01 avatar Apr 13 '23 21:04 miannoodle01

if(bot.getApi().blockedByUser(message->chat->id)) return;

Adding this condition check to the beginning of each 'listener' solved the problem for me.

For instance:

bot.getEvents().onAnyMessage([&bot](Message::Ptr message) {
       if(bot.getApi().blockedByUser(message->chat->id)) return;
       printf("User wrote %s\n", message->text.c_str());
       if (StringTools::startsWith(message->text, "/start")) {
           return;
       }
       bot.getApi().sendMessage(message->chat->id, "Your message is: " + message->text);
   });

rd181002 avatar May 14 '24 01:05 rd181002