Skip to content

Commit

Permalink
Add register and slash command
Browse files Browse the repository at this point in the history
  • Loading branch information
kekonn committed Dec 3, 2024
1 parent 2902b02 commit 9b0daad
Show file tree
Hide file tree
Showing 8 changed files with 75 additions and 18 deletions.
9 changes: 5 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions fercord_bot/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

### Added
- feat: `/reminder` not also accepts `[day|tomorrow] at [hour][am|pm]` inputs.
- feat: `/roll` command to roll dice (up to 255d255)
- feat: `@bot register` prefix-command to register slash commands

## [0.3.5] - 2024-12-02
- chore: Update dependencies
Expand Down
3 changes: 2 additions & 1 deletion fercord_bot/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ poise = { workspace = true}
serde = { workspace = true}
serde_json = { workspace = true}
tracing = { workspace = true }
tracing-subscriber = {version = "0.3", features = ["default", "env-filter"]}
chrono = { workspace = true }
chrono-tz = { workspace = true }
interim = { workspace = true }
uuid = { workspace = true }
tokio = { workspace = true }
anyhow = { workspace = true }
tracing-subscriber = {version = "0.3", features = ["default", "env-filter"]}
rand = "0.8"


[dev-dependencies]
Expand Down
60 changes: 53 additions & 7 deletions fercord_bot/src/discord/commands.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
use anyhow::{anyhow, Result};
use std::num::NonZeroU8;

use anyhow::{anyhow, Result, Context as AnyhowContext};
use chrono::{DateTime, Utc};
use chrono_tz::{Tz, TZ_VARIANTS};
use interim::{parse_date_string, Dialect};
use poise::serenity_prelude as serenity;
use tracing::{debug, event, field, trace_span, warn, Level};
use rand::prelude::*;

use fercord_storage::prelude::{
db::Repository,
model::{guild_timezone::GuildTimezone, reminder::Reminder},
*,
};

use fercord_storage::prelude::{*, guild_timezone::GuildTimezone};
use crate::discord::Context;

const FROM_NOW: &str = "from now";
const AT: &str = "at";

/// Register slash commands
#[poise::command(prefix_command)]
pub async fn register(ctx: Context<'_>) -> Result<()> {
let span = trace_span!(
"fercord.discord.register",
);
let _enter = span.enter();

poise::builtins::register_application_commands_buttons(ctx).await.context("Error registering slash commands")?;

Ok(())
}

/// Set the timezone for this server (used by time related commands).
#[poise::command(slash_command)]
pub async fn timezone(
Expand Down Expand Up @@ -75,6 +86,41 @@ pub async fn timezone(
}
}

/// Roll dice
///
/// * count: The amount of dice to roll
/// * sides: the sides on the dice
#[poise::command(slash_command)]
pub async fn roll(ctx: Context<'_>,
#[description = "How many dice do you want to roll?"] #[min = 1] #[max = 255] count: NonZeroU8,
#[description = "How many sides does the dice have?"] #[min = 2] #[max = 255] sides: NonZeroU8,
) -> Result<()> {
let span = trace_span!(
"fercord.discord.roll",
guild_id = field::Empty,
die_command = "{count}d{sides}"
);
let _enter = span.enter();
event!(Level::TRACE, "Received roll command for {count}d{sides}");
let guild_id = ctx.guild_id().context("Error retrieving guild id")?;
span.record("guild_id", field::debug(&guild_id));

ctx.defer_ephemeral().await?;

let mut rng = rand::thread_rng();

let mut rolls: Vec<usize> = Vec::with_capacity(count.get() as usize);
rolls.resize(count.get().into(), Default::default());
rolls.fill_with(move || rng.gen_range(1..=(sides.get() as usize)));

let roll_total = rolls.into_iter().sum::<usize>();
event!(Level::TRACE, "Rolled {count}d{sides} for a total value of {roll_total}");

ctx.say(format!("You rolled {count}d{sides} for a total value of {roll_total}")).await?;

Ok(())
}

/// Create a reminder
///
/// * when: When to remind you
Expand Down
10 changes: 6 additions & 4 deletions fercord_bot/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use anyhow::Context;
use discord::commands::register;
use discord::commands::roll;
use poise::serenity_prelude::{self as serenity, ActivityData};
use tracing::*;

Expand Down Expand Up @@ -42,19 +44,19 @@ async fn main() -> anyhow::Result<()> {

let db_pool = db::setup(config.database_url.as_ref())
.await
.with_context(|| "Error setting up database connection")?;
.context("Error setting up database connection")?;

// KV Setup
event!(Level::DEBUG, "Connecting to KV Store");
let kv_client = KVClient::new(&config).with_context(|| "Error building redis client")?;
let kv_client = KVClient::new(&config).context("Error building redis client")?;

// Discord setup
event!(Level::DEBUG, "Discord client setup");

let discord_config = config.clone();
let framework = poise::Framework::builder()
.options(poise::FrameworkOptions {
commands: vec![reminder(), timezone()],
commands: vec![reminder(), timezone(), roll(), register()],
..Default::default()
})
.setup(|ctx, _ready, framework| {
Expand All @@ -64,7 +66,7 @@ async fn main() -> anyhow::Result<()> {
Box::pin(async move {
poise::builtins::register_globally(ctx, &framework.options().commands)
.await
.with_context(|| "Error creating Discord client")?;
.context("Error creating Discord client")?;

Ok(ServerData {
kv_client,
Expand Down
2 changes: 2 additions & 0 deletions fercord_storage/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
<!-- next-header -->

## [Unreleased] - ReleaseDate
## Changed
- prelude now includes a lot more types

## [0.3.5] - 2024-12-02
- chore: Update dependencies
Expand Down
4 changes: 2 additions & 2 deletions fercord_storage/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub mod db;
pub mod prelude {
pub use sqlx_oldapi::any::AnyPool;

pub use crate::db;
pub use crate::db::{self, *};
pub use crate::kv::{Identifiable, KVClient, KVIdentity};
pub use crate::model;
pub use crate::model::{self, *};
}
3 changes: 3 additions & 0 deletions fercord_storage/src/model/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,6 @@ pub mod reminder;

/// Store guild timezones as setting data
pub mod guild_timezone;

pub use reminder::*;
pub use guild_timezone::*;

0 comments on commit 9b0daad

Please sign in to comment.