Something went wrong. Try again.
7 Days to Die Discord bot (old and ugly code)
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145use crate::serenity::ComponentInteractionCollector;use crate::serenity::CreateActionRow;use crate::serenity::CreateButton;use crate::settings::SettingsOption;use crate::types::{Context, Error, FetchSettings, GuildPartition};use anyhow::anyhow;use serde::{Deserialize, Serialize};use serenity::all::colours::roles::GREEN;use serenity::all::{ ChannelId, CreateEmbed, CreateInteractionResponse, CreateMessage, EditMessage,};use tracing::log::error;
#[poise::command( slash_command, guild_only, subcommands("deploy"), description_localized("en-US", "Debug tools for server status"))]pub async fn status(_ctx: Context<'_>) -> Result<(), Error> { Ok(())}
#[poise::command( prefix_command, slash_command, description_localized("en-US", "Deploy the 7 days to die status message"))]pub async fn deploy(ctx: Context<'_>) -> Result<(), Error> { let space = { ctx.get_guild_partition()? };
let channel = space.get_from_partition(SettingsOption::StatusChannelId.to_string().into())?; let addr = space.get_from_partition(SettingsOption::StatusServerIpPort.to_string().into())?;
let channel = channel.parse::<ChannelId>()?;
let ctx_id = ctx.id(); let interaction_id = format!("{ctx_id}_7dtd_upd");
let msg = create_message_parts(&interaction_id, &addr, &ctx.author().name).await?; let msg = CreateMessage::default().embed(msg.0).components(msg.1);
let mut msg = channel.send_message(ctx, msg).await?;
while let Some(mci) = ComponentInteractionCollector::new(ctx.serenity_context()) .filter(move |mci| mci.data.custom_id.starts_with(&ctx_id.to_string())) .await { // Just log and continue if let Err(why) = mci.create_response(ctx, CreateInteractionResponse::Acknowledge) .await { error!("Error while creating interaction response: {:?}", why); }
let edit = create_message_parts(&interaction_id, &addr, &mci.user.name).await; if let Err(why) = edit { error!("Error during create message parts: {why}"); continue; }
let edit = edit?; let edit = EditMessage::default().embed(edit.0).components(edit.1);
if let Err(why) = msg.edit(ctx, edit).await { error!("Error during edit message parts: {why}"); } }
Ok(())}
pub async fn create_message_parts( interaction_id: &String, addr: &String, name: &String,) -> anyhow::Result<(CreateEmbed, Vec<CreateActionRow>)> { let components = vec![CreateActionRow::Buttons(vec![ CreateButton::new(interaction_id) .label("Refresh") .style(poise::serenity_prelude::ButtonStyle::Primary), ])];
let embed = create_status_embed(addr, name).await; if let Err(why) = embed { Err(anyhow!(why)) } else { Ok((embed.unwrap(), components)) }}
#[derive(Debug, Serialize, Deserialize)]#[serde(rename_all = "PascalCase")]pub struct SevenDaysToDie { game_host: String, max_players: String, current_players: String, free_player_slots: String, current_server_time: String,}fn sdtd_to_time(tick: i64) -> String { let day = tick as f64 / 24000.0; let hour = tick % 24000 / 1000; let minute = ((tick as f64 % 24000.0) % 1000.0) * 60.0 / 1000.0;
format!("Day {}, {}:{:.0}", day as i64, hour, minute)}
pub async fn create_status_embed(addr: &String, username: &String) -> Result<CreateEmbed, Error> { let client = reqwest::ClientBuilder::new() .http09_responses() // Required .user_agent("Vamist - Discord Bot") .build()?;
let msg = client.get(addr).send().await?.text().await?; // Remove the first msg as it's a version with invalid syntax let msg = msg.split_at(msg.find('\n').unwrap_or(msg.len())).1; // And then remove the ';' from every value let msg = msg.replace(';', "");
let ini: SevenDaysToDie = serde_ini::from_str(&msg)?;
let time = sdtd_to_time(ini.current_server_time.parse::<i64>()?);
let timestamp = chrono::Local::now().timestamp();
let embed = CreateEmbed::default() .fields(vec![ ( ini.game_host.as_str(), format!("Last refreshed by {username} <t:{timestamp}:R>"), false, ), ("Current Time", time.to_string(), true), ( "Player Count", format!("{}/{}", ini.current_players, ini.max_players), true, ), ]) .colour(GREEN);
Ok(embed)}