forked from serafim/dos
1
0
Fork 0
dos/my_msg.cpp

58 lines
1.8 KiB
C++

#include <iostream>
#include <string>
#include <curl/curl.h>
#include <cctype>
using namespace std;
string telegram_id;
string bot_token;
int my_msg(const string& msg) {
cout << msg << endl;
CURL* curl = curl_easy_init();
if (!curl) return 6;
string escaped_msg = escape_json(msg);
string chat_id_field;
if (is_numeric(telegram_id)) {
chat_id_field = "\"chat_id\": " + telegram_id;
} else {
chat_id_field = "\"chat_id\": \"" + telegram_id + "\"";
}
string json_data = "{" + chat_id_field + ", \"text\": \"" + escaped_msg + "\"}";
struct curl_slist* headers = nullptr;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_URL, ("https://api.telegram.org/bot" + bot_token + "/sendMessage").c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl/7.68.0");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, [](void*, size_t size, size_t nmemb, void*) -> size_t {
return size * nmemb;
});
CURLcode res = curl_easy_perform(curl);
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
if (res != CURLE_OK) return 5;
switch (http_code) {
case 200: return 0; // Успех
case 401: return 1; // Неверный токен
case 400: return 2; // Неверный chat_id
case 404: return 3; // Неверный URL (бот не найден)
default:
return 4; // Ошибка сервера (500)
}
}