1818#include " discord.h"
1919#include < curl/curl.h>
2020#include " json.hpp"
21+ #include < atomic>
22+ #include < thread>
23+ #include < chrono>
2124
2225static std::string DiscordWebhook;
26+ static std::atomic_int threadCount;
2327
2428using namespace nlohmann ;
2529
@@ -75,13 +79,12 @@ class Notif
7579 } embed;
7680};
7781
78- static void postWebhook (const Notif& notif)
82+ static void postWebhook (Notif notif)
7983{
80- if (DiscordWebhook.empty () || notif.gameType < OOOGABOOGA || notif.gameType >= std::size (Games))
81- return ;
8284 CURL *curl = curl_easy_init ();
8385 if (curl == nullptr ) {
8486 fprintf (stderr, " Can't create curl handle\n " );
87+ threadCount.fetch_sub (1 );
8588 return ;
8689 }
8790 CURLcode res;
@@ -106,6 +109,20 @@ static void postWebhook(const Notif& notif)
106109 }
107110 curl_slist_free_all (headers);
108111 curl_easy_cleanup (curl);
112+ threadCount.fetch_sub (1 );
113+ }
114+
115+ static void discordNotif (const Notif& notif)
116+ {
117+ if (DiscordWebhook.empty () || notif.gameType < OOOGABOOGA || notif.gameType >= std::size (Games))
118+ return ;
119+ if (threadCount.fetch_add (1 ) > 5 ) {
120+ threadCount.fetch_sub (1 );
121+ fprintf (stderr, " Discord max thread count reached" );
122+ return ;
123+ }
124+ std::thread thread (postWebhook, notif);
125+ thread.detach ();
109126}
110127
111128void setDiscordWebhook (const std::string& url)
@@ -115,12 +132,18 @@ void setDiscordWebhook(const std::string& url)
115132
116133void discordLobbyJoined (GameType gameType, const std::string& username, const std::vector<std::string>& playerList)
117134{
135+ using the_clock = std::chrono::steady_clock;
136+ static the_clock::time_point last_notif;
137+ the_clock::time_point now = the_clock::now ();
138+ if (last_notif != the_clock::time_point () && now - last_notif < std::chrono::minutes (5 ))
139+ return ;
140+ last_notif = now;
118141 Notif notif (gameType);
119142 notif.content = " Player **" + username + " ** joined the lobby" ;
120143 notif.embed .title = " Lobby Players" ;
121144 for (const auto & player : playerList)
122145 notif.embed .text += player + " \n " ;
123- postWebhook (notif);
146+ discordNotif (notif);
124147}
125148
126149void discordGameCreated (GameType gameType, const std::string& username, const std::vector<std::string>& playerList)
@@ -131,5 +154,5 @@ void discordGameCreated(GameType gameType, const std::string& username, const st
131154 for (const auto & player : playerList)
132155 notif.embed .text += player + " \n " ;
133156
134- postWebhook (notif);
157+ discordNotif (notif);
135158}
0 commit comments