account logging

This commit is contained in:
Stachelbeere1248 2024-07-02 21:36:34 +02:00
parent 8e5ac7112a
commit c2fe6acecf
Signed by: Stachelbeere1248
SSH key fingerprint: SHA256:IozEKdw2dB8TZxkpPdMxcWSoWTIMwoLaCcZJ1AJnY2o
8 changed files with 53 additions and 37 deletions

10
Cargo.lock generated
View file

@ -2842,6 +2842,15 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5de17fd2f7da591098415cff336e12965a28061ddace43b59cb3c430179c9439"
dependencies = [
"getrandom",
]
[[package]] [[package]]
name = "vcpkg" name = "vcpkg"
version = "0.2.15" version = "0.2.15"
@ -3217,4 +3226,5 @@ dependencies = [
"sqlx", "sqlx",
"tokio", "tokio",
"tracing", "tracing",
"uuid",
] ]

View file

@ -17,3 +17,4 @@ sqlx = { version = "0.7.4" , features = ["sqlite", "sqlx-sqlite", "runtime-tokio
reqwest = { version = "0.12.5" } reqwest = { version = "0.12.5" }
serde = { version = "1.0.203", features = ["derive"] } serde = { version = "1.0.203", features = ["derive"] }
serde_json = { version = "1.0.119" } serde_json = { version = "1.0.119" }
uuid = { version = "1.9.1", features = ["v4"] }

View file

@ -1,8 +1,8 @@
use poise::CreateReply; use poise::CreateReply;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serenity::all::User; use serenity::all::{ChannelId, CreateMessage, User};
use serenity::builder::CreateAllowedMentions;
use sqlx::{query_as, Executor, Pool, Sqlite}; use sqlx::{query_as, Executor, Pool, Sqlite};
use crate::{Context, Error}; use crate::{Context, Error};
#[poise::command(slash_command, subcommands("add", "list"))] #[poise::command(slash_command, subcommands("add", "list"))]
@ -11,30 +11,32 @@ pub(crate) async fn account(_ctx: Context<'_>) -> Result<(), Error> {
} }
#[poise::command(slash_command)] #[poise::command(slash_command)]
pub(crate) async fn add(ctx: Context<'_>, ign: String, user: Option<User>) -> Result<(), Error> { pub(crate) async fn add(ctx: Context<'_>, ign: String) -> Result<(), Error> {
let user_id = user.clone().map(|user| user.id.get());
let user_name = user.clone().map(|user| user.name);
let author_name = ctx.author().name.clone();
let pool = ctx.data().sqlite_pool.clone(); let pool = ctx.data().sqlite_pool.clone();
let minecraft_uuid = minecraft_uuid_for_username(ign).await?; let minecraft_uuid = minecraft_uuid_for_username(ign.clone()).await?;
let hypixel_linked_discord = linked_discord_for_uuid( let hypixel_linked_discord = linked_discord_for_uuid(
ctx.data().hypixel_api_client.clone(), ctx.data().hypixel_api_client.clone(),
minecraft_uuid.as_str(), minecraft_uuid.as_str(),
) )
.await?; .await?;
if hypixel_linked_discord.eq(&user_name.unwrap_or(author_name)) { if hypixel_linked_discord.eq(ctx.author().name.as_str()) {
link( link(
user_id.unwrap_or(ctx.author().id.get()), ctx.author().id.get(),
minecraft_uuid.as_str(), minecraft_uuid.as_str(),
&pool, &pool,
) )
.await; .await;
if let Err(why) = ctx let s = format!("## User <@{}> added an account:\n### added:\n- name: {}\n- uuid: {}",
.send(CreateReply::default().content("Linked accounts.")) ctx.author().id.get(),
.await ign.clone(),
{ minecraft_uuid
println!("Error sending message: {why}"); );
} ChannelId::new(1257776992497959075).send_message(ctx,
CreateMessage::new()
.content(s)
.allowed_mentions(CreateAllowedMentions::new().empty_roles().empty_users())
).await?;
ctx.send(CreateReply::default().content("Linked accounts.")).await?;
} }
Ok(()) Ok(())
} }
@ -57,7 +59,10 @@ pub(crate) async fn list(ctx: Context<'_>, user: Option<User>) -> Result<(), Err
Some(id) => minecraft_uuids(&pool, id).await, Some(id) => minecraft_uuids(&pool, id).await,
None => Vec::new(), None => Vec::new(),
}; };
let mut content = format!("## {}'s linked accounts: ", user_name.unwrap_or(author_name)); let mut content = format!(
"## {}'s linked accounts: ",
user_name.unwrap_or(author_name)
);
for l in t { for l in t {
content.push_str(format!("\nuuid: {}", l).as_str()) content.push_str(format!("\nuuid: {}", l).as_str())
} }
@ -201,6 +206,7 @@ async fn link_id_from_minecraft(pool: &Pool<Sqlite>, minecraft_uuid: String) ->
.unwrap() .unwrap()
.map(|minecraft_link: MinecraftLink| minecraft_link.link_id.cast_unsigned()); .map(|minecraft_link: MinecraftLink| minecraft_link.link_id.cast_unsigned());
} }
async fn new_link_id(pool: &Pool<Sqlite>) -> u16 { async fn new_link_id(pool: &Pool<Sqlite>) -> u16 {
let result: Result<LinkId, sqlx::Error> = query_as("SELECT link_id FROM minecraft_links WHERE link_id = (SELECT MAX(link_id) FROM minecraft_links) LIMIT 1;") let result: Result<LinkId, sqlx::Error> = query_as("SELECT link_id FROM minecraft_links WHERE link_id = (SELECT MAX(link_id) FROM minecraft_links) LIMIT 1;")
.fetch_one(pool) .fetch_one(pool)

View file

@ -1,7 +1,7 @@
use std::string::String; use std::string::String;
use crate::{Context, Error};
use crate::commands::command_helper; use crate::commands::command_helper;
use crate::{Context, Error};
#[poise::command(slash_command, guild_only, owners_only)] #[poise::command(slash_command, guild_only, owners_only)]
pub(crate) async fn bots( pub(crate) async fn bots(

View file

@ -1,8 +1,8 @@
use poise::CreateReply; use poise::CreateReply;
use serenity::all::CreateAllowedMentions; use serenity::all::CreateAllowedMentions;
use crate::{Context, Error};
use crate::commands::command_helper; use crate::commands::command_helper;
use crate::{Context, Error};
#[poise::command(slash_command, guild_only)] #[poise::command(slash_command, guild_only)]
pub(crate) async fn helpstart( pub(crate) async fn helpstart(
@ -29,9 +29,7 @@ pub(crate) async fn helpstart(
needed_players - bots needed_players - bots
)) ))
.ephemeral(false) .ephemeral(false)
.allowed_mentions(CreateAllowedMentions::new() .allowed_mentions(CreateAllowedMentions::new().roles(vec![1008075054971621448])),
.roles(vec![1008075054971621448])
),
Err(why) => reply.content(why.to_string()).ephemeral(true), Err(why) => reply.content(why.to_string()).ephemeral(true),
} }
}; };

