discord-bot/src/main.rs

88 lines
2.3 KiB
Rust
Raw Normal View History

2023-08-27 16:38:30 +00:00
use serenity::{
async_trait,
client::{Context, EventHandler},
model::{
gateway::{GatewayIntents, Ready},
guild,
2023-08-27 16:38:30 +00:00
},
Client,
};
use std::sync::Arc;
use skynet_discord_bot::{db_init, get_config, get_server_config, get_server_member, Config, DataBase};
2023-08-27 16:38:30 +00:00
use tokio::sync::RwLock;
2023-08-25 22:36:46 +00:00
struct Handler;
2023-08-25 22:36:46 +00:00
#[async_trait]
impl EventHandler for Handler {
async fn guild_member_addition(&self, ctx: Context, mut new_member: guild::Member) {
let db_lock = {
2023-08-27 16:38:30 +00:00
let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Config in TypeMap.").clone()
2023-08-27 16:38:30 +00:00
};
let db = db_lock.read().await;
let config = match get_server_config(&db, &new_member.guild_id).await {
None => return,
Some(x) => x,
2023-08-27 16:38:30 +00:00
};
if get_server_member(&db, &new_member.guild_id, &new_member).await.is_some() {
2023-08-27 16:38:30 +00:00
let mut roles = vec![];
if let Some(role) = &config.role_past {
if !new_member.roles.contains(role) {
roles.push(role.to_owned());
}
}
2023-08-27 16:38:30 +00:00
if let Some(role) = &config.role_current {
if !new_member.roles.contains(role) {
roles.push(role.to_owned());
2023-08-27 16:38:30 +00:00
}
}
if let Err(e) = new_member.add_roles(&ctx, &roles).await {
println!("{:?}", e);
2023-08-27 16:38:30 +00:00
}
2023-08-25 22:36:46 +00:00
}
2023-08-27 16:38:30 +00:00
}
async fn ready(&self, _ctx: Context, ready: Ready) {
println!("[Main] {} is connected!", ready.user.name);
2023-08-27 16:38:30 +00:00
}
}
2023-08-25 22:36:46 +00:00
#[tokio::main]
async fn main() {
2023-08-27 16:38:30 +00:00
let config = get_config();
let db = match db_init(&config).await {
Ok(x) => x,
Err(_) => return,
};
2023-08-27 16:38:30 +00:00
// Intents are a bitflag, bitwise operations can be used to dictate which intents to use
let intents = GatewayIntents::GUILDS | GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT | GatewayIntents::GUILD_MEMBERS;
// Build our client.
let mut client = Client::builder(&config.discord_token, intents)
.event_handler(Handler {})
2023-08-27 16:38:30 +00:00
.await
.expect("Error creating client");
{
let mut data = client.data.write().await;
2023-08-27 16:30:54 +00:00
2023-08-27 16:38:30 +00:00
data.insert::<Config>(Arc::new(RwLock::new(config)));
data.insert::<DataBase>(Arc::new(RwLock::new(db)));
2023-08-27 16:38:30 +00:00
}
// Finally, start a single shard, and start listening to events.
//
// Shards will automatically attempt to reconnect, and will perform
// exponential backoff until it reconnects.
if let Err(why) = client.start().await {
println!("Client error: {:?}", why);
}
}