large refactor: reorganize code

This commit is contained in:
2024-10-11 20:33:12 -04:00
parent ecbf4cad06
commit 4e08e25575
10 changed files with 240 additions and 183 deletions

View File

@@ -0,0 +1,20 @@
use super::get_user_wealth_mut;
use crate::common::{Context, Error};
use poise::serenity_prelude as serenity;
#[poise::command(slash_command, prefix_command)]
pub async fn balance(ctx: Context<'_>, user: Option<serenity::User>) -> Result<(), Error> {
let user = user.as_ref().unwrap_or(ctx.author());
let mut users = ctx.data().users.lock().await;
let wealth = get_user_wealth_mut(&mut users, user.id);
ctx.reply(format!("{} **{}** token(s).",
if user.id == ctx.author().id {
"You have".to_string()
} else {
format!("{} has", user.name)
}, *wealth)).await?;
Ok(())
}

View File

@@ -0,0 +1,29 @@
use crate::{Context, Error};
use super::get_user_wealth_mut;
use poise::serenity_prelude as serenity;
#[poise::command(slash_command, prefix_command)]
pub async fn give(ctx: Context<'_>, user: serenity::User, amount: usize) -> Result<(), Error> {
if user.bot {
ctx.reply("Don't waste your token(s) by giving them to a bot!").await?;
return Ok(());
}
let mut users = ctx.data().users.lock().await;
let author_wealth = get_user_wealth_mut(&mut users, ctx.author().id);
if *author_wealth < amount {
ctx.reply(format!("You only have **{}** token(s) and cannot give away **{}**.",
*author_wealth, amount)).await?;
return Ok(());
}
*author_wealth -= amount;
let receiver_wealth = get_user_wealth_mut(&mut users, user.id);
*receiver_wealth += amount;
ctx.reply(format!("You've given **{}** **{}** token(s).", user.name, amount)).await?;
Ok(())
}

View File

@@ -0,0 +1,14 @@
use std::collections::HashMap;
use poise::serenity_prelude::UserId;
pub mod balance;
pub mod give;
pub mod wager;
pub(self) fn get_user_wealth_mut(users: &mut HashMap<UserId, usize>, id: UserId) -> &mut usize {
if users.get(&id).is_none() {
users.insert(id, 100);
}
users.get_mut(&id).unwrap()
}

View File

@@ -0,0 +1,26 @@
use crate::common::{Context, Error};
use super::get_user_wealth_mut;
#[poise::command(slash_command, prefix_command)]
pub async fn wager(ctx: Context<'_>, amount: usize) -> Result<(), Error> {
let mut users = ctx.data().users.lock().await;
let wealth = get_user_wealth_mut(&mut users, ctx.author().id);
if *wealth < amount {
ctx.reply("You do not have enough tokens to wager this amount.").await?;
return Ok(());
}
if rand::random() {
*wealth += amount;
ctx.reply(format!("You just gained {} token(s)! You now have **{}**.",
amount, *wealth)).await?;
} else {
*wealth -= amount;
ctx.reply(format!("You've lost **{}** token(s), you now have **{}**.",
amount, *wealth)).await?;
}
Ok(())
}