Commit 2031ad94 authored by Tim54000's avatar Tim54000 💬

Add Webhook command & some docs

- Docs not generate
parent 1a4bc7d2
Pipeline #50871 passed with stages
in 10 minutes and 19 seconds
[package]
name = "tims_bot"
version = "0.2.8"
authors = ["Tim54000 <Tim54000.18@gmail.com>"]
authors = ["Tim54000 <Tim54000@gmx.com>"] # For english-speakers
# For french-speakers : Tim54000@gmx.ca / Tim54000@gmx.fr
[dependencies]
serenity = "^0.5.2"
......
DISCORD_TOKEN=
RUST_LOG=info
DISCORD_PREFIX=-
\ No newline at end of file
#Bot
DISCORD_TOKEN= On Discord Dev' Panel
DISCORD_PREFIX=-
WEBHOOK_ID=
WEBHOOK_TOKEN=
#Log
RUST_LOG=info
\ No newline at end of file
......@@ -9,14 +9,15 @@ use bot_to_idle;
use serenity::model::prelude::*;
use serenity::utils::Colour;
use VERSION;
use PREFIX;
use serenity::framework::standard::CommandOrAlias;
use std::result::Result;
use serenity::framework::standard::CommandError;
use serenity::framework::standard::Command;
use std::env;
/// A custom help command
pub fn help(ctx: &mut Context, msg: &Message, ho: &HelpOptions, commands: HashMap<String, Arc<CommandGroup>>, args: &Args) -> Result<(), CommandError> {
msg.channel_id.broadcast_typing(); //Send typing to Discord
msg.channel_id.broadcast_typing(); // Send typing to Discord
bot_to_not_disturb(&ctx, Some(Game::playing("help")));
info!("Help!"); // For the log
......@@ -26,7 +27,8 @@ pub fn help(ctx: &mut Context, msg: &Message, ho: &HelpOptions, commands: HashMa
for (name, commandgroup) in commands { // Get all command groups
debug!("CommandGroup : {:?} @ {:?}", &name, &commandgroup);
for (name, command) in &commandgroup.commands { // Get all Command / Alias of the groups
// Get all Command or Alias of the groups
for (name, command) in &commandgroup.commands {
if let CommandOrAlias::Command(command) = command { // Keep only command
let options = command.options();
......@@ -34,12 +36,12 @@ pub fn help(ctx: &mut Context, msg: &Message, ho: &HelpOptions, commands: HashMa
let desc = (options.desc).clone().unwrap_or("No description".to_string()).clone();
let owners_only = if true == (options.owners_only){ "*" } else { "" };
commands_help.push((format!("{}{}{}", PREFIX, name, owners_only), desc, true)); // Format and push
commands_help.push((format!("{}{}{}",env::var("DISCORD_PREFIX").unwrap_or("-".to_string()), name, owners_only), desc, true)); // Format and push
}
}
}
//Send the help embed
// Send the help embed
if let Err(e) = msg.channel_id.send_message(|m| m
.embed(|e| e
.title("Tim's Bot")
......@@ -56,7 +58,7 @@ pub fn help(ctx: &mut Context, msg: &Message, ho: &HelpOptions, commands: HashMa
.fields(commands_help.into_iter())
.footer(|f| f
.text(format!("Commands with a star (*) require to be owner.\u{09}Executed by {} in #{}", msg.author.tag(), msg.channel_id.name().unwrap()))))){
error!("Error {:?}", e);
error!("Sending error {:?}", e);
}
bot_to_idle(&ctx);
return Ok(());
......
......@@ -2,6 +2,7 @@ use bot_to_not_disturb;
use bot_to_idle;
use serenity::model::prelude::gateway::Game;
/// -ping reply Pong!
command!(ping(ctx, msg) {
msg.channel_id.broadcast_typing();
bot_to_not_disturb(&ctx, Some(Game::playing("Ping-Pong")));
......
//! Mod `commands` contains all commands of bot
//! Mod `meta` contains all *"meta"* commands
//! Mod `owner` contains all commands reserved to owners
//! Mod `help` contains only the help command
//! Mod `webhook` contains all commands relative to webhook
pub mod meta;
pub mod owner;
pub mod help;
\ No newline at end of file
pub mod help;
pub mod webhook;
\ No newline at end of file
use bot_to_not_disturb;
use serenity::model::prelude::gateway::Game;
/// -quit will be restart the current shard
command!(quit(ctx, msg, _args) {
bot_to_not_disturb(&ctx, Some(Game::playing("Shutdown")));
ctx.quit();
......
use bot_to_idle;
use bot_to_not_disturb;
use serenity::http;
use std::env;
use serenity::model::channel::Embed;
use serenity::model::prelude::gateway::Game;
/// Command -wh send a Webhook (id,token required)
command!(webhook(ctx, msg) {
msg.channel_id.broadcast_typing();
bot_to_not_disturb(&ctx, Some(Game::playing("Webhook")));
info!("Webhook!");
let id = env::var("WEBHOOK_ID").unwrap();
let token = env::var("WEBHOOK_TOKEN").unwrap();
if let Ok(w) = http::get_webhook_with_token(id.parse::<u64>().unwrap_or(0), token.as_str()) {
let embed = Embed::fake(|e| e
.title("Rust's bot")
.description("Rust is a systems programming language \
that runs blazingly fast, prevents segfaults, and \
guarantees thread safety.")
.url("https://rust-lang.org")
.footer(|f| f.text(format!("Executed by {} in #{}", msg.author.tag(), msg.channel_id.name().unwrap_or("Unknowed".to_string())))
.icon_url("https://i.tim54000.tk/FoLFSjvjS.png")));
match w.execute(false, |w| w.username("Serenity 0.5.2").avatar_url("https://i.tim54000.tk/FoLFSjvjS.png").embeds(vec![embed])) {
Ok(m) => {
let _ = msg.reply("Sended !");
}
_ => {
let _ = msg.reply("Error occurred !");
}
}
} else {
let _ = msg.reply("Error occurred !");
}
bot_to_idle(&ctx);
});
......@@ -18,18 +18,33 @@ mod commands;
struct Handler;
/// Define the bot version displayed in the help
const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
const PREFIX: &'static str = env!("DISCORD_PREFIX");
/// Launch Client and verify env var
///
/// Env variables required :
/// ```
/// DISCORD_TOKEN //> Find it on Discord panel
/// WEBHOOK_ID //> Create a webhook and find it on the webhook url
/// WEBHOOK_TOKEN //> Same
/// ```
fn main() {
env_logger::init();
// Login with a bot token from the environment
// Load env var and verify
let token = env::var("DISCORD_TOKEN")
.expect("Expected a token in the environment");
info!("$DISCORD_TOKEN is correctly filled !");
let _ = env::var("WEBHOOK_ID").expect("Expected a webhook id in the environment");
let _ = env::var("WEBHOOK_TOKEN").expect("Expected a webhook token in the environment");
info!("Webhook var are correctly filled !");
// Login
let mut client = Client::new(&token, Handler).expect("Err creating client");
info!("Bot is initialized !");
// Get Owners
let owners = match http::get_current_application_info() {
Ok(info) => {
let mut set = HashSet::new();
......@@ -40,24 +55,33 @@ fn main() {
Err(why) => panic!("Couldn't get application info: {:?}", why),
};
info!("Owners is successly got !");
// Configure the bot / Register all commands
client.with_framework(StandardFramework::new()
.configure(|c| c
.owners(owners)
.prefix(PREFIX))
.prefix(env::var("DISCORD_PREFIX").unwrap_or("-".to_string()).as_str()))
.help(commands::help::help)
.command("ping", |c| c.cmd(commands::meta::ping).desc("Pong!"))
.command("ping", |c| c.cmd(commands::meta::ping)
.desc("Pong!"))
.command("quit", |c| c
.cmd(commands::owner::quit)
.desc("Restart the shard")
.owners_only(true)));
.owners_only(true))
.command("wh", | c | c.cmd(commands::webhook::webhook)
.desc("Send a Embed by Webhook")));
info!("Commands/Events is registered !");
info!("Bot is starting...");
if let Err(why) = client.start() {
if let Err(why) = client.start() { // Start of the shard
panic!("Bot error: {:?}", why);
}
}
impl EventHandler for Handler {
/// Bot connected
fn ready(&self, ctx: Context, ready: Ready) {
info!("Bot is connected as {} !", ready.user.name);
bot_to_idle(&ctx);
......@@ -68,12 +92,14 @@ impl EventHandler for Handler {
}
}
/// Set to idle and change the Presence to default
fn bot_to_idle(ctx: &Context){
let status = OnlineStatus::Idle;
let game = Game::listening(format!("-help v{}", VERSION.unwrap_or("4.0.4")).as_str());
ctx.set_presence(Some(game), status);
}
/// Set to Dnd with custom Game
fn bot_to_not_disturb(ctx: &Context, game: Option<Game>){
let status = OnlineStatus::DoNotDisturb;
let game = game.unwrap_or(Game::listening(format!("-help v{}", VERSION.unwrap_or("4.0.4")).as_str()));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment