Browse Source

Update

dev
Eragonfr 7 months ago
parent
commit
ed2f4c87b9
Signed by: Eragonfr <sam.vzh@orange.fr> GPG Key ID: B2B1BF4DA61BBB85
10 changed files with 173 additions and 146 deletions
  1. 18
    1
      .gitignore
  2. 3
    3
      Cargo.lock
  3. 1
    4
      Cargo.toml
  4. 29
    25
      main.rs
  5. 0
    28
      src/commands/admins.rs
  6. 14
    3
      src/commands/fun.rs
  7. 28
    5
      src/commands/math.rs
  8. 1
    0
      src/commands/mod.rs
  9. 27
    28
      src/commands/owner.rs
  10. 52
    49
      src/main.rs

+ 18
- 1
.gitignore View File

@@ -1,6 +1,23 @@
/target
# Generated by Cargo
# will have compiled files and executables
/target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk

# Sublime text files
# Workspace files are user-specific
*.sublime-workspace

# Project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using Sublime Text
*.sublime-project

# Manualy added
# Sqlite databases.
*.db
*.sqlite

+ 3
- 3
Cargo.lock View File

@@ -181,7 +181,7 @@ version = "0.3.3-dev"
dependencies = [
"env_logger 0.5.13 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)",
"serenity 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)",
"serenity 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)",
"simplelog 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)",
"toml 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -632,7 +632,7 @@ dependencies = [

[[package]]
name = "serenity"
version = "0.5.8"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"base64 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -982,7 +982,7 @@ dependencies = [
"checksum serde 1.0.75 (registry+https://github.com/rust-lang/crates.io-index)" = "22d340507cea0b7e6632900a176101fea959c7065d93ba555072da90aaaafc87"
"checksum serde_derive 1.0.75 (registry+https://github.com/rust-lang/crates.io-index)" = "234fc8b737737b148ccd625175fc6390f5e4dacfdaa543cb93a3430d984a9119"
"checksum serde_json 1.0.26 (registry+https://github.com/rust-lang/crates.io-index)" = "44dd2cfde475037451fa99b7e5df77aa3cfd1536575fa8e7a538ab36dcde49ae"
"checksum serenity 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)" = "0117df33fb566a910bcf7325feaeb7eacd889bba51c0d29af2aed45c0def1c2b"
"checksum serenity 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)" = "3bb4085e520baf4a87c2a8599e545fb403fa045b882a2c8d491aa6e440fec6b4"
"checksum sha1 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cc30b1e1e8c40c121ca33b86c23308a090d19974ef001b4bf6e61fd1a0fb095c"
"checksum simplelog 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9cc12b39fdf4c9a07f88bffac2d628f0118ed5ac077a4b0feece61fadf1429e5"
"checksum siphasher 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "0b8de496cf83d4ed58b6be86c3a275b8602f6ffe98d3024a869e124147a9a3ac"

+ 1
- 4
Cargo.toml View File

@@ -4,11 +4,8 @@ version = "0.3.3-dev"
authors = ["Eragonfr <sam.vzh@netc.fr>"]

[dependencies]
# Discord framwork
serenity = "0.5.8"
# Toml for toml config files
serenity = "0.5.9"
toml = "0.4"
# Loggings dependencies
log = "0.4"
env_logger = "0.5"
simplelog = "0.5"

+ 29
- 25
main.rs View File

@@ -25,12 +25,11 @@ const COW_TEXT: &'static str = r"
```
";


use serenity::client::Client;
use serenity::prelude::*;
use serenity::framework::standard::StandardFramework;
use serenity::model::channel::Message;
use serenity::model::gateway::Ready;
use serenity::framework::standard::StandardFramework;
use serenity::prelude::*;
use serenity::utils::MessageBuilder;
use std::env;

@@ -38,13 +37,13 @@ struct Handler;

impl EventHandler for Handler {
fn message(&self, ctx: Context, msg: Message) {
// if msg.content == "!ping" {
// println!("Shard {}", ctx.shard_id);
//
// if let Err(why) = msg.channel_id.say("Pong!") {
// println!("Error sending message: {:?}", why);
// }
// }
// if msg.content == "!ping" {
// println!("Shard {}", ctx.shard_id);
//
// if let Err(why) = msg.channel_id.say("Pong!") {
// println!("Error sending message: {:?}", why);
// }
// }
if msg.content == "!messageme" {
if let Err(why) = msg.author.dm(|m| m.content("Hello!")) {
println!("Error when direct messaging user: {:?}", why);
@@ -58,7 +57,7 @@ impl EventHandler for Handler {
println!("Error getting channel: {:?}", why);

return;
},
}
};

let response = MessageBuilder::new()
@@ -82,20 +81,25 @@ impl EventHandler for Handler {

fn main() {
// Login with a bot token from the environment
let mut client = Client::new(&env::var("DISCORD_TOKEN").expect("token"), Handler)
.expect("Token missing!");
client.with_framework(StandardFramework::new()
.configure(|c| c.prefix("~")) // set the bot's prefix to "~"
.on("about", |_, msg, _| {
msg.channel_id.say("A simple test bot")?;
// The `command!` macro implicitly puts an `Ok(())` at the end of each command definiton;
// signifying successful execution.
//
// However since we're using `on` that requires a function with the definition `Fn(Context, Message, Args) -> Result<(), _>`,
// we need to manually put the `Ok` ourselves.
Ok(())
})
.cmd("ping", ping).cmd("test", test).cmd("multi", multiply).cmd("add", add));
let mut client =
Client::new(&env::var("DISCORD_TOKEN").expect("token"), Handler).expect("Token missing!");
client.with_framework(
StandardFramework::new()
.configure(|c| c.prefix("~")) // set the bot's prefix to "~"
.on("about", |_, msg, _| {
msg.channel_id.say("A simple test bot")?;
// The `command!` macro implicitly puts an `Ok(())` at the end of each command definiton;
// signifying successful execution.
//
// However since we're using `on` that requires a function with the definition `Fn(Context, Message, Args) -> Result<(), _>`,
// we need to manually put the `Ok` ourselves.
Ok(())
})
.cmd("ping", ping)
.cmd("test", test)
.cmd("multi", multiply)
.cmd("add", add),
);

// start listening for events by starting a single shard
if let Err(why) = client.start() {

+ 0
- 28
src/commands/admins.rs View File

@@ -1,31 +1,3 @@
use serenity::utils::MessageBuilder;
use serenity::model::channel;

command!(say(_ctx, msg) {
channel::Message::delete(msg).unwrap();
if let Err(why) = msg.channel_id.say(
MessageBuilder::new().push(msg.content[4..].to_string())
) {
error!("Error sending message: {:?}", why);
}
});


command!(clear(_ctx, msg, args){
//let mut msg_del = args.parse().unwrap();
let messages = msg.channel_id.messages(|g| g.after(msg.id).limit(args.parse().unwrap()));
//let _messages = channel::channel.messages(|g| g.after(id).limit(100));

//channel::Message::delete(&messages).unwrap();//delete_messages(&messages).unwrap();

//let mut number = args.parse().unwrap();;
if let Err(why) = msg.channel_id.send_message(|m| m
.content("test")
.embed(|e| e.title("{} messages ont été supprimées."))) {
error!("Error sending message: {:?}", why);
}
});

/*
command!(clear(_context, message) {
unimplemented!()

+ 14
- 3
src/commands/fun.rs View File

@@ -1,4 +1,15 @@
command!(test(_context, message) {
let _ = message.channel_id.say("Just a test!");
let _ = message.edit(|m| m.content("hello"));
use serenity::utils::Colour;

command!(anniversaire(_ctx, msg) {
let colour = Colour::new(993399);
if let Err(why) = msg.channel_id.send_message(|m| m
.embed(|e| e
.title("Joyeux anniversaire!")
.description("Bon anniversaire IbanPlay!! ")
.image("https://cdn.discordapp.com/attachments/428996521212510208/504112253453336586/ibancadolol.png")
.color(colour)
.footer(|f| f
.text("Ajourd'hui c'est l'anniversaire de IbanPlay.")))) {
println!("Error sending message: {:?}", why);
}
});

+ 28
- 5
src/commands/math.rs View File

@@ -1,8 +1,31 @@
command!(multiply(_ctx, msg, args) {
let one = args.single::<f64>().unwrap();
let two = args.single::<f64>().unwrap();
command!(multiply(_context, message, args) {
let first = args.single::<f64>().unwrap();
let second = args.single::<f64>().unwrap();
let product = first * second;

let product = one * two;
if let Err(why) = message.reply(&product.to_string()) {
println!("Error sending product: {:?}", why);
}
});

command!(add(_context, message, args) {
let first = args.single::<f64>().unwrap();
let second = args.single::<f64>().unwrap();
let product = first + second;

let _ = msg.channel_id.say(product);
if let Err(why) = message.reply(&product.to_string()){
println!("Error sending product: {:?}", why);
}
});
// command!(multiply(_ctx, msg, args) {
// print!("{:?}", args.single::<u32>().unwrap());
// let one = args.single::<u32>().unwrap();
// let two = args.single::<u32>().unwrap();

// print!("{:?}", one);
// print!("{:?}", two);

// let product = one * two;

// let _ = msg.channel_id.say(product);
// });

+ 1
- 0
src/commands/mod.rs View File

@@ -9,3 +9,4 @@ pub mod kiss;
pub mod hug;
pub mod admins;
pub mod http;
pub mod fun;

+ 27
- 28
src/commands/owner.rs View File

@@ -1,18 +1,16 @@
use std::error::Error;
// use std::io::Read;
// use std::fmt::Write;
// use serenity::utils::parse_channel;
// use serenity::model::id::ChannelId;
use serenity::builder;
use serenity::framework::standard::CommandError;
// use serenity::CACHE;
// use reqwest;
// use base64;
use serenity::model::channel;
use serenity::utils::MessageBuilder;

// use serenity::client::bridge::gateway::ShardManager;
// use utils;
// use utils::config::get_pool;

// use commands::tags::split_message;
command!(say(_ctx, msg) {
channel::Message::delete(msg).unwrap();
if let Err(why) = msg.channel_id.say(
MessageBuilder::new().push(msg.content[4..].to_string())
) {
error!("Error sending message: {:?}", why);
}
});

command!(quit(ctx, msg, _args) {
let _ = msg.reply("Shutting down all shards!");
@@ -28,22 +26,23 @@ command!(quit(ctx, msg, _args) {
ctx.quit();
});

command!(username(ctx, msg, args) {
let name = match args.single::<String>() {
Ok(val) => val,
Err(_) => {
return Err(CommandError("Missing argument".to_owned()));
},
};

match ctx.edit_profile(|e| e.username(&name)) {
Ok(_) => {
let _ = msg.channel_id.say(&format!("Changed my username to {}", &name));
},
Err(e) => return Err(CommandError(e.description().to_owned())),
}
});
// command!(username(ctx, msg, args) {
// let name = match args.single::<String>() {
// Ok(val) => val,
// Err(_) => {
// return Err(CommandError("Missing argument".to_owned()));
// },
// };

// match builder::EditProfile(|profile| {
// profile.username(&name)
// }) {
// Ok(_) => {
// let _ = msg.channel_id.say(&format!("Changed my username to `{}`", &name));
// },
// Err(e) => return Err(CommandError(e.description().to_owned())),
// }
// });

// command!(set_avatar(_ctx, msg, args) {
// let url = match args.single::<String>().ok().or_else(|| msg.attachments.get(0).map(|x| x.url.clone())) {

+ 52
- 49
src/main.rs View File

@@ -1,17 +1,21 @@
#[macro_use] extern crate log;
#[macro_use] extern crate serenity;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serenity;

extern crate env_logger;
extern crate simplelog;

mod commands;

use std::env;
use std::fs::File;
use std::time::Duration;
use std::thread;
use std::env;
use std::time::Duration;

use serenity::framework::standard::{DispatchError, StandardFramework, HelpBehaviour, help_commands};
use serenity::framework::standard::{
help_commands, DispatchError, HelpBehaviour, StandardFramework,
};
use serenity::model::event::ResumedEvent;
use serenity::model::gateway::Ready;
use serenity::model::id::UserId;
@@ -26,9 +30,7 @@ impl EventHandler for Handler {
if let Some(shard) = ready.shard {
println!(
"{} is connected on shard {}/{}!",
ready.user.name,
shard[0],
shard[1],
ready.user.name, shard[0], shard[1],
);
}
}
@@ -39,38 +41,44 @@ impl EventHandler for Handler {
}

fn main() {
CombinedLogger::init(
vec![
TermLogger::new(LevelFilter::Warn, Config::default()).unwrap(),
WriteLogger::new(LevelFilter::Info, Config::default(), File::create("log/herobrine.log").unwrap()),
]
).unwrap();

let token = env::var("DISCORD_TOKEN")
.unwrap_or_else(|_| { error!("Expected a token in the environment"); panic!() });
CombinedLogger::init(vec![
TermLogger::new(LevelFilter::Warn, Config::default()).unwrap(),
WriteLogger::new(
LevelFilter::Info,
Config::default(),
File::create("log/herobrine.log").unwrap(),
),
])
.unwrap();

let token = env::var("DISCORD_TOKEN").unwrap_or_else(|_| {
error!("Expected a token in the environment");
panic!()
});

let prefix = env::var("DISCORD_PREFIX")
.unwrap_or_else(|_| { error!("Expected a prefix in the environement"); panic!() });
let prefix = env::var("DISCORD_PREFIX").unwrap_or_else(|_| {
error!("Expected a prefix in the environement");
panic!()
});

let mut client = Client::new(&token, Handler).unwrap_or_else(|_| { error!("Err creating client"); panic!() });
let mut client = Client::new(&token, Handler).unwrap_or_else(|_| {
error!("Err creating client");
panic!()
});

let manager = client.shard_manager.clone();

thread::spawn(move || {
loop {
thread::sleep(Duration::from_secs(30));
thread::spawn(move || loop {
thread::sleep(Duration::from_secs(30));

let lock = manager.lock();
let shard_runners = lock.runners.lock();
let lock = manager.lock();
let shard_runners = lock.runners.lock();

for (id, runner) in shard_runners.iter() {
info!(
"Shard ID {} is {} with a latency of {:?}",
id,
runner.stage,
runner.latency,
);
}
for (id, runner) in shard_runners.iter() {
info!(
"Shard ID {} is {} with a latency of {:?}",
id, runner.stage, runner.latency,
);
}
});

@@ -104,19 +112,15 @@ fn main() {
.command_not_found_text("Could not find: `{}`.").lacking_permissions(HelpBehaviour::Hide)
.lacking_role(HelpBehaviour::Nothing).wrong_channel(HelpBehaviour::Strike)
})
.group("Admin", |g| g
.help_available(false)
.command("clear", |c| c.bucket("admin").cmd(commands::admins::clear))
.command("say", |c| c.bucket("admin").cmd(commands::admins::say))
)
.group("Owner", |g| g
.help_available(false)
.owners_only(true)
.command("username", |c| c
.desc("Changes the bot's username.")
.owners_only(true)
.cmd(commands::owner::username)
)
.command("say", |c| c.bucket("admin").cmd(commands::owner::say))
// .command("username", |c| c
// .desc("Changes the bot's username.")
// .owners_only(true)
// .cmd(commands::owner::username)
// )
)
.group("Hidden", |g| g
.help_available(false)
@@ -124,15 +128,18 @@ fn main() {
.cmd(commands::http::cat)
.desc("A cat joke.")
)
.command("anniversaire", |c| c
.cmd(commands::fun::anniversaire)
.desc("Anniversaire command.")
)
)
.command("multiply", |c| c.known_as("*").cmd(commands::math::multiply))
.command("role", |c| c.cmd(commands::about_role::about_role))
.command("ping", |c| c.desc("Responds with 'pong'.").cmd(commands::meta::ping))
.command("multiply", |c| c.cmd(commands::math::multiply))
.command("quit", |c| c.cmd(commands::owner::quit).owners_only(true))
.command("kiss", |c| c.cmd(commands::kiss::kiss))
.command("hug", |c| c.cmd(commands::hug::hug))
.command("tbh", |c| c.cmd(commands::misc::tbh))
.command("multiply", |c| c.cmd(commands::math::multiply))
);

if let Err(why) = client.start() {
@@ -170,7 +177,3 @@ fn main() {
// .owners_only(true)
// .cmd(commands::owner::listservers)
// )
// .command("say", |c| c
// .desc("Make sushii say something in a channel.")
// .owners_only(true)
// .cmd(commands::owner::say)

Loading…
Cancel
Save