Update dependencies

This commit is contained in:
Sakuhl 2020-03-14 16:55:02 +01:00
parent 1b89cfd516
commit d7ed8b19e2
7 changed files with 1280 additions and 1012 deletions

1889
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
[package]
authors = ["Sakuhl <2012collector@gmail.com>"]
name = "wynnrobot"
version = "0.14.0"
version = "0.14.1"
[dependencies]
chrono = "0.4.0"
@ -9,7 +9,7 @@ configure = "0.1.1"
failure = "0.1.1"
failure_derive = "0.1.1"
lazy_static = "1.0.0"
reqwest = "0.8.1"
reqwest = { version = "0.10.4", features = ["blocking"] }
serde = "1.0.24"
serde_derive = "1.0.24"
serde_json = "1.0.8"
@ -21,7 +21,7 @@ version = "1.0"
[dependencies.serenity]
features = []
version = "0.4.8"
version = "0.8.0"
[dependencies.wynncraft]
git = "https://gitlab.com/Sakuhl/wynncraft"

View File

@ -1,6 +1,7 @@
use ::wynncraft;
use serenity::model::*;
use ::serenity::prelude::*;
use ::serenity::model::prelude::*;
use ::diesel;
use ::diesel::prelude::*;
@ -9,7 +10,7 @@ use ::diesel::result::DatabaseErrorKind;
use ::serde_json;
use ::serde_json::Value;
use ::reqwest;
use ::reqwest::blocking::get;
use ::std::thread;
@ -18,13 +19,13 @@ use failure::Error;
use super::establish_connection;
pub fn territory_livefeed() {
pub fn territory_livefeed(ctx: Context) {
use models::LivefeedListener;
use schema::livefeedlisteners::dsl::*;
let connection = establish_connection();
let resp = reqwest::get("https://api.wynncraft.com/public_api.php?action=territoryList").unwrap();
let resp = get("https://api.wynncraft.com/public_api.php?action=territoryList").unwrap();
let mut territories: Value = serde_json::from_reader(resp).unwrap();
@ -32,7 +33,7 @@ pub fn territory_livefeed() {
loop {
thread::sleep_ms(20_000); // 20 seconds
let resp = reqwest::get("https://api.wynncraft.com/public_api.php?action=territoryList").unwrap();
let resp = get("https://api.wynncraft.com/public_api.php?action=territoryList").unwrap();
let new_territories: Value = serde_json::from_reader(resp).unwrap();
@ -49,7 +50,7 @@ pub fn territory_livefeed() {
for listener in livefeedlisteners
.load::<LivefeedListener>(&connection)
.expect("Error loading listeners") {
let _ = ChannelId(listener.id as u64).say(format!("{}: ~~{}~~ -> **{}**",
let _ = ChannelId(listener.id as u64).say(&ctx.http, format!("{}: ~~{}~~ -> **{}**",
value.get("territory").unwrap().as_str().unwrap(),
value.get("guild").unwrap().as_str().unwrap(),
new_value.get("guild").unwrap().as_str().unwrap()
@ -62,7 +63,7 @@ pub fn territory_livefeed() {
}
}
pub fn federation_livefeed() {
pub fn federation_livefeed(ctx: Context) {
use models::FederationfeedListener;
use schema::federationfeed_listeners::dsl::*;
@ -94,7 +95,7 @@ pub fn federation_livefeed() {
let connection = establish_connection();
let resp = reqwest::get("https://api.wynncraft.com/public_api.php?action=territoryList").unwrap();
let resp = get("https://api.wynncraft.com/public_api.php?action=territoryList").unwrap();
let mut territories: Value = serde_json::from_reader(resp).unwrap();
@ -105,7 +106,7 @@ pub fn federation_livefeed() {
loop {
thread::sleep_ms(30_000); // 30 s
let resp = reqwest::get("https://api.wynncraft.com/public_api.php?action=territoryList").unwrap();
let resp = get("https://api.wynncraft.com/public_api.php?action=territoryList").unwrap();
let new_territories: Value = serde_json::from_reader(resp).unwrap();
@ -134,7 +135,7 @@ pub fn federation_livefeed() {
for listener in federationfeed_listeners
.load::<FederationfeedListener>(&connection)
.expect("Error loading listeners") {
let _ = ChannelId(listener.id as u64).say(format!("Assigned owned by others: {}
let _ = ChannelId(listener.id as u64).say(&ctx.http, format!("Assigned owned by others: {}
FFA owned by others: {}",
assigned_owned_by_enemies.join(", "),
ffa_owned_by_enemies.join(", ")
@ -148,19 +149,19 @@ FFA owned by others: {}",
}
}
pub fn war_livefeed() {
pub fn war_livefeed(ctx: Context) {
use models::WarfeedListener;
use schema::warfeedlisteners::dsl::*;
let connection = establish_connection();
let resp = reqwest::get("https://api.wynncraft.com/public_api.php?action=onlinePlayers").unwrap();
let resp = get("https://api.wynncraft.com/public_api.php?action=onlinePlayers").unwrap();
let mut players: Value = serde_json::from_reader(resp).unwrap();
loop {
thread::sleep_ms(30_000); // 30 seconds
let resp = reqwest::get("https://api.wynncraft.com/public_api.php?action=onlinePlayers").unwrap();
let resp = get("https://api.wynncraft.com/public_api.php?action=onlinePlayers").unwrap();
let new_players: Value = serde_json::from_reader(resp).unwrap();
@ -182,11 +183,11 @@ pub fn war_livefeed() {
}).filter(|&(_, is_in_it)| is_in_it).next().unwrap_or(("WC?", true)).0;
if old_server != key {
let player = player.as_str().unwrap();
let guild = wynncraft::player(player).map(|x| x.guild.name).unwrap_or("?".to_owned());
let guild = wynncraft::player(player).map(|x| x.guild.name.unwrap_or("none".to_owned())).unwrap_or("?".to_owned());
for listener in warfeedlisteners
.load::<WarfeedListener>(&connection)
.expect("Error loading listeners") {
let _ = ChannelId(listener.id as u64).say(format!("{} ({}): ~~{}~~ -> **{}**",
let _ = ChannelId(listener.id as u64).say(&ctx.http, format!("{} ({}): ~~{}~~ -> **{}**",
player.replace('_', "\\_"),
guild,
old_server,
@ -201,7 +202,7 @@ pub fn war_livefeed() {
}
}
pub fn wc_livefeed(msg: &Message) -> Result<(), Error> {
pub fn wc_livefeed(ctx: &Context, msg: &Message) -> Result<(), Error> {
use models::LivefeedListener;
use schema::livefeedlisteners;
@ -219,12 +220,12 @@ pub fn wc_livefeed(msg: &Message) -> Result<(), Error> {
}
}
msg.channel_id.say("Success!")?;
msg.channel_id.say(&ctx.http, "Success!")?;
Ok(())
}
pub fn wc_unlivefeed(msg: &Message) -> Result<(), Error> {
pub fn wc_unlivefeed(ctx: &Context, msg: &Message) -> Result<(), Error> {
use schema::livefeedlisteners::dsl::*;
let connection = establish_connection();
@ -233,12 +234,12 @@ pub fn wc_unlivefeed(msg: &Message) -> Result<(), Error> {
diesel::delete(livefeedlisteners.filter(id.eq(channel_id)))
.execute(&connection)?;
msg.channel_id.say("Success!")?;
msg.channel_id.say(&ctx.http, "Success!")?;
Ok(())
}
pub fn wc_federationfeed(msg: &Message) -> Result<(), Error> {
pub fn wc_federationfeed(ctx: &Context, msg: &Message) -> Result<(), Error> {
use models::FederationfeedListener;
use schema::federationfeed_listeners;
@ -256,12 +257,12 @@ pub fn wc_federationfeed(msg: &Message) -> Result<(), Error> {
}
}
msg.channel_id.say("Success!")?;
msg.channel_id.say(&ctx.http, "Success!")?;
Ok(())
}
pub fn wc_unfederationfeed(msg: &Message) -> Result<(), Error> {
pub fn wc_unfederationfeed(ctx: &Context, msg: &Message) -> Result<(), Error> {
use schema::federationfeed_listeners::dsl::*;
let connection = establish_connection();
@ -270,12 +271,12 @@ pub fn wc_unfederationfeed(msg: &Message) -> Result<(), Error> {
diesel::delete(federationfeed_listeners.filter(id.eq(channel_id)))
.execute(&connection)?;
msg.channel_id.say("Success!")?;
msg.channel_id.say(&ctx.http, "Success!")?;
Ok(())
}
pub fn wc_warfeed(msg: &Message) -> Result<(), Error> {
pub fn wc_warfeed(ctx: &Context, msg: &Message) -> Result<(), Error> {
use models::WarfeedListener;
use schema::warfeedlisteners;
@ -293,12 +294,12 @@ pub fn wc_warfeed(msg: &Message) -> Result<(), Error> {
}
}
msg.channel_id.say("Success!")?;
msg.channel_id.say(&ctx.http, "Success!")?;
Ok(())
}
pub fn wc_unwarfeed(msg: &Message) -> Result<(), Error> {
pub fn wc_unwarfeed(ctx: &Context, msg: &Message) -> Result<(), Error> {
use schema::warfeedlisteners::dsl::*;
let connection = establish_connection();
@ -307,7 +308,7 @@ pub fn wc_unwarfeed(msg: &Message) -> Result<(), Error> {
diesel::delete(warfeedlisteners.filter(id.eq(channel_id)))
.execute(&connection)?;
msg.channel_id.say("Success!")?;
msg.channel_id.say(&ctx.http, "Success!")?;
Ok(())
}

View File

@ -1,9 +1,10 @@
use ::wynncraft;
use ::wynncraft::APIError;
use serenity::model::*;
use ::serenity::prelude::*;
use ::serenity::model::prelude::*;
use ::reqwest;
use ::reqwest::blocking::get;
use ::serde_json;
use ::serde_json::Value;
@ -14,7 +15,7 @@ use ::std::collections::HashSet;
use ::ResponseError;
pub fn wc_guild(command: &str, msg: &Message) -> Result<(), Error> {
pub fn wc_guild(ctx: &Context, command: &str, msg: &Message) -> Result<(), Error> {
if command.len() <= 6 {
bail!("no guild specified");
}
@ -43,7 +44,7 @@ pub fn wc_guild(command: &str, msg: &Message) -> Result<(), Error> {
}
let message = (|| {
let resp = reqwest::get("https://api.wynncraft.com/public_api.php?action=territoryList")?
let resp = get("https://api.wynncraft.com/public_api.php?action=territoryList")?
.error_for_status()?
.text()?;
@ -68,7 +69,7 @@ pub fn wc_guild(command: &str, msg: &Message) -> Result<(), Error> {
})().unwrap_or_else(|e| format!("\nError getting territories: {}", e));
let online_players = (|| {
let resp = reqwest::get("https://api.wynncraft.com/public_api.php?action=onlinePlayers")?;
let resp = get("https://api.wynncraft.com/public_api.php?action=onlinePlayers")?;
let players: Value = serde_json::from_reader(resp)?;
let mut online_players = HashSet::new();
@ -101,14 +102,14 @@ pub fn wc_guild(command: &str, msg: &Message) -> Result<(), Error> {
online_players
) + &message;
for part in full_msg.split('\n').collect::<Vec<_>>().chunks(48) {
msg.channel_id.say(part.join("\n"))?;
msg.channel_id.say(&ctx.http, part.join("\n"))?;
}
Ok(())
}
fn guild_by_prefix(prefix: &str) -> Result<Option<String>, Error> {
let resp = reqwest::get("https://wynnapi.herokuapp.com/list")?.text().unwrap().replace(",]", "]");
let resp = get("https://wynnapi.herokuapp.com/list")?.text().unwrap().replace(",]", "]");
let guilds: Value = serde_json::from_str(&resp)?;
@ -125,13 +126,13 @@ fn guild_by_prefix(prefix: &str) -> Result<Option<String>, Error> {
Ok(None)
}
pub fn wc_topguilds(command: &str, msg: &Message) -> Result<(), Error> {
pub fn wc_topguilds(ctx: &Context, command: &str, msg: &Message) -> Result<(), Error> {
let limit: usize = command[10..].parse().unwrap();
wc_topguilds_limit(msg, limit)
wc_topguilds_limit(ctx, msg, limit)
}
pub fn wc_topguilds_limit(msg: &Message, limit: usize) -> Result<(), Error> {
pub fn wc_topguilds_limit(ctx: &Context, msg: &Message, limit: usize) -> Result<(), Error> {
let leaderboard = wynncraft::guild_leaderboard()?;
let mut text = "```".to_owned();
@ -140,7 +141,7 @@ pub fn wc_topguilds_limit(msg: &Message, limit: usize) -> Result<(), Error> {
}
text += "```";
msg.channel_id.say(text)?;
msg.channel_id.say(&ctx.http, text)?;
Ok(())
}

View File

@ -1,9 +1,10 @@
use ::wynncraft::APIError;
use ::serenity;
use ::serenity::model::*;
use ::serenity::prelude::*;
use ::serenity::model::prelude::*;
use ::reqwest;
use ::reqwest::blocking::get;
use ::serde_json;
use ::serde_json::Value;
@ -25,7 +26,7 @@ pub use player::*;
pub use guild::*;
pub use feed::{wc_livefeed, wc_unlivefeed, wc_warfeed, wc_unwarfeed, wc_federationfeed, wc_unfederationfeed};
pub fn wc_prefix(command: &str, msg: &Message) -> Result<(), Error> {
pub fn wc_prefix(ctx: &Context, command: &str, msg: &Message) -> Result<(), Error> {
use models::PrefixConfig;
use schema::prefixes::dsl::*;
@ -35,7 +36,7 @@ pub fn wc_prefix(command: &str, msg: &Message) -> Result<(), Error> {
diesel::insert_into(prefixes)
.values(&PrefixConfig {
id: msg.guild_id().unwrap().0 as i64,
id: msg.guild_id.unwrap().0 as i64,
prefix: new_prefix.clone()
})
.on_conflict(id)
@ -43,13 +44,13 @@ pub fn wc_prefix(command: &str, msg: &Message) -> Result<(), Error> {
.set(prefix.eq(new_prefix))
.execute(&connection)?;
msg.channel_id.say(format!("Prefix is now {:?}", new_prefix))?;
msg.channel_id.say(&ctx.http, format!("Prefix is now {:?}", new_prefix))?;
Ok(())
}
pub fn wc_status(msg: &Message) -> Result<(), Error> {
let resp = reqwest::get("https://api.wynncraft.com/public_api.php?action=onlinePlayersSum")?.text().unwrap();
pub fn wc_status(ctx: &Context, msg: &Message) -> Result<(), Error> {
let resp = get("https://api.wynncraft.com/public_api.php?action=onlinePlayersSum")?.text().unwrap();
let value: Value = if let Ok(error) = serde_json::from_str::<APIError>(&resp) {
bail!("API error ({})", error.error);
@ -57,21 +58,21 @@ pub fn wc_status(msg: &Message) -> Result<(), Error> {
serde_json::from_str(&resp)?
};
msg.channel_id.say(
msg.channel_id.say(&ctx.http,
format!("{} players online", value.get("players_online").unwrap().as_u64().unwrap())
)?;
Ok(())
}
pub fn wc_territory(command: &str, msg: &Message) -> Result<(), Error> {
pub fn wc_territory(ctx: &Context, command: &str, msg: &Message) -> Result<(), Error> {
if command.len() <= 10 {
bail!("no territory specified");
}
let territory = &command[10..];
let resp = reqwest::get("https://api.wynncraft.com/public_api.php?action=territoryList")?.text().unwrap();
let resp = get("https://api.wynncraft.com/public_api.php?action=territoryList")?.text().unwrap();
let territories: Value = if let Ok(error) = serde_json::from_str::<APIError>(&resp) {
bail!("API error ({})", error.error);
@ -95,17 +96,15 @@ pub fn wc_territory(command: &str, msg: &Message) -> Result<(), Error> {
}
if !message.is_empty() {
msg.channel_id.say(
message
)?;
msg.channel_id.say(&ctx.http, message)?;
}
Ok(())
}
pub fn wc_info(msg: &Message) -> Result<(), Error> {
let guilds = get_guild_count()?;
msg.channel_id.say(format!("Developer: Wurst#1783
pub fn wc_info(ctx: &Context, msg: &Message) -> Result<(), Error> {
let guilds = get_guild_count(ctx)?;
msg.channel_id.say(&ctx.http, format!("Developer: Wurst#1783
Forum thread: https://forums.wynncraft.com/threads/discord-bot.212142/
Discord: https://discord.gg/GbN7HeG
Version: {}
@ -114,18 +113,18 @@ Servers: {}", env!("CARGO_PKG_VERSION"), guilds))?;
Ok(())
}
fn get_guild_count() -> Result<usize, Error> {
fn get_guild_count(ctx: &Context) -> Result<usize, Error> {
let mut guilds = 0;
let mut new_guilds = serenity::http::get_guilds(&serenity::http::GuildPagination::After(GuildId(0)), 100)?;
let mut new_guilds = ctx.http.get_guilds(&serenity::http::GuildPagination::After(GuildId(0)), 100)?;
while !new_guilds.is_empty() {
guilds += new_guilds.len();
new_guilds = serenity::http::get_guilds(&serenity::http::GuildPagination::After(new_guilds.last().unwrap().id), 100)?;
new_guilds = ctx.http.get_guilds(&serenity::http::GuildPagination::After(new_guilds.last().unwrap().id), 100)?;
}
Ok(guilds)
}
pub fn wc_help(msg: &Message) -> Result<(), Error> {
if let Err(_) = msg.author.dm(|f| f.content("Command overview: (prefix is wc!)
pub fn wc_help(ctx: &Context, msg: &Message) -> Result<(), Error> {
if let Err(_) = msg.author.dm(ctx, |f| f.content("Command overview: (prefix is wc!)
Get information:
guild <name/prefix> - show guild stats and territories
@ -149,18 +148,18 @@ Misc.:
Visit the Discord for more help: https://discord.gg/GbN7HeG")) {
bail!("could not send DM");
} else {
let _ = msg.channel_id.say("Direct message sent sucessfully!");
let _ = msg.channel_id.say(&ctx.http, "Direct message sent sucessfully!");
Ok(())
}
}
pub fn wc_crop(command: &str, msg: &Message) -> Result<(), Error> {
pub fn wc_crop(ctx: &Context, command: &str, msg: &Message) -> Result<(), Error> {
let url = &command[5..];
let client = reqwest::ClientBuilder::new().timeout(::std::time::Duration::from_secs(10000)).build().unwrap();
let client = reqwest::blocking::ClientBuilder::new().timeout(::std::time::Duration::from_secs(10000)).build().unwrap();
let new_url = client.get(&format!("https://wynncraft-autocrop.herokuapp.com/crop?url={}", url)).send()?.text().unwrap();
if new_url.starts_with("https://res.cloudinary.com") {
for chunk in new_url.split(' ').collect::<Vec<_>>().chunks(21) {
msg.channel_id.say(&chunk.join(" "))?;
msg.channel_id.say(&ctx.http, &chunk.join(" "))?;
}
} else {
bail!(failure::err_msg("could not crop image"));
@ -169,15 +168,15 @@ pub fn wc_crop(command: &str, msg: &Message) -> Result<(), Error> {
Ok(())
}
pub fn wc_crop_discord_upload(msg: &Message) -> Result<(), Error> {
let last = &msg.channel_id.messages(|g| g.before(msg.id).limit(1))?[0];
pub fn wc_crop_discord_upload(ctx: &Context, msg: &Message) -> Result<(), Error> {
let last = &msg.channel_id.messages(&ctx.http, |g| g.before(msg.id).limit(1))?[0];
let mut attachments = last.attachments.clone();
attachments.extend(msg.attachments.clone());
for attachment in &attachments {
let url = &attachment.url;
let new_url = reqwest::get(&format!("https://wynncraft-autocrop.herokuapp.com/crop?url={}", url))?.text().unwrap();
let new_url = get(&format!("https://wynncraft-autocrop.herokuapp.com/crop?url={}", url))?.text().unwrap();
if new_url.starts_with("https://res.cloudinary.com") {
msg.channel_id.say(&new_url)?;
msg.channel_id.say(&ctx.http, &new_url)?;
} else {
bail!(failure::err_msg("could not crop image"));
}
@ -186,16 +185,16 @@ pub fn wc_crop_discord_upload(msg: &Message) -> Result<(), Error> {
Ok(())
}
pub fn wc_shout(command: &str, msg: &Message) -> Result<(), Error> {
pub fn wc_shout(ctx: &Context, command: &str, msg: &Message) -> Result<(), Error> {
let shout = &command[6..];
for guild_id in serenity::http::get_current_user().unwrap().guilds().unwrap() {
for guild_id in ctx.http.get_current_user().unwrap().guilds(&ctx.http).unwrap() {
println!("Showing {:?}", guild_id.name);
let mut wynnbots = vec![];
let mut botchannels = vec![];
let mut bots = vec![];
let mut general = vec![];
let mut others = vec![];
for (_channel_id, channel) in Guild::get(&guild_id).unwrap().channels().unwrap() {
for (_channel_id, channel) in Guild::get(&ctx.http, &guild_id).unwrap().channels(&ctx.http).unwrap() {
if channel.kind != ChannelType::Text {
continue;
}
@ -243,13 +242,13 @@ pub fn wc_shout(command: &str, msg: &Message) -> Result<(), Error> {
}
*/
//println!("doing it");
if let Ok(_) = channel.say(shout) {
if let Ok(_) = channel.say(&ctx.http, shout) {
println!("success!");
break;
}
}
}
msg.channel_id.say("Success!")?;
msg.channel_id.say(&ctx.http, "Success!")?;
Ok(())
}

View File

@ -1,12 +1,13 @@
use ::wynncraft;
use serenity::model::*;
use ::serenity::prelude::*;
use serenity::model::prelude::*;
use failure::Error;
use chrono::{Datelike, NaiveDateTime};
pub fn wc_player(command: &str, msg: &Message) -> Result<(), Error> {
pub fn wc_player(ctx: &Context, command: &str, msg: &Message) -> Result<(), Error> {
if command.len() <= 7 {
bail!("no player specified");
}
@ -14,13 +15,13 @@ pub fn wc_player(command: &str, msg: &Message) -> Result<(), Error> {
let player = wynncraft::player(player)?;
let current_server_msg = if player.current_server != "null" {
format!("\n**Currently online on**: {}", player.current_server)
let current_server_msg = if let Some(ref x) = player.meta.location.server {
format!("\n**Currently online on**: {}", x)
} else {
String::new()
};
msg.channel_id.say(
msg.channel_id.say(&ctx.http,
format!(
"**Player name**: {}
**Guild**: {} (joined {})
@ -29,9 +30,9 @@ pub fn wc_player(command: &str, msg: &Message) -> Result<(), Error> {
**Chests looted**: {}
**Total level**: {}{}",
player.username,
player.guild.name,
if player.guild.name != "None" {
let date = wynncraft::guild(&player.guild.name)?.unwrap().members.iter().filter(|x| x.name == player.username).next().unwrap().joined.clone();
player.guild.name.as_ref().unwrap_or(&"None".to_owned()),
if player.guild.name != None {
let date = wynncraft::guild(&player.guild.name.clone().unwrap())?.unwrap().members.iter().filter(|x| x.name == player.username).next().unwrap().joined.clone();
date[0..date.len()-2].parse::<NaiveDateTime>().map(|x| format!("{} {}, {}", match x.month() {
1 => "January",
2 => "February",
@ -48,10 +49,10 @@ pub fn wc_player(command: &str, msg: &Message) -> Result<(), Error> {
_ => "<insert Month here>"
}, x.day(), x.year())).unwrap_or(date)
} else { "never".to_owned() },
player.playtime / 60,
player.global.mobs_killed, player.global.pvp_kills,
player.global.chests_found,
player.classes.iter().map(|(_, x)| x.level).sum::<u64>(),
player.meta.playtime / 60,
player.global.mobsKilled, player.global.pvp.kills,
player.global.chestsFound,
player.classes.iter().map(|x| x.level).sum::<u64>(),
current_server_msg
)
)?;

View File

@ -2,7 +2,7 @@ extern crate wynncraft;
extern crate serenity;
use serenity::prelude::*;
use serenity::model::*;
use serenity::model::prelude::{Guild, Channel, Message, GuildChannel, PrivateChannel, User, Ready, Activity};
extern crate reqwest;
@ -81,7 +81,9 @@ pub enum ResponseError {
}
}
struct Handler;
struct Handler {
feeds: bool
}
impl EventHandler for Handler {
// Set a handler for the `on_message` event - so that whenever a new message
@ -89,7 +91,7 @@ impl EventHandler for Handler {
//
// Event handlers are dispatched through multi-threading, and so multiple
// of a single event can be dispatched simultaneously.
fn on_message(&self, _: Context, msg: Message) {
fn message(&self, ctx: Context, msg: Message) {
if msg.author.name == "WynnBot" {
return;
}
@ -99,7 +101,7 @@ impl EventHandler for Handler {
let mut prefix = prefixes::table
.select(prefixes::prefix)
.filter(prefixes::id.eq(msg.guild_id().unwrap_or(GuildId(0)).0 as i64))
.filter(prefixes::id.eq(msg.guild_id.map(|x| x.0).unwrap_or(0) as i64))
.load::<String>(&connection)
.expect("Error loading prefix").get(0)
.map(|x| x.to_owned())
@ -109,30 +111,29 @@ impl EventHandler for Handler {
prefix = String::new();
}
if let Err(error) = self.process_message(&msg, &prefix) {
if let Err(error) = self.process_message(&ctx, &msg, &prefix) {
//eprintln!("Error: {}", error);
let _ = msg.channel_id.say(format!("Error: {}", error));
let _ = msg.channel_id.say(&ctx.http, format!("Error: {}", error));
for cause in error.causes().skip(1) {
//eprintln!("caused by: {}", cause);
let _ = msg.channel_id.say(format!("caused by: {}", cause));
let _ = msg.channel_id.say(&ctx.http, format!("caused by: {}", cause));
}
}
/*
if msg.content.starts_with(&prefix) || msg.content.contains("<@392763365409292298>") {
let command = &msg.content;
// log
if let Ok(user) = "<@210743594061922306>".parse::<User>() {
let _ = user.dm(|f| f.content(format!("{}: {}: {}: {}", match msg.channel_id.get().unwrap() {
Channel::Guild(channel) => {
channel.read().unwrap().guild_id.get().unwrap().name
},
Channel::Private(_) => {
let name = if ctx.cache.read().private_channel(msg.channel_id).is_some() {
"DM".to_owned()
},
_ => unimplemented!()
}, msg.channel_id.get().unwrap(), msg.author, command)));
} else {
ctx.cache.read().guild_channel(msg.channel_id).map(|x| x.read().guild_id.to_partial_guild(&ctx.http).unwrap().name).unwrap_or("guild not in cache".to_owned())
};
let _ = user.dm(&ctx, |f| f.content(format!("{}: {}: {}: {}", name, msg.channel_id, msg.author, command)));
}
}
*/
}
// Set a handler to be called on the `on_ready` event. This is called when a
@ -141,10 +142,14 @@ impl EventHandler for Handler {
// private channels, and more.
//
// In this case, just print what the current bot's username is.
fn on_ready(&self, ctx: Context, ready: Ready) {
fn ready(&self, ctx: Context, ready: Ready) {
println!("{} is connected!", ready.user.name);
ctx.set_game(Game::playing("wc!help"));
ctx.set_activity(Activity::playing("wc!help"));
println!("Currently playing wc!help");
if self.feeds {
println!("Starting daemons...");
start_daemons(&ctx);
}
}
}
@ -158,30 +163,30 @@ struct CBResponse {
output: String
}
fn cleverbot(msg: &Message) -> Result<String, Error> {
let _ = msg.channel_id.broadcast_typing();
let resp = reqwest::get(&format!("http://www.cleverbot.com/getreply?key=CC7wgO9gQl7yPjB54eDLHmM5Jmg&input={}&cb_settings_tweak1=0&cb_settings_tweak2=100&cb_settings_tweak3=100{}",
fn cleverbot(ctx: &Context, msg: &Message) -> Result<String, Error> {
let _ = msg.channel_id.broadcast_typing(&ctx.http);
let resp = reqwest::blocking::get(&format!("http://www.cleverbot.com/getreply?key=CC7wgO9gQl7yPjB54eDLHmM5Jmg&input={}&cb_settings_tweak1=0&cb_settings_tweak2=100&cb_settings_tweak3=100{}",
msg.content.replace("<@392763365409292298>", ""), (*CS).lock().clone().map(|x| format!("&cs={}", x)).unwrap_or_else(String::new)))?
.error_for_status()?
.text()?;
thread::sleep_ms(500);
let resp: CBResponse = serde_json::from_str(&resp)?;
msg.channel_id.say(format!("{} {}", msg.author.mention(), resp.output))?;
msg.channel_id.say(&ctx.http, format!("{} {}", msg.author.mention(), resp.output))?;
Ok(resp.cs)
}
impl Handler {
fn process_message(&self, msg: &Message, prefix: &str) -> Result<(), Error> {
fn process_message(&self, ctx: &Context, msg: &Message, prefix: &str) -> Result<(), Error> {
if msg.content == "<@392763365409292298> has big gay" {
let _ = msg.channel_id.broadcast_typing();
let _ = msg.channel_id.broadcast_typing(&ctx.http);
thread::sleep_ms(5000);
let _ = msg.channel_id.say("<@395463760841539584> has bigger gay");
let _ = msg.channel_id.say(&ctx.http, "<@395463760841539584> has bigger gay");
return Ok(());
}
if msg.content == "<@392763365409292298> has biggest gay" {
let _ = msg.channel_id.broadcast_typing();
let _ = msg.channel_id.broadcast_typing(&ctx.http);
thread::sleep_ms(5000);
let _ = msg.channel_id.say("<@395463760841539584> no u");
let _ = msg.channel_id.say(&ctx.http, "<@395463760841539584> no u");
return Ok(());
}
/*
@ -215,43 +220,43 @@ impl Handler {
let command = &command;
if command.starts_with("guild") {
wc_guild(command, msg)?;
wc_guild(ctx, command, msg)?;
} else if command == "topguilds" {
wc_topguilds_limit(msg, 10)?;
wc_topguilds_limit(ctx, msg, 10)?;
} else if command.starts_with("topguilds ") {
wc_topguilds(command, msg)?;
wc_topguilds(ctx, command, msg)?;
} else if command.starts_with("territory") {
wc_territory(command, msg)?;
wc_territory(ctx, command, msg)?;
} else if command == "status" {
wc_status(msg)?;
wc_status(ctx, msg)?;
} else if command.starts_with("player") {
wc_player(command, msg)?;
wc_player(ctx, command, msg)?;
} else if command.starts_with("livefeed") {
wc_livefeed(msg)?;
wc_livefeed(ctx, msg)?;
} else if command.starts_with("unlivefeed") {
wc_unlivefeed(msg)?;
wc_unlivefeed(ctx, msg)?;
} else if command.starts_with("federationfeed") {
wc_federationfeed(msg)?;
wc_federationfeed(ctx, msg)?;
} else if command.starts_with("unfederationfeed") {
wc_unfederationfeed(msg)?;
wc_unfederationfeed(ctx, msg)?;
} else if command == "info" || command == "" {
wc_info(msg)?;
wc_info(ctx, msg)?;
} else if command == "help" {
wc_help(msg)?;
wc_help(ctx, msg)?;
} else if command.starts_with("crop ") {
wc_crop(command, msg)?;
wc_crop(ctx, command, msg)?;
} else if command == "crop" {
wc_crop_discord_upload(msg)?;
wc_crop_discord_upload(ctx, msg)?;
} else if command.starts_with("warfeed") {
wc_warfeed(msg)?;
wc_warfeed(ctx, msg)?;
} else if command.starts_with("unwarfeed") {
wc_unwarfeed(msg)?;
wc_unwarfeed(ctx, msg)?;
} else if command.starts_with("shout") {
if msg.author.name == "Wurst" && msg.author.discriminator == 1783 {
wc_shout(command, msg)?;
wc_shout(ctx, command, msg)?;
}
} else if command.starts_with("prefix") {
wc_prefix(command, msg)?;
wc_prefix(ctx, command, msg)?;
} else {
let commands = ["topguilds", "leaderboard", "top", "prefix", "warfeed", "unwarfeed", "livefeed", "unlivefeed", "status", "crop", "guild", "stats", "territories", "player", "territory", "info", "help"];
let mut min = usize::max_value();
@ -264,7 +269,7 @@ impl Handler {
}
}
if min < 25 {
msg.channel_id.say(&format!("Unknown command. Did you mean {:?}?", min_command))?;
msg.channel_id.say(&ctx.http, &format!("Unknown command. Did you mean {:?}?", min_command))?;
} else {
bail!(ResponseError::UnknownCommand { name: command.to_owned() });
}
@ -282,16 +287,11 @@ fn main() {
env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
if cfg.feeds {
println!("Starting daemons...");
start_daemons();
}
loop {
// Create a new instance of the Client, logging in as a bot. This will
// automatically prepend your bot token with "Bot ", which is a requirement
// by Discord for bot users.
let mut client = Client::new(&token, Handler);
let mut client = Client::new(&token, Handler { feeds: cfg.feeds }).unwrap();
// Finally, start a single shard, and start listening to events.
//
@ -303,26 +303,31 @@ fn main() {
}
}
fn start_daemons() {
thread::Builder::new()
.spawn(|| {
fn start_daemons(ctx1: &Context) {
let ctx = ctx1.clone();
let territory_feed = thread::Builder::new()
.spawn(move || {
loop {
println!("{:?}", panic::catch_unwind(|| commands::feed::territory_livefeed()));
let ctx = ctx.clone();
thread::Builder::new().spawn(|| { commands::feed::territory_livefeed(ctx) }).unwrap().join();
}
})
.unwrap();
thread::Builder::new()
.spawn(|| {
let ctx = ctx1.clone();
let war_feed = thread::Builder::new()
.spawn(move || {
loop {
println!("{:?}", panic::catch_unwind(|| commands::feed::war_livefeed()));
let ctx = ctx.clone();
thread::Builder::new().spawn(|| { commands::feed::war_livefeed(ctx) }).unwrap().join();
}
})
.unwrap();
thread::Builder::new()
.spawn(|| {
let ctx = ctx1.clone();
let federation_feed = thread::Builder::new()
.spawn(move || {
loop {
println!("{:?}", panic::catch_unwind(|| commands::feed::federation_livefeed()));
let ctx = ctx.clone();
thread::Builder::new().spawn(|| { commands::feed::federation_livefeed(ctx) }).unwrap().join();
}
})
.unwrap();