Compare commits

..

18 commits

Author SHA1 Message Date
93359698f0
doc: feedback 2024-11-23 00:26:00 +00:00
dda05d7ca1
doc: resized images using html tags 2024-11-23 00:25:56 +00:00
5dee9acbaa
doc: added images to suer signup 2024-11-23 00:25:51 +00:00
96a61e6fc8
git: finally added a gitattributes 2024-11-23 00:24:48 +00:00
94292fa388
fix: style was causing issues 2024-11-18 16:09:43 +00:00
2daa010d25
doc: updated committee instructions 2024-11-04 12:43:09 +00:00
da4d006bc0
doc: update user docs 2024-10-29 14:00:43 +00:00
80c9191eee
fmt: more clippy that got missed
All checks were successful
On_Push / lint_fmt (push) Successful in 5s
On_Push / lint_clippy (push) Successful in 12s
On_Push / build (push) Successful in 1m49s
On_Push / deploy (push) Successful in 13s
2024-09-30 00:19:58 +01:00
1c3ccbecf5
fmt: not sure how this one slipped by
Some checks failed
On_Push / lint_fmt (push) Successful in 7s
On_Push / lint_clippy (push) Failing after 10s
On_Push / build (push) Has been skipped
On_Push / deploy (push) Has been skipped
2024-09-30 00:12:48 +01:00
d1af8a7c1f Merge pull request '#22_Role-Joiner' (#24) from #22_Role-Joiner into main
Some checks failed
On_Push / lint_fmt (push) Successful in 7s
On_Push / lint_clippy (push) Failing after 13s
On_Push / build (push) Has been skipped
On_Push / deploy (push) Has been skipped
Reviewed-on: #24
2024-09-29 23:10:21 +00:00
0d9ce2de7f
fmt: fmt and clippy 2024-09-30 00:09:29 +01:00
5e7964ae26
feat: some cleanup in messages and added some handrails so folks wont add stupid combos 2024-09-30 00:03:03 +01:00
32292a3c0b
feat: tested out command and gt rid of the last few kinks 2024-09-29 23:47:33 +01:00
ffce78a10d
feat: command config for setting it up
(lsit command can come later to see the active ones)
2024-09-29 22:19:58 +01:00
7980739627
feat: new struct to mirror the databse 2024-09-29 21:39:27 +01:00
2aad895bb3
feat: new table for the role adder 2024-09-29 21:25:58 +01:00
ec74dc0aa7
prep: skeleton to handle roles changing from other means 2024-09-29 21:04:08 +01:00
42f301455a Merge pull request '#21_Normalise-email-inputs' (#23) from #21_Normalise-email-inputs into main
All checks were successful
On_Push / lint_fmt (push) Successful in 7s
On_Push / lint_clippy (push) Successful in 15s
On_Push / build (push) Successful in 1m52s
On_Push / deploy (push) Successful in 13s
Reviewed-on: #23
2024-09-29 19:07:38 +00:00
11 changed files with 408 additions and 37 deletions

37
.gitattributes vendored Normal file
View file

@ -0,0 +1,37 @@
# Git config here
* text eol=lf
#############################################
# Git lfs stuff
# Documents
*.pdf filter=lfs diff=lfs merge=lfs -text
*.doc filter=lfs diff=lfs merge=lfs -text
*.docx filter=lfs diff=lfs merge=lfs -text
# Excel
*.xls filter=lfs diff=lfs merge=lfs -text
*.xlsx filter=lfs diff=lfs merge=lfs -text
*.xlsm filter=lfs diff=lfs merge=lfs -text
# Powerpoints
*.ppt filter=lfs diff=lfs merge=lfs -text
*.pptx filter=lfs diff=lfs merge=lfs -text
*.ppsx filter=lfs diff=lfs merge=lfs -text
# Images
*.png filter=lfs diff=lfs merge=lfs -text
*.jpg filter=lfs diff=lfs merge=lfs -text
# Video
*.mkv filter=lfs diff=lfs merge=lfs -text
*.mp4 filter=lfs diff=lfs merge=lfs -text
*.wmv filter=lfs diff=lfs merge=lfs -text
# Misc
*.zip filter=lfs diff=lfs merge=lfs -text
# ET4011
*.cbe filter=lfs diff=lfs merge=lfs -text
*.pbs filter=lfs diff=lfs merge=lfs -text
# Open/Libre office
# from https://www.libreoffice.org/discover/what-is-opendocument/
*.odt filter=lfs diff=lfs merge=lfs -text
*.ods filter=lfs diff=lfs merge=lfs -text
*.odp filter=lfs diff=lfs merge=lfs -text
*.odg filter=lfs diff=lfs merge=lfs -text
# QT
*.ui filter=lfs diff=lfs merge=lfs -text

View file

@ -1,26 +1,58 @@
# Skynet Discord Bot # Skynet Discord Bot
This bots core purpose is to give members roles based on their status on <ulwolves.ie>. This bots core purpose is to give members roles based on their status on <https://ulwolves.ie>.
It uses an api key provided by wolves to get member lists. It uses an api key provided by wolves to get member lists.
Users are able to link their wolves account to the bot and that works across discord servers. Users are able to link their wolves account to the bot and that works across discord servers.
For example is a user links on the CompSoc Discord then they will also get their roles (automagically) on Games Dev if they are a member there. For example is a user links on the CompSoc Discord then they will also get their roles (automagically) on Games Dev if they are a member there.
## Commands - Admin ## Setup - Committee
You need admin access to run any of the commands in this section. You need admin access to run any of the commands in this section.
Either the server owner or a suer with the ``Administrator`` permission Either the server owner or a user with the ``Administrator`` permission.
### Getting the Skynet Discord bot ### Get the API Key
1. Email ``keith@assurememberships.com`` from committee email and say ye want an api key for ``193.1.99.74`` The ``api_key`` is used by the Bot in order to request information, it will be used later in the process.
2. Create a role for current members (maybe call it ``current-member`` ?)
3. (Optional) create a role for all past and current members (ye can use the existing ``member`` role for this, ) 1. Email ``keith@assurememberships.com`` from committee email and say you want an ``api_key`` for ``193.1.99.74``
4. Invite the bot https://discord.com/api/oauth2/authorize?client_id=1145761669256069270&permissions=139855185984&scope=bot * The committee email is the one here: <https://cp.ulwolves.ie/mailbox/>
5. Make sure the bot role ``@skynet`` is above these two roles (so it can manage them) * This may take up to a week to get the key.
6. Make sure that you have a role that gives ye administrator powers
7. Use the command ``/add`` and insert the api key, role current and role all (desktop recommended) ### Setup Server
The Bot reason for existing is being able to give members Roles.
So we have to create those.
1. Create a role for Current Members.
* You can call it whatever you want.
* ``member-current`` is a good choice.
* This should be a new role
2. **Optional**: you can create a role that is given to folks who were but no longer a member.
* ``member`` would be a good choice for this
* If you have an existing member role this is also a good fit.
The reason for both roles is ye have one for active members while the second is for all current and past members. The reason for both roles is ye have one for active members while the second is for all current and past members.
### Invite Bot
1. Invite the bot https://discord.com/api/oauth2/authorize?client_id=1145761669256069270&permissions=139855185984&scope=bot
2. Make sure the bot role ``@skynet`` is above these two roles created in the previous step
* This is so it can manage the roles (give and remove them from users)
### Setup Bot
This is where the bot is configured.
You will need the ``api_key`` from the start of the process.
You (personally) will need a role with ``Administrator`` permission to be able to do this.
1. Use the command ``/add`` and a list of options will pop up.
2. ``api_key`` is the key you got from Keith earlier.
3. ``role_current`` is the ``member-current`` that you created earlier.
4. ``role_past`` (optional) is the role for all current and past members.
5. ``bot_channel`` is a channel that folks are recommended to use the bot.
* You can have it so folks cannot see message history
6. ``server_name`` For example ``UL Computer Society``
* Will be removed in the future
7. ``wolves_link`` for example <https://ulwolves.ie/society/computer>
* Will be removed in the future
At this point the bot is set up and no further action is required.
### Minecraft ### Minecraft
The bot is able to manage the whitelist of a Minecraft server managed by the Computer Society. The bot is able to manage the whitelist of a Minecraft server managed by the Computer Society.
Talk to us to get a server. Talk to us to get a server.
@ -42,29 +74,24 @@ This unlinks a minecraft server from your club/society.
``/minecraft_delete SERVER_ID`` ``/minecraft_delete SERVER_ID``
## Commands - User ## Setup - Users
This is to link your Discord account with your UL Wolves account.
**You will only need to do this once**.
### Setup ### Setup
* Start the process using ``/link_wolves WOLVES_EMAIL`` 1. In a Discord server with the Skynet Bot enter ``/link_wolves YOUR_WOLVES_CONTACT_EMAIL``
* The email that is in the Contact Email here: <https://ulwolves.ie/memberships/profile> <img src="media/setup_user_01.png" alt="link process start" width="50%" height="50%">
* An email will be sent to them that they need to verify using ``/verify CODE`` * Your ``YOUR_WOLVES_CONTACT_EMAIL`` is the email in the Contact Email here: <https://ulwolves.ie/memberships/profile>
* This will only have to be done once. * This is most likely your student mail
2. An email will be sent to you with a verification code.
<img src="media/setup_user_02.png" alt="signup email" width="50%" height="50%">
3. Verify the code using ``/verify CODE_FROM_EMAIL`` in Discord.
<img src="media/setup_user_03.png" alt="verify in discord" width="50%" height="50%">
4. Once complete your Wolves and Discord accounts will be linked.
* If the user is an active member on wolves You will get member roles on any Discord that is using the bot that you are a member of.
* If they are in any servers with teh Skynet Bot
* They will get relevant roles.
* If they Join a server with teh bot enabled.
* They will be granted the roles automatically
* If the user is **not** an active member on wolves.
* If they have no Roles
* No change
* If they have Past Member Role
* No change
* If they have both Roles
* The current-member role will be removed from them
* Past Member role will remain unchanged
### Minecraft ### Minecraft
Users can link their Minecraft username to grant them access to any servers where teh whitelist is managed by teh bot. You can link your Minecraft username to grant you access to any Minecraft server run by UL Computer Society.
``/link_minecraft MINECRAFT_USERNAME`` ``/link_minecraft MINECRAFT_USERNAME``

View file

@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS roles_adder (
server integer not null,
role_a integer not null,
role_b integer not null,
role_c integer not null,
PRIMARY KEY(server,role_a,role_b,role_c)
);
CREATE INDEX IF NOT EXISTS index_roles_adder_server ON roles_adder (server);
CREATE INDEX IF NOT EXISTS index_roles_adder_from ON roles_adder (role_a,role_b);
CREATE INDEX IF NOT EXISTS index_roles_adder_to ON roles_adder (role_c);
CREATE INDEX IF NOT EXISTS index_roles_adder_search ON roles_adder (server,role_a,role_b);

BIN
media/setup_user_01.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
media/setup_user_02.png (Stored with Git LFS) Normal file

Binary file not shown.

BIN
media/setup_user_03.png (Stored with Git LFS) Normal file

Binary file not shown.

View file

@ -133,7 +133,7 @@ pub mod link {
"h2, h4 { font-family: Arial, Helvetica, sans-serif; }" "h2, h4 { font-family: Arial, Helvetica, sans-serif; }"
} }
} }
div style="display: flex; flex-direction: column; align-items: center;" { div {
h2 { "Hello from Skynet!" } h2 { "Hello from Skynet!" }
// Substitute in the name of our recipient. // Substitute in the name of our recipient.
p { "Hi " (user) "," } p { "Hi " (user) "," }

View file

@ -2,3 +2,4 @@ pub mod add_server;
pub mod committee; pub mod committee;
pub mod link_email; pub mod link_email;
pub mod minecraft; pub mod minecraft;
pub mod role_adder;

238
src/commands/role_adder.rs Normal file
View file

@ -0,0 +1,238 @@
use serenity::{
builder::CreateApplicationCommand,
client::Context,
model::{
application::interaction::application_command::ApplicationCommandInteraction,
prelude::{command::CommandOptionType, interaction::application_command::CommandDataOptionValue},
},
};
use skynet_discord_bot::{is_admin, DataBase, RoleAdder};
use sqlx::{Error, Pool, Sqlite};
pub mod edit {
use super::*;
pub async fn run(command: &ApplicationCommandInteraction, ctx: &Context) -> String {
// check if user has high enough permisssions
if let Some(msg) = is_admin(command, ctx).await {
return msg;
}
let role_a = if let CommandDataOptionValue::Role(role) = command
.data
.options
.first()
.expect("Expected role option")
.resolved
.as_ref()
.expect("Expected role object")
{
role.id.to_owned()
} else {
return "Please provide a valid role for ``Role Current``".to_string();
};
let role_b = if let CommandDataOptionValue::Role(role) = command
.data
.options
.get(1)
.expect("Expected role option")
.resolved
.as_ref()
.expect("Expected role object")
{
role.id.to_owned()
} else {
return "Please provide a valid role for ``Role Current``".to_string();
};
let role_c = if let CommandDataOptionValue::Role(role) = command
.data
.options
.get(2)
.expect("Expected role option")
.resolved
.as_ref()
.expect("Expected role object")
{
role.id.to_owned()
} else {
return "Please provide a valid role for ``Role Current``".to_string();
};
if role_a == role_b {
return "Roles A and B must be different".to_string();
}
if (role_c == role_a) || (role_c == role_b) {
return "Role C cannot be same as A or B".to_string();
}
let mut delete = false;
if let Some(x) = command.data.options.get(3) {
let tmp = x.to_owned();
if let Some(CommandDataOptionValue::Boolean(z)) = tmp.resolved {
delete = z;
}
}
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 {
server,
role_a,
role_b,
role_c,
};
match add_server(&db, &server_data, delete).await {
Ok(_) => {}
Err(e) => {
println!("{:?}", e);
return format!("Failure to insert into Servers {:?}", server_data);
}
}
let mut role_a_name = String::new();
let mut role_b_name = String::new();
let mut role_c_name = String::new();
if let Ok(x) = server.roles(&ctx).await {
if let Some(y) = x.get(&role_a) {
role_a_name = y.to_owned().name;
}
if let Some(y) = x.get(&role_b) {
role_b_name = y.to_owned().name;
}
if let Some(y) = x.get(&role_b) {
role_c_name = y.to_owned().name;
}
}
if delete {
format!("Removed {} + {} = {}", role_a_name, role_b_name, role_c_name)
} else {
format!("Added {} + {} = {}", role_a_name, role_b_name, role_c_name)
}
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command
.name("roles_adder")
.description("Combine roles together to an new one")
.create_option(|option| {
option
.name("role_a")
.description("A role you want to add to Role B")
.kind(CommandOptionType::Role)
.required(true)
})
.create_option(|option| {
option
.name("role_b")
.description("A role you want to add to Role A")
.kind(CommandOptionType::Role)
.required(true)
})
.create_option(|option| option.name("role_c").description("Sum of A and B").kind(CommandOptionType::Role).required(true))
.create_option(|option| {
option
.name("delete")
.description("Delete this entry.")
.kind(CommandOptionType::Boolean)
.required(false)
})
}
async fn add_server(db: &Pool<Sqlite>, server: &RoleAdder, delete: bool) -> Result<Option<RoleAdder>, Error> {
if delete {
sqlx::query_as::<_, RoleAdder>(
"
DELETE FROM roles_adder
WHERE server = ?1 AND role_a = ?2 AND role_b = ?3 AND role_c = ?4
",
)
.bind(*server.server.as_u64() as i64)
.bind(*server.role_a.as_u64() as i64)
.bind(*server.role_b.as_u64() as i64)
.bind(*server.role_c.as_u64() as i64)
.fetch_optional(db)
.await
} else {
sqlx::query_as::<_, RoleAdder>(
"
INSERT OR REPLACE INTO roles_adder (server, role_a, role_b, role_c)
VALUES (?1, ?2, ?3, ?4)
",
)
.bind(*server.server.as_u64() as i64)
.bind(*server.role_a.as_u64() as i64)
.bind(*server.role_b.as_u64() as i64)
.bind(*server.role_c.as_u64() as i64)
.fetch_optional(db)
.await
}
}
}
// TODO
pub mod list {}
pub mod tools {
use serenity::client::Context;
use serenity::model::guild::Member;
use skynet_discord_bot::RoleAdder;
use sqlx::{Pool, Sqlite};
pub async fn on_role_change(db: &Pool<Sqlite>, ctx: &Context, mut new_data: Member) {
// check if the role changed is part of the oens for this server
if let Ok(role_adders) = sqlx::query_as::<_, RoleAdder>(
r#"
SELECT *
FROM roles_adder
WHERE server = ?
"#,
)
.bind(*new_data.guild_id.as_u64() as i64)
.fetch_all(db)
.await
{
let mut roles_add = vec![];
let mut roles_remove = vec![];
for role_adder in role_adders {
// if the user has both A dnd B give them C
if new_data.roles.contains(&role_adder.role_a) && new_data.roles.contains(&role_adder.role_b) && !new_data.roles.contains(&role_adder.role_c)
{
roles_add.push(role_adder.role_c);
}
// If the suer has C but not A or B remove C
if new_data.roles.contains(&role_adder.role_c)
&& (!new_data.roles.contains(&role_adder.role_a) || !new_data.roles.contains(&role_adder.role_b))
{
roles_remove.push(role_adder.role_c);
}
}
if !roles_add.is_empty() {
if let Err(e) = new_data.add_roles(&ctx, &roles_add).await {
println!("{:?}", e);
}
}
if !roles_remove.is_empty() {
if let Err(e) = new_data.remove_roles(&ctx, &roles_remove).await {
println!("{:?}", e);
}
}
}
}
}

View file

@ -293,6 +293,37 @@ impl<'r> FromRow<'r, SqliteRow> for Minecraft {
} }
} }
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RoleAdder {
pub server: GuildId,
pub role_a: RoleId,
pub role_b: RoleId,
pub role_c: RoleId,
}
impl<'r> FromRow<'r, SqliteRow> for RoleAdder {
fn from_row(row: &'r SqliteRow) -> Result<Self, Error> {
let server_tmp: i64 = row.try_get("server")?;
let server = GuildId::from(server_tmp as u64);
Ok(Self {
server,
role_a: get_role_from_row(row, "role_a"),
role_b: get_role_from_row(row, "role_b"),
role_c: get_role_from_row(row, "role_c"),
})
}
}
fn get_role_from_row(row: &SqliteRow, col: &str) -> RoleId {
match row.try_get(col) {
Ok(x) => {
let tmp: i64 = x;
RoleId(tmp as u64)
}
_ => RoleId::from(0u64),
}
}
pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> { pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
let database = format!("{}/{}", &config.home, &config.database); let database = format!("{}/{}", &config.home, &config.database);

View file

@ -1,27 +1,28 @@
pub mod commands; pub mod commands;
use crate::commands::role_adder::tools::on_role_change;
use serenity::model::guild::Member;
use serenity::{ use serenity::{
async_trait, async_trait,
client::{Context, EventHandler}, client::{Context, EventHandler},
model::{ model::{
application::{command::Command, interaction::Interaction}, application::{command::Command, interaction::Interaction},
gateway::{GatewayIntents, Ready}, gateway::{GatewayIntents, Ready},
guild,
prelude::Activity, prelude::Activity,
user::OnlineStatus, user::OnlineStatus,
}, },
Client, Client,
}; };
use std::sync::Arc;
use skynet_discord_bot::{db_init, get_config, get_server_config, get_server_member, Config, DataBase}; use skynet_discord_bot::{db_init, get_config, get_server_config, get_server_member, Config, DataBase};
use std::sync::Arc;
use tokio::sync::RwLock; use tokio::sync::RwLock;
struct Handler; struct Handler;
#[async_trait] #[async_trait]
impl EventHandler for Handler { impl EventHandler for Handler {
async fn guild_member_addition(&self, ctx: Context, mut new_member: guild::Member) { // handles previously linked accounts joining the server
async fn guild_member_addition(&self, ctx: Context, mut new_member: Member) {
let db_lock = { let db_lock = {
let data_read = ctx.data.read().await; let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Config in TypeMap.").clone() data_read.get::<DataBase>().expect("Expected Config in TypeMap.").clone()
@ -75,6 +76,7 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
match Command::set_global_application_commands(&ctx.http, |commands| { match Command::set_global_application_commands(&ctx.http, |commands| {
commands commands
.create_application_command(|command| commands::add_server::register(command)) .create_application_command(|command| commands::add_server::register(command))
.create_application_command(|command| commands::role_adder::edit::register(command))
.create_application_command(|command| commands::link_email::link::register(command)) .create_application_command(|command| commands::link_email::link::register(command))
.create_application_command(|command| commands::link_email::verify::register(command)) .create_application_command(|command| commands::link_email::verify::register(command))
.create_application_command(|command| commands::minecraft::server::add::register(command)) .create_application_command(|command| commands::minecraft::server::add::register(command))
@ -106,6 +108,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, "link_minecraft" => commands::minecraft::user::add::run(&command, &ctx).await,
// admin commands // admin commands
"add" => commands::add_server::run(&command, &ctx).await, "add" => commands::add_server::run(&command, &ctx).await,
"roles_adder" => commands::role_adder::edit::run(&command, &ctx).await,
"minecraft_add" => commands::minecraft::server::add::run(&command, &ctx).await, "minecraft_add" => commands::minecraft::server::add::run(&command, &ctx).await,
"minecraft_list" => commands::minecraft::server::list::run(&command, &ctx).await, "minecraft_list" => commands::minecraft::server::list::run(&command, &ctx).await,
"minecraft_delete" => commands::minecraft::server::delete::run(&command, &ctx).await, "minecraft_delete" => commands::minecraft::server::delete::run(&command, &ctx).await,
@ -120,6 +123,20 @@ Sign up on [UL Wolves]({}) and go to https://discord.com/channels/{}/{} and use
} }
} }
} }
// handles role updates
async fn guild_member_update(&self, ctx: Context, _old_data: Option<Member>, new_data: Member) {
// get config/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 oens for this server
on_role_change(&db, &ctx, new_data).await;
}
} }
#[tokio::main] #[tokio::main]