tgbot-cpp
Loading...
Searching...
No Matches
TgWebhookServer.h
Go to the documentation of this file.
1#pragma once
2
3#include "tgbot/Bot.h"
5#include "tgbot/HttpServer.h"
6
7#include <nlohmann/json.hpp>
8
9#include <memory>
10#include <string>
11#include <unordered_map>
12#include <utility>
13
14namespace TgBot {
15
19template<typename Protocol>
20class TgWebhookServer : public HttpServer<Protocol> {
21public:
22 TgWebhookServer(const typename boost::asio::basic_socket_acceptor<Protocol>::endpoint_type& endpoint,
23 const typename HttpServer<Protocol>::ServerHandler& handler) = delete;
24
25 TgWebhookServer(const typename boost::asio::basic_socket_acceptor<Protocol>::endpoint_type& endpoint,
26 std::string path, const EventHandler& eventHandler)
27 : HttpServer<Protocol>(endpoint,
28 [this](const std::string& _1, const std::unordered_map<std::string, std::string>& _2) {
29 return _handle(_1, _2);
30 })
31 , _path(std::move(path))
32 , _eventHandler(eventHandler) {
33 }
34
35 TgWebhookServer(const typename boost::asio::basic_socket_acceptor<Protocol>::endpoint_type& endpoint,
36 const Bot& bot)
37 : TgWebhookServer(endpoint, "/" + bot.getToken(), bot.getEventHandler()) {
38 }
39
40private:
41 std::string _handle(const std::string& data, const std::unordered_map<std::string, std::string>& headers) {
42 if (headers.at("_method") == "POST" && headers.at("_path") == _path) {
43 auto update = std::make_shared<Update>();
44 nlohmann::json::parse(data).get_to(*update);
45 _eventHandler.handleUpdate(update);
46 }
47 return { };
48 }
49
50 const std::string _path;
51 const EventHandler& _eventHandler;
52};
53
54} // namespace TgBot
This object holds other objects specific for this bot instance.
Definition Bot.h:20
void handleUpdate(const std::shared_ptr< Update > &update) const
HttpServer(const typename boost::asio::basic_socket_acceptor< Protocol >::endpoint_type &endpoint, ServerHandler handler)
Definition HttpServer.h:32
std::function< std::string(const std::string &, const std::unordered_map< std::string, std::string > &)> ServerHandler
Definition HttpServer.h:29
TgWebhookServer(const typename boost::asio::basic_socket_acceptor< Protocol >::endpoint_type &endpoint, const Bot &bot)
TgWebhookServer(const typename boost::asio::basic_socket_acceptor< Protocol >::endpoint_type &endpoint, std::string path, const EventHandler &eventHandler)
TgWebhookServer(const typename boost::asio::basic_socket_acceptor< Protocol >::endpoint_type &endpoint, const typename HttpServer< Protocol >::ServerHandler &handler)=delete
Definition Api.h:17