Skip to content

Commit

Permalink
shash
Browse files Browse the repository at this point in the history
  • Loading branch information
braindigitalis committed Jun 9, 2024
1 parent abacf17 commit f882044
Show file tree
Hide file tree
Showing 7 changed files with 75 additions and 116 deletions.
2 changes: 1 addition & 1 deletion include/sporks/modules.h
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ class Module {
virtual bool OnWebhooksUpdate(const dpp::webhooks_update_t &obj);

/* Emit a simple text only embed to a channel, many modules use this for error reporting */
void EmbedSimple(const std::string &message, int64_t channelID);
void EmbedSimple(const std::string &message, uint64_t channelID, uint64_t guildID);
};


Expand Down
80 changes: 31 additions & 49 deletions modules/diagnostics/diagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ class DiagnosticsModule : public Module

if (param.size() < 3) {
/* Invalid number of parameters */
EmbedSimple("Sudo make me a sandwich.", msg.channel_id);
EmbedSimple("Sudo make me a sandwich.", msg.channel_id, msg.guild_id);
} else {
/* Module list command */
if (lowercase(subcommand) == "modules") {
Expand All @@ -143,47 +143,44 @@ class DiagnosticsModule : public Module
s << fmt::format("+ ╰─────────────────────────┴───────────┴────────────────────────────────────────────────╯") << std::endl;
s << "```";

dpp::channel* c = dpp::find_channel(msg.channel_id);
if (c) {
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == c->guild_id) {
bot->core->message_create(dpp::message(c->id, s.str()));
bot->sent_messages++;
}
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == msg.guild_id) {
bot->core->message_create(dpp::message(msg.channel_id, s.str()));
bot->sent_messages++;
}

} else if (lowercase(subcommand) == "load") {
/* Load a module */
std::string modfile;
tokens >> modfile;
if (bot->Loader->Load(modfile)) {
EmbedSimple("Loaded module: " + modfile, msg.channel_id);
EmbedSimple("Loaded module: " + modfile, msg.channel_id, msg.guild_id);
} else {
EmbedSimple(std::string("Can't do that: ``") + bot->Loader->GetLastError() + "``", msg.channel_id);
EmbedSimple(std::string("Can't do that: ``") + bot->Loader->GetLastError() + "``", msg.channel_id, msg.guild_id);
}
} else if (lowercase(subcommand) == "unload") {
/* Unload a module */
std::string modfile;
tokens >> modfile;
if (modfile == "module_diagnostics.so") {
EmbedSimple("I suppose you think that's funny, dont you? *I'm sorry. can't do that, dave.*", msg.channel_id);
EmbedSimple("I suppose you think that's funny, dont you? *I'm sorry. can't do that, dave.*", msg.channel_id, msg.guild_id);
} else {
if (bot->Loader->Unload(modfile)) {
EmbedSimple("Unloaded module: " + modfile, msg.channel_id);
EmbedSimple("Unloaded module: " + modfile, msg.channel_id, msg.guild_id);
} else {
EmbedSimple(std::string("Can't do that: ``") + bot->Loader->GetLastError() + "``", msg.channel_id);
EmbedSimple(std::string("Can't do that: ``") + bot->Loader->GetLastError() + "``", msg.channel_id, msg.guild_id);
}
}
} else if (lowercase(subcommand) == "reload") {
/* Reload a currently loaded module */
std::string modfile;
tokens >> modfile;
if (modfile == "module_diagnostics.so") {
EmbedSimple("I suppose you think that's funny, dont you? *I'm sorry. can't do that, dave.*", msg.channel_id);
EmbedSimple("I suppose you think that's funny, dont you? *I'm sorry. can't do that, dave.*", msg.channel_id, msg.guild_id);
} else {
if (bot->Loader->Reload(modfile)) {
EmbedSimple("Reloaded module: " + modfile, msg.channel_id);
EmbedSimple("Reloaded module: " + modfile, msg.channel_id, msg.guild_id);
} else {
EmbedSimple(std::string("Can't do that: `") + bot->Loader->GetLastError() + "`", msg.channel_id);
EmbedSimple(std::string("Can't do that: `") + bot->Loader->GetLastError() + "`", msg.channel_id, msg.guild_id);
}
}
} else if (lowercase(subcommand) == "sqlstats") {
Expand Down Expand Up @@ -217,7 +214,7 @@ class DiagnosticsModule : public Module
/* Listen for error messages only during execution of this query */
auto handler = bot->core->on_log([this, &had_error, sql, msg](const dpp::log_t& logmsg) {
if (logmsg.message.find("SQL Error: ") != std::string::npos) {
this->EmbedSimple(logmsg.message, msg.channel_id);
this->EmbedSimple(logmsg.message, msg.channel_id, msg.guild_id);
had_error = true;
}
});
Expand All @@ -226,7 +223,7 @@ class DiagnosticsModule : public Module
bot->core->on_log.detach(handler);
if (rs.size() == 0) {
if (!had_error) {
EmbedSimple("Successfully executed, no rows returned.", msg.channel_id);
EmbedSimple("Successfully executed, no rows returned.", msg.channel_id, msg.guild_id);
}
} else {
w << "- " << sql << std::endl;
Expand Down Expand Up @@ -270,40 +267,28 @@ class DiagnosticsModule : public Module
check = name;
w << (++check != rs[0].end() ? "" : "\n");
}
dpp::channel* c = dpp::find_channel(msg.channel_id);
if (c) {
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == c->guild_id) {
bot->core->message_create(dpp::message(msg.channel_id, "```diff\n" + w.str() + "```"));
bot->sent_messages++;
}
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == msg.guild_id) {
bot->core->message_create(dpp::message(msg.channel_id, "```diff\n" + w.str() + "```"));
bot->sent_messages++;
}
}
} else if (lowercase(subcommand) == "restart") {
EmbedSimple("Restarting...", msg.channel_id);
EmbedSimple("Restarting...", msg.channel_id, msg.guild_id);
::sleep(5);
/* Note: exit here will restart, because we run the bot via run.sh which restarts the bot on quit. */
exit(0);
} else if (lowercase(subcommand) == "ping") {
dpp::channel* c = dpp::find_channel(msg.channel_id);
if (c) {
std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now();
dpp::snowflake cid = msg.channel_id;
bot->core->message_create(dpp::message(msg.channel_id, "Pinging..."), [cid, this, start_time](const dpp::confirmation_callback_t & state) {
double microseconds_ping = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start_time).count();
dpp::snowflake mid = (std::get<dpp::message>(state.value)).id;
this->bot->core->message_delete(mid, cid);
this->EmbedSimple(fmt::format("**Pong!** REST Response time: {:.3f} ms", microseconds_ping / 1000, 4), cid);
});
}
std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now();
bot->core->message_create(dpp::message(msg.channel_id, "Pinging..."), [msg, this, start_time](const dpp::confirmation_callback_t & state) {
double microseconds_ping = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start_time).count();
dpp::snowflake mid = (std::get<dpp::message>(state.value)).id;
this->bot->core->message_delete(mid, msg.channel_id);
this->EmbedSimple(fmt::format("**Pong!** REST Response time: {:.3f} ms", microseconds_ping / 1000, 4), msg.channel_id, msg.guild_id);
});
} else if (lowercase(subcommand) == "lookup") {
int64_t gnum = 0;
tokens >> gnum;
dpp::guild* guild = dpp::find_guild(gnum);
if (guild) {
EmbedSimple(fmt::format("**Guild** {} is on **shard** #{}", gnum, 0), msg.channel_id);
} else {
EmbedSimple(fmt::format("**Guild** {} is not in my list!", gnum), msg.channel_id);
}
EmbedSimple("use /shard instead", msg.channel_id, msg.guild_id);
} else if (lowercase(subcommand) == "shardstats") {
std::stringstream w;
w << "```diff\n";
Expand Down Expand Up @@ -344,21 +329,18 @@ class DiagnosticsModule : public Module
}
w << fmt::format("+ ╰──────┴──────────┴───────┴───────┴────────────────┴───────────┴──────────╯\n");
w << "```";
dpp::channel *channel = dpp::find_channel(msg.channel_id);
if (channel) {
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == channel->guild_id) {
bot->core->message_create(dpp::message(channel->id, w.str()));
bot->sent_messages++;
}
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == msg.guild_id) {
bot->core->message_create(dpp::message(msg.channel_id, w.str()));
bot->sent_messages++;
}
} else {
/* Invalid command */
EmbedSimple("Sudo **what**? I don't know what that command means.", msg.channel_id);
EmbedSimple("Sudo **what**? I don't know what that command means.", msg.channel_id, msg.guild_id);
}
}
} else {
/* Access denied */
EmbedSimple("Make your own sandwich, mortal.", msg.channel_id);
EmbedSimple("Make your own sandwich, mortal.", msg.channel_id, msg.guild_id);
}

