Skip to content

Commit

Permalink
fixed improper logging on command registration
Browse files Browse the repository at this point in the history
  • Loading branch information
Inspirateur committed Mar 11, 2023
1 parent c8d59dd commit d292f34
Showing 1 changed file with 120 additions and 71 deletions.
191 changes: 120 additions & 71 deletions src/wordy_commands.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
use std::{io::{Cursor, Seek, SeekFrom}, sync::Arc};
use itertools::Itertools;
use log::{trace, info};
use crate::{
discord_util::{read_past, Attachment, Bot},
wordy::{read_message, register_guild, Wordy},
};
use anyhow::{anyhow, bail, Result};
use image::{write_buffer_with_format, ColorType, ImageOutputFormat};
use anyhow::{Result, bail, anyhow};
use serenity::{http::Http, model::{
prelude::{GuildId, Guild, Emoji},
application::interaction::application_command::ApplicationCommandInteraction,
Timestamp
}, prelude::Context};
use crate::{wordy::{Wordy, register_guild, read_message}, discord_util::{read_past, Bot, Attachment}};
use itertools::Itertools;
use log::{info, trace, warn};
use serenity::{
http::Http,
model::{
application::interaction::application_command::ApplicationCommandInteraction,
prelude::{Emoji, Guild, GuildId},
Timestamp,
},
prelude::Context,
};
use std::{
io::{Cursor, Seek, SeekFrom},
sync::Arc,
};
const READ_PAST: u64 = 1000;
const DAYS: i64 = 100;
const TOP_EMO: usize = 5;
Expand All @@ -17,36 +27,54 @@ fn emo_entry_mst(rank: usize, freq: f64, emos: Vec<Emoji>) -> String {
// limit to 20 emojis because the message gets too long otherwise
let ellipsis = if emos.len() > BOTTOM_EMO { "… " } else { "" };
let emo_str = emos.into_iter().take(BOTTOM_EMO).join("");
format!("{}. {}{}: {:.0}%", rank, emo_str, ellipsis, freq*100.0)
format!("{}. {}{}: {:.0}%", rank, emo_str, ellipsis, freq * 100.0)
}

