2016-08-04 17:39:48 +01:00
|
|
|
#include "APIHelper.hpp"
|
2016-07-10 01:18:13 +01:00
|
|
|
|
|
|
|
#include <cstdio>
|
2016-07-21 14:07:05 +01:00
|
|
|
#include <thread>
|
|
|
|
#include <chrono>
|
2016-07-10 01:18:13 +01:00
|
|
|
|
2016-08-04 17:39:48 +01:00
|
|
|
#include "http/HTTPHelper.hpp"
|
|
|
|
#include "Logger.hpp"
|
2016-07-10 01:18:13 +01:00
|
|
|
|
2016-07-21 14:07:05 +01:00
|
|
|
using namespace std::chrono_literals;
|
|
|
|
|
2016-07-10 19:17:35 +01:00
|
|
|
APIHelper::APIHelper() : BASE_URL("https://discordapp.com/api"), CHANNELS_URL(BASE_URL + "/channels"),
|
2016-07-20 22:57:47 +01:00
|
|
|
JSON_CTYPE("application/json") {
|
2016-07-10 01:18:13 +01:00
|
|
|
http = new HTTPHelper();
|
|
|
|
}
|
|
|
|
|
|
|
|
void APIHelper::send_message(std::string channel_id, std::string message) {
|
2016-08-04 18:16:09 +01:00
|
|
|
if (message == "") {
|
|
|
|
Logger::write("[send_message] Tried to send empty message", Logger::LogLevel::Warning);
|
2016-08-05 22:32:47 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (message.length() > 4000) {
|
|
|
|
Logger::write("[send_message] Tried to send a message over 4000 characters", Logger::LogLevel::Warning);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
else if (message.length() > 2000) {
|
|
|
|
std::cout << message.length() << std::endl;
|
|
|
|
|
|
|
|
std::string first = message.substr(0, 2000);
|
|
|
|
std::string second = message.substr(2000);
|
|
|
|
send_message(channel_id, first);
|
|
|
|
std::this_thread::sleep_for(50ms);
|
|
|
|
send_message(channel_id, second);
|
|
|
|
return;
|
2016-08-04 18:16:09 +01:00
|
|
|
}
|
|
|
|
|
2016-07-20 22:57:47 +01:00
|
|
|
const std::string url = CHANNELS_URL + "/" + channel_id + "/messages";
|
2016-07-10 01:18:13 +01:00
|
|
|
json data = {
|
|
|
|
{ "content", message }
|
|
|
|
};
|
|
|
|
|
2016-07-21 14:07:05 +01:00
|
|
|
std::string response;
|
|
|
|
long response_code = -1;
|
|
|
|
response = http->post_request(url, JSON_CTYPE, data.dump(), &response_code);
|
|
|
|
|
|
|
|
int retries = 0;
|
|
|
|
while (response_code != 200 && retries < 2) {
|
2016-08-04 17:39:48 +01:00
|
|
|
Logger::write("[send_message] Got non-200 response code, retrying", Logger::LogLevel::Warning);
|
2016-07-21 14:07:05 +01:00
|
|
|
std::this_thread::sleep_for(100ms);
|
|
|
|
// try 3 times. usually enough to prevent 502 bad gateway issues
|
|
|
|
response = http->post_request(url, JSON_CTYPE, data.dump(), &response_code);
|
|
|
|
retries++;
|
|
|
|
}
|
2016-08-04 17:39:48 +01:00
|
|
|
|
|
|
|
if (response_code != 200) {
|
|
|
|
Logger::write("[send_message] Giving up on sending message", Logger::LogLevel::Warning);
|
|
|
|
}
|
2016-07-10 01:18:13 +01:00
|
|
|
}
|