diff --git a/src/commands/commands.h b/src/commands/commands.h index ed5bb73..92cc0c6 100644 --- a/src/commands/commands.h +++ b/src/commands/commands.h @@ -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); } } diff --git a/src/commands/topic_cmd.cpp b/src/commands/topic_cmd.cpp index 55f1a97..58ad430 100644 --- a/src/commands/topic_cmd.cpp +++ b/src/commands/topic_cmd.cpp @@ -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) diff --git a/src/commands/utils.cpp b/src/commands/utils.cpp index 2745f58..547bd66 100644 --- a/src/commands/utils.cpp +++ b/src/commands/utils.cpp @@ -1,7 +1,9 @@ #include "commands.h" +#include #include #include +#include std::string cmd::utils::readFileLine(const std::string& path, int &index) { @@ -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> 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 lines = seen_files.at(path); + if (index >= lines.size()) + { + return "[!] Out of range"; + } + + return lines.at(index); + } + else + { + std::vector 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 distrib(min, max); + + return distrib(gen); +}