reo7sp / tgbot-cpp

C++ library for Telegram bot API
http://reo7sp.github.io/tgbot-cpp
MIT License
1.01k stars 246 forks source link

how to bind function istead of labmda? #102

Closed micfan closed 5 years ago

micfan commented 5 years ago

As in the demo, all the callback is lambda: https://github.com/reo7sp/tgbot-cpp/blob/master/samples/echobot-curl-client/src/main.cpp#L18

how to bind a function handler?

JellyBrick commented 5 years ago
void handler(Message::Ptr message) {
     //do something
}

…

bot.getEvents().onCommand("start", &handler);
//or bot.getEvents().onCommand("start", handler);
micfan commented 5 years ago

Thanks,

the function void hander(Message::Ptr message), how to get access of bot object?

JellyBrick commented 5 years ago

Use 'global object', or use tricks.

Example)

  1. Global Object
    
    TgBot::Bot bot(…)

void handler(TgBot::Message::Ptr message) { //do something }

bot.getEvents().onCommand("start", &handler); //or bot.getEvents().onCommand("start", handler);

2. Trick

void handler(TgBot::Message::Ptr message, TgBot::Bot& bot) { //do something } …

bot.getEvents().onCommand("start", [&bot] (TgBot::Message::Ptr message) { handler(message, bot); });

micfan commented 5 years ago

@JellyBrick Thank your kindly show case very much!