feat: can now fetch data from teh ldap api

This commit is contained in:
silver 2023-08-27 15:39:09 +01:00
parent d66f7895bc
commit f382784141
3 changed files with 1118 additions and 48 deletions

1037
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -7,4 +7,6 @@ edition = "2021"
[dependencies]
serenity = { version = "0.11.6", default-features = false, features = ["client", "gateway", "rustls_backend", "model", "cache"] }
tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }
tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }
# to make the http requests
surf = "2.3.2"

View file

@ -1,6 +1,6 @@
use std::env;
use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use serenity::async_trait;
use serenity::model::channel::Message;
@ -9,8 +9,10 @@ use serenity::model::id::GuildId;
use serenity::prelude::*;
use serenity::model::prelude::RoleId;
struct Handler;
// eoghanconlon73
struct Handler {
is_loop_running: AtomicBool,
}
#[async_trait]
impl EventHandler for Handler {
// This event will be dispatched for guilds, but not for direct messages.
@ -27,45 +29,86 @@ impl EventHandler for Handler {
}
async fn ready(&self, ctx: Context, ready: Ready) {
let ctx = Arc::new(ctx);
println!("{} is connected!", ready.user.name);
let config = Config {
members: vec![String::from("silver_golden"), String::from("eoghanconlon73")],
server: GuildId(957961810147938334),
member_role_current: RoleId::from(1144760670995370094),
member_role_past: RoleId::from(1144760548072886353),
};
bulk_check(&ctx, &config).await;
if !self.is_loop_running.load(Ordering::Relaxed) {
// We have to clone the Arc, as it gets moved into the new thread.
let ctx1 = Arc::clone(&ctx);
// tokio::spawn creates a new green thread that can run in parallel with the rest of
// the application.
tokio::spawn(async move {
loop {
// We clone Context again here, because Arc is owned, so it moves to the
// new function.
bulk_check(Arc::clone(&ctx1), &config).await;
tokio::time::sleep(Duration::from_secs(30)).await;
}
});
// And of course, we can run more than one thread at different timings.
let ctx2 = Arc::clone(&ctx);
tokio::spawn(async move {
loop {
bulk_check2(Arc::clone(&ctx2)).await;
tokio::time::sleep(Duration::from_secs(15)).await;
}
});
let ctx3 = Arc::clone(&ctx);
tokio::spawn(async move {
loop {
fetch_accounts(Arc::clone(&ctx3)).await;
tokio::time::sleep(Duration::from_secs(50)).await;
}
});
// fetch_accounts
// Now that the loop is running, we set the bool to true
self.is_loop_running.swap(true, Ordering::Relaxed);
}
}
}
struct Config {
members: Vec<String>,
server: GuildId,
member_role_current: RoleId,
member_role_past: RoleId,
}
#[derive(Default)]
struct Members {
#[derive(Default, Debug)]
struct MembersCount {
members: i32,
members_current: i32,
}
struct MemberCounter;
impl TypeMapKey for MemberCounter {
type Value = Arc<RwLock<Members>>;
type Value = Arc<RwLock<MembersCount>>;
}
async fn bulk_check(ctx: &Context, config: &Config){
struct Members;
impl TypeMapKey for Members {
type Value = Arc<RwLock<Vec<String>>>;
}
async fn bulk_check(ctx: Arc<Context>, config: &Config){
let members_lock = {
let data_read = ctx.data.read().await;
data_read.get::<Members>().expect("Expected Members in TypeMap.").clone()
};
let mut roles_set = [0,0,0];
let mut res = Members {
let mut res = MembersCount {
members: 0,
members_current: 0,
};
if let Ok(x) = config.server.members(ctx, None, None).await {
if let Ok(x) = config.server.members(&ctx, None, None).await {
for mut member in x {
if config.members.contains(&member.user.name) {
if members_lock.read().await.contains(&member.user.name) {
let mut roles = vec![];
if !member.roles.contains(&config.member_role_past){
@ -76,7 +119,7 @@ async fn bulk_check(ctx: &Context, config: &Config){
roles_set[1] += 1;
roles.push(config.member_role_current);
}
if let Err(e) = member.add_roles(&ctx, &roles).await {
println!("{:?}", e);
}
@ -87,7 +130,7 @@ async fn bulk_check(ctx: &Context, config: &Config){
println!("{:?}", e);
}
}
if member.roles.contains(&config.member_role_past){
res.members += 1;
}
@ -114,6 +157,45 @@ async fn bulk_check(ctx: &Context, config: &Config){
}
}
async fn fetch_accounts(ctx: Arc<Context>){
let auth = "abcdef";
let url = format!("http://127.0.0.1:8087/ldap/discord?auth={}", auth);
if let Ok(result) = surf::get(url).recv_json::<Vec<String>>().await {
let members_lock = {
let data_read = ctx.data.read().await;
data_read.get::<Members>().expect("Expected Members in TypeMap.").clone()
};
let mut accounts = members_lock.write().await;
*accounts = result;
}
}
async fn bulk_check2(ctx: Arc<Context>){
let counter_lock = {
let data_read = ctx.data.read().await;
data_read.get::<MemberCounter>().expect("Expected MemberCounter in TypeMap.").clone()
};
{
// The HashMap of CommandCounter is wrapped in an RwLock; since we want to write to it, we will
// open the lock in write mode.
let counter = counter_lock.read().await;
println!("Members: {:?}", counter);
}
let members_lock = {
let data_read = ctx.data.read().await;
data_read.get::<Members>().expect("Expected Members in TypeMap.").clone()
};
{
// The HashMap of CommandCounter is wrapped in an RwLock; since we want to write to it, we will
// open the lock in write mode.
let counter = members_lock.read().await;
println!("Members: {:?}", counter);
}
}
#[tokio::main]
async fn main() {
// Configure the client with your Discord bot token in the environment.
@ -124,13 +206,18 @@ async fn main() {
let intents = GatewayIntents::GUILDS | GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT | GatewayIntents::GUILD_MEMBERS;
// Build our client.
let mut client = Client::builder(token, intents)
.event_handler(Handler)
.event_handler(Handler { is_loop_running: AtomicBool::new(false)})
.await
.expect("Error creating client");
{
let mut data = client.data.write().await;
data.insert::<MemberCounter>(Arc::new(RwLock::new(Members::default())));
// will keep track of how many past and current members we have
data.insert::<MemberCounter>(Arc::new(RwLock::new(MembersCount::default())));
// a list of all current members
data.insert::<Members>(Arc::new(RwLock::new(vec![])));
}