Skip to content

Commit

Permalink
[Update]: clean code backup
Browse files Browse the repository at this point in the history
- Still cleaning
  • Loading branch information
harshfeudal committed Nov 18, 2022
1 parent ee4cc62 commit 00883ed
Show file tree
Hide file tree
Showing 5 changed files with 88 additions and 63 deletions.
72 changes: 40 additions & 32 deletions handler/btnHandler.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,7 @@

#define ID_SPACING "###"

struct Session
{
time_t created_at;
std::function<bool(const dpp::button_click_t&)> function;

uint16_t cache_duration;
Session() : created_at(time(nullptr)), cache_duration(10) {}

bool isExpired() const
{
return difftime(time(nullptr), created_at) > cache_duration * 60;
}
};
struct Session;

inline std::unordered_map<uint64_t, Session> cachedSessions;
inline std::shared_mutex cachedSessionsMutex;
Expand All @@ -41,8 +29,10 @@ inline uint64_t customIdCounter;
inline void ButtonClear()
{
std::unique_lock l(cachedSessionsMutex);

auto it = cachedSessions.begin();

// Time check button to clear
while (it != cachedSessions.end())
{
if (it->second.isExpired())
Expand All @@ -57,55 +47,55 @@ inline void ButtonClear()
inline void ButtonBind(dpp::component& component, const std::function<bool(const dpp::button_click_t&)>& function, uint16_t cache_duration = 10)
{
ButtonClear();


bool customIdAlreadyExists;
std::unique_lock l(cachedSessionsMutex);

bool customIdAlreadyExists;
do
{
// Checking initial button create
if (customIdCounter >= UINT_LEAST64_MAX)
{
customIdCounter = 0;
}

customIdCounter++;

customIdAlreadyExists = cachedSessions.find(customIdCounter) != cachedSessions.end();

// Checking if existence
if (!customIdAlreadyExists)
{
Session session;

session.function = function;
session.cache_duration = cache_duration;
component.custom_id = std::to_string(customIdCounter);

component.custom_id += ID_SPACING + std::to_string(static_cast<long int>(session.created_at));
component.custom_id = std::to_string(customIdCounter);
component.custom_id += ID_SPACING + std::to_string(static_cast<long int>(session.created_at));

cachedSessions[customIdCounter] = session;
customIdAlreadyExists = false;
}
} while (customIdAlreadyExists);
}
while (customIdAlreadyExists);
}

inline void ButtonHandle(const dpp::button_click_t& event)
{
uint64_t customId;
time_t creationTimestamp;
uint64_t customId;
time_t creationTimestamp;

try
{
const std::string id = event.custom_id.substr(0, event.custom_id.find(ID_SPACING));
const std::string creation = event.custom_id.substr(
event.custom_id.find(ID_SPACING) + std::strlen(ID_SPACING),
std::string::npos
);
customId = std::stoul(id);
const std::string id = event.custom_id.substr(0, event.custom_id.find(ID_SPACING));
const std::string creation = event.custom_id.substr(event.custom_id.find(ID_SPACING) + std::strlen(ID_SPACING), std::string::npos);

customId = std::stoul(id);
creationTimestamp = std::stol(creation);
}
catch (std::out_of_range& e)
{
event.reply(
dpp::message().set_content("Button not found!")
.set_flags(dpp::m_ephemeral)
.set_flags(dpp::m_ephemeral)
);

return;
Expand All @@ -114,21 +104,39 @@ inline void ButtonHandle(const dpp::button_click_t& event)
{
event.reply(
dpp::message().set_content("Button not found!")
.set_flags(dpp::m_ephemeral)
.set_flags(dpp::m_ephemeral)
);

return;
}

std::unique_lock l(cachedSessionsMutex);
std::unique_lock l(cachedSessionsMutex);
const auto existing = cachedSessions.find(customId);

if (existing != cachedSessions.end() && existing->second.created_at == creationTimestamp && !existing->second.isExpired())
{
bool forget = existing->second.function(event);

// If forget the button
if (forget)
{
cachedSessions.erase(existing);
}
}
}

struct Session
{
time_t created_at;
uint16_t cache_duration;

std::function<bool(const dpp::button_click_t&)> function;

Session() : created_at(time(nullptr)), cache_duration(10) {}

// If expired
bool isExpired() const
{
return difftime(time(nullptr), created_at) > cache_duration * 60;
}
};
9 changes: 7 additions & 2 deletions handler/builder.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@

void SlashCommandCreate(dpp::cluster& client);

// Slash coomand builder
inline std::map<std::string, commandDef> commands
{
{
Expand Down Expand Up @@ -206,14 +207,18 @@ inline void SlashCommandCreate(dpp::cluster& client)
{
dpp::slashcommand cmd;

// Create slash command template
cmd.set_name(def.first)
.set_description(def.second.description)
.set_application_id(client.me.id);
.set_description(def.second.description)
.set_application_id(client.me.id);

cmd.options = def.second.param;

// Pushing all commands
slashCmds.push_back(cmd);
}

// Create a global slash commands
client.global_bulk_command_create(slashCmds);
}
}
28 changes: 14 additions & 14 deletions handler/handler.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,24 @@
#pragma once

#include <functional>

#include <dpp/dpp.h>

using commandFunc = std::function<void(dpp::cluster&, const dpp::slashcommand_t&)>;

struct commandDef
{
std::string description;
commandFunc function;
std::vector<dpp::command_option> param = {};
};
using commandFunc = std::function<void(dpp::cluster&, const dpp::slashcommand_t&)>;
struct commandDef;

inline void EmbedBuild(dpp::embed& embed, uint32_t col, std::string title, std::string fieldTitle, std::string fieldDes, const dpp::user& tgtUser)
{
embed = dpp::embed().set_color(col)
.set_title(title)
.add_field(fieldTitle, fieldDes)
.set_footer(dpp::embed_footer().set_text(tgtUser.username).set_icon(tgtUser.get_avatar_url()))
.set_timestamp(time(nullptr));
embed = dpp::embed()
.set_color(col)
.set_title(title)
.add_field(fieldTitle, fieldDes)
.set_footer(dpp::embed_footer().set_text(tgtUser.username).set_icon(tgtUser.get_avatar_url()))
.set_timestamp(time(nullptr));
}

struct commandDef
{
std::string description;
commandFunc function;
std::vector<dpp::command_option> param = {};
};
24 changes: 18 additions & 6 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

#include <fstream>
#include <map>

#include <spdlog/spdlog.h>
#include <dpp/nlohmann/json.hpp>
#include <dpp/dpp.h>
Expand All @@ -29,54 +28,67 @@ using json = nlohmann::json;

int main()
{
// Reading JSON configuration file
json reader;
{
std::ifstream reading("config.json");

// If cannot read find the configuration file to read
if (!reading)
{
// Send a warning on console log
std::cout << "No configuration file found! Please add it with the name \"config.json\"!";
std::cin.get();

// Stop the project immediately
exit(0);
}

// Navigate and read
reading >> reader;
}

const std::string token = harshfeudal::Base64::Decode(reader["token"]);

// Client variable
dpp::cluster client(token, dpp::i_all_intents);

// Starting the bot
client.start(dpp::st_wait);

client.on_ready([&client](const dpp::ready_t& event)
{
// Set presence for the bot
client.set_presence(
dpp::presence(dpp::ps_dnd, dpp::at_game, "Genshin Impact")
);

// Slash command registration
SlashCommandCreate(client);

// Confirm logger
fmt::print("[{} - STARTED]: {} is online!\n", dpp::utility::current_date_time(), client.me.format_username());
fmt::print("[{} - REGISTERED]: Successfully registered slash commands!\n", dpp::utility::current_date_time());
});

client.on_slashcommand([&client](const dpp::slashcommand_t& event)
{
dpp::command_interaction commandData = event.command.get_command_interaction();
auto commandFilter = commands.find(commandData.name);
dpp::command_interaction commandData = event.command.get_command_interaction();
auto commandFilter = commands.find(commandData.name);

// Check commands
if (commandFilter != commands.end())
{
commandFilter->second.function(client, event);
}
});

client.on_button_click([](const dpp::button_click_t& event)
{
// Handling the button event
ButtonHandle(event);
});

// Console log prettier
SetConsoleTitle(TEXT("[BETA] v0.1.6.0 - Raiden Shogun Discord Bot - The Harshfeudal Projects"));

client.start(dpp::st_wait);
return 0;
}
18 changes: 9 additions & 9 deletions src/utility/sha.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,18 @@

void sha(dpp::cluster& client, const dpp::slashcommand_t& event)
{
auto inputStr = std::get<std::string>(event.get_parameter("input"));
auto encryptStr = harshfeudal::hash256_hex_string(inputStr);
std::string content = fmt::format("`{}`", encryptStr);
const auto inputStr = std::get<std::string>(event.get_parameter("input"));
const auto encryptStr = harshfeudal::hash256_hex_string(inputStr);
const std::string content = fmt::format("`{}`", encryptStr);

dpp::embed embed;

embed = dpp::embed().set_color(0xAA7EEE)
.set_title("SHA256 convert result")
.add_field("Input text", inputStr, true)
.add_field("Output result", content, true)
.set_footer(dpp::embed_footer().set_text(event.command.usr.username)
.set_icon(event.command.usr.get_avatar_url()))
.set_timestamp(time(nullptr));
.set_title("SHA256 convert result")
.add_field("Input text", inputStr, true)
.add_field("Output result", content, true)
.set_footer(dpp::embed_footer().set_text(event.command.usr.username).set_icon(event.command.usr.get_avatar_url()))
.set_timestamp(time(nullptr));

event.reply(
dpp::message(event.command.channel_id, embed)
Expand Down

0 comments on commit 00883ed

Please sign in to comment.