Compare commits

...

3 Commits

Author SHA1 Message Date
fd16e499b3 fixes 2025-01-20 16:07:42 +05:00
7079675d94 deleted try catch 2025-01-20 15:14:27 +05:00
b85478d64b compiler 2025-01-20 15:12:57 +05:00
14 changed files with 107 additions and 106 deletions

View File

@ -8,11 +8,27 @@ set(SOURCE sources/main.cpp)
set(LIBS ${CMAKE_SOURCE_DIR}/libs/) set(LIBS ${CMAKE_SOURCE_DIR}/libs/)
set(INCLUDE ${CMAKE_SOURCE_DIR}/include/) set(INCLUDE ${CMAKE_SOURCE_DIR}/include/)
set(TESTS ${CMAKE_SOURCE_DIR}/tests) set(TESTS ${CMAKE_SOURCE_DIR}/tests)
set(CMAKE_C_COMPILER "clang")
set(CMAKE_CXX_COMPILER "clang++")
find_program(CMAKE_C_COMPILER clang)
find_program(CLANG_CXX_COMPILER clang++)
find_package(CURL REQUIRED) find_package(CURL REQUIRED)
find_path(IXWEBSOCKET_INCLUDE_DIR ixwebsocket) find_path(IXWEBSOCKET_INCLUDE_DIR ixwebsocket)
find_library(IXWEBSOCKET_LIBRARIES ixwebsocket) find_library(IXWEBSOCKET_LIBRARIES ixwebsocket)
if(NOT CMAKE_C_COMPILER OR NOT CLANG_CXX_COMPILER)
message(STATUS "clang not found")
set(CMAKE_C_COMPILER "gcc")
set(CMAKE_CXX_COMPILER "g++")
find_program(CMAKE_C_COMPILER clang)
find_program(CLANG_CXX_COMPILER clang++)
if(NOT CMAKE_C_COMPILER OR NOT CLANG_CXX_COMPILER)
message(FATAL_ERROR "gcc not found")
endif()
endif()
message(STATUS "current compiler: ${CMAKE_C_COMPILER}")
if(NOT IXWEBSOCKET_INCLUDE_DIR OR NOT IXWEBSOCKET_LIBRARIES) if(NOT IXWEBSOCKET_INCLUDE_DIR OR NOT IXWEBSOCKET_LIBRARIES)
message(FATAL_ERROR "ixwebsocket not found") message(FATAL_ERROR "ixwebsocket not found")
endif() endif()
@ -61,4 +77,3 @@ target_link_libraries(${PROJECT_NAME} PRIVATE
set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED True) set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_CXX_FLAGS "-march=native -O2 -pipe") set(CMAKE_CXX_FLAGS "-march=native -O2 -pipe")
#set(CMAKE_CXX_FLAGS "-O0 -pipe")

View File

