Commit 291b80d9 authored by Tim54000's avatar Tim54000

Merge branch 'indev' into 'master'

Indev - Add Webhook command, Docs and others

See merge request !1
parents 1a4bc7d2 dd7b5c5c
Pipeline #50884 passed with stages
in 11 minutes and 1 second
......@@ -9,6 +9,7 @@ build:
stage: build
cache:
paths:
- cargo/
- target/
artifacts:
paths:
......@@ -16,10 +17,14 @@ build:
script:
- rustc --version && cargo --version # Print version info for debugging
- cargo build --verbose --jobs 1 --release # Don't paralize to make errors more readable
only:
- master
debug:
stage: debug
cache:
paths:
- cargo/
- target/
artifacts:
paths:
......@@ -27,3 +32,18 @@ debug:
script:
- rustc --version && cargo --version # Print version info for debugging
- cargo build --verbose --jobs 1 # Don't paralize to make errors more readable
doc:
stage: build
cache:
paths:
- cargo/
- target/
artifacts:
paths:
- target/doc
script:
- rustc --version && cargo --version # Print version info for debugging
- cargo doc --no-deps --verbose --jobs 1 --release # Don't paralize to make errors more readable
only:
- master
[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"
serenity = "^0.5.3"
env_logger = "^0.5.9"
log = "^0.4.1"
\ No newline at end of file
# Tim's Bot
### Dependencies
* [Serenity ^0.5.3](https://docs.rs/crate/serenity/0.5.3)
### License
This bot is currently under any open-source licenses: it is therefore protected by French laws. Tim's Bot belongs to Timothée BRILLAUD. You can just now view sources and run this bot.
\ No newline at end of file
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
//! Mod [`help`](#) contains only the help command
//!
//! ## Commands :
//! * -help: A custom help command
use serenity::prelude::Context;
use serenity::framework::standard::HelpOptions;
use std::collections::HashMap;
......@@ -9,14 +13,14 @@ 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;
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 +30,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 +39,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 +61,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(());
......
//! Mod [`meta`](#) contains all *"meta"* commands
//!
//! ## Commands :
//! * -ping reply Pong!
use bot_to_not_disturb;
use bot_to_idle;
use serenity::model::prelude::gateway::Game;
......
//! Mod `commands` contains all commands of bot
//!
//! Mod [`meta`](meta/index.html) contains all *"meta"* commands
//!
//! Mod [`owner`](owner/index.html) contains all commands reserved to owners
//!
//! Mod [`help`](help/index.html) contains only the help command
//!
//! Mod [`webhook`](webhook/index.html) 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
//! Mod [`owner`](#) contains all commands reserved to owners
//!
//! ## Commands :
//! * -quit will be restart the current shard
use bot_to_not_disturb;
use serenity::model::prelude::gateway::Game;
......
//! Mod [`webhook`](#) contains all commands relative to webhook
//!
//! ## Commands :
//! * -wh send a Webhook (id,token required)
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!(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);
});
......@@ -14,22 +14,56 @@ use std::collections::HashSet;
use serenity::framework::StandardFramework;
use serenity::model::gateway::Game;
mod commands;
pub mod commands;
struct Handler;
/// It's an [EventHandler], it recieve all events
/// [EventHandler]: https://docs.rs/serenity/*/serenity/client/event_handler/trait.EventHandler.html
pub struct Handler;
const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
const PREFIX: &'static str = env!("DISCORD_PREFIX");
/// Define the bot version displayed in the help
/// Its value is CARGO_PKG_VERSION
pub const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
fn main() {
/// Entry point of the program
///
/// 1. 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
/// ```
///
/// 2. It login the [Client]
/// with `DISCORD_TOKEN`
///
/// 3. It get the bot's owners
///
/// 4. It register [Handler] & [Commands]
///
/// 5. If not error is occured, the [Handler] will be [Ready]
///
/// [Client]: https://docs.rs/serenity/*/serenity/client/struct.Client.html
/// [Handler]: struct.Handler.html
/// [Commands]: commands/index.html
/// [Ready]: https://docs.rs/serenity/*/serenity/client/event_handler/trait.EventHandler.html#method.ready
pub 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 +74,32 @@ 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 {
fn ready(&self, ctx: Context, ready: Ready) {
info!("Bot is connected as {} !", ready.user.name);
bot_to_idle(&ctx);
......@@ -68,13 +110,25 @@ impl EventHandler for Handler {
}
}
fn bot_to_idle(ctx: &Context){
/// Set to idle and change the [Presence] to default
///
/// The default presence is : `-help v{VERSION}`
/// [VERSION]'s value is CARGO_PKG_VERSION
///
/// [VERSION]: constant.VERSION.html
pub 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);
}
fn bot_to_not_disturb(ctx: &Context, game: Option<Game>){
/// Set to Do Not Disturb with custom Game
///
/// The default Game is : `-help v{VERSION}`
/// [VERSION]'s value is CARGO_PKG_VERSION
///
/// [VERSION]: constant.VERSION.html
pub 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()));
ctx.set_presence(Some(game), status);
......
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