2020-01-03 11:19:53 +01:00
use super ::config ::* ;
2020-01-02 23:10:28 +01:00
use cmd_lib ::{ CmdResult , Process } ;
2020-01-02 17:51:02 +01:00
use serde ::Deserialize ;
use serenity ::model ::channel ::Message ;
2020-01-03 11:19:53 +01:00
#[ derive(Deserialize, Debug, PartialEq, Clone) ]
2020-01-02 23:10:28 +01:00
pub struct Command {
trigger : String ,
command : String ,
2020-01-02 17:51:02 +01:00
users : Vec < u64 > ,
}
pub fn print_commands ( ) {
2020-01-02 23:10:28 +01:00
CONFIG . commands . iter ( ) . for_each ( | c | println! ( " {:?} " , c ) ) ;
2020-01-02 17:51:02 +01:00
}
2020-01-03 11:19:53 +01:00
pub fn find_matching < ' a > ( message : & str , cfg : & ' a Config ) -> Option < & ' a Command > {
cfg . commands
. iter ( )
. find ( | & c | message [ cfg . prefix . len ( ) .. ] = = c . trigger )
2020-01-02 17:51:02 +01:00
}
2020-01-02 23:10:28 +01:00
impl Command {
/// Check permissions for a command and execute it.
/// Returns an error for insufficient permissions or non-zero return codes.
pub fn execute ( & self , msg : & Message ) -> Result < ( ) , String > {
println! (
" User {} tried to execute command {} " ,
& msg . author , & msg . content
) ;
2020-01-02 17:51:02 +01:00
if ! self . users . contains ( & msg . author . id . 0 ) {
2020-01-02 23:10:28 +01:00
return Err ( " You don’t have the permissions to execute this command. " . to_owned ( ) ) ;
2020-01-02 17:51:02 +01:00
}
2020-01-02 23:10:28 +01:00
Process ::new ( self . command . clone ( ) )
. wait ::< CmdResult > ( )
. map_err ( | e | format! ( " {:?} " , e ) )
2020-01-02 17:51:02 +01:00
}
2020-01-03 11:19:53 +01:00
pub fn new ( command : & str , trigger : & str , users : Vec < u64 > ) -> Self {
Self {
command : String ::from ( command ) ,
trigger : String ::from ( trigger ) ,
users ,
}
}
2020-01-02 17:51:02 +01:00
}