FrenBot/src/discord/fren_coin.rs

135 lines
3.5 KiB
Rust

use crate::config::GlobalData;
use crate::error::Error;
use crate::user::{User, UserError};
use crate::{command, group};
use rand::{thread_rng, Rng};
use serenity::all::parse_user_mention;
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;
#[command]
#[description("Get your current balance")]
#[aliases("audit")]
async fn balance(ctx: &Context, msg: &Message, args: Args) -> CommandResult {
let mut data = ctx.data.write().await;
let global_data = data.get_mut::<GlobalData>().unwrap();
let user = if args.is_empty() {
msg.author.id
} else {
let mention = args.parse::<String>().unwrap();
parse_user_mention(&mention).unwrap()
};
let wallet = User::get_user(&global_data.db, user)?;
msg.reply(
&ctx.http,
format!(
"{}'s current balance is {} fren coins!",
user.mention(),
wallet.coin_count
),
)
.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 = args.parse::<String>().unwrap();
let target = match parse_user_mention(&target) {
None => {
msg.reply(
&ctx.http,
"Gonna be real honest with you gamer, no clue who that is",
)
.await?;
return Ok(());
}
Some(t) => t,
};
args.advance();
let amount = match args.parse::<u32>() {
Ok(amount) => amount,
Err(err) => {
msg.reply(&ctx.http, format!("Invalid coin amount: {}", err))
.await?;
return Ok(());
}
};
let mut data = ctx.data.write().await;
let global_data = data.get_mut::<GlobalData>().unwrap();
if let Err(e) = User::transfer_funds(&global_data.db, msg.author.id, target, amount) {
if let Error::UserError(err) = e {
match err {
UserError::NotEnoughFunds => {
msg.reply(
&ctx.http,
"Sorry pal, I can't give credit. Come back when you're a bit mmmm richer.",
)
.await?;
}
UserError::InvalidTarget => {
msg.reply(
&ctx.http,
"Sorry pal, I can't make a friend up for you. Come back when you got friends.",
)
.await?;
}
_ => {}
}
}
} else {
msg.reply(
&ctx.http,
format!(
"You have gifted {} {} fren coins!",
target.mention(),
amount
),
)
.await?;
}
Ok(())
}
pub async fn give_coin(
ctx: &Context,
user: UserId,
percent: f64,
number_of_coins: i64,
) -> Result<bool, Error> {
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::<GlobalData>().unwrap();
User::give_funds(&global_data.db, user, number_of_coins as u32)?;
}
Ok(should_get_coin)
}