Compare commits

..

No commits in common. "f3f08962a4d46f207d5c698fe725d55d0953cea2" and "d8f785b0db241c677b2eadec6e12d23b84d7e99b" have entirely different histories.

19 changed files with 351 additions and 200 deletions

View file

@ -41,7 +41,7 @@ async fn main() {
let mut data = client.data.write().await;
data.insert::<Config>(Arc::new(RwLock::new(config)));
data.insert::<DataBase>(Arc::new(db));
data.insert::<DataBase>(Arc::new(RwLock::new(db)));
}
if let Err(why) = client.start().await {
@ -69,11 +69,13 @@ impl EventHandler for Handler {
async fn guild_members_chunk(&self, ctx: Context, chunk: GuildMembersChunkEvent) {
if (chunk.chunk_index + 1) == chunk.chunk_count {
println!("Cache built successfully!");
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Config in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = {
let data_read = ctx.data.read().await;
data_read.get::<Config>().expect("Expected Config in TypeMap.").clone()

View file

@ -36,7 +36,7 @@ async fn main() {
let mut data = client.data.write().await;
data.insert::<Config>(Arc::new(RwLock::new(config)));
data.insert::<DataBase>(Arc::new(db));
data.insert::<DataBase>(Arc::new(RwLock::new(db)));
}
if let Err(why) = client.start().await {

View file

@ -38,7 +38,7 @@ async fn main() {
let mut data = client.data.write().await;
data.insert::<Config>(Arc::new(RwLock::new(config)));
data.insert::<DataBase>(Arc::new(db));
data.insert::<DataBase>(Arc::new(RwLock::new(db)));
}
if let Err(why) = client.start().await {

View file

@ -35,7 +35,7 @@ async fn main() {
let mut data = client.data.write().await;
data.insert::<Config>(Arc::new(RwLock::new(config)));
data.insert::<DataBase>(Arc::new(db));
data.insert::<DataBase>(Arc::new(RwLock::new(db)));
}
if let Err(why) = client.start().await {
@ -50,10 +50,11 @@ impl EventHandler for Handler {
let ctx = Arc::new(ctx);
println!("{} is connected!", ready.user.name);
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Config in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = {
let data_read = ctx.data.read().await;

View file

@ -12,13 +12,8 @@ use skynet_discord_bot::{
},
get_config, Config,
};
use std::{
process,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{process, sync::Arc};
use tokio::sync::RwLock;
#[tokio::main]
@ -45,7 +40,7 @@ async fn main() {
let mut data = client.data.write().await;
data.insert::<Config>(Arc::new(RwLock::new(config)));
data.insert::<DataBase>(Arc::new(db));
data.insert::<DataBase>(Arc::new(RwLock::new(db)));
}
if let Err(why) = client.start().await {
@ -84,11 +79,13 @@ impl EventHandler for Handler {
}
async fn check_bulk(ctx: &Context) {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Config in TypeMap.").clone()
};
let db = db_lock.read().await;
for server_config in get_server_config_bulk(&db).await {
normal::update_server(ctx, &server_config, &[], &[]).await;
}

View file

@ -10,19 +10,31 @@ use skynet_discord_bot::common::{
use sqlx::{Error, Pool, Sqlite};
pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
let Some(CommandDataOption {
value: CommandDataOptionValue::SubCommand(sub_options),
let sub_options = if let Some(CommandDataOption {
value: CommandDataOptionValue::SubCommand(options),
..
}) = command.data.options.first()
else {
{
options
} else {
return "Please provide sub options".to_string();
};
let Some(CommandDataOptionValue::String(wolves_api)) = sub_options.first().map(|opt| &opt.value) else {
let wolves_api = if let Some(x) = sub_options.first() {
match &x.value {
CommandDataOptionValue::String(key) => key.to_string(),
_ => return "Please provide a wolves API key".to_string(),
}
} else {
return "Please provide a wolves API key".to_string();
};
let Some(&CommandDataOptionValue::Role(role_current)) = sub_options.get(1).map(|opt| &opt.value) else {
let role_current = if let Some(x) = sub_options.get(1) {
match &x.value {
CommandDataOptionValue::Role(role) => role.to_owned(),
_ => return "Please provide a valid role for ``Role Current``".to_string(),
}
} else {
return "Please provide a valid role for ``Role Current``".to_string();
};
@ -35,18 +47,24 @@ pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
None
};
let Some(&CommandDataOptionValue::Channel(bot_channel_id)) = sub_options.get(2).map(|opt| &opt.value) else {
let bot_channel_id = if let Some(x) = sub_options.get(2) {
match &x.value {
CommandDataOptionValue::Channel(channel) => channel.to_owned(),
_ => return "Please provide a valid channel for ``Bot Channel``".to_string(),
}
} else {
return "Please provide a valid channel for ``Bot Channel``".to_string();
};
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
let server_data = Servers {
server: command.guild_id.unwrap_or_default(),
wolves_api: wolves_api.to_string(),
wolves_api,
wolves_id: 0,
role_past,
role_current,
@ -55,10 +73,13 @@ pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
bot_channel_id,
};
if let Err(e) = add_server(&db, ctx, &server_data).await {
match add_server(&db, ctx, &server_data).await {
Ok(_) => {}
Err(e) => {
println!("{e:?}");
return format!("Failure to insert into Servers {server_data:?}");
}
}
"Added/Updated server info".to_string()
}

View file

@ -8,26 +8,30 @@ pub mod committee {
use skynet_discord_bot::common::{database::DataBase, set_roles::committee::db_roles_get};
pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
let Some(CommandDataOption {
value: CommandDataOptionValue::SubCommand(sub_options),
let sub_options = if let Some(CommandDataOption {
value: CommandDataOptionValue::SubCommand(key),
..
}) = command.data.options.first()
else {
{
key
} else {
return "Please provide a wolves API key".to_string();
};
let all = sub_options
.first()
.map(|x| match x.value {
let all = if let Some(x) = sub_options.first() {
match x.value {
CommandDataOptionValue::Boolean(y) => y,
_ => false,
})
.unwrap_or(false);
}
} else {
false
};
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
let mut cs = vec![];
// pull it from a DB
@ -38,24 +42,30 @@ pub mod committee {
cs.push((committee.count, committee.name_role.to_owned()));
}
cs.sort_by_key(|(count, _)| std::cmp::Reverse(*count));
cs.sort_by_key(|(count, _)| *count);
cs.reverse();
// msg can be a max 2000 chars long
let limit = 2000 - 3;
let mut limit = 2000 - 3;
let mut response = "```".to_string();
let mut response = vec!["```".to_string()];
for (count, name) in cs {
use std::fmt::Write;
let len_before = response.len();
_ = writeln!(response, "{count:>2} {name}");
if response.len() >= limit {
// Discard the line that didn't fit
response.truncate(len_before);
let leading = if count < 10 { " " } else { "" };
let line = format!("{leading}{count} {name}");
let length = line.len() + 1;
if length < (limit + 3) {
response.push(line);
limit -= length;
} else {
break;
}
}
response.push_str("```");
response
response.push("```".to_string());
response.join("\n")
}
pub fn register() -> CreateCommand {
@ -85,13 +95,18 @@ pub mod servers {
use std::collections::HashMap;
pub async fn run(_command: &CommandInteraction, ctx: &Context) -> String {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
let committees = get_committees(&db).await.into_iter().flatten().map(|committee| (committee.id, committee));
let committees: HashMap<_, _> = committees.collect();
let mut committees = HashMap::new();
if let Some(x) = get_committees(&db).await {
for committee in x {
committees.insert(committee.id, committee.to_owned());
}
}
let mut cs = vec![];
// pull it from a DB
@ -114,22 +129,40 @@ pub mod servers {
cs.reverse();
// msg can be a max 2000 chars long
let limit = 2000 - 3;
let mut limit = 2000 - 3;
let mut response = "```".to_string();
let mut response = vec!["```".to_string()];
for (current, past, name) in cs {
use std::fmt::Write;
let len_before = response.len();
_ = writeln!(response, "{current:>3} {past:>} {name}");
if response.len() >= limit {
// Discard the line that didn't fit
response.truncate(len_before);
let current_leading = if current < 10 {
" "
} else if current < 100 {
" "
} else {
""
};
let past_leading = if past < 10 {
" "
} else if past < 100 {
" "
} else {
""
};
let line = format!("{current_leading}{current} {past_leading}{past} {name}");
let length = line.len() + 1;
// +3 is to account for the closing fence
if length < (limit + 3) {
response.push(line);
limit -= length;
} else {
break;
}
}
response.push_str("```");
response.push("```".to_string());
response
response.join("\n")
}
#[derive(Debug, Clone, Deserialize, Serialize, sqlx::FromRow)]

View file

@ -23,10 +23,11 @@ pub(crate) mod user {
use sqlx::Error;
pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = {
let data_read = ctx.data.read().await;
@ -228,10 +229,11 @@ pub(crate) mod server {
return String::from("Expected Server ID");
};
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
match add_server(&db, &g_id, &server_minecraft).await {
Ok(_) => {}
@ -288,10 +290,11 @@ pub(crate) mod server {
Some(x) => x,
};
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
let servers = get_minecraft_config_server(&db, g_id).await;
@ -363,10 +366,11 @@ pub(crate) mod server {
return String::from("Expected Server ID");
};
let db = {
let data = ctx.data.read().await;
data.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
match server_remove(&db, &g_id, &server_minecraft).await {
Ok(_) => {}

View file

@ -62,10 +62,11 @@ pub mod edit {
false
};
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
let server = command.guild_id.unwrap_or_default();
let server_data = RoleAdder {

View file

@ -18,10 +18,11 @@ pub(crate) mod admin {
use super::*;
pub async fn run(_command: &CommandInteraction, ctx: &Context) -> String {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = {
let data_read = ctx.data.read().await;
@ -68,10 +69,11 @@ pub(crate) mod user {
use sqlx::{Pool, Sqlite};
pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_toml = get_config_icons::minimal();
@ -143,10 +145,11 @@ pub(crate) mod user {
use sqlx::{Pool, Sqlite};
pub async fn run(_command: &CommandInteraction, ctx: &Context) -> String {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_toml = get_config_icons::minimal();

View file

@ -21,10 +21,11 @@ pub mod link {
use serenity::all::{CommandDataOption, CommandDataOptionValue, CommandInteraction};
pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = {
let data_read = ctx.data.read().await;
@ -313,10 +314,11 @@ pub mod verify {
use sqlx::Error;
pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Database in TypeMap.").clone()
};
let db = db_lock.read().await;
// check if user has used /link_wolves
let details = if let Some(x) = get_verify_from_db(&db, &command.user.id).await {
@ -492,10 +494,11 @@ pub mod unlink {
use sqlx::{Pool, Sqlite};
pub async fn run(command: &CommandInteraction, ctx: &Context) -> String {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
};
let db = db_lock.read().await;
// doesn't matter if there is one or not, it will be removed regardless
delete_link(&db, &command.user.id).await;

View file

@ -12,10 +12,11 @@ use sqlx::{
Error, FromRow, Pool, Row, Sqlite,
};
use std::{str::FromStr, sync::Arc};
use tokio::sync::RwLock;
pub struct DataBase;
impl TypeMapKey for DataBase {
type Value = Arc<Pool<Sqlite>>;
type Value = Arc<RwLock<Pool<Sqlite>>>;
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@ -67,11 +68,17 @@ impl<'r> FromRow<'r, SqliteRow> for ServerMembersWolves {
}
fn get_discord_from_row(row: &SqliteRow) -> Option<UserId> {
let x: i64 = row.try_get("discord").ok()?;
if x == 0 {
return None;
match row.try_get("discord") {
Ok(x) => {
let tmp: i64 = x;
if tmp == 0 {
None
} else {
Some(UserId::from(tmp as u64))
}
}
_ => None,
}
Some(UserId::from(x as u64))
}
#[derive(Debug, Clone, Deserialize, Serialize)]

View file

@ -49,7 +49,7 @@ pub async fn post<T: Serialize>(url: &str, bearer: &str, data: &T) {
.body_json(&data)
{
Ok(req) => {
_ = req.await;
req.await.ok();
}
Err(e) => {
dbg!(e);
@ -71,14 +71,20 @@ pub struct ServerDetailsRes {
}
async fn get<T: Serialize + DeserializeOwned>(url: &str, bearer: &str) -> Option<T> {
surf::get(url)
match surf::get(url)
.header("Authorization", bearer)
.header("Content-Type", "application/json")
.header("Accept", "Application/vnd.pterodactyl.v1+json")
.recv_json()
.await
.map_err(|e| dbg!(e))
.ok()
{
Ok(res) => Some(res),
Err(e) => {
dbg!(e);
None
}
}
}
#[derive(Deserialize, Serialize, Debug)]
@ -151,9 +157,14 @@ pub async fn whitelist_update(add: &Vec<(String, bool)>, server: &str, token: &s
let bearer = format!("Bearer {token}");
for (name, java) in add {
let command = if *java { format!("whitelist add {name}") } else { format!("fwhitelist add {name}") };
let data = BodyCommand {
command,
let data = if *java {
BodyCommand {
command: format!("whitelist add {name}"),
}
} else {
BodyCommand {
command: format!("fwhitelist add {name}"),
}
};
post(&format!("{url_base}/command"), &bearer, &data).await;
}

View file

@ -54,47 +54,62 @@ impl Renderer {
count: 0,
};
this.colors = if args.colors.contains(':') {
let obj = args.colors.split(',').map(|s| {
let mut iter = s.split(':');
let [Some(a), Some(b), None] = std::array::from_fn(|_| iter.next()) else {
let colors = if args.colors.contains(':') {
//? object
let obj = args
.colors
.split(',')
.map(|s| {
let s = s.split(':').collect::<Vec<&str>>();
if s.len() < 2 {
dbg!("Invalid color object, try checking help");
return None;
};
}
Some((a.to_string(), b.to_string()))
});
let colors = obj
.flatten()
.map(|c| {
std::fs::create_dir_all(args.output.join(&c.0))?;
Ok(c)
Some((s[0].to_string(), s[1].to_string()))
})
.collect::<std::io::Result<_>>()?;
.collect::<Vec<Option<(String, String)>>>();
let mut colors = Vec::new();
for c in obj.into_iter().flatten() {
std::fs::create_dir_all(args.output.join(&c.0))?;
colors.push(c);
}
ColorType::Object(colors)
} else {
let colors = args
.colors
.split(',')
.map(|color| -> std::io::Result<String> {
//? list
// let colors = args.colors.split(",").map(|s| {
// s.to_string()
// })
// .collect::<Vec<String>>();
let mut colors = Vec::new();
for color in args.colors.split(',') {
std::fs::create_dir_all(args.output.join(color))?;
Ok(color.to_string())
})
.collect::<std::io::Result<_>>()?;
colors.push(color.to_string())
}
ColorType::Array(colors)
};
this.colors = colors;
Ok(this)
}
pub fn render(&mut self, fi: &Path, args: &Args) -> Result<()> {
if fi.extension().is_none_or(|ext| ext != "svg") {
match fi.extension() {
Some(e) if e.to_str() == Some("svg") => {}
Some(_) | None => {
dbg!("Filer {:?} is not of type SVG", fi);
// util::logger::warning(format!("File '{}' is not of SVG type", fi.clone().to_str().unwrap()));
bail!("Failed to render");
}
};
match self.colors.clone() {
ColorType::Array(c) => {

View file

@ -60,11 +60,17 @@ pub mod get_config_icons {
let config_source = minimal();
let file_path = format!("{}/open-governance/{}/{}", &config.home, &config_source.source.directory, &config_source.source.file);
let contents = fs::read_to_string(file_path).map_err(|e| dbg!(e)).unwrap_or_default();
let festivals = toml::from_str::<ConfigTomlRemote>(&contents)
.map(|config| config.festivals)
.map_err(|e| dbg!(e))
.unwrap_or_default();
let contents = fs::read_to_string(file_path).unwrap_or_else(|e| {
dbg!(e);
"".to_string()
});
let festivals = match toml::from_str::<ConfigTomlRemote>(&contents) {
Ok(config_festivals) => config_festivals.festivals,
Err(e) => {
dbg!(e);
vec![]
}
};
ConfigToml {
source: config_source.source,
@ -242,9 +248,12 @@ pub mod update_icon {
for tmp in paths.flatten() {
let path_local = tmp.path().to_owned();
let path_local2 = tmp.path().to_owned();
let Some(name) = path_local2.file_name().map(ToOwned::to_owned) else {
let name = match path_local2.file_name() {
None => {
dbg!(path_local2);
continue;
}
Some(x) => x.to_owned(),
};
let mut path = tmp.path();
@ -299,15 +308,16 @@ pub mod update_icon {
fn logos_filter(festival_data: &FestivalData, existing: Vec<LogoData>) -> Vec<LogoData> {
let mut filtered: Vec<LogoData> = vec![];
let allowed_extensions = ["png", "jpeg", "gif", "svg"];
let allowed_files = vec![".png", ".jpeg", ".gif", ".svg"];
'outer: for logo in existing {
let name_lowercase = logo.name.to_ascii_lowercase();
let name_lowercase = name_lowercase.to_str().unwrap_or_default();
let allowed = {
let extension = name_lowercase.split('.').next_back().unwrap_or_default();
allowed_extensions.contains(&extension)
};
let name_lowercase0 = logo.name.to_ascii_lowercase();
let name_lowercase = name_lowercase0.to_str().unwrap_or_default();
let mut allowed = false;
for allowed_type in &allowed_files {
if name_lowercase.ends_with(allowed_type) {
allowed = true;
}
}
if !allowed {
continue;
}
@ -322,7 +332,13 @@ pub mod update_icon {
}
} else {
// else filter using the excluded ones
let excluded = festival_data.exclusions.iter().any(|festival| name_lowercase.contains(festival));
let mut excluded = false;
for festival in &festival_data.exclusions {
if name_lowercase.contains(festival) {
excluded = true;
}
}
if !excluded {
filtered.push(logo);
}
@ -333,15 +349,13 @@ pub mod update_icon {
}
async fn logo_set(ctx: &Context, db: &Pool<Sqlite>, server: &GuildId, logo_selected: &LogoData) {
// add to the database
if logo_set_db(db, logo_selected).await.is_err() {
// add to teh database
if !logo_set_db(db, logo_selected).await {
// something went wrong
return;
}
let Some(logo_path) = logo_selected.path.to_str() else {
return;
};
if let Some(logo_path) = logo_selected.path.to_str() {
match CreateAttachment::path(logo_path).await {
Ok(icon) => {
// assuming a `guild` has already been bound
@ -355,12 +369,19 @@ pub mod update_icon {
}
}
}
}
async fn logo_set_db(db: &Pool<Sqlite>, logo_selected: &LogoData) -> Result<(), ()> {
let name = logo_selected.name.to_str().ok_or(())?;
let path = logo_selected.path.to_str().ok_or(())?;
async fn logo_set_db(db: &Pool<Sqlite>, logo_selected: &LogoData) -> bool {
let name = match logo_selected.name.to_str() {
None => return false,
Some(x) => x,
};
let path = match logo_selected.path.to_str() {
None => return false,
Some(x) => x,
};
sqlx::query_as::<_, ServerIcons>(
match sqlx::query_as::<_, ServerIcons>(
"
INSERT OR REPLACE INTO server_icons (name, date, path)
VALUES (?1, ?2, ?3)
@ -371,9 +392,13 @@ pub mod update_icon {
.bind(path)
.fetch_optional(db)
.await
.map_err(|e| {
{
Ok(_) => {}
Err(e) => {
dbg!(e);
})?;
Ok(())
return false;
}
}
true
}
}

View file

@ -17,11 +17,13 @@ pub mod normal {
}
pub async fn update_server(ctx: &Context, server: &Servers, remove_roles: &[Option<RoleId>], members_changed: &[UserId]) {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Database in TypeMap.").clone()
};
let db = db_lock.read().await;
let Servers {
server,
role_past,
@ -172,11 +174,13 @@ pub mod committee {
use std::collections::HashMap;
pub async fn check_committee(ctx: &Context) {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Config in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = {
let data_read = ctx.data.read().await;
data_read.get::<Config>().expect("Expected Config in TypeMap.").clone()

View file

@ -24,7 +24,7 @@ struct WolvesResultUserMin {
}
async fn add_users_wolves(db: &Pool<Sqlite>, user: &WolvesResultUserMin) {
// expiry
if let Err(e) = sqlx::query_as::<_, Wolves>(
match sqlx::query_as::<_, Wolves>(
"
INSERT INTO wolves (id_wolves, email)
VALUES ($1, $2)
@ -36,10 +36,13 @@ async fn add_users_wolves(db: &Pool<Sqlite>, user: &WolvesResultUserMin) {
.fetch_optional(db)
.await
{
Ok(_) => {}
Err(e) => {
println!("Failure to insert into Wolves {user:?}");
println!("{e:?}");
}
}
}
/**
This is getting data for Clubs and Socs
@ -66,10 +69,11 @@ pub mod cns {
}
pub async fn get_wolves(ctx: &Context) {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Database in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = {
let data_read = ctx.data.read().await;
@ -88,6 +92,7 @@ pub mod cns {
wolves_id,
..
} = &server_config;
// dbg!(&server_config);
let existing_tmp = get_server_member(&db, server).await;
let existing = existing_tmp.iter().map(|data| (data.id_wolves, data)).collect::<BTreeMap<_, _>>();
@ -95,6 +100,7 @@ pub mod cns {
// list of users that need to be updated for this server
let mut server_name_tmp = None;
for user in wolves.get_members(wolves_api).await {
// dbg!(&user.committee);
if server_name_tmp.is_none() {
server_name_tmp = Some(user.committee_id);
}
@ -218,10 +224,11 @@ pub mod committees {
}
pub async fn get_cns(ctx: &Context) {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Database in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = {
let data_read = ctx.data.read().await;

View file

@ -106,19 +106,21 @@ pub fn get_config() -> Config {
}
}
if let Ok(x) = env::var("COMMITTEE_ROLE") {
if let Ok(x) = x.trim().parse() {
if let Ok(x) = x.trim().parse::<u64>() {
config.committee_role = RoleId::new(x);
}
}
if let Ok(x) = env::var("COMMITTEE_CATEGORY") {
for id in x.split(',').flat_map(|part| part.trim().parse()) {
config.committee_category.push(ChannelId::new(id));
for part in x.split(',') {
if let Ok(x) = part.trim().parse::<u64>() {
config.committee_category.push(ChannelId::new(x));
}
}
}
if let Ok(x) = env::var("COMPSOC_DISCORD") {
if let Ok(x) = x.trim().parse() {
config.compsoc_server = GuildId::new(x)
if let Ok(x) = x.trim().parse::<u64>() {
config.compsoc_server = GuildId::new(x);
}
}

View file

@ -41,11 +41,13 @@ impl EventHandler for Handler {
// handles previously linked accounts joining the server
async fn guild_member_addition(&self, ctx: Context, new_member: Member) {
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Config in TypeMap.").clone()
};
let db = db_lock.read().await;
let config_lock = {
let data_read = ctx.data.read().await;
data_read.get::<Config>().expect("Expected Config in TypeMap.").clone()
@ -54,14 +56,15 @@ impl EventHandler for Handler {
// committee server takes priority
let committee_server = config_global.committee_server;
if new_member.guild_id == committee_server {
if new_member.guild_id.get() == committee_server.get() {
let mut member = vec![new_member.clone()];
update_committees(&db, &ctx, &config_global, &mut member).await;
return;
}
let Some(config_server) = get_server_config(&db, &new_member.guild_id).await else {
return;
let config_server = match get_server_config(&db, &new_member.guild_id).await {
None => return,
Some(x) => x,
};
if get_server_member(&db, &new_member.guild_id, &new_member).await.is_ok() {
@ -80,12 +83,10 @@ impl EventHandler for Handler {
if let Err(e) = new_member.add_roles(&ctx, &roles).await {
println!("{e:?}");
}
return;
}
} else {
let tmp = get_committee(&db, config_server.wolves_id).await;
let Some(committee) = tmp.first() else {
return;
};
if !tmp.is_empty() {
let committee = &tmp[0];
let msg = format!(
r#"
Welcome {} to the {} server!
@ -102,19 +103,24 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
dbg!(err);
}
}
}
}
// handles role updates
async fn guild_member_update(&self, ctx: Context, _old_data: Option<Member>, new_data: Option<Member>, _: GuildMemberUpdateEvent) {
// get config/db
let db = {
let db_lock = {
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Config in TypeMap.").clone()
};
let db = db_lock.read().await;
// check if the role changed is part of the ones for this server
let Some(x) = new_data else { return };
if let Some(x) = new_data {
on_role_change(&db, &ctx, x).await;
}
}
async fn ready(&self, ctx: Context, ready: Ready) {
println!("[Main] {} is connected!", ready.user.name);
@ -126,7 +132,7 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
};
let config = config_lock.read().await;
if let Err(e) = Command::set_global_commands(
match Command::set_global_commands(
&ctx.http,
vec![
commands::wolves::register(),
@ -138,16 +144,22 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
)
.await
{
Ok(_) => {}
Err(e) => {
println!("{e:?}")
}
}
// Inter-Committee server
if let Err(e) = config.committee_server.set_commands(&ctx.http, vec![commands::count::committee::register()]).await {
match config.committee_server.set_commands(&ctx.http, vec![commands::count::committee::register()]).await {
Ok(_) => {}
Err(e) => {
println!("{e:?}")
}
}
// CompSoc Server
if let Err(e) = config
match config
.compsoc_server
.set_commands(
&ctx.http,
@ -159,13 +171,16 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
)
.await
{
Ok(_) => {}
Err(e) => {
println!("{e:?}")
}
}
}
async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
if let Interaction::Command(command) = interaction {
_ = command.defer_ephemeral(&ctx.http).await;
let _ = command.defer_ephemeral(&ctx.http).await;
// println!("Received command interaction: {:#?}", command);
let content = match command.data.name.as_str() {
@ -179,7 +194,7 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
"link_minecraft" => commands::minecraft::user::add::run(&command, &ctx).await,
"docs" => commands::wolves::link_docs::users::run(&command, &ctx).await,
// "link" => commands::count::servers::run(&command, &ctx).await,
_ => format!("not implemented :( wolves {}", x.name.as_str()),
&_ => format!("not implemented :( wolves {}", x.name.as_str()),
},
},
@ -194,7 +209,7 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
None => "error".to_string(),
Some(z) => match z.name.as_str() {
"change" => commands::server_icon::admin::change::run(&command, &ctx).await,
_ => format!("not implemented :( count {}", x.name.as_str()),
&_ => format!("not implemented :( count {}", x.name.as_str()),
},
},
_ => {
@ -203,7 +218,7 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
},
// TODO: move teh minecraft commands in here as a subgroup
// "link" => commands::count::servers::run(&command, &ctx).await,
_ => format!("not implemented :( committee {}", x.name.as_str()),
&_ => format!("not implemented :( committee {}", x.name.as_str()),
},
},
"minecraft_add" => commands::minecraft::server::add::run(&command, &ctx).await,
@ -215,7 +230,7 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
Some(x) => match x.name.as_str() {
"committee" => commands::count::committee::run(&command, &ctx).await,
"servers" => commands::count::servers::run(&command, &ctx).await,
_ => format!("not implemented :( count {}", x.name.as_str()),
&_ => format!("not implemented :( count {}", x.name.as_str()),
},
},
@ -229,16 +244,16 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
Some(z) => match z.name.as_str() {
"icon" => commands::server_icon::user::current::icon::run(&command, &ctx).await,
"festival" => commands::server_icon::user::current::festival::run(&command, &ctx).await,
_ => format!("not implemented :( count {}", x.name.as_str()),
&_ => format!("not implemented :( count {}", x.name.as_str()),
},
},
_ => format!("not implemented :( {}", command.data.name.as_str()),
&_ => format!("not implemented :( {}", command.data.name.as_str()),
};
result
}
"stats" => commands::server_icon::user::stats::run(&command, &ctx).await,
_ => format!("not implemented :( count {}", x.name.as_str()),
&_ => format!("not implemented :( count {}", x.name.as_str()),
},
},
_ => format!("not implemented :( {}", command.data.name.as_str()),
@ -289,7 +304,7 @@ async fn main() {
let mut data = client.data.write().await;
data.insert::<Config>(Arc::new(RwLock::new(config)));
data.insert::<DataBase>(Arc::new(db));
data.insert::<DataBase>(Arc::new(RwLock::new(db)));
}
// Finally, start a single shard, and start listening to events.