yatbcpp  0.0.1
Yet another Telegram Bot CPP Library
telegram_simplemethodJSON.h
Go to the documentation of this file.
1 #ifndef YATBCPP_TELEGRAM_SIMPLEMETHODJSON_H
2 #define YATBCPP_TELEGRAM_SIMPLEMETHODJSON_H
3 
4 #include <curl/curl.h>
5 #include <jsoncpp/json/json.h>
6 #include "../exceptions/telegram_api_error.h"
7 #include "../exceptions/curl_error.h"
8 #include "../types/telegram_type.h"
9 #include "../exceptions/essential_key_missing.h"
10 #include "../bot/Token.h"
11 
12 namespace yatbcpp{
13 
19  public:
20 
21  telegram_simplemethodJSON(std::string functionname) : functionname(functionname){
22 
23  }
24 
25  static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *stringptr){
26  using namespace std;
27  ((string*)stringptr)->append((char*)contents, size * nmemb);
28  return size * nmemb;
29  }
30 
38  using namespace std;
39  string curl_payload( method_body.toJson().toStyledString() );
40  string api_url ( "https://api.telegram.org/bot" + T.getToken() + "/" + method_body.getFunctionname() );
41  string readBuffer;
42  Json::Reader reader;
43  Json::Value Response;
44  struct curl_slist * curl_header_list =NULL;
45  curl_header_list = curl_slist_append( curl_header_list , "Content-Type: application/json" );
46  CURL* curl = curl_easy_init();
47  curl_easy_setopt(curl,CURLOPT_URL,api_url.c_str());
48  curl_easy_setopt(curl,CURLOPT_POSTFIELDS,curl_payload.c_str());
49  curl_easy_setopt(curl,CURLOPT_HTTPHEADER,curl_header_list);
50  curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,WriteCallback);
51  curl_easy_setopt(curl,CURLOPT_WRITEDATA,&readBuffer);
52 
53  CURLcode res = curl_easy_perform(curl);
54  reader.parse(readBuffer,Response);
55  if(res!=CURLE_OK){
56  throw curl_error(res,curl_easy_strerror(res));
57  }
58  if(Response.isMember("ok")){
59  curl_slist_free_all(curl_header_list);
60  curl_easy_cleanup(curl);
61  return Response["ok"].asBool();
62  }
63  else{
64  curl_easy_cleanup(curl);
65  curl_slist_free_all(curl_header_list);
66  throw telegram_api_error(Response["error_code"].asInt(),Response["description"].asString());
67  }
68  }
73  virtual Json::Value toJson(){}
74 
79  const std::string &getFunctionname() const {
80  return functionname;
81  }
82 
83  protected:
84  std::string functionname;
85  };
86 
87 }
88 
89 
90 #endif //YATBCPP_TELEGRAM_SIMPLEMETHODJSON_H
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *stringptr)
Definition: Bot.h:27
static bool perform_simplerequestJSON(Token T, telegram_simplemethodJSON &method_body)
const std::string & getFunctionname() const
const std::string getToken() const
Definition: Token.cc:23
telegram_simplemethodJSON(std::string functionname)