aboutsummaryrefslogtreecommitdiff
path: root/src/commands/roll.rs
diff options
context:
space:
mode:
authorNathan Perry <avaglir@gmail.com>2018-06-01 06:44:41 -0400
committerNathan Perry <avaglir@gmail.com>2018-06-01 06:44:41 -0400
commit21ce509ef21eb8f21c68173005f4f8fe537f7443 (patch)
tree6e9f4ae02ed632d6d75031c9dd3d8270a049f7b4 /src/commands/roll.rs
parent413384896f66aeb2737f5f60433c2467d867fb36 (diff)
add a roll command, relax semver requirements on dependencies
Diffstat (limited to 'src/commands/roll.rs')
-rw-r--r--src/commands/roll.rs60
1 files changed, 60 insertions, 0 deletions
diff --git a/src/commands/roll.rs b/src/commands/roll.rs
new file mode 100644
index 0000000..fb5c71a
--- /dev/null
+++ b/src/commands/roll.rs
@@ -0,0 +1,60 @@
+use serenity::prelude::*;
+use serenity::framework::standard::Args;
+use serenity::model::channel::Message;
+use regex::Regex;
+use rand::prelude::*;
+
+use Result;
+
+use super::send;
+
+lazy_static! {
+ static ref ROLL_REGEX: Regex = Regex::new(r"([0-9]+)?(?:d([0-9]+)(?:\s+\+\s+([0-9]+))?)")
+ .expect("error parsing roll regex");
+}
+
+pub fn roll(_ctx: &mut Context, msg: &Message, args: Args) -> Result<()> {
+ let captures = match ROLL_REGEX.captures(args.full()) {
+ Some(captures) => captures,
+ None => return send(msg.channel_id, "conway is a goldfish", msg.tts),
+ };
+
+ let dice_count = match captures.get(1) {
+ Some(x) => {
+ match x.as_str().parse::<usize>() {
+ Ok(x) => x,
+ Err(e) => {
+ send(msg.channel_id, "conway is a goldfish", msg.tts)?;
+ return Err(e.into());
+ },
+ }
+ },
+ None => 1,
+ };
+
+ if dice_count > 1000000 {
+ send(msg.channel_id, "no.", msg.tts)?;
+ return Ok(());
+ }
+
+ let faces = match captures.get(2).unwrap().as_str().parse::<usize>() {
+ Ok(faces) => faces,
+ Err(e) => {
+ send(msg.channel_id, "conway is a goldfish", msg.tts)?;
+ return Err(e.into())
+ },
+ };
+
+ let adjust = match captures.get(3).map(|adjust| adjust.as_str().parse::<usize>()).transpose() {
+ Ok(adjust) => adjust.unwrap_or(0),
+ Err(e) => {
+ send(msg.channel_id, "conway is a goldfish", msg.tts)?;
+ return Err(e.into())
+ },
+ };
+
+ let mut rng = thread_rng();
+ let total = (0..dice_count).map(|_| rng.gen_range(0, faces)).sum::<usize>() + adjust + 1;
+
+ send(msg.channel_id, &format!("{}", total), msg.tts)
+}