fn emo_ranking_msg(emo_ranking: Vec<(Emoji, f64)>) -> String {
if emo_ranking.len() == 0 {
return "No entries :(".to_string();
}
let mut grouped_ranking = Vec::new();
for (freq, emos) in &emo_ranking.into_iter().group_by(|(_, freq)| (freq*100.0).round()/100.) {
for (freq, emos) in &emo_ranking
.into_iter()
.group_by(|(_, freq)| (freq * 100.0).round() / 100.)
{
grouped_ranking.push((freq, emos.map(|(emoji_id, _)| emoji_id).collect_vec()));
}
let toplen = if grouped_ranking.len() <= TOP_EMO+1 { TOP_EMO+1 } else { TOP_EMO };
let top = grouped_ranking.iter().cloned().enumerate().take(toplen)
.map(|(i, (freq, emos))| emo_entry_mst(i+1, freq, emos))
.join("\n");
if toplen == TOP_EMO+1 {
let toplen = if grouped_ranking.len() <= TOP_EMO + 1 {
TOP_EMO + 1
} else {
TOP_EMO
};
let top = grouped_ranking
.iter()
.cloned()
.enumerate()
.take(toplen)
.map(|(i, (freq, emos))| emo_entry_mst(i + 1, freq, emos))
.join("\n");
if toplen == TOP_EMO + 1 {
top
} else {
let (freq, emos) = grouped_ranking.pop().unwrap();
let bottom = emo_entry_mst(grouped_ranking.len(), freq, emos);
format!("{}\n...\n{}", top, bottom)
format!("{}\n...\n{}", top, bottom)
}
}

impl Wordy {
pub async fn cloud_command(&self, ctx: Context, command: ApplicationCommandInteraction) -> Result<()> {
pub async fn cloud_command(
&self,
ctx: Context,
command: ApplicationCommandInteraction,
) -> Result<()> {
if command.guild_id.is_none() {
bail!("Command wasn't invoked in a Guild.");
}
let member = command.member.as_ref().ok_or(anyhow!("Couldn't get member."))?;
let member = command
.member
.as_ref()
.ok_or(anyhow!("Couldn't get member."))?;
let image = self.cloud(&ctx, &member).await;
let mut img_file = Cursor::new(Vec::new());
write_buffer_with_format(
Expand All @@ -60,72 +88,87 @@ impl Wordy {
.unwrap();
img_file.seek(SeekFrom::Start(0)).unwrap();
let img_vec = img_file.into_inner();
ctx.http.answer(
&command,
"",
vec![Attachment {
file: img_vec,
filename: format!("WordCloud_{}.png", member.display_name())
}]
).await
ctx.http
.answer(
&command,
"",
vec![Attachment {
file: img_vec,
filename: format!("WordCloud_{}.png", member.display_name()),
}],
)
.await
}

pub async fn emojis_command(&self, ctx: Context, command: ApplicationCommandInteraction) -> Result<()> {
let guild_id = command.guild_id.as_ref().ok_or(anyhow!("Couldn't get member."))?;
pub async fn emojis_command(
&self,
ctx: Context,
command: ApplicationCommandInteraction,
) -> Result<()> {
let guild_id = command
.guild_id
.as_ref()
.ok_or(anyhow!("Couldn't get member."))?;
let emoji_rankings = self.emojis(*guild_id)?;
let png_msg = "Static emoji ranking:\n".to_string()
+ &emo_ranking_msg(emoji_rankings.png);
let gif_msg = "Animated emoji ranking:\n".to_string()
+ &emo_ranking_msg(emoji_rankings.gif);
let png_msg = "Static emoji ranking:\n".to_string() + &emo_ranking_msg(emoji_rankings.png);
let gif_msg =
"Animated emoji ranking:\n".to_string() + &emo_ranking_msg(emoji_rankings.gif);
ctx.http.answer(&command, &png_msg, vec![]).await?;
ctx.http.followup(&command, &gif_msg, vec![]).await
}

pub async fn info_command(&self, ctx: Context, command: ApplicationCommandInteraction) -> Result<()> {
ctx.http.answer(
&command,
"Made with ❤️ by Inspi#8989\n
Repository: <https://github.com/Inspirateur/wordy>",
vec![]
).await
pub async fn info_command(
&self,
ctx: Context,
command: ApplicationCommandInteraction,
) -> Result<()> {
ctx.http
.answer(
&command,
"Made with ❤️ by Inspi#8989\n
Repository: <https://github.com/Inspirateur/wordy>",
vec![],
)
.await
}

pub async fn register_commands(&self, http: Arc<Http>, guild_id: GuildId) {
trace!("Registering slash commands for Guild {}", guild_id);
if let Err(why) =
GuildId::set_application_commands(&guild_id, http, |commands| {
commands
.create_application_command(|command| {
command.name("cloud").description(
"Discover the word cloud that defines you !",
)
})
.create_application_command(|command| {
command.name("emojis").description(
"Recent emoji usage stats.",
)
})
.create_application_command(|command| {
command
.name("info")
.description("Information about this bot.")
})
}).await {
println!("Couldn't register slash commmands: {}", why);
trace!(target: "wordy", "Registering slash commands for Guild {}", guild_id);
if let Err(why) = GuildId::set_application_commands(&guild_id, http, |commands| {
commands
.create_application_command(|command| {
command
.name("cloud")
.description("Discover the word cloud that defines you !")
})
.create_application_command(|command| {
command
.name("emojis")
.description("Recent emoji usage stats.")
})
.create_application_command(|command| {
command
.name("info")
.description("Information about this bot.")
})
})
.await
{
warn!(target: "wordy", "Couldn't register slash commmands: {}", why);
};
}

pub async fn register_guild(&self, http: Arc<Http>, guild: Guild) {
// only read messages that are less than 100 days old
let cutoff_date = Timestamp::from_unix_timestamp(
Timestamp::now().unix_timestamp() - 3600*24*DAYS
).unwrap();
let cutoff_date =
Timestamp::from_unix_timestamp(Timestamp::now().unix_timestamp() - 3600 * 24 * DAYS)
.unwrap();
if let Ok(channels) = guild.channels(&http).await {
if !register_guild(
&guild,
self.idioms.clone(),
self.recents_emos.clone(),
self.servers_emos.clone()
&guild,
self.idioms.clone(),
self.recents_emos.clone(),
self.servers_emos.clone(),
) {
return;
}
Expand All @@ -138,7 +181,13 @@ impl Wordy {
let messages = read_past(&http, &channel, READ_PAST, cutoff_date).await;
let len = messages.len();
for message in messages {
read_message(guild.id, message, idioms.clone(), recents_emos.clone(), servers_emos.clone());
read_message(
guild.id,
message,
idioms.clone(),
recents_emos.clone(),
servers_emos.clone(),
);
}
if len > 0 {
info!(target: "wordy", "Read {} past messages in {}/{}", len, guild.name, channel.name())
Expand All @@ -147,4 +196,4 @@ impl Wordy {
});
}
}
}
}

0 comments on commit d292f34

Please sign in to comment.