Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/commands/commands.h
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,22 @@ namespace cmd
* @return content of next line
*/
std::string readFileLine(const std::string& path, int& index);

/**
* @brief Read a line of a file, but cached
* @param path to the file
* @param index (not line number)
* @return content of that line
*/
std::string readFileLineCached(const std::string& path, int index);

/**
* @brief Gets a random number between range (min, max)
* @param min Lower bounds
* @param max Upper bounds
* @return
*/
int getRandomNumber(int min, int max);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/commands/topic_cmd.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

void cmd::topicCommand(dpp::cluster& bot, const dpp::slashcommand_t& event)
{
static int index;
const std::string topic = cmd::utils::readFileLine("res/topic.txt", index);
int index = cmd::utils::getRandomNumber(0, 15);
const std::string topic = cmd::utils::readFileLineCached("res/topic.txt", index);

const dpp::embed embed = dpp::embed()
.set_color(globals::color::defaultColor)
Expand Down
56 changes: 56 additions & 0 deletions src/commands/utils.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#include "commands.h"

#include <random>
#include <string>
#include <fstream>
#include <unordered_map>

std::string cmd::utils::readFileLine(const std::string& path, int &index)
{
Expand All @@ -24,3 +26,57 @@ std::string cmd::utils::readFileLine(const std::string& path, int &index)
line = "[!] Could not open " + path;
return line;
}

std::string cmd::utils::readFileLineCached(const std::string& path, int index)
{
static std::unordered_map<std::string, std::vector<std::string>> seen_files;
if (seen_files.find(path) == seen_files.end())
{
seen_files[path] = {};
std::ifstream file(path);

if (!file.is_open())
{
return "[!] Could not open " + path;
}

std::string line;
while (std::getline(file, line)) {
seen_files[path].push_back(line);
}

file.close();

std::vector<std::string> lines = seen_files.at(path);
if (index >= lines.size())
{
return "[!] Out of range";
}

return lines.at(index);
}
else
{
std::vector<std::string> lines = seen_files.at(path);
if (index >= lines.size())
{
return "[!] Out of range";
}

return lines.at(index);
}
}

int cmd::utils::getRandomNumber(int min, int max)
{
if (min > max)
{
return 0;
}

static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<int> distrib(min, max);

return distrib(gen);
}
Loading