From 626ffb25af35f5b91a76fdccf6788382a1c39455 Mon Sep 17 00:00:00 2001 From: Illia Date: Wed, 7 Dec 2016 20:09:04 +0200 Subject: Allow mentionable structs to be used as command arguments Add EmojiIdentifier, allow User, UserId, Role, RoleId, EmojiIdentifier, Channel and ChannelId to be used as arguments for commands and add more parsing functions to utils --- src/utils/mod.rs | 83 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) (limited to 'src/utils') diff --git a/src/utils/mod.rs b/src/utils/mod.rs index aa97f4a..2401a1b 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -18,6 +18,7 @@ use std::fs::File; use std::io::Read; use std::path::Path; use ::internal::prelude::*; +use ::model::{EmojiIdentifier, EmojiId}; pub use self::message_builder::MessageBuilder; @@ -83,6 +84,88 @@ pub fn parse_invite(code: &str) -> &str { } } +/// Retreives Id from a username mention. +pub fn parse_username(mention: &str) -> Option { + if mention.len() < 4 { + return None; + } + + if mention.starts_with("<@!") { + let len = mention.len() - 1; + mention[3..len].parse::().ok() + } else if mention.starts_with("<@") { + let len = mention.len() - 1; + mention[2..len].parse::().ok() + } else { + None + } +} + +/// Retreives Id from a role mention. +pub fn parse_role(mention: &str) -> Option { + if mention.len() < 4 { + return None; + } + + if mention.starts_with("<@&") { + let len = mention.len() - 1; + mention[3..len].parse::().ok() + } else { + None + } +} + +/// Retreives Id from a channel mention. +pub fn parse_channel(mention: &str) -> Option { + if mention.len() < 4 { + return None; + } + + if mention.starts_with("<#") { + let len = mention.len() - 1; + mention[2..len].parse::().ok() + } else { + None + } +} + +/// Retreives name and Id from an emoji mention. +pub fn parse_emoji(mention: &str) -> Option { + let len = mention.len(); + if len < 6 || len > 56 { + return None; + } + + if mention.starts_with("<:") { + let mut name = String::default(); + let mut id = String::default(); + for (i, x) in mention[2..].chars().enumerate() { + if x == ':' { + let from = i + 3; + for y in mention[from..].chars() { + if y == '>' { + break; + } else { + id.push(y); + } + } + break; + } else { + name.push(x); + } + } + match id.parse::() { + Ok(x) => Some(EmojiIdentifier { + name: name, + id: EmojiId(x) + }), + _ => None + } + } else { + None + } +} + /// Reads an image from a path and encodes it into base64. /// /// This can be used for methods like [`EditProfile::avatar`]. -- cgit v1.2.3