soundfx-bot/src/main.rs

361 lines
8.8 KiB
Rust
Raw Normal View History

2020-04-13 23:22:31 +00:00
use serenity::{
2020-04-26 00:51:51 +00:00
client::{
2020-04-26 22:12:31 +00:00
bridge::{
gateway::GatewayIntents,
voice::ClientVoiceManager,
},
Client, Context,
2020-04-26 00:51:51 +00:00
},
framework::standard::{
2020-04-26 22:12:31 +00:00
Args, CommandResult, StandardFramework,
macros::{
command, group,
}
2020-04-26 00:51:51 +00:00
},
model::{
channel::Message
},
2020-04-28 00:24:06 +00:00
prelude::{
Mutex as SerenityMutex,
*
},
2020-04-26 22:12:31 +00:00
voice::ffmpeg,
2020-04-13 23:22:31 +00:00
};
use sqlx::{
Pool,
2020-04-26 22:12:31 +00:00
mysql::{
MySqlPool,
MySqlConnection,
}
2020-04-13 23:22:31 +00:00
};
use dotenv::dotenv;
2020-04-26 22:12:31 +00:00
use tokio::{
fs::File,
};
use std::{
env,
path::Path,
sync::Arc,
};
2020-04-28 00:24:06 +00:00
use serenity::model::guild::Guild;
2020-04-13 23:22:31 +00:00
struct SQLPool;
impl TypeMapKey for SQLPool {
type Value = Pool<MySqlConnection>;
}
2020-04-26 00:51:51 +00:00
struct VoiceManager;
impl TypeMapKey for VoiceManager {
2020-04-28 00:24:06 +00:00
type Value = Arc<SerenityMutex<ClientVoiceManager>>;
2020-04-26 00:51:51 +00:00
}
2020-04-28 00:24:06 +00:00
static THEME_COLOR: u32 = 0x00e0f3;
2020-04-13 23:22:31 +00:00
#[group]
2020-04-28 00:24:06 +00:00
#[commands(play, info, )]
2020-04-26 00:51:51 +00:00
struct General;
struct Sound {
name: String,
id: u32,
src: Vec<u8>,
}
2020-04-13 23:22:31 +00:00
2020-04-28 00:24:06 +00:00
struct GuildData {
id: u64,
name: Option<String>,
prefix: String,
volume: u8,
}
impl GuildData {
async fn get_from_id(guild_id: u64, db_pool: MySqlPool) -> Result<GuildData, Box<dyn std::error::Error>> {
let guild = sqlx::query_as!(
GuildData,
"
SELECT *
FROM servers
WHERE id = ?
", guild_id
)
.fetch_one(&db_pool)
.await?;
Ok(guild)
}
async fn create_from_id(guild: Guild, db_pool: MySqlPool) -> Result<GuildData, Box<dyn std::error::Error>> {
let guild_data = sqlx::query!(
"
INSERT INTO servers (id, name)
VALUES (?, ?)
", guild.id.as_u64(), guild.name
)
.execute(&db_pool)
.await?;
Ok(GuildData {
id: *guild.id.as_u64(),
name: Some(guild.name),
prefix: String::from("?"),
volume: 100,
})
}
async fn commit(&self, db_pool: MySqlPool) -> Result<(), Box<dyn std::error::Error>> {
sqlx::query!(
"
UPDATE servers
SET
name = ?,
prefix = ?,
volume = ?
WHERE
id = ?
",
self.name, self.prefix, self.volume, self.id
)
.execute(&db_pool)
.await?;
Ok(())
}
}
2020-04-13 23:22:31 +00:00
// create event handler for bot
struct Handler;
2020-04-26 22:12:31 +00:00
#[serenity::async_trait]
2020-04-13 23:22:31 +00:00
impl EventHandler for Handler {}
// entry point
2020-04-26 00:51:51 +00:00
#[tokio::main]
2020-04-26 22:12:31 +00:00
async fn main() -> Result<(), Box<dyn std::error::Error>> {
dotenv()?;
2020-04-13 23:22:31 +00:00
2020-04-26 00:51:51 +00:00
let framework = StandardFramework::new()
2020-04-28 00:24:06 +00:00
.configure(|c| c.dynamic_prefix(|ctx, msg| Box::pin(async move {
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
match GuildData::get_from_id(*msg.guild_id.unwrap().as_u64(), pool).await {
Ok(guild) => Some(guild.prefix),
Err(_) => Some(String::from("?"))
}
})))
2020-04-26 00:51:51 +00:00
.group(&GENERAL_GROUP);
2020-04-13 23:22:31 +00:00
2020-04-26 22:12:31 +00:00
let mut client = Client::new_with_extras(
&env::var("DISCORD_TOKEN").expect("Missing token from environment"),
|extras| { extras
.framework(framework)
.event_handler(Handler)
.intents(GatewayIntents::GUILD_VOICE_STATES | GatewayIntents::GUILD_MESSAGES | GatewayIntents::GUILDS)
}).await.expect("Error occurred creating client");
2020-04-13 23:22:31 +00:00
2020-04-26 00:51:51 +00:00
{
2020-04-26 22:12:31 +00:00
let pool = MySqlPool::new(&env::var("DATABASE_URL").expect("No database URL provided")).await.unwrap();
2020-04-13 23:22:31 +00:00
2020-04-26 00:51:51 +00:00
let mut data = client.data.write().await;
2020-04-13 23:22:31 +00:00
data.insert::<SQLPool>(pool);
2020-04-26 00:51:51 +00:00
data.insert::<VoiceManager>(Arc::clone(&client.voice_manager));
2020-04-13 23:22:31 +00:00
}
2020-04-26 22:12:31 +00:00
client.start().await?;
Ok(())
2020-04-26 00:51:51 +00:00
}
2020-04-28 00:24:06 +00:00
async fn search_for_sound(query: &str, guild_id: u64, user_id: u64, db_pool: MySqlPool) -> Result<Sound, sqlx::Error> {
2020-04-26 00:51:51 +00:00
2020-04-28 00:24:06 +00:00
fn extract_id(s: &str) -> Option<u32> {
if s.to_lowercase().starts_with("id:") {
match s[3..].parse::<u32>() {
Ok(id) => Some(id),
Err(_) => None
}
}
else {
None
}
}
2020-04-26 00:51:51 +00:00
2020-04-28 00:24:06 +00:00
if let Some(id) = extract_id(&query[3..]) {
2020-04-26 22:12:31 +00:00
let sound = sqlx::query_as_unchecked!(
Sound,
2020-04-26 00:51:51 +00:00
"
2020-04-26 22:12:31 +00:00
SELECT id, name, src
FROM sounds
2020-04-28 00:24:06 +00:00
WHERE id = ? AND (
public = 1 OR
uploader_id = ? OR
server_id = ?
)
2020-04-26 22:12:31 +00:00
LIMIT 1
2020-04-26 00:51:51 +00:00
",
2020-04-28 00:24:06 +00:00
id, user_id, guild_id
2020-04-26 00:51:51 +00:00
)
2020-04-26 22:12:31 +00:00
.fetch_one(&db_pool)
2020-04-26 00:51:51 +00:00
.await?;
2020-04-26 22:12:31 +00:00
Ok(sound)
2020-04-26 00:51:51 +00:00
}
else {
let name = query;
2020-04-26 22:12:31 +00:00
let sound = sqlx::query_as_unchecked!(
Sound,
2020-04-26 00:51:51 +00:00
"
2020-04-26 22:12:31 +00:00
SELECT id, name, src
FROM sounds
2020-04-28 00:24:06 +00:00
WHERE name = ? AND (
public = 1 OR
uploader_id = ? OR
server_id = ?
)
ORDER BY rand(), public = 1, server_id = ?, uploader_id = ?
2020-04-26 22:12:31 +00:00
LIMIT 1
2020-04-26 00:51:51 +00:00
",
2020-04-28 00:24:06 +00:00
name, user_id, guild_id, guild_id, user_id
2020-04-26 00:51:51 +00:00
)
2020-04-26 22:12:31 +00:00
.fetch_one(&db_pool)
2020-04-26 00:51:51 +00:00
.await?;
2020-04-26 22:12:31 +00:00
Ok(sound)
2020-04-26 00:51:51 +00:00
}
2020-04-13 23:22:31 +00:00
}
2020-04-26 22:12:31 +00:00
async fn store_sound_source(sound: &Sound) -> Result<String, Box<dyn std::error::Error>> {
let caching_location = env::var("CACHING_LOCATION").unwrap_or(String::from("/tmp"));
2020-04-26 00:51:51 +00:00
2020-04-26 22:12:31 +00:00
let path_name = format!("{}/sound-{}", caching_location, sound.id);
let path = Path::new(&path_name);
2020-04-26 00:51:51 +00:00
2020-04-26 22:12:31 +00:00
if !path.exists() {
use tokio::prelude::*;
2020-04-26 00:51:51 +00:00
2020-04-26 22:12:31 +00:00
let mut file = File::create(&path).await?;
2020-04-26 00:51:51 +00:00
2020-04-26 22:12:31 +00:00
file.write_all(sound.src.as_ref()).await?;
}
2020-04-13 23:22:31 +00:00
2020-04-26 22:12:31 +00:00
Ok(path_name)
}
2020-04-26 00:51:51 +00:00
2020-04-26 22:12:31 +00:00
#[command]
async fn play(ctx: &mut Context, msg: &Message, args: Args) -> CommandResult {
let guild = match msg.guild(&ctx.cache).await {
Some(guild) => guild,
2020-04-26 00:51:51 +00:00
2020-04-26 22:12:31 +00:00
None => {
return Ok(());
2020-04-26 00:51:51 +00:00
}
2020-04-26 22:12:31 +00:00
};
let guild_id = guild.read().await.id;
2020-04-26 00:51:51 +00:00
2020-04-26 22:12:31 +00:00
let channel_to_join = guild.read().await
.voice_states.get(&msg.author.id)
.and_then(|voice_state| voice_state.channel_id);
2020-04-26 00:51:51 +00:00
2020-04-26 22:12:31 +00:00
match channel_to_join {
Some(user_channel) => {
let search_term = args.rest();
let pool = ctx.data.read().await
.get::<SQLPool>().cloned().expect("Could not get SQLPool from data");
2020-04-28 00:24:06 +00:00
let sound_res = search_for_sound(
search_term,
*guild_id.as_u64(),
*msg.author.id.as_u64(),
pool).await;
2020-04-26 22:12:31 +00:00
2020-04-28 00:24:06 +00:00
match sound_res {
Ok(sound) => {
let fp = store_sound_source(&sound).await?;
2020-04-26 22:12:31 +00:00
2020-04-28 00:24:06 +00:00
let voice_manager_lock = ctx.data.read().await
.get::<VoiceManager>().cloned().expect("Could not get VoiceManager from data");
2020-04-26 22:12:31 +00:00
2020-04-28 00:24:06 +00:00
let mut voice_manager = voice_manager_lock.lock().await;
2020-04-26 22:12:31 +00:00
2020-04-28 00:24:06 +00:00
match voice_manager.get_mut(guild_id) {
2020-04-26 22:12:31 +00:00
Some(handler) => {
2020-04-28 00:24:06 +00:00
// play sound
2020-04-26 22:12:31 +00:00
handler.play(ffmpeg(fp).await?);
}
None => {
2020-04-28 00:24:06 +00:00
// try & join a voice channel
match voice_manager.join(guild_id, user_channel) {
Some(handler) => {
handler.play(ffmpeg(fp).await?);
}
None => {
msg.channel_id.say(&ctx, "Failed to join channel").await?;
}
};
2020-04-26 22:12:31 +00:00
}
2020-04-28 00:24:06 +00:00
}
}
Err(_) => {
msg.channel_id.say(&ctx, "Couldn't find sound by term provided").await?;
2020-04-26 22:12:31 +00:00
}
}
}
None => {
msg.channel_id.say(&ctx, "You are not in a voice chat!").await?;
2020-04-26 00:51:51 +00:00
}
}
2020-04-26 22:12:31 +00:00
Ok(())
2020-04-13 23:22:31 +00:00
}
2020-04-28 00:24:06 +00:00
#[command]
async fn help(ctx: &mut Context, msg: &Message, _args: Args) -> CommandResult {
msg.channel_id.send_message(&ctx, |m| m
.embed(|e| e
.title("Help")
.color(THEME_COLOR)
.description("Please visit our website at https://soundfx.jellywx.com/help"))).await?;
Ok(())
}
#[command]
async fn info(ctx: &mut Context, msg: &Message, _args: Args) -> CommandResult {
msg.channel_id.send_message(&ctx, |m| m
.embed(|e| e
.title("Info")
.color(THEME_COLOR)
.description("Default prefix: `?`
Reset prefix: `@SoundFX prefix ?`
Invite me: https://discordapp.com/oauth2/authorize?client_id=430384808200372245&scope=bot&permissions=36703232
**Welcome to SoundFX!**
Developer: <@203532103185465344>
Find me on https://discord.jellywx.com/ and on https://github.com/JellyWX :)
**An online dashboard is available!** Visit https://soundfx.jellywx.com/dashboard
There is a maximum sound limit per user. This can be removed by donating at https://patreon.com/jellywx"))).await?;
Ok(())
}