feat: moved the update server icon to the main thread

This commit is contained in:
silver 2025-07-20 23:12:02 +01:00
parent 227db8a741
commit feff293043
Signed by: silver
GPG key ID: 36F93D61BAD3FD7D
5 changed files with 40 additions and 86 deletions

View file

@ -7,9 +7,6 @@ edition = "2021"
[[bin]]
name = "update_minecraft"
[[bin]]
name = "update_server-icon"
[[bin]]
name = "cleanup_committee"

View file

@ -153,9 +153,8 @@
# modify these
scripts = {
# minecraft stuff is updated at 5am
# this service does not depend on teh discord cache
"update_minecraft" = "5:10:00";
# server icon gets updated daily at midnight
"update_server-icon" = "0:01:00";
};
in {
options.services."${package_name}" = {

View file

@ -1,78 +0,0 @@
use serenity::all::{ChunkGuildFilter, GuildId};
use serenity::{
async_trait,
client::{Context, EventHandler},
model::gateway::{GatewayIntents, Ready},
Client,
};
use skynet_discord_bot::common::server_icon::{get_config_icons, update_icon};
use skynet_discord_bot::{
common::database::{db_init, DataBase},
get_config, Config,
};
use std::{process, sync::Arc};
use tokio::sync::RwLock;
#[tokio::main]
async fn main() {
let config = get_config();
let db = match db_init(&config).await {
Ok(x) => x,
Err(_) => return,
};
// Intents are a bitflag, bitwise operations can be used to dictate which intents to use
let intents = GatewayIntents::GUILDS | GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT | GatewayIntents::GUILD_MEMBERS;
// Build our client.
let mut client = Client::builder(&config.discord_token, intents)
.event_handler(Handler {})
.cache_settings(serenity::cache::Settings::default())
.await
.expect("Error creating client");
{
let mut data = client.data.write().await;
data.insert::<Config>(Arc::new(RwLock::new(config)));
data.insert::<DataBase>(Arc::new(RwLock::new(db)));
}
if let Err(why) = client.start().await {
println!("Client error: {:?}", why);
}
}
struct Handler;
#[async_trait]
impl EventHandler for Handler {
async fn cache_ready(&self, ctx: Context, guilds: Vec<GuildId>) {
for guild in guilds {
ctx.shard.chunk_guild(guild, Some(2000), false, ChunkGuildFilter::None, None);
}
println!("Cache built successfully!");
}
async fn ready(&self, ctx: Context, ready: Ready) {
let ctx = Arc::new(ctx);
println!("{} is connected!", ready.user.name);
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Config in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = {
let data_read = ctx.data.read().await;
data_read.get::<Config>().expect("Expected Config in TypeMap.").clone()
};
let config_global = config_lock.read().await;
let config_toml = get_config_icons::minimal();
update_icon::update_icon_main(&ctx, &db, &config_global, &config_toml).await;
// finish up
process::exit(0);
}
}

View file

@ -93,7 +93,7 @@ pub(crate) mod user {
}
}
async fn get_current_icon(db: &Pool<Sqlite>) -> Option<ServerIcons> {
pub async fn get_current_icon(db: &Pool<Sqlite>) -> Option<ServerIcons> {
match sqlx::query_as::<_, ServerIcons>(
"
SELECT * from server_icons ORDER BY id DESC LIMIT 1

View file

@ -1,9 +1,11 @@
pub mod commands;
use crate::commands::role_adder::tools::on_role_change;
use crate::commands::server_icon::user::current::icon::get_current_icon;
use chrono::{Days, SecondsFormat, TimeDelta, Utc};
use serenity::all::{
ActivityData, Command, CommandDataOptionValue, CreateMessage, EditInteractionResponse, GuildId, GuildMemberUpdateEvent, GuildMembersChunkEvent,
Interaction,
ActivityData, Command, CommandDataOptionValue, CreateAttachment, CreateMessage, EditInteractionResponse, GuildId, GuildMemberUpdateEvent,
GuildMembersChunkEvent, Interaction,
};
use serenity::{
async_trait,
@ -17,6 +19,7 @@ use serenity::{
Client,
};
use skynet_discord_bot::common::database::{db_init, get_server_config, get_server_config_bulk, get_server_member, DataBase};
use skynet_discord_bot::common::server_icon::{get_config_icons, update_icon};
use skynet_discord_bot::common::set_roles::committee::update_committees;
use skynet_discord_bot::common::set_roles::{committee, normal};
use skynet_discord_bot::common::wolves::cns::get_wolves;
@ -103,6 +106,39 @@ impl EventHandler for Handler {
});
}
{
// this updates teh server icon once a day
let ctx_task = Arc::clone(&ctx);
tokio::spawn(async move {
let db_lock = {
let data_read = ctx_task.data.read().await;
data_read.get::<DataBase>().expect("Expected Database in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = {
let data_read = ctx.data.read().await;
data_read.get::<Config>().expect("Expected Config in TypeMap.").clone()
};
let config_global = config_lock.read().await;
let config_toml = get_config_icons::minimal();
loop {
println!("Update - Logo - Start");
// even though this task will run every 5 min it will only actually change the icon when its a day old
if let Some(logo) = get_current_icon(&db).await {
let now = Utc::now();
let yesterday = now.checked_sub_days(Days::new(1)).unwrap_or_default();
if logo.date < yesterday.to_rfc3339_opts(SecondsFormat::Millis, true) {
update_icon::update_icon_main(&ctx, &db, &config_global, &config_toml).await;
}
}
println!("Update - Logo - End");
tokio::time::sleep(Duration::from_secs(60 * 5)).await;
}
});
}
// Now that the loop is running, we set the bool to true
self.is_loop_running.swap(true, Ordering::Relaxed);
}