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]]
name = "bot-database"
version = "0.5.0"
version = "0.6.0"
dependencies = [
"chrono",
"diesel",

@ -1,6 +1,6 @@
[package]
name = "bot-database"
version = "0.5.0"
version = "0.6.0"
authors = ["trivernis <trivernis@protonmail.com>"]
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 {
/// Returns a list of all gifs in the database
pub async fn get_all_gifs(&self) -> DatabaseResult<Vec<Gif>> {
use gifs::dsl;
pub async fn get_all_media(&self) -> DatabaseResult<Vec<Media>> {
use media::dsl;
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)
}
/// Returns a list of gifs by assigned category
pub async fn get_gifs_by_category(&self, category: &str) -> DatabaseResult<Vec<Gif>> {
use gifs::dsl;
pub async fn get_media_by_category(&self, category: &str) -> DatabaseResult<Vec<Media>> {
use media::dsl;
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))
.load_async::<Gif>(&self.pool)
.load_async::<Media>(&self.pool)
.await?;
Ok(gifs)
}
/// Adds a gif to the database
pub async fn add_gif(
pub async fn add_media(
&self,
url: &str,
category: Option<String>,
name: Option<String>,
) -> DatabaseResult<()> {
use gifs::dsl;
use media::dsl;
log::debug!(
"Inserting gif with url '{}' and name {:?} and category {:?}",
url,
name,
category
);
insert_into(dsl::gifs)
.values(GifInsert {
insert_into(dsl::media)
.values(MediaInsert {
url: url.to_string(),
name,
category,

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

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

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

@ -8,14 +8,14 @@ use serenity::framework::standard::{Args, CommandResult};
use serenity::model::channel::Message;
#[command]
#[description("Simple ping test command")]
#[description("Adds media to the database")]
#[usage("<url> [<category>] [<name>]")]
#[bucket("general")]
#[aliases("add-gif", "addgif")]
#[aliases("add_gif", "add-gif", "addgif", "add-media", "addmedia")]
#[min_args(1)]
#[max_args(3)]
#[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>()?;
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 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| {
c.reference_message(msg)
.content("Gif added to the database.")
.content("Media entry added to the database.")
})
.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 serenity::client::Context;
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")]
#[bucket("general")]
#[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 gifs = database.get_all_gifs().await?;
create_gifs_menu(ctx, msg.channel_id, gifs).await?;
let gifs = database.get_all_media().await?;
create_media_menu(ctx, msg.channel_id, gifs).await?;
Ok(())
}

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

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

@ -6,7 +6,7 @@ use serenity::framework::standard::macros::command;
use serenity::framework::standard::CommandResult;
use serenity::model::channel::Message;
static GIF_CATEGORY: &str = "matsuri";
static MEDIA_CATEGORY: &str = "matsuri";
#[command]
#[description("Posts a random matsuri gif")]
@ -14,8 +14,8 @@ static GIF_CATEGORY: &str = "matsuri";
#[bucket("general")]
async fn matsuri(ctx: &Context, msg: &Message) -> CommandResult {
let database = get_database_from_context(ctx).await;
let gifs = database.get_gifs_by_category(GIF_CATEGORY).await?;
let gif = gifs
let media = database.get_media_by_category(MEDIA_CATEGORY).await?;
let gif = media
.into_iter()
.choose(&mut rand::thread_rng())
.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::error::{BotError, BotResult};
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
static PEKOS: &[&str] = &[
@ -18,7 +18,7 @@ static PEKOS: &[&str] = &[
"🇵 🇪 🇰 🇴",
"p3k0",
];
static GIF_CATEGORY: &str = "pain-peko";
static MEDIA_CATEGORY: &str = "pain-peko";
#[command]
#[description("Pekofy messages")]
@ -48,7 +48,7 @@ async fn pekofy(ctx: &Context, msg: &Message, args: Args) -> CommandResult {
alpha_lowercase.retain(|c| c.is_alphanumeric());
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) {
random_peko()
} else {
@ -114,10 +114,10 @@ fn random_peko() -> String {
}
/// 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 gifs = database.get_gifs_by_category(GIF_CATEGORY).await?;
let gifs = database.get_media_by_category(MEDIA_CATEGORY).await?;
gifs.into_iter()
.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 bot_database::models::Gif;
use bot_database::models::Media;
use bot_serenityutils::menu::{MenuBuilder, Page};
use serenity::builder::CreateMessage;
use serenity::client::Context;
@ -7,16 +7,16 @@ use serenity::model::id::ChannelId;
use std::time::Duration;
/// Creates a new gifs embed
pub async fn create_gifs_menu(
pub async fn create_media_menu(
ctx: &Context,
channel_id: ChannelId,
gifs: Vec<Gif>,
media: Vec<Media>,
) -> BotResult<()> {
let total_pages = (gifs.len() as f32 / 10.0).ceil() as usize;
let pages: Vec<Page> = gifs
let total_pages = (media.len() as f32 / 10.0).ceil() as usize;
let pages: Vec<Page> = media
.chunks(10)
.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();
MenuBuilder::new_paginator()
@ -30,21 +30,21 @@ pub async fn create_gifs_menu(
}
/// 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 description_lines: Vec<String> = gifs
let description_lines: Vec<String> = media
.into_iter()
.map(|g| {
.map(|m| {
format!(
"{} - {} - [Source]({})",
g.category.unwrap_or("*N/A*".to_string()),
g.name.unwrap_or("*N/A*".to_string()),
g.url
m.category.unwrap_or("*N/A*".to_string()),
m.name.unwrap_or("*N/A*".to_string()),
m.url
)
})
.collect();
message.embed(|e| {
e.title("Gifs")
e.title("Media")
.description(description_lines.join("\n"))
.footer(|f| f.text(format!("Page {} of {}", page, total_pages)))
});

Loading…
Cancel
Save