@ -2,56 +2,44 @@
#define API_AUTHOR_HPP_ #define API_AUTHOR_HPP_
#include <includes.h> #include <includes.h>
#include <net.h> #include <net.h>
using std::string, std::cout, std::endl, nlohmann::json;
class Author { class Author {
private: private:
json data; nlohmann::json data;
const nlohmann::json &d;
WebSocket& web; WebSocket& web;
NetworkManager& req; NetworkManager& req;
public: public:
Author(const json& data) : Author(const nlohmann::json& data) :
data(data), data(data),
d(data["d"]),
web(WebSocket::getInstance()), web(WebSocket::getInstance()),
req(NetworkManager::getInstance()), req(NetworkManager::getInstance()),
channel_id(functions::isNull(data["d"]["channel_id"])), channel_id(functions::isNull(d["channel_id"])),
global_name(functions::isNull(data["d"]["author"]["global_name"])), global_name(functions::isNull(d["author"]["global_name"])),
id(data["d"]["author"]["id"]) id(d["author"]["id"]),
content(d["content"]),
isBot(d["author"].contains("bot") ? d["author"]["bot"].get<bool>() : false)
{ {
}; };
string content() const { const std::string channel_id, global_name, id, content;
try { bool isBot;
return data["d"]["content"]; std::string discriminator() const {
}
catch (...) {
return "";
}
}
const string channel_id, global_name, id;
string discriminator() const {
return data["d"]["author"]["discriminator"]; return data["d"]["author"]["discriminator"];
} }
bool isBot() const { std::string guild_id() {
try {
return data["d"]["author"]["bot"];
}
catch (...) {
return 0;
}
}
string guild_id() {
return data["d"]["guild_id"]; return data["d"]["guild_id"];
} }
string msg_id() { std::string msg_id() {
return data["d"]["id"]; return data["d"]["id"];
} }
bool isPinned() { bool isPinned() {
return data["d"]["pinned"]; return data["d"]["pinned"];
} }
string avatar() { std::string avatar() {
return data["d"]["author"]["avatar"]; return data["d"]["author"]["avatar"];
} }
string send(const json& msg) { std::string send(const nlohmann::json& msg) {
return req.request(HttpMethods::POST, DiscordEndpoints::details::latest + "/channels/" + data["d"]["channel_id"].get<string>() + "/messages", msg.dump()); return req.request(HttpMethods::POST, DiscordEndpoints::details::latest + "/channels/" + data["d"]["channel_id"].get<std::string>() + "/messages", msg.dump());
} }
}; };
#endif #endif

View File