View file

@ -109,7 +109,7 @@ pub(crate) async fn lfg(
let ping = match guild_id { let ping = match guild_id {
1256217633959841853 => new_ping, 1256217633959841853 => new_ping,
995300932164276234 => old_ping, 995300932164276234 => old_ping,
_ => 0 _ => 0,
}; };
let difficulty: Difficulty = match map { let difficulty: Difficulty = match map {
DeadEnd | BadBlood | Prison => difficulty.unwrap_or(Normal), DeadEnd | BadBlood | Prison => difficulty.unwrap_or(Normal),
@ -155,11 +155,10 @@ enum Expert {
Speedrun, Speedrun,
} }
#[poise::command(slash_command, guild_only, rename = "expert-lfg")] #[poise::command(slash_command, guild_only, rename = "expert-lfg")]
pub(crate) async fn expert ( pub(crate) async fn expert(
ctx: Context<'_>, ctx: Context<'_>,
#[rename = "map"] #[rename = "map"] mode: Expert,
mode: Expert,
#[min = 1_u8] #[min = 1_u8]
#[max = 3_u8] #[max = 3_u8]

View file

@ -1,6 +1,6 @@
pub(crate) mod account;
pub(crate) mod bots; pub(crate) mod bots;
pub(crate) mod command_helper; pub(crate) mod command_helper;
pub(crate) mod helpstart; pub(crate) mod helpstart;
pub(crate) mod lfg; pub(crate) mod lfg;
pub(crate) mod xd; pub(crate) mod xd;
pub(crate) mod account;

View file

@ -7,9 +7,12 @@ use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use poise::{async_trait, serenity_prelude as serenity}; use poise::{async_trait, serenity_prelude as serenity};
use serenity::{client::EventHandler, FullEvent, model::id::UserId};
use serenity::all::{ActivityData, Attachment, ChannelId, CreateAttachment, CreateMessage, Event, Guild, GuildChannel};
use serenity::all::Route::Channel; use serenity::all::Route::Channel;
use serenity::all::{
ActivityData, Attachment, ChannelId, CreateAttachment, CreateMessage, Event, Guild,
GuildChannel,
};
use serenity::{client::EventHandler, model::id::UserId, FullEvent};
use sqlx::{Acquire, ConnectOptions, Executor, Sqlite}; use sqlx::{Acquire, ConnectOptions, Executor, Sqlite};
use tokio::sync::RwLock; use tokio::sync::RwLock;
@ -18,7 +21,7 @@ mod commands;
struct Data { struct Data {
bots: Arc<RwLock<u8>>, bots: Arc<RwLock<u8>>,
sqlite_pool: sqlx::Pool<Sqlite>, sqlite_pool: sqlx::Pool<Sqlite>,
hypixel_api_client: reqwest::Client hypixel_api_client: reqwest::Client,
} // User data, which is stored and accessible in all command invocations } // User data, which is stored and accessible in all command invocations
type Error = Box<dyn std::error::Error + Send + Sync>; type Error = Box<dyn std::error::Error + Send + Sync>;
type Context<'a> = poise::Context<'a, Data, Error>; type Context<'a> = poise::Context<'a, Data, Error>;
@ -26,12 +29,11 @@ struct ReadyHandler;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let sqlite_pool = sqlx::sqlite::SqlitePoolOptions::new() let sqlite_pool = sqlx::sqlite::SqlitePoolOptions::new()
.idle_timeout(Duration::from_secs(10)) .idle_timeout(Duration::from_secs(10))
.max_connections(3) .max_connections(3)
.connect_lazy("sqlite:accounts.db").unwrap(); .connect_lazy("sqlite:accounts.db")
.unwrap();
let hypixel_api: String = std::env::var("HYPIXEL_API_KEY").unwrap(); let hypixel_api: String = std::env::var("HYPIXEL_API_KEY").unwrap();
let hypixel_api_client = { let hypixel_api_client = {
@ -42,10 +44,10 @@ async fn main() {
); );
reqwest::ClientBuilder::new() reqwest::ClientBuilder::new()
.default_headers(headers) .default_headers(headers)
.build().unwrap() .build()
.unwrap()
}; };
let options = poise::FrameworkOptions { let options = poise::FrameworkOptions {
commands: vec![ commands: vec![
commands::lfg::lfg(), commands::lfg::lfg(),
@ -82,7 +84,7 @@ async fn main() {
Ok(Data { Ok(Data {
bots: Arc::new(RwLock::new(0)), bots: Arc::new(RwLock::new(0)),
sqlite_pool, sqlite_pool,
hypixel_api_client hypixel_api_client,
}) })
}) })
}) })
@ -107,7 +109,7 @@ async fn event_handler(
match event { match event {
FullEvent::Ready { data_about_bot, .. } => { FullEvent::Ready { data_about_bot, .. } => {
println!("Logged in as {}", data_about_bot.user.name); println!("Logged in as {}", data_about_bot.user.name);
}, }
_ => {} _ => {}
} }
Ok(()) Ok(())