FrenBot/src/discord/fren_coin.rs
2023-01-06 18:01:07 -07:00

137 lines
3.3 KiB
Rust

use crate::config::GlobalData;
use crate::error::Error;
use crate::wallet::WalletError;
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;
#[command]
#[description("Get your current balance")]
#[aliases("audit")]
#[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::<GlobalData>().unwrap();
let user = args.parse::<UserId>().unwrap_or(msg.author.id);
let wallet = global_data.cfg.wallet_manager.get_user_wallet(user);
msg.reply(
&ctx.http,
format!(
"{}'s current balance is {} fren coins!",
msg.guild(&ctx.cache)
.unwrap()
.member(&ctx.http, user)
.await
.unwrap()
.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 = match args.parse::<UserId>() {
Ok(t) => t,
Err(_) => {
msg.reply(&ctx.http, "Sorry I don't know who that is!")
.await?;
return Ok(());
}
};
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) = global_data
.cfg
.wallet_manager
.transfer_funds(msg.author.id, target, amount)
{
if let WalletError::NotEnoughFunds = e {
msg.reply(
&ctx.http,
"Sorry pal, I can't give credit. Come back when you're a bit mmmm richer.",
)
.await?;
}
} else {
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?;
}
Ok(())
}
pub async fn give_coin(
ctx: &Context,
user: UserId,
percent: f64,
numer_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();
{
let wallet = global_data.cfg.wallet_manager.get_user_wallet(user);
wallet.coin_count += numer_of_coins;
}
global_data
.cfg
.save(&global_data.args.cfg_path)
.await
.unwrap();
}
Ok(should_get_coin)
}