Fix messages occasionally not going through
Discord API will occasionally throw 502 Bad Gateway errors. Retrying normally means this is not a problem.
This commit is contained in:
parent
db3ab59daf
commit
6b2464bad4
@ -1,9 +1,13 @@
|
||||
#include "http/HTTPHelper.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
|
||||
#include "APIHelper.hpp"
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
APIHelper::APIHelper() : BASE_URL("https://discordapp.com/api"), CHANNELS_URL(BASE_URL + "/channels"),
|
||||
JSON_CTYPE("application/json") {
|
||||
http = new HTTPHelper();
|
||||
@ -15,6 +19,15 @@ void APIHelper::send_message(std::string channel_id, std::string message) {
|
||||
{ "content", message }
|
||||
};
|
||||
|
||||
const std::string response = http->post_request(url, JSON_CTYPE, data.dump());
|
||||
// TODO: verify success
|
||||
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) {
|
||||
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++;
|
||||
}
|
||||
}
|
@ -6,7 +6,7 @@ extern std::string bot_token;
|
||||
* Warning: (Awful) C Code
|
||||
*/
|
||||
|
||||
std::string HTTPHelper::post_request(std::string url, std::string content_type, std::string data) {
|
||||
std::string HTTPHelper::post_request(std::string url, std::string content_type, std::string data, long *response_code) {
|
||||
CURL *curl;
|
||||
CURLcode res;
|
||||
std::string read_buffer;
|
||||
@ -37,8 +37,10 @@ std::string HTTPHelper::post_request(std::string url, std::string content_type,
|
||||
|
||||
res = curl_easy_perform(curl);
|
||||
|
||||
if (res != CURLE_OK) {
|
||||
return "ERROR";
|
||||
if (res == CURLE_OK) {
|
||||
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, response_code);
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
|
||||
/* always cleanup */
|
||||
@ -50,6 +52,6 @@ std::string HTTPHelper::post_request(std::string url, std::string content_type,
|
||||
}
|
||||
|
||||
size_t HTTPHelper::write_callback(void *contents, size_t size, size_t nmemb, void *userp) {
|
||||
((std::string *) userp)->append((char *)contents, size * nmemb);
|
||||
((std::string *) userp)->append((char *) contents, size * nmemb);
|
||||
return size * nmemb;
|
||||
}
|
@ -7,7 +7,7 @@
|
||||
|
||||
class HTTPHelper {
|
||||
public:
|
||||
std::string post_request(std::string url, std::string content_type, std::string data);
|
||||
std::string post_request(std::string url, std::string content_type, std::string data, long *response_code);
|
||||
|
||||
private:
|
||||
static size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp);
|
||||
|
Loading…
Reference in New Issue
Block a user