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

View File

@ -1,6 +1,7 @@
use ::wynncraft; use ::wynncraft;
use serenity::model::*; use ::serenity::prelude::*;
use ::serenity::model::prelude::*;
use ::diesel; use ::diesel;
use ::diesel::prelude::*; use ::diesel::prelude::*;
@ -9,7 +10,7 @@ use ::diesel::result::DatabaseErrorKind;
use ::serde_json; use ::serde_json;
use ::serde_json::Value; use ::serde_json::Value;
use ::reqwest; use ::reqwest::blocking::get;
use ::std::thread; use ::std::thread;
@ -18,13 +19,13 @@ use failure::Error;
use super::establish_connection; use super::establish_connection;
pub fn territory_livefeed() { pub fn territory_livefeed(ctx: Context) {
use models::LivefeedListener; use models::LivefeedListener;
use schema::livefeedlisteners::dsl::*; use schema::livefeedlisteners::dsl::*;
let connection = establish_connection(); 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(); let mut territories: Value = serde_json::from_reader(resp).unwrap();
@ -32,7 +33,7 @@ pub fn territory_livefeed() {
loop { loop {
thread::sleep_ms(20_000); // 20 seconds 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(); let new_territories: Value = serde_json::from_reader(resp).unwrap();
@ -49,7 +50,7 @@ pub fn territory_livefeed() {
for listener in livefeedlisteners for listener in livefeedlisteners
.load::<LivefeedListener>(&connection) .load::<LivefeedListener>(&connection)
.expect("Error loading listeners") { .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("territory").unwrap().as_str().unwrap(),
value.get("guild").unwrap().as_str().unwrap(), value.get("guild").unwrap().as_str().unwrap(),
new_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 models::FederationfeedListener;
use schema::federationfeed_listeners::dsl::*; use schema::federationfeed_listeners::dsl::*;
@ -94,7 +95,7 @@ pub fn federation_livefeed() {
let connection = establish_connection(); 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(); let mut territories: Value = serde_json::from_reader(resp).unwrap();
@ -105,7 +106,7 @@ pub fn federation_livefeed() {
loop { loop {
thread::sleep_ms(30_000); // 30 s 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(); let new_territories: Value = serde_json::from_reader(resp).unwrap();
@ -134,7 +135,7 @@ pub fn federation_livefeed() {
for listener in federationfeed_listeners for listener in federationfeed_listeners
.load::<FederationfeedListener>(&connection) .load::<FederationfeedListener>(&connection)
.expect("Error loading listeners") { .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: {}", FFA owned by others: {}",
assigned_owned_by_enemies.join(", "), assigned_owned_by_enemies.join(", "),
ffa_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 models::WarfeedListener;
use schema::warfeedlisteners::dsl::*; use schema::warfeedlisteners::dsl::*;
let connection = establish_connection(); 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(); let mut players: Value = serde_json::from_reader(resp).unwrap();
loop { loop {
thread::sleep_ms(30_000); // 30 seconds 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(); 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; }).filter(|&(_, is_in_it)| is_in_it).next().unwrap_or(("WC?", true)).0;
if old_server != key { if old_server != key {
let player = player.as_str().unwrap(); 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 for listener in warfeedlisteners
.load::<WarfeedListener>(&connection) .load::<WarfeedListener>(&connection)
.expect("Error loading listeners") { .expect("Error loading listeners") {
let _ = ChannelId(listener.id as u64).say(format!("{} ({}): ~~{}~~ -> **{}**", let _ = ChannelId(listener.id as u64).say(&ctx.http, format!("{} ({}): ~~{}~~ -> **{}**",
player.replace('_', "\\_"), player.replace('_', "\\_"),
guild, guild,
old_server, 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 models::LivefeedListener;
use schema::livefeedlisteners; 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(()) Ok(())
} }
pub fn wc_unlivefeed(msg: &Message) -> Result<(), Error> { pub fn wc_unlivefeed(ctx: &Context, msg: &Message) -> Result<(), Error> {
use schema::livefeedlisteners::dsl::*; use schema::livefeedlisteners::dsl::*;
let connection = establish_connection(); let connection = establish_connection();
@ -233,12 +234,12 @@ pub fn wc_unlivefeed(msg: &Message) -> Result<(), Error> {
diesel::delete(livefeedlisteners.filter(id.eq(channel_id))) diesel::delete(livefeedlisteners.filter(id.eq(channel_id)))
.execute(&connection)?; .execute(&connection)?;
msg.channel_id.say("Success!")?; msg.channel_id.say(&ctx.http, "Success!")?;
Ok(()) Ok(())
} }
pub fn wc_federationfeed(msg: &Message) -> Result<(), Error> { pub fn wc_federationfeed(ctx: &Context, msg: &Message) -> Result<(), Error> {
use models::FederationfeedListener; use models::FederationfeedListener;
use schema::federationfeed_listeners; 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(()) Ok(())
} }
pub fn wc_unfederationfeed(msg: &Message) -> Result<(), Error> { pub fn wc_unfederationfeed(ctx: &Context, msg: &Message) -> Result<(), Error> {
use schema::federationfeed_listeners::dsl::*; use schema::federationfeed_listeners::dsl::*;
let connection = establish_connection(); 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))) diesel::delete(federationfeed_listeners.filter(id.eq(channel_id)))
.execute(&connection)?; .execute(&connection)?;
msg.channel_id.say("Success!")?; msg.channel_id.say(&ctx.http, "Success!")?;
Ok(()) Ok(())
} }
pub fn wc_warfeed(msg: &Message) -> Result<(), Error> { pub fn wc_warfeed(ctx: &Context, msg: &Message) -> Result<(), Error> {
use models::WarfeedListener; use models::WarfeedListener;
use schema::warfeedlisteners; 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(()) Ok(())
} }
pub fn wc_unwarfeed(msg: &Message) -> Result<(), Error> { pub fn wc_unwarfeed(ctx: &Context, msg: &Message) -> Result<(), Error> {
use schema::warfeedlisteners::dsl::*; use schema::warfeedlisteners::dsl::*;
let connection = establish_connection(); let connection = establish_connection();
@ -307,7 +308,7 @@ pub fn wc_unwarfeed(msg: &Message) -> Result<(), Error> {
diesel::delete(warfeedlisteners.filter(id.eq(channel_id))) diesel::delete(warfeedlisteners.filter(id.eq(channel_id)))
.execute(&connection)?; .execute(&connection)?;
msg.channel_id.say("Success!")?; msg.channel_id.say(&ctx.http, "Success!")?;
Ok(()) Ok(())
} }

View File

@ -1,9 +1,10 @@
use ::wynncraft; use ::wynncraft;
use ::wynncraft::APIError; 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;
use ::serde_json::Value; use ::serde_json::Value;
@ -14,7 +15,7 @@ use ::std::collections::HashSet;
use ::ResponseError; 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 { if command.len() <= 6 {
bail!("no guild specified"); bail!("no guild specified");
} }
@ -43,7 +44,7 @@ pub fn wc_guild(command: &str, msg: &Message) -> Result<(), Error> {
} }
let message = (|| { 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()? .error_for_status()?
.text()?; .text()?;
@ -68,7 +69,7 @@ pub fn wc_guild(command: &str, msg: &Message) -> Result<(), Error> {
})().unwrap_or_else(|e| format!("\nError getting territories: {}", e)); })().unwrap_or_else(|e| format!("\nError getting territories: {}", e));
let online_players = (|| { 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 players: Value = serde_json::from_reader(resp)?;
let mut online_players = HashSet::new(); let mut online_players = HashSet::new();
@ -101,14 +102,14 @@ pub fn wc_guild(command: &str, msg: &Message) -> Result<(), Error> {
online_players online_players
) + &message; ) + &message;
for part in full_msg.split('\n').collect::<Vec<_>>().chunks(48) { 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(()) Ok(())
} }
fn guild_by_prefix(prefix: &str) -> Result<Option<String>, Error> { 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)?; let guilds: Value = serde_json::from_str(&resp)?;
@ -125,13 +126,13 @@ fn guild_by_prefix(prefix: &str) -> Result<Option<String>, Error> {
Ok(None) 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(); 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 leaderboard = wynncraft::guild_leaderboard()?;
let mut text = "```".to_owned(); let mut text = "```".to_owned();
@ -140,7 +141,7 @@ pub fn wc_topguilds_limit(msg: &Message, limit: usize) -> Result<(), Error> {
} }
text += "```"; text += "```";
msg.channel_id.say(text)?; msg.channel_id.say(&ctx.http, text)?;
Ok(()) Ok(())
} }

View File

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

View File

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

View File

@ -2,7 +2,7 @@ extern crate wynncraft;
extern crate serenity; extern crate serenity;
use serenity::prelude::*; use serenity::prelude::*;
use serenity::model::*; use serenity::model::prelude::{Guild, Channel, Message, GuildChannel, PrivateChannel, User, Ready, Activity};
extern crate reqwest; extern crate reqwest;
@ -46,7 +46,7 @@ mod commands;
use commands::*; use commands::*;
lazy_static! { lazy_static! {
static ref GUILD_PREFIXES: RwLock<HashMap<String, String>> = RwLock::new(HashMap::new()); static ref GUILD_PREFIXES: RwLock<HashMap<String, String>> = RwLock::new(HashMap::new());
} }
#[derive(Deserialize, Configure)] #[derive(Deserialize, Configure)]
@ -57,39 +57,41 @@ struct Config {
} }
impl Default for Config { impl Default for Config {
fn default() -> Config { fn default() -> Config {
Config { Config {
prefix: "wcdev!".to_owned(), prefix: "wcdev!".to_owned(),
feeds: false feeds: false
} }
} }
} }
#[derive(Debug, Fail)] #[derive(Debug, Fail)]
pub enum ResponseError { pub enum ResponseError {
#[fail(display = "unknown command: {}", name)] #[fail(display = "unknown command: {}", name)]
UnknownCommand { UnknownCommand {
name: String name: String
}, },
#[fail(display = "unknown guild: {}", name)] #[fail(display = "unknown guild: {}", name)]
UnknownGuild { UnknownGuild {
name: String name: String
}, },
#[fail(display = "unknown guild prefix: {}", name)] #[fail(display = "unknown guild prefix: {}", name)]
UnknownGuildPrefix { UnknownGuildPrefix {
name: String name: String
} }
} }
struct Handler; struct Handler {
feeds: bool
}
impl EventHandler for Handler { impl EventHandler for Handler {
// Set a handler for the `on_message` event - so that whenever a new message // Set a handler for the `on_message` event - so that whenever a new message
// is received - the closure (or function) passed will be called. // is received - the closure (or function) passed will be called.
// //
// Event handlers are dispatched through multi-threading, and so multiple // Event handlers are dispatched through multi-threading, and so multiple
// of a single event can be dispatched simultaneously. // 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" { if msg.author.name == "WynnBot" {
return; return;
} }
@ -99,7 +101,7 @@ impl EventHandler for Handler {
let mut prefix = prefixes::table let mut prefix = prefixes::table
.select(prefixes::prefix) .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) .load::<String>(&connection)
.expect("Error loading prefix").get(0) .expect("Error loading prefix").get(0)
.map(|x| x.to_owned()) .map(|x| x.to_owned())
@ -109,43 +111,46 @@ impl EventHandler for Handler {
prefix = String::new(); 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); //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) { for cause in error.causes().skip(1) {
//eprintln!("caused by: {}", cause); //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>") { if msg.content.starts_with(&prefix) || msg.content.contains("<@392763365409292298>") {
let command = &msg.content; let command = &msg.content;
// log // log
if let Ok(user) = "<@210743594061922306>".parse::<User>() { if let Ok(user) = "<@210743594061922306>".parse::<User>() {
let _ = user.dm(|f| f.content(format!("{}: {}: {}: {}", match msg.channel_id.get().unwrap() { let name = if ctx.cache.read().private_channel(msg.channel_id).is_some() {
Channel::Guild(channel) => { "DM".to_owned()
channel.read().unwrap().guild_id.get().unwrap().name } 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())
Channel::Private(_) => { };
"DM".to_owned() let _ = user.dm(&ctx, |f| f.content(format!("{}: {}: {}: {}", name, msg.channel_id, msg.author, command)));
},
_ => unimplemented!()
}, msg.channel_id.get().unwrap(), msg.author, command)));
} }
} }
} */
}
// Set a handler to be called on the `on_ready` event. This is called when a // Set a handler to be called on the `on_ready` event. This is called when a
// shard is booted, and a READY payload is sent by Discord. This payload // shard is booted, and a READY payload is sent by Discord. This payload
// contains data like the current user's guild Ids, current user data, // contains data like the current user's guild Ids, current user data,
// private channels, and more. // private channels, and more.
// //
// In this case, just print what the current bot's username is. // 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); 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"); println!("Currently playing wc!help");
} if self.feeds {
println!("Starting daemons...");
start_daemons(&ctx);
}
}
} }
lazy_static! { lazy_static! {
@ -158,30 +163,30 @@ struct CBResponse {
output: String output: String
} }
fn cleverbot(msg: &Message) -> Result<String, Error> { fn cleverbot(ctx: &Context, msg: &Message) -> Result<String, Error> {
let _ = msg.channel_id.broadcast_typing(); let _ = msg.channel_id.broadcast_typing(&ctx.http);
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{}", 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)))? msg.content.replace("<@392763365409292298>", ""), (*CS).lock().clone().map(|x| format!("&cs={}", x)).unwrap_or_else(String::new)))?
.error_for_status()? .error_for_status()?
.text()?; .text()?;
thread::sleep_ms(500); thread::sleep_ms(500);
let resp: CBResponse = serde_json::from_str(&resp)?; 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) Ok(resp.cs)
} }
impl Handler { 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" { 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); 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(()); return Ok(());
} }
if msg.content == "<@392763365409292298> has biggest gay" { 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); thread::sleep_ms(5000);
let _ = msg.channel_id.say("<@395463760841539584> no u"); let _ = msg.channel_id.say(&ctx.http, "<@395463760841539584> no u");
return Ok(()); return Ok(());
} }
/* /*
@ -215,43 +220,43 @@ impl Handler {
let command = &command; let command = &command;
if command.starts_with("guild") { if command.starts_with("guild") {
wc_guild(command, msg)?; wc_guild(ctx, command, msg)?;
} else if command == "topguilds" { } else if command == "topguilds" {
wc_topguilds_limit(msg, 10)?; wc_topguilds_limit(ctx, msg, 10)?;
} else if command.starts_with("topguilds ") { } else if command.starts_with("topguilds ") {
wc_topguilds(command, msg)?; wc_topguilds(ctx, command, msg)?;
} else if command.starts_with("territory") { } else if command.starts_with("territory") {
wc_territory(command, msg)?; wc_territory(ctx, command, msg)?;
} else if command == "status" { } else if command == "status" {
wc_status(msg)?; wc_status(ctx, msg)?;
} else if command.starts_with("player") { } else if command.starts_with("player") {
wc_player(command, msg)?; wc_player(ctx, command, msg)?;
} else if command.starts_with("livefeed") { } else if command.starts_with("livefeed") {
wc_livefeed(msg)?; wc_livefeed(ctx, msg)?;
} else if command.starts_with("unlivefeed") { } else if command.starts_with("unlivefeed") {
wc_unlivefeed(msg)?; wc_unlivefeed(ctx, msg)?;
} else if command.starts_with("federationfeed") { } else if command.starts_with("federationfeed") {
wc_federationfeed(msg)?; wc_federationfeed(ctx, msg)?;
} else if command.starts_with("unfederationfeed") { } else if command.starts_with("unfederationfeed") {
wc_unfederationfeed(msg)?; wc_unfederationfeed(ctx, msg)?;
} else if command == "info" || command == "" { } else if command == "info" || command == "" {
wc_info(msg)?; wc_info(ctx, msg)?;
} else if command == "help" { } else if command == "help" {
wc_help(msg)?; wc_help(ctx, msg)?;
} else if command.starts_with("crop ") { } else if command.starts_with("crop ") {
wc_crop(command, msg)?; wc_crop(ctx, command, msg)?;
} else if command == "crop" { } else if command == "crop" {
wc_crop_discord_upload(msg)?; wc_crop_discord_upload(ctx, msg)?;
} else if command.starts_with("warfeed") { } else if command.starts_with("warfeed") {
wc_warfeed(msg)?; wc_warfeed(ctx, msg)?;
} else if command.starts_with("unwarfeed") { } else if command.starts_with("unwarfeed") {
wc_unwarfeed(msg)?; wc_unwarfeed(ctx, msg)?;
} else if command.starts_with("shout") { } else if command.starts_with("shout") {
if msg.author.name == "Wurst" && msg.author.discriminator == 1783 { if msg.author.name == "Wurst" && msg.author.discriminator == 1783 {
wc_shout(command, msg)?; wc_shout(ctx, command, msg)?;
} }
} else if command.starts_with("prefix") { } else if command.starts_with("prefix") {
wc_prefix(command, msg)?; wc_prefix(ctx, command, msg)?;
} else { } else {
let commands = ["topguilds", "leaderboard", "top", "prefix", "warfeed", "unwarfeed", "livefeed", "unlivefeed", "status", "crop", "guild", "stats", "territories", "player", "territory", "info", "help"]; 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(); let mut min = usize::max_value();
@ -264,7 +269,7 @@ impl Handler {
} }
} }
if min < 25 { 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 { } else {
bail!(ResponseError::UnknownCommand { name: command.to_owned() }); bail!(ResponseError::UnknownCommand { name: command.to_owned() });
} }
@ -277,54 +282,54 @@ fn main() {
use_default_config!(); use_default_config!();
let cfg = Config::generate().expect("config error"); let cfg = Config::generate().expect("config error");
// Configure the client with your Discord bot token in the environment. // Configure the client with your Discord bot token in the environment.
let token = env::var("DISCORD_TOKEN").expect("DISCORD_TOKEN must be set"); let token = env::var("DISCORD_TOKEN").expect("DISCORD_TOKEN must be set");
env::var("DATABASE_URL") env::var("DATABASE_URL")
.expect("DATABASE_URL must be set"); .expect("DATABASE_URL must be set");
if cfg.feeds {
println!("Starting daemons...");
start_daemons();
}
loop { loop {
// Create a new instance of the Client, logging in as a bot. This will // 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 // automatically prepend your bot token with "Bot ", which is a requirement
// by Discord for bot users. // 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. // Finally, start a single shard, and start listening to events.
// //
// Shards will automatically attempt to reconnect, and will perform // Shards will automatically attempt to reconnect, and will perform
// exponential backoff until it reconnects. // exponential backoff until it reconnects.
if let Err(why) = client.start() { if let Err(why) = client.start() {
println!("Client error: {:?}", why); println!("Client error: {:?}", why);
} }
} }
} }
fn start_daemons() { fn start_daemons(ctx1: &Context) {
thread::Builder::new() let ctx = ctx1.clone();
.spawn(|| { let territory_feed = thread::Builder::new()
.spawn(move || {
loop { 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(); .unwrap();
let ctx = ctx1.clone();
thread::Builder::new() let war_feed = thread::Builder::new()
.spawn(|| { .spawn(move || {
loop { 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(); .unwrap();
thread::Builder::new() let ctx = ctx1.clone();
.spawn(|| { let federation_feed = thread::Builder::new()
.spawn(move || {
loop { 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(); .unwrap();
println!("Started daemons."); println!("Started daemons.");
} }