Add tgbot-cpp connector
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
#include <iostream>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
#include "connectors/tgbot-cpp/TgbotCppConnector.h"
|
||||
#include "connectors/BotToken.h"
|
||||
#include "connectors/Types.h"
|
||||
|
||||
namespace MBFT
|
||||
{
|
||||
TgbotCppConnector::TgbotCppConnector(void)
|
||||
{
|
||||
char token_buf[MBFT::BotToken::get_token_length() + 1];
|
||||
|
||||
if (!MBFT::BotToken::load_token(token_buf))
|
||||
{
|
||||
std::cout << __FILE__ << ": Failed to load token\n";
|
||||
return;
|
||||
}
|
||||
|
||||
bot = std::make_unique<TgBot::Bot>(std::string(token_buf));
|
||||
|
||||
(*bot).getEvents().onAnyMessage(
|
||||
[this](TgBot::Message::Ptr message)
|
||||
{
|
||||
inbound_message_callback(message);
|
||||
}
|
||||
);
|
||||
|
||||
inbound_thread = std::thread(TgbotCppConnector::inbound_message_thread, std::ref(*bot));
|
||||
outbound_thread = std::thread(TgbotCppConnector::outbound_message_thread, std::ref(*bot), std::ref(sendQ));
|
||||
}
|
||||
|
||||
void TgbotCppConnector::inbound_message_thread(TgBot::Bot& bot)
|
||||
{
|
||||
TgBot::TgLongPoll longPoll(bot);
|
||||
|
||||
for ( ; ; )
|
||||
{
|
||||
std::cout << __FILE__ << ": Started polling\n";
|
||||
longPoll.start();
|
||||
}
|
||||
}
|
||||
|
||||
void TgbotCppConnector::inbound_message_callback(TgBot::Message::Ptr message)
|
||||
{
|
||||
std::shared_ptr<MBFT::InboundMessage> new_msg = std::make_shared<MBFT::InboundMessage>();
|
||||
MBFT::InboundMessage& msg_ref = *new_msg;
|
||||
|
||||
msg_ref.id = message->messageId;
|
||||
msg_ref.date = message->date;
|
||||
msg_ref.text = message->text;
|
||||
|
||||
msg_ref.from = std::make_shared<User>();
|
||||
msg_ref.from->id = message->from->id;
|
||||
msg_ref.from->firstName = message->from->firstName;
|
||||
msg_ref.from->lastName = message->from->lastName;
|
||||
msg_ref.from->username = message->from->username;
|
||||
|
||||
msg_ref.chat = std::make_shared<Chat>();
|
||||
msg_ref.chat->id = message->chat->id;
|
||||
msg_ref.chat->title = message->chat->title;
|
||||
|
||||
recvQ.push(new_msg);
|
||||
}
|
||||
|
||||
void TgbotCppConnector::outbound_message_thread(TgBot::Bot& bot, MBFT::ThreadSafeQueue<std::shared_ptr<MBFT::OutboundMessage>>& q)
|
||||
{
|
||||
std::shared_ptr<MBFT::OutboundMessage> msg;
|
||||
|
||||
for ( ; ; )
|
||||
{
|
||||
msg = q.pop();
|
||||
bot.getApi().sendMessage(msg->target_chat_id, msg->text);
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<MBFT::InboundMessage> TgbotCppConnector::receive(void)
|
||||
{
|
||||
return recvQ.pop();
|
||||
}
|
||||
|
||||
void TgbotCppConnector::send(std::shared_ptr<MBFT::OutboundMessage>& msg)
|
||||
{
|
||||
sendQ.push(msg);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user