Skip to content

Commit

Permalink
Get docker working, fix clippy, use stdout for logging and fix crash …
Browse files Browse the repository at this point in the history
…if api takes too long to respond
  • Loading branch information
miam-miam committed Mar 6, 2024
1 parent 68c02a9 commit c0ad498
Show file tree
Hide file tree
Showing 6 changed files with 118 additions and 104 deletions.
5 changes: 3 additions & 2 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
Dockerfile
.dockerignore
node_modules
README.md
target
log
*.md
docker
.git
47 changes: 42 additions & 5 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,8 +1,45 @@
FROM rust:1.76 as builder
#FROM rust:1.76-alpine as builder
#
#WORKDIR /usr/src/verify-bot
#COPY . .
#
#RUN apk update && apk install libssl-dev && rm -rf /var/lib/apt/lists/*
#
#RUN cargo install --path .
#
#CMD ["verify-bot"]

WORKDIR /usr/src/verify-vbot
COPY . .
FROM rust:1.76-buster as build

# create a new empty shell project
RUN USER=root cargo new --bin verify-bot
WORKDIR /verify-bot

# copy over your manifests
COPY ./Cargo.lock ./Cargo.lock
COPY ./Cargo.toml ./Cargo.toml

# this build step will cache your dependencies
RUN cargo build --release
RUN rm src/*.rs

# copy your source tree
COPY ./src ./src
COPY ./log4rs.yml ./log4rs.yml

# build for release
RUN rm ./target/release/deps/verify_bot*
RUN cargo build --release

# our final base
FROM debian:buster

RUN apt-get update && apt-get -y install libssl1.1 && apt clean && rm -rf /var/lib/apt/lists/*

# copy the build artifact from the build stage
COPY --from=build /verify-bot/target/release/verify-bot .

# set the startup command to run your binary
CMD ["./verify-bot"]

RUN cargo install --path .

CMD ["verify-bot"]
21 changes: 3 additions & 18 deletions log4rs.yml
Original file line number Diff line number Diff line change
@@ -1,26 +1,11 @@
refresh_rate: 30 seconds

appenders:
file:
kind: rolling_file
path: log/verify.log
stdout:
kind: console

append: true

encoder:
kind: pattern

policy:
kind: compound

trigger:
kind: size
limit: 10 mb

roller:
kind: delete

root:
level: warn
appenders:
- file
- stdout
120 changes: 58 additions & 62 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,67 +31,63 @@ mod api;

pub async fn verify(ctx: &Context, command: CommandInteraction) -> Result<()> {
let guild_id = command.guild_id.unwrap();
match api::is_verified(command.user.id, guild_id)
.await
.context(concat!(file!(), ":", line!()))
{
Ok(()) => match api::get_role_id(guild_id)
.await
.context(concat!(file!(), ":", line!()))
{
Ok(role) => {
match ctx
.http
.add_member_role(command.guild_id.unwrap(), command.user.id, role, None)
.await
.context(concat!(file!(), ":", line!()))
{
Ok(_) => {
command
.create_response(
ctx,
CreateInteractionResponse::Message(
CreateInteractionResponseMessage::new()
.ephemeral(true)
.content("You have now been verified!"),
),
)
.await
.context(concat!(file!(), ":", line!()))?;
Ok(())
}
Err(e) => {
command
.create_response(ctx, CreateInteractionResponse::Message(CreateInteractionResponseMessage::new().content("I was unable to add the verified role, please make sure my role has higher permissions than the verified role.")))
.await.context(concat!(file!(), ":", line!()))?;
Err(e).context("Could not add verified role.")
}
}
}
Err(e) => {
let (ephemeral, role_future) = join!(command.defer_ephemeral(ctx), api::get_role_id(guild_id));
ephemeral?;
match role_future.context(concat!(file!(), ":", line!())) {
Ok(role) => {
if let Err(e) = api::is_verified(command.user.id, guild_id)
.await
.context(concat!(file!(), ":", line!()))
{
TASK_LIST
.get()
.expect("OnceCell should be instantiated")
.send((command.user.id, guild_id))
.ok();

command
.create_response(ctx, CreateInteractionResponse::Message(CreateInteractionResponseMessage::new().content("It looks like your server doesn't support this bot, please contact the admins."))
)
.await.context(concat!(file!(), ":", line!()))?;
Err(e)
.edit_response(ctx, EditInteractionResponse::new().content(format!(
"Please verify yourself by going to {} and then run this command again.",
env::var("DISPLAY_URL")
.expect("DISPLAY_URL environment var has not been set")
)))
.await
.context(concat!(file!(), ":", line!()))?;
return Err(e);
}
},
e => {
TASK_LIST
.get()
.expect("OnceCell should be instantiated")
.send((command.user.id, guild_id))
.ok();

command
.create_response(ctx, CreateInteractionResponse::Message(CreateInteractionResponseMessage::new().ephemeral(true).content(format!(
"Please verify yourself by going to {} and then run this command again.",
env::var("DISPLAY_URL")
.expect("DISPLAY_URL environment var has not been set.")
))))
match ctx
.http
.add_member_role(command.guild_id.unwrap(), command.user.id, role, None)
.await
.context(concat!(file!(), ":", line!()))?;
e
.context(concat!(file!(), ":", line!()))
{
Ok(_) => {
command
.edit_response(
ctx,
EditInteractionResponse::new().content("You have now been verified!"),
)
.await
.context(concat!(file!(), ":", line!()))?;
Ok(())
}
Err(e) => {
let message = command
.edit_response(ctx, EditInteractionResponse::new().content("I was unable to add the verified role, please make sure my role has higher permissions than the verified role."))
.await.context(concat!(file!(), ":", line!()))?;
message.channel_id.say(ctx, "This bot has not been correctly setup. Please contact the admins so they can ensure the bot's role has higher permissions than the verified role.").await.context(concat!(file!(), ":", line!()))?;
Err(e).context("Could not add verified role.")
}
}
}
Err(e) => {
let message = command
.edit_response(ctx, EditInteractionResponse::new().content("It looks like your server doesn't support this bot, please contact the admins.")
)
.await.context(concat!(file!(), ":", line!()))?;
message.channel_id.say(ctx, "This bot has not been correctly setup. Please contact the admins so they can run /setup.").await.context(concat!(file!(), ":", line!()))?;
Err(e)
}
}
}
Expand Down Expand Up @@ -246,14 +242,14 @@ async fn get_verified_role(
.context(concat!(file!(), ":", line!()))?;
bail!("Not given permission to manage roles.")
}
let mut role = Role::default();
let role;
let bot_position = bot
.roles
.iter()
.filter_map(|r| partial_guild.roles.get(r).map(|r| r.position))
.max();

match command.data.options.get(0).map(|o| o.value.clone()) {
match command.data.options.first().map(|o| o.value.clone()) {
Some(CommandDataOptionValue::Role(r)) => {
role = ctx
.http
Expand Down Expand Up @@ -341,7 +337,7 @@ async fn modal_response(
.data
.components
.iter()
.filter_map(|a| a.components.get(0))
.filter_map(|a| a.components.first())
{
match t {
InputText(t) if t.custom_id == "name" => name = t.value.clone(),
Expand All @@ -358,15 +354,15 @@ async fn modal_response(
let name = name.ok_or_else(|| anyhow!("name was not sent."))?;
let susu_link = match susu
.filter(|s| !s.trim().is_empty())
.map(|s| Url::parse(&*s))
.map(|s| Url::parse(&s))
{
Some(Err(e)) => {
return Err(e).context("Unable to parse susu link, please make sure it is a url.");
}
Some(Ok(l)) => Some(l),
None => None,
};
let invite_link = Url::parse(&*invite.ok_or_else(|| anyhow!("invite was not sent."))?)
let invite_link = Url::parse(&invite.ok_or_else(|| anyhow!("invite was not sent."))?)
.context("Unable to parse invite link, please make sure it is a url.")?;

let resp = register_guild(RegisterParams {
Expand Down
8 changes: 4 additions & 4 deletions src/commands/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ static CLIENT: Lazy<Client> = Lazy::new(|| {
headers.insert(
"Authorization",
HeaderValue::from_str(
&*env::var("API_KEY").expect("API_KEY environment var has not been set."),
&env::var("API_KEY").expect("API_KEY environment var has not been set"),
)
.unwrap(),
);
Expand Down Expand Up @@ -65,7 +65,7 @@ pub async fn is_verified(user_id: UserId, guild_id: GuildId) -> Result<()> {
let params = VerifiedParams { user_id, guild_id };
let resp = CLIENT
.get(
&*(env::var("API_URL").expect("API_URL environment var has not been set.")
&*(env::var("API_URL").expect("API_URL environment var has not been set")
+ "/api/v1/verified"),
)
.json(&params)
Expand Down Expand Up @@ -113,7 +113,7 @@ pub async fn get_role_id(guild_id: GuildId) -> Result<RoleId> {
let elapsed = Instant::now();
let resp = CLIENT
.get(
env::var("API_URL").expect("API_URL environment var has not been set.")
env::var("API_URL").expect("API_URL environment var has not been set")
+ &*format!("/api/v1/guild/{guild_id}"),
)
.json(&GuildParams { guild_id })
Expand Down Expand Up @@ -168,7 +168,7 @@ pub async fn register_guild(info: RegisterParams) -> Result<Register> {
let elapsed = Instant::now();
let resp = CLIENT
.post(
env::var("API_URL").expect("API_URL environment var has not been set.")
env::var("API_URL").expect("API_URL environment var has not been set")
+ "/api/v1/guild/register",
)
.json(&info)
Expand Down
21 changes: 8 additions & 13 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,14 @@ use crate::commands::{re_verify, setup, silent_verify, verify};
mod commands;

fn create_commands() -> Vec<CreateCommand> {
let mut result = vec![];
result.push(
vec![
CreateCommand::new("verify")
.description("Verifies you and gives you a nice role!")
.dm_permission(false),
);
result.push(
CreateCommand::new("re-verify")
.description("Re-verifies everyone on the server.")
.dm_permission(false)
.default_member_permissions(Permissions::MANAGE_ROLES),
);
result.push(
CreateCommand::new("setup")
.description("Sets your server up so that users can be verified.")
.dm_permission(false)
Expand All @@ -48,8 +43,7 @@ fn create_commands() -> Vec<CreateCommand> {
)
.required(true),
),
);
result
]
}

struct Handler;
Expand All @@ -71,7 +65,7 @@ impl EventHandler for Handler {

let commands = if let Some(guild_id) = env::var("TEST_GUILD_ID")
.ok()
.map(|f| GuildId::new(f.parse().expect("TEST_GUILD_ID must be an integer.")))
.map(|f| GuildId::new(f.parse().expect("TEST_GUILD_ID must be an integer")))
{
GuildId::set_commands(guild_id, &ctx.http, create_commands()).await
} else {
Expand All @@ -88,7 +82,7 @@ impl EventHandler for Handler {
}

let (send, recv) = unbounded_channel();
TASK_LIST.set(send).expect("OnceCell has not yet been set.");
TASK_LIST.set(send).expect("OnceCell has not yet been set");
tokio::task::spawn(check_for_verify(ctx, recv));
}

Expand Down Expand Up @@ -138,10 +132,11 @@ async fn check_for_verify(ctx: Context, mut rec: UnboundedReceiver<(UserId, Guil
}

while let Some(task) = task_list_a.next().await {
match tries.get_mut(&task.user_id).map(|t| {
let new_tries = tries.get_mut(&task.user_id).map(|t| {
*t -= 1;
*t
}) {
});
match new_tries {
Some(0) | None => {
tries.remove(&task.user_id);
}
Expand All @@ -165,7 +160,7 @@ async fn main() {
log4rs::init_raw_config(config).unwrap();

dotenv::dotenv().ok();
let token = env::var("DISCORD_TOKEN").expect("DISCORD_TOKEN environment var has not been set.");
let token = env::var("DISCORD_TOKEN").expect("DISCORD_TOKEN environment var has not been set");

let mut client = Client::builder(token, GatewayIntents::GUILD_MEMBERS)
.event_handler(Handler)
Expand Down

0 comments on commit c0ad498

Please sign in to comment.