reo7sp/tgbot-cpp

`sendMessage` does work with literal but not with passed variable.

milkpirate opened this issue · 2 comments

Hey,

Disclaimer: Please be aware, I am not suuuper familiar with C++, so any improvements and best practise suggestions are most welcome!

I am having trouble with sending messages if the text is passed though function args. My code looks pretty much like the following, could you please have a look and tell me whats wrong?

#pragma once

#include <string>

#include <tgbot/tgbot.h>

class TgAuthBot : public TgBot::Bot {
    public:
        TgAuthBot(const std::string& apiKey, std::int64_t chatId);
        bool isApproved(const std::string& prompt);

    private:
        std::int64_t _chatId;
};
#include "TgAuthBot.hpp"

TgAuthBot::TgAuthBot(const std::string& apiKey, std::int64_t chatId):
    _chatId(chatId),
    _log(log),
    TgBot::Bot(apiKey)
{
}

bool TgAuthBot::isApproved(const std::string& prompt) {
    TgBot::InlineKeyboardMarkup::Ptr keyboard(new TgBot::InlineKeyboardMarkup);
    TgBot::InlineKeyboardButton::Ptr lApprove(new TgBot::InlineKeyboardButton);
    TgBot::InlineKeyboardButton::Ptr rDecline(new TgBot::InlineKeyboardButton);
    std::vector<TgBot::InlineKeyboardButton::Ptr> keyboardRow;

    lApprove->text = "✅ Approve";
    rDecline->text = "Decline ❌";
    lApprove->callbackData = "approve";
    rDecline->callbackData = "decline";

    keyboardRow.push_back(lApprove);
    keyboardRow.push_back(rDecline);
    keyboard->inlineKeyboard.push_back(keyboardRow);

    this->getApi().sendMessage(_chatId, "literal", false, 0, keyboard, "MarkdownV2", false);    // works
    this->getApi().sendMessage(_chatId, prompt, false, 0, keyboard, "MarkdownV2", false);    // doesnt work (may raises exception?)
    this->getApi().sendMessage(_chatId, "another", false, 0, keyboard, "MarkdownV2", false);    // not executed ...

    return false;
}
...
    auto tgBot = TgAuthBot(apiKey, chatId);
    auto foo = tgBot.isApproved("decide!");
...

Stupid me, not escaping the ! in decide! and not catching exceptions while calling sendMessage like so 🙄:

    try {
        this->getApi().sendMessage(_chatId, prompt, false, 0, keyboard, "MarkdownV2", false);
    } catch (std::exception& e) {
        cout<<e.what()<<endl;
    }

Maybe you should close this issue then