Skip to content

Commit

Permalink
testing poise
Browse files Browse the repository at this point in the history
  • Loading branch information
HadziqM committed Dec 12, 2023
1 parent 68c9bac commit 361678b
Show file tree
Hide file tree
Showing 11 changed files with 441 additions and 18 deletions.
259 changes: 247 additions & 12 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[workspace]
members = ["discord","material","image-edit","binding"]
members = ["discord","material","image-edit","binding", "test-bot"]
resolver = "2"
1 change: 1 addition & 0 deletions binding/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ material = { version = "0.1.0", path = "../material" }
serde = { version = "1.0.193", features = ["derive"] }
serde_json = "1.0.108"
sqlx = { version = "0.7.3", features = ["postgres", "chrono", "runtime-tokio-native-tls"] }
tokio = { version = "1.35.0", features = ["full"] }
77 changes: 77 additions & 0 deletions binding/src/bounty/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#![allow(unused)]

use std::{collections::HashMap, path::Path, sync::Arc};
use crate::postgres::custom;
use super::*;

#[derive(Serialize,Deserialize,Clone,Default)]
pub struct BBQConfig {
pub description:String,
pub cooldown_timer:u32,
pub public_cooldown :Option<u32>,
pub icon:String,
pub thumbnail:String,
pub rules:Vec<String>,
pub solo:BountyReward,
pub multi:BountyReward
}



impl Category {
pub fn name(&self) -> &'static str {
match self {
Self::Gold => "gold",
Self::Free => "free",
Self::Event => "event",
Self::Bronze => "bronze",
Self::Silver => "silver",
Self::Custom => "Custom",
}
}
pub fn config_name(&self) -> String {
format!("bounty_{}.json",self.name())
}
pub async fn load(&self) -> Result<HashMap<BBQ,BBQConfig>,BountyErr> {
let path = Path::new(".").join("static").join(&self.config_name());
Ok(serde_json::from_slice(&tokio::fs::read(path).await?)?)
}
}

impl title::Title {
pub async fn load(&self) -> Result<Self,BountyErr> {
let path = Path::new(".").join("static").join("title.json");
Ok(serde_json::from_slice(&tokio::fs::read(path).await?)?)
}
}

struct Cooldown(HashMap<BBQ,u32>);

impl From<HashMap<BBQ,BBQConfig>> for Cooldown {
fn from(value: HashMap<BBQ,BBQConfig>) -> Self {
Cooldown(value.into_iter()
.map(|(k,v)|(k,v.public_cooldown.unwrap_or(999)))
.collect())
}
}


impl BountyGlobal {
pub fn create() -> Arc<Self> {
Arc::new(Self { cooldown: Mutex::new(HashMap::new()), submision: Mutex::new(HashMap::new()) })
}
pub async fn refresh(&self) -> Result<(),BountyErr> {
let free = Category::Free.load().await?;
let new_cd:Cooldown = free.into();
*self.cooldown.lock().await = new_cd.0;
Ok(())
}
pub async fn caching(&self) -> Result<(),BountyErr> {
let data = self.submision.lock().await;
let path = Path::new(".").join("CACHE");
tokio::fs::write(path, serde_json::to_string(&*data)?.as_bytes()).await?;
Ok(())
}
}


54 changes: 51 additions & 3 deletions binding/src/bounty/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,57 @@
use std::collections::HashMap;
use tokio::sync::Mutex;
use serde::{Serialize,Deserialize};
use crate::{bitwise::ItemCode, postgres::card::Event};

use title::Progresion;

pub mod title;
pub mod config;
pub mod submit;


pub struct BountyGlobal {
pub cooldown: Mutex<HashMap<BBQ,u32>>,
pub submision: Mutex<HashMap<String,BountySubmit>>
}



#[derive(Debug)]
pub enum BountyErr {
Custom(String),
Tokio(tokio::io::Error),
Serde(serde_json::Error)
}

impl std::error::Error for BountyErr {}

impl std::fmt::Display for BountyErr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Custom(x) => x.fmt(f),
Self::Tokio(x) => x.fmt(f),
Self::Serde(x) => x.fmt(f)
}
}
}

impl From<tokio::io::Error> for BountyErr {
fn from(value: tokio::io::Error) -> Self {
Self::Tokio(value)
}
}

