summaryrefslogtreecommitdiff
path: root/src/timer.cpp
diff options
context:
space:
mode:
authorilotterytea <iltsu@alright.party>2024-05-09 00:36:56 +0500
committerilotterytea <iltsu@alright.party>2024-05-09 00:36:56 +0500
commit54e2744e3135f0eab9c9ec1e2cb84d831233df68 (patch)
tree93727773bff284a16afbb915b26a066c0c9fb5a8 /src/timer.cpp
parent8c9f4843fc904f53197d6008c29df7ba5b1353e9 (diff)
feat: handler for timers
Diffstat (limited to 'src/timer.cpp')
-rw-r--r--src/timer.cpp70
1 files changed, 70 insertions, 0 deletions
diff --git a/src/timer.cpp b/src/timer.cpp
new file mode 100644
index 0000000..ccdf176
--- /dev/null
+++ b/src/timer.cpp
@@ -0,0 +1,70 @@
+#include "timer.hpp"
+
+#include <chrono>
+#include <pqxx/pqxx>
+#include <string>
+#include <thread>
+
+#include "config.hpp"
+#include "irc/client.hpp"
+#include "utils/chrono.hpp"
+
+namespace bot {
+ void create_timer_thread(irc::Client *irc_client,
+ Configuration *configuration) {
+ while (true) {
+ pqxx::connection conn(GET_DATABASE_CONNECTION_URL_POINTER(configuration));
+ pqxx::work *work = new pqxx::work(conn);
+
+ pqxx::result timers = work->exec(
+ "SELECT id, interval_sec, message, channel_id, last_executed_at FROM "
+ "timers");
+
+ for (const auto &timer : timers) {
+ int id = timer[0].as<int>();
+ int interval_sec = timer[1].as<int>();
+ std::string message = timer[2].as<std::string>();
+ int channel_id = timer[3].as<int>();
+
+ // it could be done in sql query
+ std::chrono::system_clock::time_point last_executed_at =
+ utils::chrono::string_to_time_point(timer[4].as<std::string>());
+ auto now = std::chrono::system_clock::now();
+ auto now_time_it = std::chrono::system_clock::to_time_t(now);
+ auto now_tm = std::gmtime(&now_time_it);
+ now = std::chrono::system_clock::from_time_t(std::mktime(now_tm));
+
+ auto difference = std::chrono::duration_cast<std::chrono::seconds>(
+ now - last_executed_at);
+
+ if (difference.count() > interval_sec) {
+ pqxx::result channels =
+ work->exec("SELECT alias_name FROM channels WHERE id = " +
+ std::to_string(channel_id));
+
+ if (!channels.empty()) {
+ std::string alias_name = channels[0][0].as<std::string>();
+
+ irc_client->say(alias_name, message);
+ }
+
+ work->exec(
+ "UPDATE timers SET last_executed_at = timezone('utc', now()) "
+ "WHERE "
+ "id = " +
+ std::to_string(id));
+
+ work->commit();
+
+ delete work;
+ work = new pqxx::work(conn);
+ }
+ }
+
+ delete work;
+ conn.close();
+
+ std::this_thread::sleep_for(std::chrono::seconds(1));
+ }
+ }
+}