Rename gifs to media

Signed-off-by: trivernis <trivernis@protonmail.com>
pull/26/head
trivernis 3 years ago
parent 32ba3d8bf0
commit 4d67dce3cd
Signed by: Trivernis
GPG Key ID: DFFFCC2C7A02DB45

2
Cargo.lock generated

@ -195,7 +195,7 @@ dependencies = [
[[package]] [[package]]
name = "bot-database" name = "bot-database"
version = "0.5.0" version = "0.6.0"
dependencies = [ dependencies = [
"chrono", "chrono",
"diesel", "diesel",

@ -1,6 +1,6 @@
[package] [package]
name = "bot-database" name = "bot-database"
version = "0.5.0" version = "0.6.0"
authors = ["trivernis <trivernis@protonmail.com>"] authors = ["trivernis <trivernis@protonmail.com>"]
edition = "2018" edition = "2018"

@ -0,0 +1,2 @@
-- This file should undo anything in `up.sql`
ALTER TABLE media RENAME TO gifs;

@ -0,0 +1,2 @@
-- Your SQL goes here
ALTER TABLE gifs RENAME TO media;

@ -9,42 +9,42 @@ use crate::Database;
impl Database { impl Database {
/// Returns a list of all gifs in the database /// Returns a list of all gifs in the database
pub async fn get_all_gifs(&self) -> DatabaseResult<Vec<Gif>> { pub async fn get_all_media(&self) -> DatabaseResult<Vec<Media>> {
use gifs::dsl; use media::dsl;
log::debug!("Loading all gifs from the database"); log::debug!("Loading all gifs from the database");
let gifs: Vec<Gif> = dsl::gifs.load_async::<Gif>(&self.pool).await?; let gifs: Vec<Media> = dsl::media.load_async::<Media>(&self.pool).await?;
Ok(gifs) Ok(gifs)
} }
/// Returns a list of gifs by assigned category /// Returns a list of gifs by assigned category
pub async fn get_gifs_by_category(&self, category: &str) -> DatabaseResult<Vec<Gif>> { pub async fn get_media_by_category(&self, category: &str) -> DatabaseResult<Vec<Media>> {
use gifs::dsl; use media::dsl;
log::debug!("Searching for gifs in category '{}'", category); log::debug!("Searching for gifs in category '{}'", category);
let gifs: Vec<Gif> = dsl::gifs let gifs: Vec<Media> = dsl::media
.filter(dsl::category.eq(category)) .filter(dsl::category.eq(category))
.load_async::<Gif>(&self.pool) .load_async::<Media>(&self.pool)
.await?; .await?;
Ok(gifs) Ok(gifs)
} }
/// Adds a gif to the database /// Adds a gif to the database
pub async fn add_gif( pub async fn add_media(
&self, &self,
url: &str, url: &str,
category: Option<String>, category: Option<String>,
name: Option<String>, name: Option<String>,
) -> DatabaseResult<()> { ) -> DatabaseResult<()> {
use gifs::dsl; use media::dsl;
log::debug!( log::debug!(
"Inserting gif with url '{}' and name {:?} and category {:?}", "Inserting gif with url '{}' and name {:?} and category {:?}",
url, url,
name, name,
category category
); );
insert_into(dsl::gifs) insert_into(dsl::media)
.values(GifInsert { .values(MediaInsert {
url: url.to_string(), url: url.to_string(),
name, name,
category, category,

@ -1,16 +1,16 @@
pub use ephemeral_messages::*; pub use ephemeral_messages::*;
pub use gifs::*;
pub use guild_playlists::*; pub use guild_playlists::*;
pub use guild_playlists::*; pub use guild_playlists::*;
pub use media::*;
pub use statistics::*; pub use statistics::*;
pub use youtube_songs::*; pub use youtube_songs::*;
use crate::PoolConnection; use crate::PoolConnection;
mod ephemeral_messages; mod ephemeral_messages;
mod gifs;
mod guild_playlists; mod guild_playlists;
mod guild_settings; mod guild_settings;
mod media;
mod statistics; mod statistics;
mod youtube_songs; mod youtube_songs;

@ -32,7 +32,7 @@ pub struct GuildPlaylistInsert {
} }
#[derive(Queryable, Debug, Clone)] #[derive(Queryable, Debug, Clone)]
pub struct Gif { pub struct Media {
pub id: i64, pub id: i64,
pub category: Option<String>, pub category: Option<String>,
pub name: Option<String>, pub name: Option<String>,
@ -40,8 +40,8 @@ pub struct Gif {
} }
#[derive(Insertable, Debug)] #[derive(Insertable, Debug)]
#[table_name = "gifs"] #[table_name = "media"]
pub struct GifInsert { pub struct MediaInsert {
pub category: Option<String>, pub category: Option<String>,
pub name: Option<String>, pub name: Option<String>,
pub url: String, pub url: String,

@ -6,15 +6,6 @@ table! {
} }
} }
table! {
gifs (id) {
id -> Int8,
category -> Nullable<Varchar>,
name -> Nullable<Varchar>,
url -> Varchar,
}
}
table! { table! {
guild_playlists (guild_id, name) { guild_playlists (guild_id, name) {
guild_id -> Int8, guild_id -> Int8,
@ -31,6 +22,15 @@ table! {
} }
} }
table! {
media (id) {
id -> Int8,
category -> Nullable<Varchar>,
name -> Nullable<Varchar>,
url -> Varchar,
}
}
table! { table! {
statistics (id) { statistics (id) {
id -> Int8, id -> Int8,
@ -56,9 +56,9 @@ table! {
allow_tables_to_appear_in_same_query!( allow_tables_to_appear_in_same_query!(
ephemeral_messages, ephemeral_messages,
gifs,
guild_playlists, guild_playlists,
guild_settings, guild_settings,
media,
statistics, statistics,
youtube_songs, youtube_songs,
); );

@ -8,14 +8,14 @@ use serenity::framework::standard::{Args, CommandResult};
use serenity::model::channel::Message; use serenity::model::channel::Message;
#[command] #[command]
#[description("Simple ping test command")] #[description("Adds media to the database")]
#[usage("<url> [<category>] [<name>]")] #[usage("<url> [<category>] [<name>]")]
#[bucket("general")] #[bucket("general")]
#[aliases("add-gif", "addgif")] #[aliases("add_gif", "add-gif", "addgif", "add-media", "addmedia")]
#[min_args(1)] #[min_args(1)]
#[max_args(3)] #[max_args(3)]
#[owners_only] #[owners_only]
async fn add_gif(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { async fn add_media(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let url = args.single::<String>()?; let url = args.single::<String>()?;
if !url::is_valid(&url) { if !url::is_valid(&url) {
@ -26,10 +26,10 @@ async fn add_gif(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult
let name = args.single_quoted::<String>().ok(); let name = args.single_quoted::<String>().ok();
let database = get_database_from_context(&ctx).await; let database = get_database_from_context(&ctx).await;
database.add_gif(&url, category, name).await?; database.add_media(&url, category, name).await?;
EphemeralMessage::create(&ctx.http, msg.channel_id, SHORT_TIMEOUT, |c| { EphemeralMessage::create(&ctx.http, msg.channel_id, SHORT_TIMEOUT, |c| {
c.reference_message(msg) c.reference_message(msg)
.content("Gif added to the database.") .content("Media entry added to the database.")
}) })
.await?; .await?;

@ -1,4 +1,4 @@
use crate::messages::gifs::create_gifs_menu; use crate::messages::gifs::create_media_menu;
use crate::utils::context_data::get_database_from_context; use crate::utils::context_data::get_database_from_context;
use serenity::client::Context; use serenity::client::Context;
use serenity::framework::standard::macros::command; use serenity::framework::standard::macros::command;
@ -9,10 +9,10 @@ use serenity::model::channel::Message;
#[description("Displays a list of all gifs used by the bot")] #[description("Displays a list of all gifs used by the bot")]
#[bucket("general")] #[bucket("general")]
#[only_in(guilds)] #[only_in(guilds)]
async fn gifs(ctx: &Context, msg: &Message) -> CommandResult { async fn media(ctx: &Context, msg: &Message) -> CommandResult {
let database = get_database_from_context(ctx).await; let database = get_database_from_context(ctx).await;
let gifs = database.get_all_gifs().await?; let gifs = database.get_all_media().await?;
create_gifs_menu(ctx, msg.channel_id, gifs).await?; create_media_menu(ctx, msg.channel_id, gifs).await?;
Ok(()) Ok(())
} }

@ -1,9 +1,9 @@
use serenity::framework::standard::macros::group; use serenity::framework::standard::macros::group;
use about::ABOUT_COMMAND; use about::ABOUT_COMMAND;
use add_gif::ADD_GIF_COMMAND; use add_media::ADD_MEDIA_COMMAND;
use clear::CLEAR_COMMAND; use clear::CLEAR_COMMAND;
use gifs::GIFS_COMMAND; use media::MEDIA_COMMAND;
use pain::PAIN_COMMAND; use pain::PAIN_COMMAND;
use ping::PING_COMMAND; use ping::PING_COMMAND;
use qalc::QALC_COMMAND; use qalc::QALC_COMMAND;
@ -13,10 +13,10 @@ use time::TIME_COMMAND;
use timezones::TIMEZONES_COMMAND; use timezones::TIMEZONES_COMMAND;
mod about; mod about;
mod add_gif; mod add_media;
mod clear; mod clear;
mod gifs;
pub(crate) mod help; pub(crate) mod help;
mod media;
mod pain; mod pain;
mod ping; mod ping;
mod qalc; mod qalc;
@ -27,6 +27,6 @@ mod timezones;
#[group] #[group]
#[commands( #[commands(
ping, stats, shutdown, time, timezones, qalc, about, add_gif, gifs, pain, clear ping, stats, shutdown, time, timezones, qalc, about, add_media, media, pain, clear
)] )]
pub struct Misc; pub struct Misc;

@ -20,23 +20,23 @@ async fn pain(ctx: &Context, msg: &Message, args: Args) -> CommandResult {
log::debug!("Got pain command"); log::debug!("Got pain command");
let pain_type = args.message().to_lowercase(); let pain_type = args.message().to_lowercase();
let database = get_database_from_context(ctx).await; let database = get_database_from_context(ctx).await;
let mut gifs = database let mut media = database
.get_gifs_by_category(format!("{}{}", CATEGORY_PREFIX, pain_type).as_str()) .get_media_by_category(format!("{}{}", CATEGORY_PREFIX, pain_type).as_str())
.await?; .await?;
if gifs.is_empty() { if media.is_empty() {
log::debug!("No gif found for pain {}. Using 404", pain_type); log::debug!("No media found for pain {}. Using 404", pain_type);
gifs = database media = database
.get_gifs_by_category(format!("{}{}", CATEGORY_PREFIX, NOT_FOUND_PAIN).as_str()) .get_media_by_category(format!("{}{}", CATEGORY_PREFIX, NOT_FOUND_PAIN).as_str())
.await?; .await?;
} }
let gif = gifs let entry = media
.into_iter() .into_iter()
.choose(&mut rand::thread_rng()) .choose(&mut rand::thread_rng())
.ok_or(BotError::from("No gifs found."))?; .ok_or(BotError::from("No gifs found."))?;
log::trace!("Gif for pain is {:?}", gif); log::trace!("Gif for pain is {:?}", entry);
msg.reply(ctx, gif.url).await?; msg.reply(ctx, entry.url).await?;
Ok(()) Ok(())
} }

@ -6,7 +6,7 @@ use serenity::framework::standard::macros::command;
use serenity::framework::standard::CommandResult; use serenity::framework::standard::CommandResult;
use serenity::model::channel::Message; use serenity::model::channel::Message;
static GIF_CATEGORY: &str = "matsuri"; static MEDIA_CATEGORY: &str = "matsuri";
#[command] #[command]
#[description("Posts a random matsuri gif")] #[description("Posts a random matsuri gif")]
@ -14,8 +14,8 @@ static GIF_CATEGORY: &str = "matsuri";
#[bucket("general")] #[bucket("general")]
async fn matsuri(ctx: &Context, msg: &Message) -> CommandResult { async fn matsuri(ctx: &Context, msg: &Message) -> CommandResult {
let database = get_database_from_context(ctx).await; let database = get_database_from_context(ctx).await;
let gifs = database.get_gifs_by_category(GIF_CATEGORY).await?; let media = database.get_media_by_category(MEDIA_CATEGORY).await?;
let gif = gifs let gif = media
.into_iter() .into_iter()
.choose(&mut rand::thread_rng()) .choose(&mut rand::thread_rng())
.ok_or(BotError::from("No gifs found."))?; .ok_or(BotError::from("No gifs found."))?;

@ -7,7 +7,7 @@ use serenity::{framework::standard::macros::command, prelude::*};
use crate::utils::context_data::get_database_from_context; use crate::utils::context_data::get_database_from_context;
use crate::utils::error::{BotError, BotResult}; use crate::utils::error::{BotError, BotResult};
use crate::utils::get_previous_message_or_reply; use crate::utils::get_previous_message_or_reply;
use bot_database::models::Gif; use bot_database::models::Media;
// return a normal peko in most cases // return a normal peko in most cases
static PEKOS: &[&str] = &[ static PEKOS: &[&str] = &[
@ -18,7 +18,7 @@ static PEKOS: &[&str] = &[
"🇵 🇪 🇰 🇴", "🇵 🇪 🇰 🇴",
"p3k0", "p3k0",
]; ];
static GIF_CATEGORY: &str = "pain-peko"; static MEDIA_CATEGORY: &str = "pain-peko";
#[command] #[command]
#[description("Pekofy messages")] #[description("Pekofy messages")]
@ -48,7 +48,7 @@ async fn pekofy(ctx: &Context, msg: &Message, args: Args) -> CommandResult {
alpha_lowercase.retain(|c| c.is_alphanumeric()); alpha_lowercase.retain(|c| c.is_alphanumeric());
let pekofied: String = if alpha_lowercase == "pain" { let pekofied: String = if alpha_lowercase == "pain" {
random_pain_gif(ctx).await?.url random_pain_media(ctx).await?.url
} else if PEKOS.contains(&&*alpha_lowercase) { } else if PEKOS.contains(&&*alpha_lowercase) {
random_peko() random_peko()
} else { } else {
@ -114,10 +114,10 @@ fn random_peko() -> String {
} }
/// Chooses a random pain peko gif /// Chooses a random pain peko gif
async fn random_pain_gif(ctx: &Context) -> BotResult<Gif> { async fn random_pain_media(ctx: &Context) -> BotResult<Media> {
let database = get_database_from_context(ctx).await; let database = get_database_from_context(ctx).await;
let gifs = database.get_gifs_by_category(GIF_CATEGORY).await?; let gifs = database.get_media_by_category(MEDIA_CATEGORY).await?;
gifs.into_iter() gifs.into_iter()
.choose(&mut rand::thread_rng()) .choose(&mut rand::thread_rng())
.ok_or(BotError::from("No gifs found")) .ok_or(BotError::from("No media found"))
} }

@ -1,5 +1,5 @@
use crate::utils::error::BotResult; use crate::utils::error::BotResult;
use bot_database::models::Gif; use bot_database::models::Media;
use bot_serenityutils::menu::{MenuBuilder, Page}; use bot_serenityutils::menu::{MenuBuilder, Page};
use serenity::builder::CreateMessage; use serenity::builder::CreateMessage;
use serenity::client::Context; use serenity::client::Context;
@ -7,16 +7,16 @@ use serenity::model::id::ChannelId;
use std::time::Duration; use std::time::Duration;
/// Creates a new gifs embed /// Creates a new gifs embed
pub async fn create_gifs_menu( pub async fn create_media_menu(
ctx: &Context, ctx: &Context,
channel_id: ChannelId, channel_id: ChannelId,
gifs: Vec<Gif>, media: Vec<Media>,
) -> BotResult<()> { ) -> BotResult<()> {
let total_pages = (gifs.len() as f32 / 10.0).ceil() as usize; let total_pages = (media.len() as f32 / 10.0).ceil() as usize;
let pages: Vec<Page> = gifs let pages: Vec<Page> = media
.chunks(10) .chunks(10)
.enumerate() .enumerate()
.map(|(page, gifs)| create_gifs_page(page + 1, total_pages, gifs.to_vec())) .map(|(page, media)| create_media_page(page + 1, total_pages, media.to_vec()))
.collect(); .collect();
MenuBuilder::new_paginator() MenuBuilder::new_paginator()
@ -30,21 +30,21 @@ pub async fn create_gifs_menu(
} }
/// Creates a new gif page /// Creates a new gif page
pub fn create_gifs_page(page: usize, total_pages: usize, gifs: Vec<Gif>) -> Page<'static> { pub fn create_media_page(page: usize, total_pages: usize, media: Vec<Media>) -> Page<'static> {
let mut message = CreateMessage::default(); let mut message = CreateMessage::default();
let description_lines: Vec<String> = gifs let description_lines: Vec<String> = media
.into_iter() .into_iter()
.map(|g| { .map(|m| {
format!( format!(
"{} - {} - [Source]({})", "{} - {} - [Source]({})",
g.category.unwrap_or("*N/A*".to_string()), m.category.unwrap_or("*N/A*".to_string()),
g.name.unwrap_or("*N/A*".to_string()), m.name.unwrap_or("*N/A*".to_string()),
g.url m.url
) )
}) })
.collect(); .collect();
message.embed(|e| { message.embed(|e| {
e.title("Gifs") e.title("Media")
.description(description_lines.join("\n")) .description(description_lines.join("\n"))
.footer(|f| f.text(format!("Page {} of {}", page, total_pages))) .footer(|f| f.text(format!("Page {} of {}", page, total_pages)))
}); });

Loading…
Cancel
Save