@ -1,20 +1,20 @@
#ifndef API_BOT_HPP_ #ifndef API_BOT_HPP_
#define API_BOT_HPP_ #define API_BOT_HPP_
#include <includes.h> #include <includes.h>
using std::string, std::cout, std::endl, nlohmann::json;
template<typename...Args> template<typename...Args>
class Discord { class Discord {
private: private:
std::tuple<std::unique_ptr<Args>...> net; std::tuple<std::unique_ptr<Args>...> net;
json data; nlohmann::json data;
void initializeNets(const json& data) { void initializeNets(const nlohmann::json& data) {
initializeNetsImpl(data, std::index_sequence_for<Args...>{}); initializeNetsImpl(data, std::index_sequence_for<Args...>{});
} }
template<unsigned long... Is>void initializeNetsImpl(const json& data, std::index_sequence<Is...>) { template<unsigned long... Is>
void initializeNetsImpl(const nlohmann::json& data, std::index_sequence<Is...>) {
net = std::make_tuple(std::make_unique<Args>(data)...); net = std::make_tuple(std::make_unique<Args>(data)...);
} }
public: public:
Discord(const json& data) : data(data) { Discord(const nlohmann::json& data) : data(data) {
initializeNets(data); initializeNets(data);
} }
template<unsigned long Index> template<unsigned long Index>
@ -24,10 +24,10 @@ public:
}; };
class Bot { class Bot {
private: private:
json data; nlohmann::json data;
public: public:
Bot(const json& data) : data(data) {}; Bot(const nlohmann::json& data) : data(data) {};
string id() const { std::string id() const {
return data["d"]["id"]; return data["d"]["id"];
} }
bool isBot() const { bool isBot() const {

View File

@ -2,16 +2,15 @@
#define API_CHANNEL_HPP_ #define API_CHANNEL_HPP_
#include <includes.h> #include <includes.h>
#include <net.h> #include <net.h>
using std::string, std::cout, std::endl, nlohmann::json;
class Channel { class Channel {
private: private:
json data; nlohmann::json data;
WebSocket& web; WebSocket& web;
NetworkManager& req; NetworkManager& req;
public: public:
Channel(const json& data = "") : data(data), web(WebSocket::getInstance()), req(NetworkManager::getInstance()) {} Channel(const nlohmann::json& data = "") : data(data), web(WebSocket::getInstance()), req(NetworkManager::getInstance()) {}
string send(const json& msg) { std::string send(const nlohmann::json& msg) {
return req.request(HttpMethods::POST, DiscordEndpoints::details::latest + "/channels/" + data["d"]["channel_id"].get<string>() + "/messages", msg.dump()); return req.request(HttpMethods::POST, DiscordEndpoints::details::latest + "/channels/" + data["d"]["channel_id"].get<std::string>() + "/messages", msg.dump());
} }
}; };
#endif #endif

View File

@ -1,58 +1,57 @@
#ifndef API_EMBED_HPP_ #ifndef API_EMBED_HPP_
#define API_EMBED_HPP_ #define API_EMBED_HPP_
#include <includes.h> #include <includes.h>
using std::string, std::cout, std::endl, nlohmann::json;
class EmbedBuilder { class EmbedBuilder {
private: private:
json embed = { nlohmann::json embed = {
{"content", ""}, {"content", ""},
{"tts", false}, {"tts", false},
{"embeds", json::array()} {"embeds", nlohmann::json::array()}
}, data; }, data;
public: public:
EmbedBuilder(const json& data) : data(data) { EmbedBuilder(const nlohmann::json& data) : data(data) {
embed = { embed = {
{"content", ""}, {"content", ""},
{"tts", false}, {"tts", false},
{"embeds", json::array()} {"embeds", nlohmann::json::array()}
}; };
} }
EmbedBuilder& addTitle(const string& title) { EmbedBuilder& addTitle(const std::string& title) {
if (embed["embeds"].size() == 0) { if (embed["embeds"].size() == 0) {
embed["embeds"].push_back(json::object()); embed["embeds"].push_back(nlohmann::json::object());
} }
embed["embeds"].back()["title"] = title; embed["embeds"].back()["title"] = title;
return *this; return *this;
} }
EmbedBuilder& addDescription(const string& desc) { EmbedBuilder& addDescription(const std::string& desc) {
if (embed["embeds"].size() == 0) { if (embed["embeds"].size() == 0) {
embed["embeds"].push_back(json::object()); embed["embeds"].push_back(nlohmann::json::object());
} }
embed["embeds"].back()["description"] = desc; embed["embeds"].back()["description"] = desc;
return *this; return *this;
} }
EmbedBuilder& addColor(const string& color) { EmbedBuilder& addColor(const std::string& color) {
if (embed["embeds"].size() == 0) { if (embed["embeds"].size() == 0) {
embed["embeds"].push_back(json::object()); embed["embeds"].push_back(nlohmann::json::object());
} }
embed["embeds"].back()["color"] = color; embed["embeds"].back()["color"] = color;
return *this; return *this;
} }
EmbedBuilder& addUrl(const string& url) { EmbedBuilder& addUrl(const std::string& url) {
if (embed["embeds"].size() == 0) { if (embed["embeds"].size() == 0) {
embed["embeds"].push_back(json::object()); embed["embeds"].push_back(nlohmann::json::object());
} }
embed["embeds"].back()["url"] = url; embed["embeds"].back()["url"] = url;
return *this; return *this;
} }
EmbedBuilder& addImage(const string& imageurl) { EmbedBuilder& addImage(const std::string& imageurl) {
if (embed["embeds"].size() == 0) { if (embed["embeds"].size() == 0) {
embed["embeds"].push_back(json::object()); embed["embeds"].push_back(nlohmann::json::object());
} }
embed["embeds"].back()["image"] = { {"url", imageurl} }; embed["embeds"].back()["image"] = { {"url", imageurl} };
return *this; return *this;
} }
json getEmbed() const { nlohmann::json getEmbed() const {
return embed; return embed;
} }
}; };

View File

@ -1,14 +1,13 @@
#ifndef API_GUILD_HPP_ #ifndef API_GUILD_HPP_
#define API_GUILD_HPP_ #define API_GUILD_HPP_
#include <includes.h> #include <includes.h>
//#include <net.h> #include <net.h>
using std::string, std::cout, std::endl, nlohmann::json;
class Guild { class Guild {
private: private:
json data; nlohmann::json data;
public: public:
Guild(const json& data) : data(data) {} Guild(const nlohmann::json& data) : data(data) {}
string id() const { std::string id() const {
return data["d"]["user"]["id"]; return data["d"]["user"]["id"];
} }
}; };

View File

@ -2,18 +2,18 @@
#define API_MESSAGE_HPP_ #define API_MESSAGE_HPP_
#include <includes.h> #include <includes.h>
#include <net.h> #include <net.h>
using std::string, std::cout, std::endl, nlohmann::json;
class Message { class Message {
private: private:
json data; nlohmann::json data;
WebSocket& web; WebSocket& web;
NetworkManager& req; NetworkManager& req;
public: public:
Message(const json& data) : data(data), web(WebSocket::getInstance()), req(NetworkManager::getInstance()) {}; Message(const nlohmann::json& data) : data(data), web(WebSocket::getInstance()), req(NetworkManager::getInstance()) {};
string send(const string& id, const json& msg) { std::string send(const std::string& id, const nlohmann::json& msg) {
std::cout << id << msg << std::endl;
return req.request(HttpMethods::POST, DiscordEndpoints::details::latest + "/channels/" + id + "/messages", msg.dump()); return req.request(HttpMethods::POST, DiscordEndpoints::details::latest + "/channels/" + id + "/messages", msg.dump());
} }
string getMessages(const string& id, const string& count, const string& before = "") { std::string getMessages(const std::string& id, const std::string& count, const std::string& before = "") {
if (before.empty()) { if (before.empty()) {
return req.request(HttpMethods::GET, DiscordEndpoints::details::latest + "/channels/" + id + "/messages?limit=" + count); return req.request(HttpMethods::GET, DiscordEndpoints::details::latest + "/channels/" + id + "/messages?limit=" + count);
} }
@ -22,11 +22,11 @@ public:
} }
return ""; return "";
} }
string deleteMessage(const string& channel_id, const string& message_id) { std::string deleteMessage(const std::string& channel_id, const std::string& message_id) {
return req.request(HttpMethods::DELETE, DiscordEndpoints::details::latest + "/channels/" + channel_id + "/messages/" + message_id); return req.request(HttpMethods::DELETE, DiscordEndpoints::details::latest + "/channels/" + channel_id + "/messages/" + message_id);
} }
json pack(const json& pack) const { nlohmann::json pack(const nlohmann::json& key, const std::string& value) const {
return { pack }; return {{ key, value }};
} }
}; };
#endif #endif

View File

@ -3,18 +3,18 @@
#include <includes.h> #include <includes.h>
#include <net.h> #include <net.h>
#include <vector> #include <vector>
using std::string, std::cout, std::endl, nlohmann::json;
class User { class User {
private: private:
json data; nlohmann::json data;
WebSocket& web; WebSocket& web;
NetworkManager& req; NetworkManager& req;
public: public:
User(const json& data = "") : data(data), web(WebSocket::getInstance()), req(NetworkManager::getInstance()) {} User(const nlohmann::json& data = "") : data(data), web(WebSocket::getInstance()), req(NetworkManager::getInstance()) {}
json extract(const std::vector<string>& keys) { #ifdef DEBUG
std::vector<string> d = { "d" }; nlohmann::json extract(const std::vector<std::string>& keys) {
std::vector<std::string> d = { "d" };
d.insert(d.end(), keys.begin(), keys.end()); d.insert(d.end(), keys.begin(), keys.end());
json current = data; nlohmann::json current = data;
for (const auto& key : d) { for (const auto& key : d) {
if (current.contains(key)) { if (current.contains(key)) {
current = current[key]; current = current[key];
@ -25,7 +25,8 @@ public:
} }
return current; return current;
} }
virtual string me() { #endif
std::string me() {
return req.request(HttpMethods::GET, DiscordEndpoints::details::latest + "/users/@me"); return req.request(HttpMethods::GET, DiscordEndpoints::details::latest + "/users/@me");
} }
bool isBot() const { bool isBot() const {

View File

@ -5,7 +5,6 @@
#include <chrono> #include <chrono>
#include <ixwebsocket/IXNetSystem.h> #include <ixwebsocket/IXNetSystem.h>
#include <ixwebsocket/IXWebSocket.h> #include <ixwebsocket/IXWebSocket.h>
using std::string, std::cout, std::endl, nlohmann::json;
using namespace std::chrono; using namespace std::chrono;
using namespace std::chrono_literals; using namespace std::chrono_literals;
class WebSocket { class WebSocket {
@ -14,11 +13,11 @@ private:
int intents; int intents;
std::string token; std::string token;
ix::WebSocket webSocket; ix::WebSocket webSocket;
json payload = { {"op", 1},{"d", nullptr} }, id; nlohmann::json payload = { {"op", 1},{"d", nullptr} }, id;
std::unordered_map<std::string, std::function<void(const json&)>> eventHandlers; std::unordered_map<std::string, std::function<void(const nlohmann::json&)>> eventHandlers;
WebSocket& operator=(const WebSocket&) = delete; WebSocket& operator=(const WebSocket&) = delete;
WebSocket(const WebSocket&) = delete; WebSocket(const WebSocket&) = delete;
WebSocket(const std::string& token, const int& intents, bool& isBot) { WebSocket(const std::string& token, const int& intents, const bool& isBot) {
WebSocket::token = token; WebSocket::token = token;
WebSocket::intents = intents; WebSocket::intents = intents;
WebSocket::isBot = isBot; WebSocket::isBot = isBot;
@ -34,7 +33,7 @@ private:
}}, }},
//{"compress", 1}, //{"compress", 1},
{"presence", { {"presence", {
{"activities", json::array({ {"activities", nlohmann::json::array({
{ {
//{"name", "asdsadsadsadsa"}, //{"name", "asdsadsadsadsa"},
//{"type", 2} //{"type", 2}
@ -50,9 +49,9 @@ private:
webSocket.setUrl("wss://gateway.discord.gg/?v=10&encoding=json"); webSocket.setUrl("wss://gateway.discord.gg/?v=10&encoding=json");
webSocket.setHandshakeTimeout(5); webSocket.setHandshakeTimeout(5);
Log::create(INFO, WEBSOCKET, "ixwebsocket init"); Log::create(INFO, WEBSOCKET, "ixwebsocket init");
webSocket.setOnMessageCallback([this, res = json(), heartbeat_interval = 0, connected = false](const ix::WebSocketMessagePtr& msg) mutable { webSocket.setOnMessageCallback([this, res = nlohmann::json(), heartbeat_interval = 0, connected = false](const ix::WebSocketMessagePtr& msg) mutable {
if (msg->type == ix::WebSocketMessageType::Message) { if (msg->type == ix::WebSocketMessageType::Message) {
res = json::parse(msg->str); res = nlohmann::json::parse(msg->str);
Log::create(INFO, WEBSOCKET, res["op"].dump() + " " + res["t"].dump()); Log::create(INFO, WEBSOCKET, res["op"].dump() + " " + res["t"].dump());
switch (res["op"].get<int>()) { switch (res["op"].get<int>()) {
case 10: case 10:
@ -106,14 +105,14 @@ public:
int getIntents() const { int getIntents() const {
return WebSocket::intents; return WebSocket::intents;
} }
void on(const string& event, std::function<void(const json&)> handler) { void on(const std::string& event, std::function<void(const nlohmann::json&)> handler) {
eventHandlers[event] = [handler](const json& message) { eventHandlers[event] = [handler](const nlohmann::json& message) {
handler(message.get<json>()); handler(message.get<nlohmann::json>());
}; };
} }
void once(const string& event, std::function<void(const json&)> handler) { void once(const std::string& event, std::function<void(const nlohmann::json&)> handler) {
eventHandlers[event] = [event, handler, isCalled = false](const json& message) mutable { eventHandlers[event] = [event, handler, isCalled = false](const nlohmann::json& message) mutable {
isCalled == false ? isCalled = true : 0, handler(message.get<json>()); isCalled == false ? isCalled = true : 0, handler(message.get<nlohmann::json>());
}; };
} }
void start() { void start() {

View File

@ -3,7 +3,6 @@
#include <includes.h> #include <includes.h>
#include <gateway/Websocket.hpp> #include <gateway/Websocket.hpp>
#include <curl/curl.h> #include <curl/curl.h>
using std::string, std::cout, std::endl, nlohmann::json;
class NetworkManager { class NetworkManager {
private: private:
CURL* curl; CURL* curl;
@ -53,6 +52,9 @@ public:
if ((res = curl_easy_perform(curl)) != 0) Log::create(ERROR, NETWORK, "curl_easy_perform() failed: " + std::string(curl_easy_strerror(res))); if ((res = curl_easy_perform(curl)) != 0) Log::create(ERROR, NETWORK, "curl_easy_perform() failed: " + std::string(curl_easy_strerror(res)));
curl_slist_free_all(headers); curl_slist_free_all(headers);
} }
#ifdef DEBUG
Log::create(INFO, NETWORK, response);
#endif
return response; return response;
} }
}; };

View File

@ -2,12 +2,7 @@
#define UTILS_FUNCTIONS_HPP_ #define UTILS_FUNCTIONS_HPP_
struct functions { struct functions {
static inline std::string isNull(const nlohmann::json& str) { static inline std::string isNull(const nlohmann::json& str) {
try {
return str.is_null() ? str.dump() : str.get<std::string>(); return str.is_null() ? str.dump() : str.get<std::string>();
} }
catch (...) {
return "null";
}
}
}; };
#endif #endif

View File

@ -5,7 +5,6 @@
#include <iostream> #include <iostream>
#include <iomanip> #include <iomanip>
#include <ctime> #include <ctime>
using std::setfill, std::setw;
enum level { INFO, WARNING, ERROR, CRITICAL }; enum level { INFO, WARNING, ERROR, CRITICAL };
enum type { WEBSOCKET, NETWORK, API }; enum type { WEBSOCKET, NETWORK, API };
class Log { class Log {
@ -28,7 +27,10 @@ private:
std::time_t now_c = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); std::time_t now_c = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::tm* timer = std::localtime(&now_c); std::tm* timer = std::localtime(&now_c);
std::ostringstream oss; std::ostringstream oss;
oss << setfill('0') << setw(2) << timer->tm_hour << ":" << setfill('0') << setw(2) << timer->tm_min << ":" << setfill('0') << setw(2) << timer->tm_sec; oss << std::setfill('0') << std::setw(2)
<< timer->tm_hour << ":" << std::setfill('0') << std::setw(2)
<< timer->tm_min << ":" << std::setfill('0') << std::setw(2)
<< timer->tm_sec;
return oss.str(); return oss.str();
} }
static std::string str(const level& lvl) { static std::string str(const level& lvl) {

View File

@ -1,4 +1,4 @@
#ifndef UTILS_TYPES_HPP_ #ifndef UTILS_TYPES_HPP_
#define UTILS_TYPES_HPP_ #define UTILS_TYPES_HPP_
#define RELEASE #define DEBUG
#endif #endif

View File

@ -3,11 +3,13 @@
int main(int argc, char* argv[]) { int main(int argc, char* argv[]) {
if (argc != 3) return -1; if (argc != 3) return -1;
WebSocket* bot = &WebSocket::getInstance(argv[2], GatewayIntents::AllIntents); WebSocket* bot = &WebSocket::getInstance(argv[2], GatewayIntents::AllIntents);
bot->on(GatewayEvents::READY, [](const Discord<Message, User>&a) { bot->on(GatewayEvents::READY, [](const Discord<Message, User>& a) {
cout << DiscordEndpoints::details::latest << endl; std::cout << DiscordEndpoints::details::latest << std::endl;
}); });
bot->on(GatewayEvents::MESSAGE_CREATE, [bot](const Discord<Message, User, Author>& msg) { bot->on(GatewayEvents::MESSAGE_CREATE, [bot](const Discord<Message, User, Author>& msg) {
msg.get<0>().send("939957962972229634", msg.get<0>().pack({ "content", msg.get<2>().id })); if (msg.get<2>().isBot == false) {
msg.get<0>().send("939957962972229634", msg.get<0>().pack("content", msg.get<2>().global_name));
}
}); });
bot->start(); bot->start();
return 0; return 0;