Skip to content
This repository has been archived by the owner on Mar 16, 2023. It is now read-only.

Commit

Permalink
Cleaned up and switched to async serenity branch (#1)
Browse files Browse the repository at this point in the history
* Fixed Typo

* Switching to async serenity

* Relocated Automod

* Only haHaa if clean message

* Added ping kill commands back
  • Loading branch information
timcole committed Jul 5, 2020
1 parent 83b3d4c commit 8c0eaf4
Show file tree
Hide file tree
Showing 16 changed files with 534 additions and 282 deletions.
412 changes: 254 additions & 158 deletions Cargo.lock

Large diffs are not rendered by default.

11 changes: 6 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ authors = ["Timothy Cole <tim@timcole.me>"]
edition = "2018"

[dependencies]
serenity = "0.8.6"
dotenv = "0.15.0"
chrono = "0.4.11"
reqwest = "0.10.6"
tokio = { version = "0.2", features = ["macros"] }
serenity = { git = "https://github.com/Lakelezz/serenity.git", branch = "await" }
tokio = { version = "0.2.21", features = ["macros", "time"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
dotenv = "0.15.0"
reqwest = "0.10.6"
pretty_env_logger = "0.4"
log = "0.4"
10 changes: 10 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use std::process::Command;

fn main() {
let output = Command::new("git")
.args(&["rev-parse", "HEAD"])
.output()
.unwrap();
let git_hash = String::from_utf8(output.stdout).unwrap();
println!("cargo:rustc-env=GIT_HASH={}", git_hash);
}
17 changes: 17 additions & 0 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use serenity::framework::standard::macros::group;

// pub mod general;

// #[group]
// #[commands()]
// struct General;

pub mod admin;
use admin::{kill::*, ping::*};

#[group]
#[commands(ping, kill)]
#[owners_only]
struct Admin;

pub mod help;
1 change: 0 additions & 1 deletion src/commands/mod.rs → src/commands/admin.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
pub mod help;
pub mod kill;
pub mod ping;
20 changes: 20 additions & 0 deletions src/commands/admin/kill.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use crate::ShardManagerContainer;
use serenity::framework::standard::{macros::command, CommandResult};
use serenity::model::prelude::*;
use serenity::prelude::*;

#[command]
async fn kill(ctx: &Context, msg: &Message) -> CommandResult {
let data = ctx.data.read().await;

if let Some(manager) = data.get::<ShardManagerContainer>() {
let _ = msg.reply(&ctx.http, "Goodbye :(").await;
manager.lock().await.shutdown_all().await;
} else {
let _ = msg
.reply(&ctx.http, "There was a problem getting the shard manager")
.await;
}

Ok(())
}
49 changes: 49 additions & 0 deletions src/commands/admin/ping.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use crate::ShardManagerContainer;
use serenity::{
client::bridge::gateway::ShardId,
framework::standard::{macros::command, CommandResult},
model::prelude::*,
prelude::*,
};

#[command]
async fn ping(ctx: &Context, msg: &Message) -> CommandResult {
let data = ctx.data.read().await;
let shard_manager = match data.get::<ShardManagerContainer>() {
Some(v) => v,
None => {
log::error!("Error getting the shard manager.");
return Ok(());
}
};

let manager = shard_manager.lock().await;
let runners = manager.runners.lock().await;
let runner = match runners.get(&ShardId(ctx.shard_id)) {
Some(runner) => runner,
None => {
log::error!("No shards found.");
return Ok(());
}
};

match runner.latency {
Some(x) => {
msg
.channel_id
.say(
&ctx.http,
&format!("Shard {} - {}ms", ctx.shard_id + 1, x.as_millis()),
)
.await?;
}
None => {
msg
.channel_id
.say(&ctx.http, "Too soon to measure.")
.await?;
}
};

Ok(())
}
Empty file added src/commands/general.rs
Empty file.
61 changes: 53 additions & 8 deletions src/commands/help.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,55 @@
use serenity::client::Context;
use serenity::framework::standard::macros::command;
use serenity::framework::standard::CommandResult;
use serenity::model::prelude::Message;

#[command]
fn help(ctx: &mut Context, msg: &Message) -> CommandResult {
let _ = msg.channel_id.say(&ctx.http, "Go to bed");
use serenity::{
client::Context,
framework::standard::{macros::help, Args, CommandGroup, CommandResult, HelpOptions},
model::prelude::*,
};
use std::{collections::HashSet, env};

#[help]
async fn help(
ctx: &Context,
msg: &Message,
_: Args,
_: &'static HelpOptions,
groups: &[&'static CommandGroup],
owners: HashSet<UserId>,
) -> CommandResult {
let mut fields = HashSet::new();

for group in groups {
if group.options.owners_only && !owners.contains(&msg.author.id) {
continue;
}

let mut commands = String::from("```\n");
for y in group.options.commands {
commands.push_str(&format!("{} ", &y.options.names.first().unwrap()[..]));
}
commands.push_str("\n```");

fields.insert((group.name, commands, false));
}

msg
.channel_id
.send_message(&ctx.http, |m| {
m.embed(|e| {
e.author(|a| {
a.name("Developed in Rust by Timothy Cole")
.icon_url("https://github.com/timothycole.png")
.url("https://github.com/ModestLand/discord-bot")
})
.fields(fields)
.footer(|f| {
f.text(format!(
"Commit Hash: {}",
&env::var("GIT_HASH").unwrap()[0..7]
))
})
})
})
.await?;

Ok(())
}

22 changes: 0 additions & 22 deletions src/commands/kill.rs

This file was deleted.

14 changes: 0 additions & 14 deletions src/commands/ping.rs

This file was deleted.

84 changes: 42 additions & 42 deletions src/handler.rs
Original file line number Diff line number Diff line change
@@ -1,66 +1,66 @@
use crate::twitch::automod::*;
use serenity::client::Context;
use serenity::model::{channel::Message, gateway::Ready, id::UserId};
use serenity::prelude::EventHandler;
use std::thread;
use std::time::Duration;
use crate::twitch::automod;
use crate::utils::mention;
use serenity::{
async_trait,
client::Context,
model::{channel::Message, gateway::Activity, gateway::Ready, user::OnlineStatus},
prelude::EventHandler,
};
use std::env;

pub struct Handler;

#[async_trait]
impl EventHandler for Handler {
fn ready(&self, _: Context, ready: Ready) {
async fn ready(&self, ctx: Context, ready: Ready) {
if let Some(shard) = ready.shard {
println!(
log::info!(
"{} connected on shard {}/{}",
ready.user.name,
shard[0] + 1,
shard[1],
);
}
ctx
.set_presence(
Some(Activity::listening(&format!(
"Version: {}",
&env::var("GIT_HASH").unwrap()[0..7]
))),
OnlineStatus::DoNotDisturb,
)
.await;
}
fn message(&self, ctx: Context, msg: Message) {
println!(
"({id}) {name}#{discrim}: {content}",
async fn message(&self, ctx: Context, msg: Message) {
let guild = match msg.guild_id {
Some(id) => id,
// Ignore DMs
None => return,
};

let channel = msg.channel_id;

log::info!(
"[{guild}|{channel}] - ({id}) {name}#{discrim}: {content}",
guild = guild,
channel = channel,
id = msg.author.id,
name = msg.author.name,
discrim = msg.author.discriminator,
content = msg.content
);

// Ignore messages from the bot
if msg.is_own(&ctx) {
// Ignore messages from bots
if msg.author.bot {
return;
}

let tim = UserId(83281345949728768).to_user(&ctx).unwrap();
if msg.mentions.contains(&tim) {
let _ = msg.channel_id.say(
&ctx.http,
"Imagine pinging Tim... <:haHaa:340276843523473409>",
);

return;
if automod::automod(ctx.clone(), msg.clone())
.await
.ok()
.unwrap()
{
mention::tim(ctx.clone(), msg.clone()).await;
}

match automod(msg.content.clone()) {
Ok(bool) => {
if !bool {
let _ = msg.delete(&ctx);
match msg.reply(
&ctx,
"**Your message blocked by Automod. Please watch what you say.**",
) {
Ok(msg) => {
thread::spawn(move || {
thread::sleep(Duration::from_millis(15000));
let _ = msg.delete(&ctx);
});
}
Err(e) => println!("{}", e),
};
}
}
Err(e) => println!("Automod Error: {}", e),
};
}
}
Loading

0 comments on commit 8c0eaf4

Please sign in to comment.