impl From<serde_json::Error> for BountyErr {
fn from(value: serde_json::Error) -> Self {
Self::Serde(value)
}
}
impl From<&str> for BountyErr {
fn from(value: &str) -> Self {
Self::Custom(value.to_string())
}
}


#[derive(PartialEq, Eq,Clone,Hash,Serialize,Deserialize)]
Expand Down Expand Up @@ -54,20 +102,20 @@ pub enum BBQ{
BBQ25,
}

#[derive(Serialize,Deserialize,PartialEq, Eq,Clone,Debug)]
#[derive(Serialize,Deserialize,PartialEq, Eq,Clone,Debug,Default)]
pub struct BountyReward{
coin:u32,
ticket:u32,
items:Vec<ItemCode>
}

#[derive(Clone)]
#[derive(Clone,Serialize,Deserialize)]
pub struct Hunter{
pub member:String,
pub title:Progresion,
pub event:Event,
}
#[derive(Clone)]
#[derive(Clone,Serialize,Deserialize)]
pub struct BountySubmit{
pub method:Methode,
pub category:Category,
Expand Down
Empty file added binding/src/bounty/submit.rs
Empty file.
3 changes: 2 additions & 1 deletion binding/src/postgres/card.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use sqlx::{Row, FromRow,Result};
use super::{Db,PgCustomError};
use serde::{Serialize,Deserialize};

#[derive(Debug,FromRow)]
pub struct Card {
Expand Down Expand Up @@ -30,7 +31,7 @@ impl Default for Card{
}
}

#[derive(FromRow,Clone,Debug)]
#[derive(FromRow,Clone,Debug,Serialize,Deserialize)]
pub struct Event {
pub bounty:i32,
pub gacha:i32,
Expand Down
1 change: 0 additions & 1 deletion discord/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ edition = "2021"

[dependencies]
serenity = { version = "0.12.0", default-features = false, features = ["client", "gateway", "rustls_backend", "model","collector"] }
hertz = { path = "../hertz" }
tokio = { version = "1.0", features = ["full"] }
reqwest = { version = "0.11", features = ["json"] }
sqlx = { version = "0.7.3", features = [ "runtime-tokio-native-tls" , "postgres","chrono","macros"] }
Expand Down
1 change: 1 addition & 0 deletions test-bot/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.env
12 changes: 12 additions & 0 deletions test-bot/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "test-bot"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
dotenv = "0.15.0"
poise = { version = "0.5.7", features = ["time", "collector"] }
serenity = { version = "0.12.0", features = ["client", "gateway", "rustls_backend", "model", "collector"] }
tokio = { version = "1.35.0", features = ["full"] }
49 changes: 49 additions & 0 deletions test-bot/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#![allow(unused)]
use dotenv::{dotenv,var};
use poise::{serenity_prelude as serenity, CreateReply};
use ::serenity::futures::future::ok;

struct Data;

type Error = Box<dyn std::error::Error + Send + Sync>;
type Context<'a> = poise::Context<'a,Data,Error>;

#[poise::command(slash_command,prefix_command)]
async fn ping(ctx:Context<'_>) -> Result<(),Error> {
ctx.say("pong").await?;
Ok(())
}
#[poise::command(slash_command,prefix_command)]
async fn error(ctx:Context<'_>) -> Result<(),Error> {
ctx.say("a".parse::<u8>()?.to_string()).await?;
Ok(())
}

async fn on_error(err:poise::FrameworkError<'_,Data,Error>) {
match err {
poise::FrameworkError::Setup { error, .. } => {
panic!("failed to setup with err messages {error:?}")
}
poise::FrameworkError::Command { error, ctx } => {
ctx.say("this can be error").await;
}
error => {
if let Err(e) = poise::builtins::on_error(error).await {
println!("Error while handling error: {}", e)
}
}
}
}

#[tokio::main]
async fn main() {
dotenv();
let token = var("TOKEN")
.expect("cant find token in .env");

let opt = poise::FrameworkOptions {
commands:vec![ping(),error()],
on_error: |err| Box::pin(on_error(err)),
..Default::default()
};
}

0 comments on commit 361678b

Please sign in to comment.