/* Eat the event */
Expand Down
31 changes: 13 additions & 18 deletions modules/trivia/commands.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -483,40 +483,35 @@ void TriviaModule::handle_command(const in_cmd &cmd, const dpp::interaction_crea
std::stringstream tokens(cmd.msg);
std::string base_command;
tokens >> base_command;
dpp::channel* c = const_cast<dpp::channel*>(&event.command.channel);

dpp::channel* c = dpp::find_channel(cmd.channel_id);
dpp::user* user = (dpp::user*)&cmd.user;
if (cmd.from_dashboard) {
dashboard_dummy.username = "Dashboard";
dashboard_dummy.flags = 0;
user = &dashboard_dummy;
}
if (!c) {
return;
}

guild_settings_t settings = GetGuildSettings(cmd.guild_id);

/* Check for moderator status - first check if owner */
dpp::guild* g = dpp::find_guild(cmd.guild_id);
bool moderator = (g && (cmd.from_dashboard || g->owner_id == cmd.author_id));
dpp::permission p = event.command.get_resolved_permission(cmd.author_id);
bool moderator = (cmd.from_dashboard || p.has(dpp::p_administrator) || p.has(dpp::p_manage_guild));
/* Now iterate the list of moderator roles from settings */
if (!moderator) {
if (g) {
for (auto modrole = settings.moderator_roles.begin(); modrole != settings.moderator_roles.end(); ++modrole) {
/* Check for when user cache is off, and guild member passed in via the message */
for (auto role = cmd.member.roles.begin(); role != cmd.member.roles.end(); ++role) {
if (*role == *modrole) {
moderator = true;
break;
}
}

if (moderator) {
/* Short-circuit out of outer loop */
for (auto modrole = settings.moderator_roles.begin(); modrole != settings.moderator_roles.end(); ++modrole) {
/* Check for when user cache is off, and guild member passed in via the message */
for (auto role = cmd.member.get_roles().begin(); role != cmd.member.get_roles().end(); ++role) {
if (*role == *modrole) {
moderator = true;
break;
}
}

if (moderator) {
/* Short-circuit out of outer loop */
break;
}
}
}

Expand Down
27 changes: 12 additions & 15 deletions modules/trivia/trivia.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -283,15 +283,15 @@ bool TriviaModule::OnChannelDelete(const dpp::channel_delete_t &cd)
bool TriviaModule::OnGuildDelete(const dpp::guild_delete_t &gd)
{
/* Unavailable guilds means an outage. We don't remove them if it's just an outage */
if (!gd.deleted->is_unavailable()) {
if (!gd.deleted.is_unavailable()) {
{
std::unique_lock locker(settingcache_mutex);
settings_cache.erase(gd.deleted->id);
settings_cache.erase(gd.guild_id);
}
db::backgroundquery("UPDATE trivia_guild_cache SET kicked = 1 WHERE snowflake_id = ?", {gd.deleted->id});
bot->core->log(dpp::ll_info, fmt::format("Kicked from guild id {}", gd.deleted->id));
db::backgroundquery("UPDATE trivia_guild_cache SET kicked = 1 WHERE snowflake_id = ?", {gd.guild_id});
bot->core->log(dpp::ll_info, fmt::format("Kicked from guild id {}", gd.guild_id));
} else {
bot->core->log(dpp::ll_info, fmt::format("Outage on guild id {}", gd.deleted->id));
bot->core->log(dpp::ll_info, fmt::format("Outage on guild id {}", gd.guild_id));
}
return true;
}
Expand Down Expand Up @@ -539,12 +539,14 @@ dpp::user dummyuser;

void TriviaModule::CheckForQueuedStarts()
{
uint64_t max_shards = from_string<uint32_t>(Bot::GetConfig("shardcount"), std::dec);
db::resultset rs = db::query("SELECT * FROM start_queue ORDER BY queuetime", {});
for (auto r = rs.begin(); r != rs.end(); ++r) {
uint64_t guild_id = from_string<uint64_t>((*r)["guild_id"], std::dec);
/* Check that this guild is on this cluster, if so we can start this game */
dpp::guild* g = dpp::find_guild(guild_id);
if (g) {
uint64_t shard = (guild_id >> 22) % max_shards;
uint64_t cluster = shard % bot->GetMaxClusters();
if (cluster == bot->GetClusterID()) {

uint64_t channel_id = from_string<uint64_t>((*r)["channel_id"], std::dec);
uint64_t user_id = from_string<uint64_t>((*r)["user_id"], std::dec);
Expand All @@ -565,14 +567,9 @@ void TriviaModule::CheckForQueuedStarts()

void TriviaModule::CacheUser(dpp::snowflake user, dpp::user _user, dpp::guild_member gm, dpp::snowflake channel_id)
{
dpp::channel* c = dpp::find_channel(channel_id);
if (c) {
dpp::guild* g = dpp::find_guild(c->guild_id);
if (g) {
cache_user(&_user, g, &gm);
}
} else {
bot->core->log(dpp::ll_debug, "Command with no user!");
dpp::guild* g = dpp::find_guild(gm.guild_id);
if (g) {
cache_user(&_user, g, &gm);
}
}

Expand Down
18 changes: 2 additions & 16 deletions modules/trivia/webrequest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -430,28 +430,14 @@ void cache_user(const dpp::user *_user, const dpp::guild *_guild, const dpp::gui

std::string member_roles;
std::string comma_roles;
for (auto r = gi->roles.begin();r != gi->roles.end(); ++r) {
for (auto r = gi->get_roles().begin();r != gi->get_roles().end(); ++r) {
member_roles.append(std::to_string(*r)).append(" ");
}
member_roles = trim(member_roles);
db::backgroundquery("INSERT INTO trivia_guild_membership (guild_id, user_id, roles) VALUES('?', '?', '?') ON DUPLICATE KEY UPDATE roles = '?'",
{guild_id, user_id, member_roles, member_roles});

// TODO: Gather these in the dashboard via a REST API request when the user wants them. No need to be constantly caching and writing them here, removes our need to check roles at all.
/*for (auto n = _guild->roles.begin(); n != _guild->roles.end(); ++n) {
dpp::role* r = dpp::find_role(*n);
if (r) {
comma_roles.append(std::to_string(r->id)).append(",");
db::backgroundquery("INSERT INTO trivia_role_cache (id, guild_id, colour, permissions, position, hoist, managed, mentionable, name) VALUES('?', '?', '?', '?', '?', '?', '?', '?', '?') ON DUPLICATE KEY UPDATE colour = '?', permissions = '?', position = '?', hoist = '?', managed = '?', mentionable = '?', name = '?'",
{
r->id, guild_id, r->colour, r->permissions, r->position, (r->is_hoisted() ? 1 : 0), (r->is_managed() ? 1 : 0), (r->is_mentionable() ? 1 : 0), r->name,
r->colour, r->permissions, r->position, (r->is_hoisted() ? 1 : 0), (r->is_managed() ? 1 : 0), (r->is_mentionable() ? 1 : 0), r->name
});
}
}
comma_roles = trim(comma_roles.substr(0, comma_roles.length() - 1));*/
/* Delete any that have been deleted from discord */
//db::backgroundquery("DELETE FROM trivia_role_cache WHERE guild_id = ? AND id NOT IN (" + comma_roles + ")", {guild_id});
// TODO: Gather roles in the dashboard via a REST API request when the user wants them. No need to be constantly caching and writing them here, removes our need to check roles at all.
}

/* Fetch a question by ID from the database */
Expand Down
16 changes: 10 additions & 6 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -323,13 +323,17 @@ int main(int argc, char** argv) {

/* Set cache policy for D++ library
* --------------------------------
* User caching: none
* Emoji caching: none
* Role caching: none (WAS: aggressive)
*/
dpp::cache_policy_t cp = { dpp::cp_none, dpp::cp_none, dpp::cp_none };
* User caching: none
* Emoji caching: none
* Role caching: none
* Channel caching: none
* Guild caching: aggressive
*/
dpp::cache_policy_t cp = { dpp::cp_none, dpp::cp_none, dpp::cp_none, dpp::cp_none, dpp::cp_aggressive };
const bool compressed = false;

/* Construct cluster */
dpp::cluster bot(token, intents, dev ? 1 : from_string<uint32_t>(Bot::GetConfig("shardcount"), std::dec), clusterid, maxclusters, true, cp);
dpp::cluster bot(token, intents, dev ? 1 : from_string<uint32_t>(Bot::GetConfig("shardcount"), std::dec), clusterid, maxclusters, compressed, cp);

/* Connect to SQL database */
if (!db::connect(&bot, Bot::GetConfig("dbhost"), Bot::GetConfig("dbuser"), Bot::GetConfig("dbpass"), Bot::GetConfig("dbname"), from_string<uint32_t>(Bot::GetConfig("dbport"), std::dec))) {
Expand Down
17 changes: 6 additions & 11 deletions src/modules.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ bool Module::OnAllShardsReady()
/**
* Output a simple embed to a channel consisting just of a message.
*/
void Module::EmbedSimple(const std::string &message, int64_t channelID)
void Module::EmbedSimple(const std::string &message, uint64_t channelID, uint64_t guildID)
{
std::stringstream s;
json embed_json;
Expand All @@ -529,15 +529,10 @@ void Module::EmbedSimple(const std::string &message, int64_t channelID)
catch (const std::exception &e) {
bot->core->log(dpp::ll_error, fmt::format("Invalid json for channel {} created by EmbedSimple: ", channelID, s.str()));
}
dpp::channel* channel = dpp::find_channel(channelID);
if (channel) {
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == channel->guild_id) {
dpp::message m;
m.channel_id = channel->id;
m.embeds.push_back(dpp::embed(&embed_json));
bot->core->message_create(m);
}
} else {
bot->core->log(dpp::ll_error, fmt::format("Invalid channel {} passed to EmbedSimple", channelID));
if (!bot->IsTestMode() || from_string<uint64_t>(Bot::GetConfig("test_server"), std::dec) == guildID) {
dpp::message m;
m.channel_id = channelID;
m.embeds.push_back(dpp::embed(&embed_json));
bot->core->message_create(m);
}
}

0 comments on commit f882044

Please sign in to comment.