diff options
Diffstat (limited to 'src/commands/meme')
| -rw-r--r-- | src/commands/meme/create.rs | 104 | ||||
| -rw-r--r-- | src/commands/meme/delete.rs | 29 | ||||
| -rw-r--r-- | src/commands/meme/history.rs | 151 | ||||
| -rw-r--r-- | src/commands/meme/invoke.rs | 149 | ||||
| -rw-r--r-- | src/commands/meme/mod.rs | 75 |
5 files changed, 226 insertions, 282 deletions
diff --git a/src/commands/meme/create.rs b/src/commands/meme/create.rs index 9aff370..cad9bfc 100644 --- a/src/commands/meme/create.rs +++ b/src/commands/meme/create.rs @@ -2,25 +2,12 @@ use std::process::Stdio; use anyhow::anyhow; use diesel::result::Error as DieselError; -use lazy_static::lazy_static; use log::{ debug, error, warn, }; -use serenity::{ - all::ReactionType, - framework::standard::{ - macros::command, - Args, - CommandError, - CommandResult, - Delimiter, - }, - futures::TryFutureExt, - model::channel::Message, - prelude::*, -}; +use serenity::all::ReactionType; use tap::Pipe; use tokio::{ io::AsyncReadExt, @@ -37,20 +24,16 @@ use crate::{ }, parse_times, util, + PoiseContext, FFMPEG_COMMAND, }; -lazy_static! { - static ref DELIMS: Vec<Delimiter> = vec![' '.into(), '\n'.into(), '\t'.into()]; -} - -#[command] -pub async fn addmeme(ctx: &Context, msg: &Message, args: Args) -> CommandResult { - let mut args = Args::new(args.rest(), DELIMS.as_ref()); - - let title = args.single_quoted::<String>()?; - let text = args.rest().to_owned(); - +#[poise::command(slash_command, prefix_command, guild_only, category = "memes")] +pub async fn addmeme( + ctx: PoiseContext<'_>, + title: String, + #[rest] text: String, +) -> anyhow::Result<()> { let text = if text.is_empty() { None } else { @@ -59,20 +42,21 @@ pub async fn addmeme(ctx: &Context, msg: &Message, args: Args) -> CommandResult let mut conn = connection().await?; - let image = msg.attachments.first(); + let image = util::msg(ctx).and_then(|msg| msg.attachments.first()); if image.is_none() && text.is_none() { warn!("tried to create non-audio meme with no image or text"); - return util::send(ctx, msg.channel_id, "hahAA it's empty xdddd", msg.tts) - .map_err(CommandError::from) - .await; + + util::reply(ctx, "hahAA it's empty xdddd").await?; + return Ok(()); } let mut image_id = None; if let Some(att) = image { let data = att.download().await?; - image_id = Some(Image::create(&mut conn, &att.filename, data, msg.author.id.get()).await?); + image_id = + Some(Image::create(&mut conn, &att.filename, data, ctx.author().id.get()).await?); }; let save_result = NewMeme { @@ -82,24 +66,25 @@ pub async fn addmeme(ctx: &Context, msg: &Message, args: Args) -> CommandResult audio_id: None, metadata_id: 0, } - .save(&mut conn, msg.author.id.get()) + .save(&mut conn, ctx.author().id.get()) .await .map(|_| {}); use diesel::result::DatabaseErrorKind; match save_result { Ok(_) => { - msg.react(&ctx, ReactionType::Unicode("👌".to_string())).await?; + util::react(ctx, ReactionType::Unicode("👌".to_string())).await?; }, Err(e) => { if let Some(DieselError::DatabaseError(DatabaseErrorKind::UniqueViolation, _)) = e.downcast_ref::<DieselError>() { error!("tried to create meme that already exists"); - msg.react(&ctx, ReactionType::Unicode("❌".to_owned())).await?; - return util::send(ctx, msg.channel_id, "that meme already exists", msg.tts) - .map_err(CommandError::from) - .await; + + util::react(ctx, ReactionType::Unicode("❌".to_owned())).await?; + util::reply(ctx, "that meme already exists").await?; + + return Ok(()); } return Err(e.into()); @@ -109,19 +94,19 @@ pub async fn addmeme(ctx: &Context, msg: &Message, args: Args) -> CommandResult Ok(()) } -#[command] -pub async fn addaudiomeme(ctx: &Context, msg: &Message, args: Args) -> CommandResult { +#[poise::command(slash_command, prefix_command, guild_only, category = "memes")] +pub async fn addaudiomeme( + ctx: PoiseContext<'_>, + title: String, + audio_str: String, + #[rest] rest: String, +) -> anyhow::Result<()> { debug!("running addaudiomeme"); - let mut args = Args::new(args.rest(), DELIMS.as_ref()); - - let title = args.single_quoted::<String>()?; - let audio_str = args.single_quoted::<String>()?; - let elems = audio_str.split_whitespace().collect::<Vec<_>>(); if elems.is_empty() { - util::send(ctx, msg.channel_id, "are you stupid", msg.tts).await?; + util::reply(ctx, "are you stupid").await?; return Err(anyhow!("no audio link was provided").into()); } @@ -168,23 +153,23 @@ pub async fn addaudiomeme(ctx: &Context, msg: &Message, args: Args) -> CommandRe let mut audio_reader = ffmpeg_command.stdout.unwrap(); - let text = args.rest().to_owned(); - let text = if text.is_empty() { + let text = if rest.is_empty() { None } else { - Some(text) + Some(rest) }; let mut conn = connection().await?; - let image_att = msg.attachments.first().ok_or(anyhow!("no attachment")); + let image_att = + util::msg(ctx).and_then(|x| x.attachments.first()).ok_or(anyhow!("no attachment")); let mut image_id = None; if let Ok(att) = image_att { let data = att.download().await?; image_id = - Image::create(&mut conn, &att.filename, data, msg.author.id.get()).await?.pipe(Some); + Image::create(&mut conn, &att.filename, data, ctx.author().id.get()).await?.pipe(Some); } let mut audio_data = Vec::new(); @@ -193,12 +178,12 @@ pub async fn addaudiomeme(ctx: &Context, msg: &Message, args: Args) -> CommandRe if bytes == 0 { debug!("read 0 bytes from audio reader"); - return util::send(ctx, msg.channel_id, "🔇🔇🔇🔕🔕🔕🔕🔕🔇🔕🔕🔇🔕🔕📣📢📣📢📣", msg.tts) - .map_err(CommandError::from) - .await; + + util::reply(ctx, "🔇🔇🔇🔕🔕🔕🔕🔕🔇🔕🔕🔇🔕🔕📣📢📣📢📣").await?; + return Ok(()); } - let audio_id = Audio::create(&mut conn, audio_data, msg.author.id.get()).await?; + let audio_id = Audio::create(&mut conn, audio_data, ctx.author().id.get()).await?; let save_result = NewMeme { title, @@ -207,24 +192,25 @@ pub async fn addaudiomeme(ctx: &Context, msg: &Message, args: Args) -> CommandRe audio_id: Some(audio_id), metadata_id: 0, } - .save(&mut conn, msg.author.id.get()) + .save(&mut conn, ctx.author().id.get()) .await .map(|_| {}); use diesel::result::DatabaseErrorKind; match save_result { Ok(_) => { - msg.react(&ctx, ReactionType::Unicode("👌".to_owned())).await?; + util::react(ctx, ReactionType::Unicode("👌".to_owned())).await?; }, Err(e) => { if let Some(DieselError::DatabaseError(DatabaseErrorKind::UniqueViolation, _)) = e.downcast_ref::<DieselError>() { error!("tried to create meme that already exists"); - msg.react(&ctx, ReactionType::Unicode("❌".to_owned())).await?; - return util::send(ctx, msg.channel_id, "that meme already exists", msg.tts) - .map_err(CommandError::from) - .await; + + util::react(ctx, ReactionType::Unicode("❌".to_owned())).await?; + util::reply(ctx, "that meme already exists").await?; + + return Ok(()); } return Err(e.into()); diff --git a/src/commands/meme/delete.rs b/src/commands/meme/delete.rs index 6af1b6b..25ddf0d 100644 --- a/src/commands/meme/delete.rs +++ b/src/commands/meme/delete.rs @@ -3,42 +3,33 @@ use diesel::{ NotFound, }; use log::info; -use serenity::{ - all::ReactionType, - framework::standard::{ - macros::command, - Args, - CommandResult, - }, - model::channel::Message, - prelude::*, -}; +use serenity::all::ReactionType; use crate::{ db::{ connection, delete_meme, }, + msg, util, + PoiseContext, }; -#[command] -#[aliases("delmem")] -pub async fn delmeme(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { - let title = args.single_quoted::<String>()?; - +#[poise::command(slash_command, prefix_command, guild_only, category = "memes", aliases("delmem"))] +pub async fn delmeme(ctx: PoiseContext<'_>, title: String) -> anyhow::Result<()> { let mut conn = connection().await?; - match delete_meme(&mut conn, &title, msg.author.id.get()).await { + match delete_meme(&mut conn, &title, ctx.author().id.get()).await { Ok(_) => { - msg.react(ctx, ReactionType::Unicode("💀".to_owned())).await?; + util::react(ctx, ReactionType::Unicode("💀".to_owned())).await?; Ok(()) }, Err(e) => { if let Some(NotFound) = e.downcast_ref::<DieselError>() { - msg.react(&ctx, ReactionType::Unicode("❓".to_owned())).await?; info!("attempted to delete nonexistent meme: '{}'", title); - util::send(ctx, msg.channel_id, "nice try", msg.tts).await?; + + util::react(ctx, ReactionType::Unicode("❓".to_owned())).await?; + util::reply(ctx, "nice try").await?; return Ok(()); } diff --git a/src/commands/meme/history.rs b/src/commands/meme/history.rs index edc75cd..cfd78df 100644 --- a/src/commands/meme/history.rs +++ b/src/commands/meme/history.rs @@ -1,4 +1,3 @@ -use anyhow::anyhow; use diesel::{ result::Error as DieselError, NotFound, @@ -11,18 +10,10 @@ use log::{ info, }; use serenity::{ - framework::standard::{ - macros::command, - Args, - CommandError, - CommandResult, - }, futures::{ StreamExt, - TryFutureExt, TryStreamExt, }, - model::channel::Message, prelude::*, }; use tap::Pipe; @@ -32,6 +23,7 @@ use timeago::{ }; use crate::{ + commands::game::get_user_id, db::{ self, connection, @@ -40,6 +32,7 @@ use crate::{ Metadata, }, util, + PoiseContext, CONFIG, }; @@ -55,9 +48,14 @@ lazy_static! { static CLEAN_DATE_FORMAT: &str = "%b %-e %Y"; -#[command] -#[aliases("what", "hwaet", "hwæt")] -pub async fn wat(ctx: &Context, msg: &Message, _: Args) -> CommandResult { +#[poise::command( + slash_command, + prefix_command, + guild_only, + category = "memes", + aliases("what", "hwaet", "hwæt") +)] +pub async fn wat(ctx: PoiseContext<'_>) -> anyhow::Result<()> { let mut conn = connection().await?; let record = match InvocationRecord::last(&mut conn).await { @@ -65,12 +63,12 @@ pub async fn wat(ctx: &Context, msg: &Message, _: Args) -> CommandResult { Err(e) => { if let Some(NotFound) = e.downcast_ref::<DieselError>() { info!("found no memes in history"); - return util::send(ctx, msg.channel_id, "no one has ever memed before", msg.tts) - .map_err(CommandError::from) - .await; + + util::reply(ctx, "no one has ever memed before").await?; + return Ok(()); } - util::send(ctx, msg.channel_id, "BAD MEME BAD MEME", msg.tts).await?; + util::reply(ctx, "BAD MEME BAD MEME").await?; return Err(e.into()); }, }; @@ -82,44 +80,41 @@ pub async fn wat(ctx: &Context, msg: &Message, _: Args) -> CommandResult { let metadata = Metadata::find(&mut conn, meme.metadata_id).await?; let author = CONFIG.discord.guild().member(&ctx, metadata.created_by as u64).await?; - util::send( + util::reply( ctx, - msg.channel_id, &format!( "that was \"{}\" by {} ({})", meme.title, author.mention(), metadata.created.date().format(CLEAN_DATE_FORMAT) ), - msg.tts, ) - .await? + .await?; }, Err(e) => { if let Some(NotFound) = e.downcast_ref::<DieselError>() { info!("last meme not found in database"); - return util::send(ctx, msg.channel_id, "heuueueeeeh?", msg.tts) - .await - .map_err(CommandError::from); + + util::reply(ctx, "heuueueeeeh?").await?; + return Ok(()); } - util::send(ctx, msg.channel_id, "do i look like i know what a jpeg is", msg.tts) - .await?; + util::reply(ctx, "do i look like i know what a jpeg is").await?; return Err(e.into()); }, }; - meme.map(|_| {}).map_err(CommandError::from) + let _meme = meme?; + Ok(()) } -#[command] -#[aliases("hist")] -pub async fn history(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { - let n = args.single_quoted::<usize>().unwrap_or(CONFIG.default_hist); - +#[poise::command(slash_command, prefix_command, guild_only, category = "memes", aliases("hist"))] +pub async fn history(ctx: PoiseContext<'_>, n: Option<usize>) -> anyhow::Result<()> { + let n = n.unwrap_or(CONFIG.default_hist); + if n > CONFIG.max_hist { debug!("user requested more than MAX_HIST ({}) items from history", CONFIG.max_hist); - util::send(ctx, msg.channel_id, "YER PUSHIN ME OVER THE FUCKIN LINE", true).await?; + util::reply(ctx, "YER PUSHIN ME OVER THE FUCKIN LINE").await?; } let n = n.min(CONFIG.max_hist); @@ -131,9 +126,9 @@ pub async fn history(ctx: &Context, msg: &Message, mut args: Args) -> CommandRes if records.is_empty() { info!("no memes in history"); - return util::send(ctx, msg.channel_id, "i don't remember anything :(", msg.tts) - .map_err(CommandError::from) - .await; + util::reply(ctx, "i don't remember anything :(").await?; + + return Ok(()); } info!("reporting meme history (len {})", n); @@ -198,19 +193,19 @@ pub async fn history(ctx: &Context, msg: &Message, mut args: Args) -> CommandRes }, }; - Result::<_, CommandError>::Ok(result) + anyhow::Ok(result) }) .try_collect::<Vec<String>>() .await?; let resp = resp.join("\n"); + util::reply(ctx, resp).await?; - util::send(ctx, msg.channel_id, &resp, false).await.map_err(CommandError::from) + Ok(()) } -#[command] -#[aliases("stat")] -pub async fn stats(ctx: &Context, msg: &Message, _: Args) -> CommandResult { +#[poise::command(slash_command, prefix_command, guild_only, category = "memes", aliases("stat"))] +pub async fn stats(ctx: PoiseContext<'_>) -> anyhow::Result<()> { use db; use serenity::model::{ id::UserId, @@ -277,11 +272,12 @@ and *{}* was the most-memed overall ({})"#, stats.most_popular_meme_overall_count, ); - util::send(ctx, msg.channel_id, s, msg.tts).map_err(CommandError::from).await + util::reply(ctx, s).await?; + Ok(()) } -#[command] -pub async fn memers(ctx: &Context, msg: &Message, _args: Args) -> CommandResult { +#[poise::command(slash_command, prefix_command, guild_only, category = "memes")] +pub async fn memers(ctx: PoiseContext<'_>) -> anyhow::Result<()> { use serenity::model::id::UserId; let s = db::memers() @@ -302,25 +298,25 @@ pub async fn memers(ctx: &Context, msg: &Message, _args: Args) -> CommandResult info.most_used_meme_count, ); - Result::<_, CommandError>::Ok(res) + anyhow::Ok(res) }) .try_collect::<Vec<String>>() .await? .into_iter() .join("\n"); - util::send(ctx, msg.channel_id, &s, msg.tts).map_err(CommandError::from).await + util::reply(ctx, s).await?; + + Ok(()) } -#[command] -pub async fn query(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { +#[poise::command(prefix_command, guild_only, category = "memes")] +pub async fn query(ctx: PoiseContext<'_>, rest: util::RestVec) -> anyhow::Result<()> { use regex::Regex; use serenity::model::id::UserId; - use std::borrow::Borrow; use crate::{ db, - game::get_user_id, CONFIG, }; @@ -329,42 +325,31 @@ pub async fn query(ctx: &Context, msg: &Message, mut args: Args) -> CommandResul static ref AGE_REGEX: Regex = Regex::new(r"(?i)(?:age|order)=(.*)").unwrap(); } - let creator: Option<u64> = { - let guild = - msg.channel_id.to_channel(&ctx).await?.guild().ok_or(anyhow!("couldn't find guild"))?; + let mut rest = rest.into_inner(); - let guild = guild.guild(&ctx).ok_or(anyhow!("couldn't find guild"))?; + let creator: Option<u64> = try { + let fst = rest.first()?; + let captures = CREATOR_REGEX.captures(fst)?; + let creator = captures.get(1)?.as_str().to_owned(); - let creator = args.quoted().current().map(|s| CREATOR_REGEX.is_match(s)).unwrap_or(false); - if creator { - args.single_quoted::<String>() - .ok() - .and_then(|s| { - CREATOR_REGEX.captures(&s).and_then(|c| c.get(1)).map(|x| x.as_str().to_owned()) - }) - .and_then(|s| get_user_id(guild.borrow(), s).ok().map(UserId::get)) - } else { - None - } + let guild = ctx.guild()?; + let user_id = get_user_id(&guild, creator).ok()?.get(); + rest.pop(); + + user_id }; - let order = { - let order = args.quoted().current().map(|s| AGE_REGEX.is_match(s)).unwrap_or(false); + let order: Option<String> = try { + let fst = rest.first()?; + let captures = AGE_REGEX.captures(fst)?; + let order = captures.get(1)?.as_str().to_owned(); - if order { - args.single_quoted::<String>() - .ok() - .and_then(|s| { - AGE_REGEX.captures(&s).and_then(|c| c.get(1)).map(|x| x.as_str().to_owned()) - }) - .map(|s: String| s.contains("new")) - .unwrap_or(true) - } else { - true - } + order }; - let iter = db::query_meme(args.rest(), creator, order).await?.into_iter(); + let order = order.is_some_and(|o| o.contains("new")); + + let iter = db::query_meme(rest.join(" "), creator, order).await?.into_iter(); let result = iter .pipe(serenity::futures::stream::iter) @@ -380,7 +365,7 @@ pub async fn query(ctx: &Context, msg: &Message, mut args: Args) -> CommandResul meme.content.map_or(0, |s| s.len()), meme.image_id.map_or("NO", |_s| "YES"), meme.audio_id.map_or("NO", |_s| "YES"), - )) as Result<String, CommandError> + )) as anyhow::Result<String> }) .try_collect::<Vec<String>>() .await; @@ -401,10 +386,10 @@ pub async fn query(ctx: &Context, msg: &Message, mut args: Args) -> CommandResul if result.is_empty() { info!("no memes matched query"); - return util::send(ctx, msg.channel_id, "no match".to_owned(), msg.tts) - .map_err(CommandError::from) - .await; + util::reply(ctx, "no match").await?; + return Ok(()); } - util::send(ctx, msg.channel_id, &result, msg.tts).map_err(CommandError::from).await + util::reply(ctx, result).await?; + Ok(()) } diff --git a/src/commands/meme/invoke.rs b/src/commands/meme/invoke.rs index 1400452..e399e82 100644 --- a/src/commands/meme/invoke.rs +++ b/src/commands/meme/invoke.rs @@ -2,19 +2,7 @@ use diesel::{ result::Error as DieselError, NotFound, }; -use itertools::Itertools; use log::info; -use serenity::{ - framework::standard::{ - macros::command, - Args, - CommandError, - CommandResult, - }, - futures::TryFutureExt, - model::channel::Message, - prelude::*, -}; use crate::{ commands::meme::send_meme, @@ -25,42 +13,49 @@ use crate::{ InvocationRecord, }, util, + PoiseContext, }; -#[command] -#[aliases("mem")] -pub async fn meme(ctx: &Context, msg: &Message, args: Args) -> CommandResult { - _meme(ctx, msg, args, AudioPlayback::Optional).await +#[poise::command(slash_command, prefix_command, guild_only, category = "memes", aliases("mem"))] +pub async fn meme(ctx: PoiseContext<'_>, #[rest] rest: String) -> anyhow::Result<()> { + _meme(ctx, rest, AudioPlayback::Optional).await } -#[command] -pub async fn omen(ctx: &Context, msg: &Message, _args: Args) -> CommandResult { - let args = Args::new("", &[]); - _meme(ctx, msg, args, AudioPlayback::Optional).await +#[poise::command(slash_command, prefix_command, guild_only, category = "memes")] +pub async fn omen(ctx: PoiseContext<'_>) -> anyhow::Result<()> { + _meme(ctx, "", AudioPlayback::Optional).await } -#[command] -pub async fn silentomen(ctx: &Context, msg: &Message, _args: Args) -> CommandResult { - let args = Args::new("", &[]); - _meme(ctx, msg, args, AudioPlayback::Prohibited).await +#[poise::command(slash_command, prefix_command, guild_only, category = "memes")] +pub async fn silentomen(ctx: PoiseContext<'_>) -> anyhow::Result<()> { + _meme(ctx, "", AudioPlayback::Prohibited).await } -#[command] -pub async fn audioomen(ctx: &Context, msg: &Message, _args: Args) -> CommandResult { - let args = Args::new("", &[]); - _meme(ctx, msg, args, AudioPlayback::Required).await +#[poise::command(slash_command, prefix_command, guild_only, category = "memes")] +pub async fn audioomen(ctx: PoiseContext<'_>) -> anyhow::Result<()> { + _meme(ctx, "", AudioPlayback::Required).await } -#[command] -#[aliases("audiomeme", "audiomem")] -pub async fn audio_meme(ctx: &Context, msg: &Message, args: Args) -> CommandResult { - _meme(ctx, msg, args, AudioPlayback::Required).await +#[poise::command( + slash_command, + prefix_command, + guild_only, + category = "memes", + aliases("audiomeme", "audiomem") +)] +pub async fn audio_meme(ctx: PoiseContext<'_>, #[rest] rest: String) -> anyhow::Result<()> { + _meme(ctx, rest, AudioPlayback::Required).await } -#[command] -#[aliases("silentmeme", "silentmem")] -pub async fn silent_meme(ctx: &Context, msg: &Message, args: Args) -> CommandResult { - _meme(ctx, msg, args, AudioPlayback::Prohibited).await +#[poise::command( + slash_command, + prefix_command, + guild_only, + category = "memes", + aliases("silentmeme", "silentmem") +)] +pub async fn silent_meme(ctx: PoiseContext<'_>, #[rest] rest: String) -> anyhow::Result<()> { + _meme(ctx, rest, AudioPlayback::Prohibited).await } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -71,21 +66,20 @@ enum AudioPlayback { } async fn _meme( - ctx: &Context, - msg: &Message, - args: Args, + ctx: PoiseContext<'_>, + args: impl AsRef<str>, audio_playback: AudioPlayback, -) -> CommandResult { +) -> anyhow::Result<()> { + let args = args.as_ref().trim(); + if args.is_empty() || audio_playback != AudioPlayback::Optional { - return rand_meme(ctx, msg, audio_playback).await; + return rand_meme(ctx, audio_playback).await; } - let search = args.raw().join(" "); - let mut conn = connection().await?; - let mem = match find_meme(&mut conn, search).await { + let mem = match find_meme(&mut conn, args).await { Ok(x) => { - InvocationRecord::create(&mut conn, msg.author.id.get(), msg.id.get(), x.id, false) + InvocationRecord::create(&mut conn, ctx.author().id.get(), ctx.id(), x.id, false) .await?; x @@ -93,27 +87,23 @@ async fn _meme( Err(e) => { return if let Some(NotFound) = e.downcast_ref::<DieselError>() { info!("requested meme not found in database"); - util::send(ctx, msg.channel_id, "c'mon baby, guesstimate", msg.tts) - .await - .map_err(CommandError::from) + + util::reply(ctx, "c'mon baby, guesstimate").await?; + Ok(()) } else { - util::send(ctx, msg.channel_id, "what in ryan's name", msg.tts).await?; + util::reply(ctx, "what in ryan's name").await?; Err(e.into()) }; }, }; - send_meme(ctx, &mem, &mut conn, msg).await + send_meme(ctx, &mem, &mut conn).await } -async fn rand_meme( - ctx: &Context, - message: &Message, - audio_playback: AudioPlayback, -) -> CommandResult { +async fn rand_meme(ctx: PoiseContext<'_>, audio_playback: AudioPlayback) -> anyhow::Result<()> { let mut conn = connection().await?; - let should_audio = util::users_listening(ctx).await?; + let should_audio = util::users_listening(ctx.serenity_context()).await?; let mem = match audio_playback { AudioPlayback::Required => db::rand_audio_meme(&mut conn).await, @@ -123,56 +113,53 @@ async fn rand_meme( match mem { Ok(mem) => { - InvocationRecord::create( - &mut conn, - message.author.id.get(), - message.id.get(), - mem.id, - true, - ) - .await?; - send_meme(ctx, &mem, &mut conn, message).await?; + InvocationRecord::create(&mut conn, ctx.author().id.get(), ctx.id(), mem.id, true) + .await?; + send_meme(ctx, &mem, &mut conn).await?; Ok(()) }, Err(e) => { if let Some(NotFound) = e.downcast_ref::<DieselError>() { info!("random meme not found"); - return util::send(ctx, message.channel_id, "i don't know any :(", message.tts) - .map_err(CommandError::from) - .await; + + util::reply(ctx, "i don't know any :(").await?; + return Ok(()); } - util::send(ctx, message.channel_id, "HELP", message.tts).await?; + util::reply(ctx, "HELP").await?; Err(e.into()) }, } } -#[command] -#[aliases("rarememe", "raremem")] -pub async fn rare_meme(ctx: &Context, msg: &Message, _args: Args) -> CommandResult { - let should_audio = util::users_listening(ctx).await?; +#[poise::command( + slash_command, + prefix_command, + guild_only, + category = "memes", + aliases("raremem", "rarememe") +)] +pub async fn rare_meme(ctx: PoiseContext<'_>) -> anyhow::Result<()> { + let should_audio = util::users_listening(ctx.serenity_context()).await?; let mut conn = connection().await?; let meme = db::rare_meme(&mut conn, should_audio).await; match meme { Ok(meme) => { - InvocationRecord::create(&mut conn, msg.author.id.get(), msg.id.get(), meme.id, true) + InvocationRecord::create(&mut conn, ctx.author().id.get(), ctx.id(), meme.id, true) .await?; - send_meme(ctx, &meme, &mut conn, msg).await + send_meme(ctx, &meme, &mut conn).await }, Err(e) => { if let Some(NotFound) = e.downcast_ref::<DieselError>() { info!("rare meme not found"); - return util::send(ctx, msg.channel_id, "i don't know any :(", msg.tts) - .map_err(CommandError::from) - .await; + util::reply(ctx, "i don't know any :(").await?; + + return Ok(()); } - util::send(ctx, msg.channel_id, "THE MEME MARKET IS IN FREEFALL", msg.tts) - .map_err(CommandError::from) - .await?; + util::reply(ctx, "THE MEME MARKET IS IN FREEFALL").await?; Err(e.into()) }, diff --git a/src/commands/meme/mod.rs b/src/commands/meme/mod.rs index cfe02ee..0108219 100644 --- a/src/commands/meme/mod.rs +++ b/src/commands/meme/mod.rs @@ -8,12 +8,6 @@ use serenity::{ CreateAttachment, CreateMessage, }, - framework::standard::{ - macros::group, - CommandResult, - }, - model::channel::Message, - prelude::*, }; use songbird::input::{ core::{ @@ -26,53 +20,54 @@ use songbird::input::{ Input, }; +pub use self::{ + create::*, + delete::*, + history::*, + invoke::*, +}; use crate::{ - commands::songbird, + commands::playback::songbird, db::{ Audio, Meme, }, + msg, + util, + PoiseContext, CONFIG, }; -pub use self::{ - create::*, - delete::*, - history::*, - invoke::*, -}; - mod create; mod delete; mod history; mod invoke; -#[group] -#[commands( - meme, - audio_meme, - silent_meme, - omen, - audioomen, - silentomen, - addmeme, - addaudiomeme, - delmeme, - wat, - stats, - history, - rare_meme, - memers, - query -)] -struct Memes; +pub fn commands() -> Vec<poise::Command<crate::PoiseData, anyhow::Error>> { + vec![ + meme(), + silent_meme(), + audio_meme(), + rare_meme(), + omen(), + silentomen(), + audioomen(), + addmeme(), + addaudiomeme(), + delmeme(), + history(), + stats(), + memers(), + wat(), + query(), + ] +} async fn send_meme( - ctx: &Context, + ctx: PoiseContext<'_>, t: &Meme, conn: &mut AsyncPgConnection, - msg: &Message, -) -> CommandResult { +) -> anyhow::Result<()> { let should_tts = t.content.as_ref().map(|t| !t.is_empty()).unwrap_or(false) && random::<u32>() % 25 == 0; @@ -95,12 +90,12 @@ async fn send_meme( let image = image?; let att = CreateAttachment::bytes(image.data.as_slice(), &image.filename); - msg.channel_id.send_files(ctx, vec![att], cmsg).await?; + ctx.channel_id().send_files(ctx, vec![att], cmsg).await?; }, None => { if t.content.is_some() { - msg.channel_id.send_message(ctx, cmsg).await?; + ctx.channel_id().send_message(ctx, cmsg).await?; } }, }; @@ -108,7 +103,7 @@ async fn send_meme( if let Some(audio) = audio { let audio = audio?; - let (_sb, call) = songbird(ctx, msg).await?; + let (_sb, call) = songbird(ctx).await?; let mut call = call.lock().await; if call.current_channel().is_none() { @@ -117,7 +112,7 @@ async fn send_meme( call.enqueue_input(Input::Lazy(Box::new(audio))).await; - msg.react(ctx, ReactionType::Unicode("📣".to_owned())).await?; + util::react(ctx, ReactionType::Unicode("📣".to_owned())).await?; } Ok(()) |
