use crate::config::{BotConfig, GlobalData, Wallet}; use crate::error::Error; use crate::{command, group}; use rand::{thread_rng, Rng}; use serenity::client::Context; use serenity::framework::standard::{Args, CommandResult}; use serenity::model::channel::Message; use serenity::model::id::UserId; use serenity::prelude::Mentionable; #[group] #[commands(balance, gift)] pub struct FrenCoin; pub fn get_user_wallet(cfg: &mut BotConfig, discord_id: UserId) -> &mut Wallet { if let Some(user_ndx) = cfg.wallets.iter().position(|u| u.owner == discord_id) { &mut cfg.wallets[user_ndx] } else { cfg.wallets.push(Wallet { owner: discord_id, coin_count: 100, }); cfg.wallets.last_mut().unwrap() } } #[command] #[description("Get your current balance")] #[only_in(guilds)] async fn balance(ctx: &Context, msg: &Message, _args: Args) -> CommandResult { let mut data = ctx.data.write().await; let global_data = data.get_mut::().unwrap(); let wallet = get_user_wallet(&mut global_data.cfg, msg.author.id); msg.reply( &ctx.http, format!("Your current balance is {} fren coins!", wallet.coin_count), ) .await?; global_data.cfg.save(&global_data.args.cfg_path).await?; Ok(()) } #[command] #[only_in(guilds)] #[description("Gift your frens coins!")] #[usage("@fren 25")] async fn gift(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let target = match args.parse::() { Ok(t) => t, Err(_) => { msg.reply(&ctx.http, "Sorry I don't know who that is!") .await?; return Ok(()); } }; args.advance(); let amount = args.parse::()?; let mut data = ctx.data.write().await; let global_data = data.get_mut::().unwrap(); { let author_wallet = get_user_wallet(&mut global_data.cfg, msg.author.id); if author_wallet.coin_count < amount { msg.reply( &ctx.http, "Sorry pal, I can't give credit. Come back when you're a bit mmmm richer.", ) .await?; return Ok(()); } author_wallet.coin_count -= amount; } { let target_wallet = get_user_wallet(&mut global_data.cfg, target); target_wallet.coin_count += amount; } let target_user = msg .guild(&ctx.cache) .unwrap() .member(&ctx.http, target) .await?; msg.reply( &ctx.http, format!( "You have gifted {} {} fren coins!", target_user.mention(), amount ), ) .await?; global_data.cfg.save(&global_data.args.cfg_path).await?; Ok(()) } pub async fn give_coin( ctx: &Context, user: UserId, percent: f64, numer_of_coins: i64, ) -> Result { let should_get_coin = { let mut thread_rng = thread_rng(); thread_rng.gen_bool(percent) }; if should_get_coin { let mut data = ctx.data.write().await; let global_data = data.get_mut::().unwrap(); { let wallet = get_user_wallet(&mut global_data.cfg, user); wallet.coin_count += numer_of_coins; } global_data .cfg .save(&global_data.args.cfg_path) .await .unwrap(); } Ok(should_get_coin) }