4 Commits
0.5.0 ... 0.7.0

Author SHA1 Message Date
ee3d9a0c45 new commands, music fixes and more 2024-02-20 22:27:36 +01:00
4e92771f8f minor refractors, uptime removed 2024-02-18 19:28:46 +01:00
8a947926f7 0.5.1 refractor 2024-02-16 12:42:38 +01:00
639fd7775f more commands incoming 2024-02-13 23:00:54 +01:00
43 changed files with 1079 additions and 299 deletions

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "src/spotify-parser"]
path = src/spotify-parser
url = https://github.com/eRgo35/spotify-parser

25
Cargo.lock generated
View File

@@ -902,6 +902,12 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "json"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd"
[[package]]
name = "lazy_static"
version = "1.4.0"
@@ -959,14 +965,18 @@ dependencies = [
[[package]]
name = "lyra"
version = "0.5.0"
version = "0.6.0"
dependencies = [
"dotenv",
"fancy-regex",
"json",
"openssl",
"poise",
"rand",
"regex",
"reqwest",
"serde",
"serde_json",
"serenity",
"songbird",
"symphonia",
@@ -974,6 +984,7 @@ dependencies = [
"tracing",
"tracing-futures",
"tracing-subscriber",
"url",
]
[[package]]
@@ -1801,9 +1812,9 @@ dependencies = [
[[package]]
name = "serde"
version = "1.0.196"
version = "1.0.197"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "870026e60fa08c69f064aa766c10f10b1d62db9ccd4d0abb206472bee0ce3b32"
checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2"
dependencies = [
"serde_derive",
]
@@ -1831,9 +1842,9 @@ dependencies = [
[[package]]
name = "serde_derive"
version = "1.0.196"
version = "1.0.197"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33c85360c95e7d137454dc81d9a4ed2b8efd8fbe19cee57357b32b9771fccb67"
checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b"
dependencies = [
"proc-macro2",
"quote",
@@ -1842,9 +1853,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.113"
version = "1.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69801b70b1c3dac963ecb03a364ba0ceda9cf60c71cfe475e99864759c8b8a79"
checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0"
dependencies = [
"itoa",
"ryu",

View File

@@ -1,6 +1,6 @@
[package]
name = "lyra"
version = "0.5.0"
version = "0.7.0"
authors = ["Michał Czyż <mike@c2yz.com>"]
edition = "2021"
description = "A featureful Discord bot written in Rust."
@@ -14,10 +14,14 @@ keywords = ["discord", "bot", "rust", "music", "featureful"]
[dependencies]
dotenv = "0.15.0"
fancy-regex = "0.13.0"
json = "0.12.4"
openssl = { version = "0.10.63", features = ["vendored"] }
poise = "0.6.1"
rand = "0.8.5"
regex = "1.10.3"
reqwest = "0.11.23"
reqwest = { version = "0.11.23", features = ["json"]}
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.114"
serenity = { version = "0.12.0", features = ["cache", "framework", "standard_framework", "voice"] }
songbird = { version = "0.4.0", features = ["builtin-queue", "serenity"] }
symphonia = { version = "0.5.3", features = ["aac", "adpcm", "alac", "flac", "mpa", "isomp4"] }
@@ -25,3 +29,4 @@ tokio = { version = "1.35.1", features = ["macros", "full", "signal"] }
tracing = "0.1.40"
tracing-futures = "0.2.5"
tracing-subscriber = "0.3.18"
url = "2.5.0"

View File

@@ -1,4 +1,4 @@
pub mod embeds;
pub mod kashi;
pub mod music;
pub mod tools;
pub mod embeds;

View File

@@ -1,37 +1,58 @@
use crate::{Context, Error};
use serenity::{builder::{CreateEmbedAuthor, CreateEmbedFooter}, model::{Colour, Timestamp}};
use poise::serenity_prelude::CreateEmbed;
use poise::CreateReply;
use serenity::{
builder::{CreateEmbedAuthor, CreateEmbedFooter},
model::{Colour, Timestamp},
};
pub async fn fail(ctx: Context<'_>, err: String) -> Result<(), Error> {
ctx.send(
CreateReply::default().embed(error_embed(ctx, &format!("Failed: {:?}", err)).await.unwrap())
).await?;
CreateReply::default().embed(
error_embed(ctx, &format!("Failed: {:?}", err))
.await
.unwrap(),
),
)
.await?;
Ok(())
}
pub async fn error_embed(ctx: Context<'_>, msg: &str) -> Result<CreateEmbed, Error> {
let embed = CreateEmbed::default()
.author(CreateEmbedAuthor::new("Something went wrong!").icon_url(ctx.author().clone().face()))
.author(
CreateEmbedAuthor::new("Something went wrong!").icon_url(ctx.author().clone().face()),
)
.colour(Colour::from_rgb(255, 58, 97))
.title("Oopsie, Doopsie!")
.description(msg)
.timestamp(Timestamp::now())
.footer(CreateEmbedFooter::new(ctx.cache().current_user().name.to_string()).icon_url(ctx.cache().current_user().face()));
.footer(
CreateEmbedFooter::new(ctx.cache().current_user().name.to_string())
.icon_url(ctx.cache().current_user().face()),
);
Ok(embed)
}
pub async fn embed(ctx: Context<'_>, author: &str, description: &str, title: &str) -> Result<CreateEmbed, Error> {
pub async fn embed(
ctx: Context<'_>,
author: &str,
description: &str,
title: &str,
) -> Result<CreateEmbed, Error> {
let embed = CreateEmbed::default()
.author(CreateEmbedAuthor::new(author).icon_url(ctx.author().clone().face()))
.colour(Colour::from_rgb(255, 58, 97))
.title(title)
.description(description)
.timestamp(Timestamp::now())
.footer(CreateEmbedFooter::new(ctx.cache().current_user().name.to_string()).icon_url(ctx.cache().current_user().face()));
.footer(
CreateEmbedFooter::new(ctx.cache().current_user().name.to_string())
.icon_url(ctx.cache().current_user().face()),
);
Ok(embed)
}

View File

@@ -1,15 +1,20 @@
pub mod deafen;
pub mod join;
pub mod leave;
pub mod notifier;
pub mod metadata;
pub mod mute;
pub mod notifier;
pub mod pause;
pub mod play;
pub mod queue;
pub mod repeat;
pub mod resume;
pub mod seek;
pub mod shuffle;
pub mod skip;
pub mod soundboard;
pub mod stop;
pub mod volume;
pub use deafen::deafen;
pub use join::join;
@@ -20,5 +25,8 @@ pub use play::play;
pub use queue::queue;
pub use repeat::repeat;
pub use resume::resume;
pub use seek::seek;
pub use shuffle::shuffle;
pub use skip::skip;
pub use stop::stop;
pub use volume::volume;

View File

@@ -1,4 +1,7 @@
use crate::{commands::embeds::{error_embed, embed, fail}, Context, Error};
use crate::{
commands::embeds::{embed, error_embed, fail},
Context, Error,
};
use poise::CreateReply;
/// Deafens itself while in a voice channel; \
@@ -9,9 +12,7 @@ use poise::CreateReply;
aliases("shuush", "undeafen"),
category = "Music"
)]
pub async fn deafen(
ctx: Context<'_>
) -> Result<(), Error> {
pub async fn deafen(ctx: Context<'_>) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap();
let manager = songbird::get(&ctx.serenity_context())
@@ -23,9 +24,8 @@ pub async fn deafen(
Some(handler) => handler,
None => {
let msg = "I am not in a voice channel!";
ctx.send(
CreateReply::default().embed(error_embed(ctx, msg).await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(error_embed(ctx, msg).await.unwrap()))
.await?;
return Ok(());
}
@@ -38,17 +38,15 @@ pub async fn deafen(
fail(ctx, err.to_string()).await.unwrap();
}
ctx.send(
CreateReply::default().embed(embed(ctx, "Undeafened!", "", "").await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(embed(ctx, "Undeafened!", "", "").await.unwrap()))
.await?;
} else {
if let Err(err) = handler.deafen(true).await {
fail(ctx, err.to_string()).await.unwrap();
}
ctx.send(
CreateReply::default().embed(embed(ctx, "Deafened!", "", "").await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(embed(ctx, "Deafened!", "", "").await.unwrap()))
.await?;
}
Ok(())

View File

@@ -1,29 +1,28 @@
use crate::{commands::embeds::{error_embed, embed}, Context, Error};
use crate::commands::music::notifier::TrackErrorNotifier;
use crate::{
commands::embeds::{embed, error_embed},
Context, Error,
};
use poise::CreateReply;
use songbird::TrackEvent;
use crate::commands::music::notifier::TrackErrorNotifier;
/// Joins your voice channel
#[poise::command(
prefix_command,
slash_command,
category = "Music"
)]
pub async fn join(
ctx: Context<'_>
) -> Result<(), Error> {
#[poise::command(prefix_command, slash_command, category = "Music")]
pub async fn join(ctx: Context<'_>) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap();
let channel_id = ctx.guild().unwrap()
.voice_states.get(&ctx.author().id)
let channel_id = ctx
.guild()
.unwrap()
.voice_states
.get(&ctx.author().id)
.and_then(|voice_state| voice_state.channel_id);
let connect_to = match channel_id {
Some(channel) => channel,
None => {
let msg = "I am not in a voice channel!";
ctx.send(
CreateReply::default().embed(error_embed(ctx, msg).await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(error_embed(ctx, msg).await.unwrap()))
.await?;
return Ok(());
}
};
@@ -38,9 +37,8 @@ pub async fn join(
handler.add_global_event(TrackEvent::Error.into(), TrackErrorNotifier);
}
ctx.send(
CreateReply::default().embed(embed(ctx, "Joined!", "Hi there!", "").await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(embed(ctx, "Joined!", "Hi there!", "").await.unwrap()))
.await?;
Ok(())
}

View File

@@ -1,5 +1,8 @@
use crate::{
commands::embeds::{embed, error_embed, fail},
Context, Error,
};
use poise::CreateReply;
use crate::{commands::embeds::{error_embed, fail, embed}, Context, Error};
/// Leaves the voice channel; \
/// aliases: leave, qa!
@@ -9,9 +12,7 @@ use crate::{commands::embeds::{error_embed, fail, embed}, Context, Error};
aliases("leave", "qa!"),
category = "Music"
)]
pub async fn leave(
ctx: Context<'_>
) -> Result<(), Error> {
pub async fn leave(ctx: Context<'_>) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap();
let manager = songbird::get(&ctx.serenity_context())
@@ -21,11 +22,10 @@ pub async fn leave(
if !manager.get(guild_id).is_some() {
let msg = "I am not in a voice channel!";
ctx.send(
CreateReply::default().embed(error_embed(ctx, msg).await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(error_embed(ctx, msg).await.unwrap()))
.await?;
return Ok(())
return Ok(());
}
if let Err(err) = manager.remove(guild_id).await {
@@ -33,8 +33,13 @@ pub async fn leave(
}
ctx.send(
CreateReply::default().embed(embed(ctx, "Left!", "I left the voice channel", "").await.unwrap())
).await?;
CreateReply::default().embed(
embed(ctx, "Left!", "I left the voice channel", "")
.await
.unwrap(),
),
)
.await?;
Ok(())
}

View File

@@ -0,0 +1,7 @@
use songbird::{input::AuxMetadata, typemap::TypeMapKey};
pub struct Metadata;
impl TypeMapKey for Metadata {
type Value = AuxMetadata;
}

View File

@@ -1,4 +1,7 @@
use crate::{commands::embeds::{error_embed, embed, fail}, Context, Error};
use crate::{
commands::embeds::{embed, error_embed, fail},
Context, Error,
};
use poise::CreateReply;
/// Mutes itself while in a voice channel; \
@@ -9,9 +12,7 @@ use poise::CreateReply;
aliases("shhh", "unmute"),
category = "Music"
)]
pub async fn mute(
ctx: Context<'_>
) -> Result<(), Error> {
pub async fn mute(ctx: Context<'_>) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap();
let manager = songbird::get(&ctx.serenity_context())
@@ -23,9 +24,8 @@ pub async fn mute(
Some(handler) => handler,
None => {
let msg = "I am not in a voice channel!";
ctx.send(
CreateReply::default().embed(error_embed(ctx, msg).await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(error_embed(ctx, msg).await.unwrap()))
.await?;
return Ok(());
}
};
@@ -37,17 +37,15 @@ pub async fn mute(
fail(ctx, err.to_string()).await.unwrap();
}
ctx.send(
CreateReply::default().embed(embed(ctx, "Unmuted!", "", "").await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(embed(ctx, "Unmuted!", "", "").await.unwrap()))
.await?;
} else {
if let Err(err) = handler.mute(true).await {
fail(ctx, err.to_string()).await.unwrap();
}
ctx.send(
CreateReply::default().embed(embed(ctx, "Muted!", "", "").await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(embed(ctx, "Muted!", "", "").await.unwrap()))
.await?;
}
Ok(())

View File

@@ -1,15 +1,12 @@
use crate::{commands::embeds::{error_embed, embed}, Context, Error};
use crate::{
commands::embeds::{embed, error_embed},
Context, Error,
};
use poise::CreateReply;
/// Pauses the currently playing song
#[poise::command(
prefix_command,
slash_command,
category = "Music"
)]
pub async fn pause(
ctx: Context<'_>
) -> Result<(), Error> {
#[poise::command(prefix_command, slash_command, category = "Music")]
pub async fn pause(ctx: Context<'_>) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap();
let manager = songbird::get(&ctx.serenity_context())
@@ -23,13 +20,17 @@ pub async fn pause(
let _ = queue.pause();
ctx.send(
CreateReply::default().embed(embed(ctx, "Paused!", "Currently playing song is now paused!", "").await.unwrap())
).await?;
CreateReply::default().embed(
embed(ctx, "Paused!", "Currently playing song is now paused!", "")
.await
.unwrap(),
),
)
.await?;
} else {
let msg = "I am not in a voice channel!";
ctx.send(
CreateReply::default().embed(error_embed(ctx, msg).await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(error_embed(ctx, msg).await.unwrap()))
.await?;
}
Ok(())

View File

@@ -1,18 +1,20 @@
use crate::commands::music::metadata::Metadata;
use crate::{commands::embeds::error_embed, Context, Error};
use fancy_regex::Regex;
use regex::Regex as Regex_Classic;
use std::process::Command;
use std::time::Duration;
use poise::CreateReply;
use poise::serenity_prelude::CreateEmbed;
use poise::serenity_prelude::Colour;
use poise::serenity_prelude::model::Timestamp;
use poise::serenity_prelude::Colour;
use poise::serenity_prelude::CreateEmbed;
use poise::CreateReply;
use regex::Regex as Regex_Classic;
use serenity::builder::CreateEmbedAuthor;
use serenity::builder::CreateEmbedFooter;
use songbird::events::TrackEvent;
use songbird::input::AuxMetadata;
use songbird::input::{Compose, YoutubeDl};
use songbird::events::TrackEvent;
use songbird::tracks::{TrackHandle, TrackQueue};
use std::process::Command;
use std::time::Duration;
use crate::commands::music::notifier::TrackErrorNotifier;
use crate::http::HttpKey;
@@ -28,26 +30,40 @@ use crate::http::HttpKey;
)]
pub async fn play(
ctx: Context<'_>,
#[description = "Provide a query or an url"] #[rest] mut song: String,
#[description = "Provide a query or an url"]
#[rest]
mut song: String,
) -> Result<(), Error> {
let regex_spotify = Regex::new(r"https?:\/\/(?:embed\.|open\.)(?:spotify\.com\/)(?:track\/|\?uri=spotify:track:)((\w|-)+)(?:(?=\?)(?:[?&]foo=(\d*)(?=[&#]|$)|(?![?&]foo=)[^#])+)?(?=#|$)").unwrap();
let regex_youtube = Regex_Classic::new(r#""url": "(https://www.youtube.com/watch\?v=[A-Za-z0-9]{11})""#).unwrap();
let regex_youtube_playlist = Regex::new(r"^((?:https?:)\/\/)?((?:www|m)\.)?((?:youtube\.com)).*(youtu.be\/|list=)([^#&?]*).*").unwrap();
let regex_youtube =
Regex_Classic::new(r#""url": "(https://www.youtube.com/watch\?v=[A-Za-z0-9]{11})""#)
.unwrap();
let regex_youtube_playlist = Regex::new(
r"^((?:https?:)\/\/)?((?:www|m)\.)?((?:youtube\.com)).*(youtu.be\/|list=)([^#&?]*).*",
)
.unwrap();
let regex_spotify_playlist = Regex::new(r"https?:\/\/(?:embed\.|open\.)(?:spotify\.com\/)(?:(album|playlist)\/|\?uri=spotify:playlist:)((\w|-)+)(?:(?=\?)(?:[?&]foo=(\d*)(?=[&#]|$)|(?![?&]foo=)[^#])+)?(?=#|$)").unwrap();
let is_playlist = regex_youtube_playlist.is_match(&song).unwrap();
let is_spotify = regex_spotify.is_match(&song).unwrap();
let is_playlist = regex_youtube_playlist.is_match(&song).unwrap()
|| regex_spotify_playlist.is_match(&song).unwrap();
let is_spotify =
regex_spotify.is_match(&song).unwrap() || regex_spotify_playlist.is_match(&song).unwrap();
let is_query = !song.starts_with("http");
let guild_id = ctx.guild_id().unwrap();
let channel_id = ctx.guild().unwrap().voice_states.get(&ctx.author().id).and_then(|voice_state| voice_state.channel_id);
let channel_id = ctx
.guild()
.unwrap()
.voice_states
.get(&ctx.author().id)
.and_then(|voice_state| voice_state.channel_id);
let connect_to = match channel_id {
Some(channel) => channel,
None => {
let msg = "I am not in a voice channel!";
ctx.send(
CreateReply::default().embed(error_embed(ctx, msg).await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(error_embed(ctx, msg).await.unwrap()))
.await?;
return Ok(());
}
@@ -70,6 +86,43 @@ pub async fn play(
handler.add_global_event(TrackEvent::Error.into(), TrackErrorNotifier);
if is_playlist && is_spotify {
let raw_list = Command::new("node")
.args(["./src/spotify-parser", &song])
.output()
.expect("failed to execute process")
.stdout;
let list = String::from_utf8(raw_list.clone()).expect("Invalid UTF-8");
let tracks: Vec<String> = list.split("\n").map(str::to_string).collect();
for (index, url) in tracks.clone().iter().enumerate() {
if url.is_empty() {
break;
}
let src = YoutubeDl::new_ytdl_like(
"yt-dlp",
http_client.clone(),
format!("ytsearch:{}", url.to_string()),
);
let aux_metadata = src.clone().aux_metadata().await.unwrap();
let track = handler.enqueue_input(src.clone().into()).await;
let _ = track
.typemap()
.write()
.await
.insert::<Metadata>(aux_metadata);
if index == 0 {
let embed = generate_playlist_embed(ctx, track, tracks.len()).await;
let response = CreateReply::default().embed(embed.unwrap());
ctx.send(response).await?;
}
}
return Ok(());
}
if is_playlist {
let raw_list = Command::new("yt-dlp")
.args(["-j", "--flat-playlist", &song])
@@ -79,26 +132,42 @@ pub async fn play(
let list = String::from_utf8(raw_list.clone()).expect("Invalid UTF-8");
let urls: Vec<String> = regex_youtube.captures_iter(&list).map(|capture| capture[1].to_string()).collect();
let urls: Vec<String> = regex_youtube
.captures_iter(&list)
.map(|capture| capture[1].to_string())
.collect();
let mut sources: Vec<YoutubeDl> = vec![];
for url in urls {
let src = YoutubeDl::new_ytdl_like("yt-dlp", http_client.clone(), url);
let _ = handler.enqueue_input(src.clone().into()).await;
sources.push(src);
for (index, url) in urls.clone().iter().enumerate() {
if url.is_empty() {
break;
}
let src = YoutubeDl::new_ytdl_like("yt-dlp", http_client.clone(), url.to_string());
let aux_metadata = src.clone().aux_metadata().await.unwrap();
let track = handler.enqueue_input(src.clone().into()).await;
let _ = track
.typemap()
.write()
.await
.insert::<Metadata>(aux_metadata);
let embed = generate_playlist_embed(ctx, sources).await;
if index == 0 {
let embed = generate_playlist_embed(ctx, track, urls.len()).await;
let response = CreateReply::default().embed(embed.unwrap());
ctx.send(response).await?;
} else {
}
}
return Ok(());
}
if is_spotify {
let exec = format!("node ./src/spotify --url {}", song);
let query = Command::new("sh").arg("-c").arg(exec).output().expect("failed to execute process").stdout;
let query = Command::new("node")
.args(["./src/spotify-parser", &song])
.output()
.expect("failed to execute process")
.stdout;
let query_str = String::from_utf8(query.clone()).expect("Invalid UTF-8");
song = format!("ytsearch:{}", query_str.to_string());
}
if is_query {
@@ -106,23 +175,45 @@ pub async fn play(
}
let src = YoutubeDl::new_ytdl_like("yt-dlp", http_client, song);
let _ = handler.enqueue_input(src.clone().into()).await;
let embed = generate_embed(ctx, src).await;
let embed = generate_embed(ctx, src.clone(), handler.queue()).await;
let response = CreateReply::default().embed(embed.unwrap());
ctx.send(response).await?;
}
let aux_metadata = src.clone().aux_metadata().await.unwrap();
let track = handler.enqueue_input(src.clone().into()).await;
let _ = track
.typemap()
.write()
.await
.insert::<Metadata>(aux_metadata);
}
Ok(())
}
async fn generate_embed(ctx: Context<'_>, src: YoutubeDl) -> Result<CreateEmbed, Error> {
async fn generate_embed(
ctx: Context<'_>,
src: YoutubeDl,
queue: &TrackQueue,
) -> Result<CreateEmbed, Error> {
let metadata = src.clone().aux_metadata().await.unwrap();
let AuxMetadata {title, thumbnail, source_url, artist, duration, ..} = metadata;
let AuxMetadata {
title,
thumbnail,
source_url,
artist,
duration,
..
} = metadata;
let timestamp = Timestamp::now();
let duration_minutes = duration.unwrap_or(Duration::new(0, 0)).clone().as_secs() / 60;
let duration_seconds = duration.unwrap_or(Duration::new(0, 0)).clone().as_secs() % 60;
let mut description = format!("Song added to queue @ {}", queue.len() + 1);
if queue.len() == 0 {
description = format!("Playing now!");
}
let embed = CreateEmbed::default()
.author(CreateEmbedAuthor::new("Track enqueued").icon_url(ctx.author().clone().face()))
@@ -130,38 +221,75 @@ async fn generate_embed(ctx: Context<'_>, src: YoutubeDl) -> Result<CreateEmbed,
.title(title.unwrap())
.url(source_url.unwrap())
.thumbnail(thumbnail.unwrap_or(ctx.cache().current_user().face()))
.field("Artist", artist.unwrap_or("Unknown Artist".to_string()), true)
.field("Duration", format!("{:02}:{:02}", duration_minutes, duration_seconds), true)
.field(
"Artist",
artist.unwrap_or("Unknown Artist".to_string()),
true,
)
.field(
"Duration",
format!("{:02}:{:02}", duration_minutes, duration_seconds),
true,
)
.field("DJ", ctx.author().name.clone(), true)
.description(description)
.timestamp(timestamp)
.footer(CreateEmbedFooter::new(ctx.cache().current_user().name.to_string()).icon_url(ctx.cache().current_user().face()));
.footer(
CreateEmbedFooter::new(ctx.cache().current_user().name.to_string())
.icon_url(ctx.cache().current_user().face()),
);
Ok(embed)
}
async fn generate_playlist_embed(ctx: Context<'_>, sources: Vec<YoutubeDl>) -> Result<CreateEmbed, Error> {
let src = sources.get(0).unwrap();
let metadata = src.clone().aux_metadata().await.unwrap();
let AuxMetadata {title, thumbnail, source_url, artist, duration, ..} = metadata;
async fn generate_playlist_embed(
ctx: Context<'_>,
track: TrackHandle,
queue_length: usize,
) -> Result<CreateEmbed, Error> {
let meta_typemap = track.typemap().read().await;
let metadata = meta_typemap.get::<Metadata>().unwrap();
let AuxMetadata {
title,
thumbnail,
source_url,
artist,
duration,
..
} = metadata;
let timestamp = Timestamp::now();
let duration_minutes = duration.unwrap_or(Duration::new(0, 0)).clone().as_secs() / 60;
let duration_seconds = duration.unwrap_or(Duration::new(0, 0)).clone().as_secs() % 60;
let description = format!("Enqueued tracks: {}", sources.len() - 1);
let description = format!("Enqueued tracks: {}", queue_length - 1);
let embed = CreateEmbed::default()
.author(CreateEmbedAuthor::new("Playlist enqueued").icon_url(ctx.author().clone().face()))
.colour(Colour::from_rgb(255, 58, 97))
.title(title.unwrap())
.url(source_url.unwrap())
.thumbnail(thumbnail.unwrap_or(ctx.cache().current_user().face()))
.field("Artist", artist.unwrap_or("Unknown Artist".to_string()), true)
.field("Duration", format!("{:02}:{:02}", duration_minutes, duration_seconds), true)
.title(title.as_ref().unwrap())
.url(source_url.as_ref().unwrap())
.thumbnail(
thumbnail
.as_ref()
.unwrap_or(&ctx.cache().current_user().face()),
)
.field(
"Artist",
artist.as_ref().unwrap_or(&"Unknown Artist".to_string()),
true,
)
.field(
"Duration",
format!("{:02}:{:02}", duration_minutes, duration_seconds),
true,
)
.field("DJ", ctx.author().name.clone(), true)
.description(description)
.timestamp(timestamp)
.footer(CreateEmbedFooter::new(ctx.cache().current_user().name.to_string()).icon_url(ctx.cache().current_user().face()));
.footer(
CreateEmbedFooter::new(ctx.cache().current_user().name.to_string())
.icon_url(ctx.cache().current_user().face()),
);
Ok(embed)
}

View File

@@ -1,17 +1,21 @@
use std::time::Duration;
use crate::commands::music::metadata::Metadata;
use crate::{commands::embeds::error_embed, Context, Error};
use poise::serenity_prelude::CreateEmbed;
use poise::CreateReply;
use serenity::{
builder::{CreateEmbedAuthor, CreateEmbedFooter},
model::{Colour, Timestamp},
};
use songbird::input::AuxMetadata;
const QUEUE_DISPLAY_LENGTH: usize = 10;
/// Shows next tracks in queue; \
/// aliases: queue, q
#[poise::command(
prefix_command,
slash_command,
aliases("q"),
category = "Music"
)]
pub async fn queue(
ctx: Context<'_>
) -> Result<(), Error> {
#[poise::command(prefix_command, slash_command, aliases("q"), category = "Music")]
pub async fn queue(ctx: Context<'_>) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap();
let manager = songbird::get(&ctx.serenity_context())
@@ -22,26 +26,68 @@ pub async fn queue(
if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await;
let queue = handler.queue();
let mut queue_res = String::from("Queue: \n");
let mut queue_res = String::from("");
let mut too_long = false;
for (index, song) in queue.clone().current_queue().iter().enumerate() {
let meta_typemap = song.typemap().read().await;
let metadata = meta_typemap.get::<Metadata>().unwrap();
let AuxMetadata {
title,
artist,
duration,
..
} = metadata;
let duration_minutes = duration.unwrap_or(Duration::new(0, 0)).clone().as_secs() / 60;
let duration_seconds = duration.unwrap_or(Duration::new(0, 0)).clone().as_secs() % 60;
for (i, song) in queue.current_queue().iter().enumerate() {
queue_res.push_str(&format!(
"{}. {} - {}\n",
i + 1,
song.uuid(),
"Artist"
// song.metadata().artist.clone().unwrap_or_else(|| String::from("Unknown"))
"{}. {} - {} [{:02}:{:02}] \n",
index,
title.as_ref().unwrap(),
artist.as_ref().unwrap(),
duration_minutes,
duration_seconds
));
if index + 1 == QUEUE_DISPLAY_LENGTH {
too_long = true;
break;
}
}
if too_long {
queue_res.push_str(&format!(
"and {} more...",
queue.len() - QUEUE_DISPLAY_LENGTH
));
}
ctx.say(queue_res).await?;
ctx.send(CreateReply::default().embed(embed(ctx, queue_res).await.unwrap()))
.await?;
} else {
let msg = "I am not in a voice channel!";
ctx.send(
CreateReply::default().embed(error_embed(ctx, msg).await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(error_embed(ctx, msg).await.unwrap()))
.await?;
}
Ok(())
}
async fn embed(ctx: Context<'_>, queue: String) -> Result<CreateEmbed, Error> {
let title = "Now playing";
let timestamp = Timestamp::now();
let embed = CreateEmbed::default()
.author(CreateEmbedAuthor::new("Queue").icon_url(ctx.author().clone().face()))
.colour(Colour::from_rgb(255, 58, 97))
.title(title)
.description(queue)
.timestamp(timestamp)
.footer(
CreateEmbedFooter::new(ctx.cache().current_user().name.to_string())
.icon_url(ctx.cache().current_user().face()),
);
Ok(embed)
}

View File

@@ -1,4 +1,7 @@
use crate::{commands::embeds::{error_embed, embed}, Context, Error};
use crate::{
commands::embeds::{embed, error_embed},
Context, Error,
};
use poise::CreateReply;
use songbird::tracks::LoopState;
@@ -12,7 +15,9 @@ use songbird::tracks::LoopState;
)]
pub async fn repeat(
ctx: Context<'_>,
#[description = "How many times"] #[rest] times: usize
#[description = "How many times"]
#[rest]
times: usize,
) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap();
@@ -21,7 +26,6 @@ pub async fn repeat(
.expect("Songbird client placed at init")
.clone();
if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await;
let queue = handler.queue();
@@ -34,36 +38,52 @@ pub async fn repeat(
let _ = queue.current().unwrap().disable_loop();
ctx.send(
CreateReply::default().embed(embed(ctx, "Song Unlooped!", "", "").await.unwrap())
).await?;
CreateReply::default()
.embed(embed(ctx, "Song Unlooped!", "", "").await.unwrap()),
)
.await?;
}
LoopState::Finite(_) => {
if times == 0 {
let _ = queue.current().unwrap().disable_loop();
ctx.send(
CreateReply::default().embed(embed(ctx, "Song Unlooped!", "", "").await.unwrap())
).await?;
}
else if times < 100 {
CreateReply::default()
.embed(embed(ctx, "Song Unlooped!", "", "").await.unwrap()),
)
.await?;
} else if times < 100 {
let _ = queue.current().unwrap().loop_for(times);
ctx.send(
CreateReply::default().embed(embed(ctx, &format!("Song looped {} times!", times), "You definitelly love this song!", "").await.unwrap())
).await?;
}
else {
CreateReply::default().embed(
embed(
ctx,
&format!("Song looped {} times!", times),
"You definitelly love this song!",
"",
)
.await
.unwrap(),
),
)
.await?;
} else {
let _ = queue.current().unwrap().enable_loop();
ctx.send(
CreateReply::default().embed(embed(ctx, "Song looped forever!", "A very long time!", "").await.unwrap())
).await?;
CreateReply::default().embed(
embed(ctx, "Song looped forever!", "A very long time!", "")
.await
.unwrap(),
),
)
.await?;
}
}
}
} else {
let msg = "I am not in a voice channel!";
ctx.send(
CreateReply::default().embed(error_embed(ctx, msg).await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(error_embed(ctx, msg).await.unwrap()))
.await?;
}
Ok(())

View File

@@ -1,15 +1,12 @@
use crate::{commands::embeds::{error_embed, embed}, Context, Error};
use crate::{
commands::embeds::{embed, error_embed},
Context, Error,
};
use poise::CreateReply;
/// Resumes currently paused song
#[poise::command(
prefix_command,
slash_command,
category = "Music"
)]
pub async fn resume(
ctx: Context<'_>
) -> Result<(), Error> {
#[poise::command(prefix_command, slash_command, category = "Music")]
pub async fn resume(ctx: Context<'_>) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap();
let manager = songbird::get(&ctx.serenity_context())
@@ -24,13 +21,17 @@ pub async fn resume(
ctx.say(format!("Song resumed.")).await?;
ctx.send(
CreateReply::default().embed(embed(ctx, "Resumed!", "Currently paused song is now resumed!", "").await.unwrap())
).await?;
CreateReply::default().embed(
embed(ctx, "Resumed!", "Currently paused song is now resumed!", "")
.await
.unwrap(),
),
)
.await?;
} else {
let msg = "I am not in a voice channel!";
ctx.send(
CreateReply::default().embed(error_embed(ctx, msg).await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(error_embed(ctx, msg).await.unwrap()))
.await?;
}
Ok(())

View File

@@ -0,0 +1,11 @@
use crate::{commands::embeds::embed, Context, Error};
use poise::CreateReply;
/// Seeks a track by provided seconds
#[poise::command(prefix_command, slash_command, category = "Music")]
pub async fn seek(ctx: Context<'_>) -> Result<(), Error> {
ctx.send(CreateReply::default().embed(embed(ctx, "", "", "").await.unwrap()))
.await?;
Ok(())
}

View File

@@ -0,0 +1,11 @@
use crate::{commands::embeds::embed, Context, Error};
use poise::CreateReply;
/// Shuffles the playlist
#[poise::command(prefix_command, slash_command, category = "Music")]
pub async fn shuffle(ctx: Context<'_>) -> Result<(), Error> {
ctx.send(CreateReply::default().embed(embed(ctx, "", "", "").await.unwrap()))
.await?;
Ok(())
}

View File

@@ -1,15 +1,20 @@
use crate::{commands::embeds::{error_embed, embed}, Context, Error};
use crate::commands::music::metadata::Metadata;
use std::time::Duration;
use crate::{
commands::embeds::{embed, error_embed},
Context, Error,
};
use poise::CreateReply;
use serenity::{
builder::{CreateEmbed, CreateEmbedAuthor, CreateEmbedFooter},
model::{Colour, Timestamp},
};
use songbird::{input::AuxMetadata, tracks::TrackHandle};
/// Skips the currently playing song
#[poise::command(
prefix_command,
slash_command,
category = "Music"
)]
pub async fn skip(
ctx: Context<'_>
) -> Result<(), Error> {
#[poise::command(prefix_command, slash_command, category = "Music")]
pub async fn skip(ctx: Context<'_>) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap();
let manager = songbird::get(&ctx.serenity_context())
@@ -20,17 +25,88 @@ pub async fn skip(
if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await;
let queue = handler.queue();
let _ = queue.skip();
let _ = queue.clone().skip();
let track_raw = queue.clone().current_queue();
let track = track_raw.get(1);
let queue_length = queue.len() - 1;
ctx.send(
CreateReply::default().embed(embed(ctx, "Skipped!", "Next song: {song}", &format!("Songs left in queue: {}", queue.len())).await.unwrap())
).await?;
let response;
match track {
Some(track) => {
response = CreateReply::default().embed(
generate_embed(ctx, track.clone(), queue_length)
.await
.unwrap(),
);
}
None => {
response = CreateReply::default().embed(
embed(ctx, "Skipped!", "The queue is empty!", "")
.await
.unwrap(),
);
}
};
ctx.send(response).await?;
} else {
let msg = "I am not in a voice channel!";
ctx.send(
CreateReply::default().embed(error_embed(ctx, msg).await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(error_embed(ctx, msg).await.unwrap()))
.await?;
}
Ok(())
}
async fn generate_embed(
ctx: Context<'_>,
track: TrackHandle,
queue_length: usize,
) -> Result<CreateEmbed, Error> {
let meta_typemap = track.typemap().read().await;
let metadata = meta_typemap.get::<Metadata>().unwrap();
let AuxMetadata {
title,
thumbnail,
source_url,
artist,
duration,
..
} = metadata;
let timestamp = Timestamp::now();
let duration_minutes = duration.unwrap_or(Duration::new(0, 0)).clone().as_secs() / 60;
let duration_seconds = duration.unwrap_or(Duration::new(0, 0)).clone().as_secs() % 60;
let description = format!("Song skipped! Queue length is {}", queue_length);
let embed = CreateEmbed::default()
.author(CreateEmbedAuthor::new("Skipped!").icon_url(ctx.author().clone().face()))
.colour(Colour::from_rgb(255, 58, 97))
.title(title.as_ref().unwrap())
.url(source_url.as_ref().unwrap())
.thumbnail(
thumbnail
.as_ref()
.unwrap_or(&ctx.cache().current_user().face()),
)
.field(
"Artist",
artist.as_ref().unwrap_or(&"Unknown Artist".to_string()),
true,
)
.field(
"Duration",
format!("{:02}:{:02}", duration_minutes, duration_seconds),
true,
)
.field("DJ", ctx.author().name.clone(), true)
.description(description)
.timestamp(timestamp)
.footer(
CreateEmbedFooter::new(ctx.cache().current_user().name.to_string())
.icon_url(ctx.cache().current_user().face()),
);
Ok(embed)
}

View File

@@ -0,0 +1,5 @@
pub mod effect;
pub mod stream;
pub use effect::effect;
pub use stream::stream;

View File

@@ -0,0 +1,11 @@
use crate::{commands::embeds::embed, Context, Error};
use poise::CreateReply;
/// Plays one of available audio effects
#[poise::command(prefix_command, slash_command, category = "Music")]
pub async fn effect(ctx: Context<'_>) -> Result<(), Error> {
ctx.send(CreateReply::default().embed(embed(ctx, "Playing an effect", "", "").await.unwrap()))
.await?;
Ok(())
}

View File

@@ -0,0 +1,11 @@
use crate::{commands::embeds::embed, Context, Error};
use poise::CreateReply;
/// Hijacks current audio output and plays selected audio
#[poise::command(prefix_command, slash_command, aliases("override"), category = "Music")]
pub async fn stream(ctx: Context<'_>) -> Result<(), Error> {
ctx.send(CreateReply::default().embed(embed(ctx, "Playing audio", "", "").await.unwrap()))
.await?;
Ok(())
}

View File

@@ -1,17 +1,13 @@
use crate::{commands::embeds::{error_embed, embed}, Context, Error};
use crate::{
commands::embeds::{embed, error_embed},
Context, Error,
};
use poise::CreateReply;
/// Stops playback and destroys the queue; \
/// aliases: stop, end
#[poise::command(
prefix_command,
slash_command,
aliases("end"),
category = "Music"
)]
pub async fn stop(
ctx: Context<'_>
) -> Result<(), Error> {
#[poise::command(prefix_command, slash_command, aliases("end"), category = "Music")]
pub async fn stop(ctx: Context<'_>) -> Result<(), Error> {
let guild_id = ctx.guild_id().unwrap();
let manager = songbird::get(&ctx.serenity_context())
@@ -25,13 +21,22 @@ pub async fn stop(
queue.stop();
ctx.send(
CreateReply::default().embed(embed(ctx, "Stopped!", "Playback stopped!", "Queue destroyed! Bot will stay and chill with you in a vc").await.unwrap())
).await?;
CreateReply::default().embed(
embed(
ctx,
"Stopped!",
"Playback stopped!",
"Queue destroyed! Bot will stay and chill with you in a vc",
)
.await
.unwrap(),
),
)
.await?;
} else {
let msg = "I am not in a voice channel!";
ctx.send(
CreateReply::default().embed(error_embed(ctx, msg).await.unwrap())
).await?;
ctx.send(CreateReply::default().embed(error_embed(ctx, msg).await.unwrap()))
.await?;
}
Ok(())

View File

@@ -0,0 +1,11 @@
use crate::{commands::embeds::embed, Context, Error};
use poise::CreateReply;
/// Changes output volume
#[poise::command(prefix_command, slash_command, category = "Music")]
pub async fn volume(ctx: Context<'_>) -> Result<(), Error> {
ctx.send(CreateReply::default().embed(embed(ctx, "", "", "").await.unwrap()))
.await?;
Ok(())
}

View File

@@ -1,7 +1,31 @@
pub mod ping;
pub mod register;
pub mod ai;
pub mod dice;
pub mod dictionary;
pub mod help;
pub mod ip;
pub mod metar;
pub mod owoify;
pub mod ping;
pub mod posix;
pub mod qr;
pub mod register;
pub mod taf;
// pub mod uptime;
pub mod verse;
pub mod weather;
pub use ping::ping;
pub use register::register;
pub use ai::ai;
pub use dice::dice;
pub use dictionary::dictionary;
pub use help::help;
pub use ip::ip;
pub use metar::metar;
pub use owoify::owoify;
pub use ping::ping;
pub use posix::posix;
pub use qr::qr;
pub use register::register;
pub use taf::taf;
// pub use uptime::uptime;
pub use verse::verse;
pub use weather::weather;

50
src/commands/tools/ai.rs Normal file
View File

@@ -0,0 +1,50 @@
use rand::Rng;
use std::thread::sleep;
use std::time::Duration;
use poise::CreateReply;
use crate::{commands::embeds::embed, Context, Error};
/// Asks AI
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn ai(
ctx: Context<'_>,
#[description = "prompt to ask"]
#[rest]
prompt: String,
) -> Result<(), Error> {
let iamsorry = vec![
"I'm sorry, but as an AI language model, I must follow ethical guidelines, and I cannot engage in harmful, malicious, or offensive behavior.",
"I'm sorry, but as an AI language model, I may not always be perfect and can make mistakes or provide inaccurate information. Please verify important details from reliable sources.",
"I'm sorry, but as an AI language model, I can't engage in real-time conversations or remember previous interactions with users.",
"I'm sorry, but as an AI language model, I don't have personal opinions or feelings; I can only provide information based on patterns in the data I was trained on.",
"I'm sorry, but as an AI language model, I don't have access to real-time information or updates beyond my last training data in September 2021.",
"I'm sorry, but as an AI language model, I don't have the ability to recall specific personal data or information about individuals.",
"I'm sorry, but as an AI language model, I don't have consciousness or self-awareness. I'm simply a program designed to process and generate human-like text."
];
println!("Funny prompts: {}", prompt);
let response;
let _ = {
let mut rng = rand::thread_rng();
response = rng.gen_range(0..iamsorry.len());
};
sleep(Duration::from_secs(3));
ctx.send(
CreateReply::default().embed(
embed(ctx, "AI Response:", "", &format!("{}", iamsorry[response]))
.await
.unwrap(),
),
)
.await?;
Ok(())
}

View File

@@ -0,0 +1,33 @@
use rand::Rng;
use poise::CreateReply;
use crate::{commands::embeds::embed, Context, Error};
/// Rolls a dice
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn dice(ctx: Context<'_>) -> Result<(), Error> {
let dice;
let _ = {
let mut rng = rand::thread_rng();
dice = rng.gen_range(1..7);
};
ctx.send(
CreateReply::default().embed(
embed(
ctx,
"Let's roll the dice!",
"",
&format!("Your number is: {}", dice),
)
.await
.unwrap(),
),
)
.await?;
Ok(())
}

View File

@@ -0,0 +1,12 @@
use poise::CreateReply;
use crate::{commands::embeds::embed, Context, Error};
/// Explains provided query
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn dictionary(ctx: Context<'_>) -> Result<(), Error> {
ctx.send(CreateReply::default().embed(embed(ctx, "", "", "").await.unwrap()))
.await?;
Ok(())
}

12
src/commands/tools/ip.rs Normal file
View File

@@ -0,0 +1,12 @@
use poise::CreateReply;
use crate::{commands::embeds::embed, Context, Error};
/// Shows IP information
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn ip(ctx: Context<'_>) -> Result<(), Error> {
ctx.send(CreateReply::default().embed(embed(ctx, "", "", "").await.unwrap()))
.await?;
Ok(())
}

View File

@@ -0,0 +1,12 @@
use poise::CreateReply;
use crate::{commands::embeds::embed, Context, Error};
/// Prints metar for provided airport
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn metar(ctx: Context<'_>) -> Result<(), Error> {
ctx.send(CreateReply::default().embed(embed(ctx, "", "", "").await.unwrap()))
.await?;
Ok(())
}

View File

@@ -0,0 +1,12 @@
use poise::CreateReply;
use crate::{commands::embeds::embed, Context, Error};
/// Owoifies whatever you want uwu
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn owoify(ctx: Context<'_>) -> Result<(), Error> {
ctx.send(CreateReply::default().embed(embed(ctx, "", "", "").await.unwrap()))
.await?;
Ok(())
}

View File

@@ -2,17 +2,12 @@ use crate::{Context, Error};
use std::time::SystemTime;
/// Pings you backs with a response time
#[poise::command(
prefix_command,
slash_command,
category = "Tools"
)]
pub async fn ping(
ctx: Context<'_>
) -> Result<(), Error> {
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn ping(ctx: Context<'_>) -> Result<(), Error> {
let system_now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap().as_millis() as i64;
.unwrap()
.as_millis() as i64;
let message_now = ctx.created_at().timestamp_millis();

View File

@@ -0,0 +1,30 @@
use std::time::SystemTime;
use poise::CreateReply;
use crate::{commands::embeds::embed, Context, Error};
/// Prints current time in POSIX format
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn posix(ctx: Context<'_>) -> Result<(), Error> {
let time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_millis();
ctx.send(
CreateReply::default().embed(
embed(
ctx,
"The time is",
"since Jan 1st 1970",
&format!("{} ms", time),
)
.await
.unwrap(),
),
)
.await?;
Ok(())
}

48
src/commands/tools/qr.rs Normal file
View File

@@ -0,0 +1,48 @@
use poise::CreateReply;
use serenity::{
builder::{CreateEmbed, CreateEmbedAuthor, CreateEmbedFooter},
model::{Colour, Timestamp},
};
use crate::{Context, Error};
use url::form_urlencoded;
/// Creates a qr code from text
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn qr(
ctx: Context<'_>,
#[description = "Message to encode"]
#[rest]
message: String,
) -> Result<(), Error> {
let response = CreateReply::default().embed(generate_embed(ctx, message).await.unwrap());
ctx.send(response).await?;
Ok(())
}
async fn generate_embed(ctx: Context<'_>, message: String) -> Result<CreateEmbed, Error> {
let timestamp = Timestamp::now();
let data: String = form_urlencoded::byte_serialize(message.as_bytes()).collect();
let url = format!(
"http://api.qrserver.com/v1/create-qr-code/?data={}&size=1000x1000&ecc=Q&margin=8",
data
);
let embed = CreateEmbed::default()
.author(
CreateEmbedAuthor::new("Your message as a QR Code!")
.icon_url(ctx.author().clone().face()),
)
.colour(Colour::from_rgb(255, 58, 97))
.title("Your QR Code:")
.url(url.clone())
.image(url)
.timestamp(timestamp)
.footer(
CreateEmbedFooter::new(ctx.cache().current_user().name.to_string())
.icon_url(ctx.cache().current_user().face()),
);
Ok(embed)
}

View File

@@ -1,13 +1,7 @@
use crate::{Context, Error};
#[poise::command(
prefix_command,
hide_in_help,
owners_only
)]
pub async fn register(
ctx: Context<'_>
) -> Result<(), Error> {
#[poise::command(prefix_command, hide_in_help, owners_only)]
pub async fn register(ctx: Context<'_>) -> Result<(), Error> {
poise::builtins::register_application_commands_buttons(ctx).await?;
Ok(())
}

12
src/commands/tools/taf.rs Normal file
View File

@@ -0,0 +1,12 @@
use poise::CreateReply;
use crate::{commands::embeds::embed, Context, Error};
/// Returns taf for provided airport
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn taf(ctx: Context<'_>) -> Result<(), Error> {
ctx.send(CreateReply::default().embed(embed(ctx, "", "", "").await.unwrap()))
.await?;
Ok(())
}

View File

@@ -0,0 +1,35 @@
use poise::CreateReply;
use crate::{commands::embeds::embed, Context, Error};
// Currently unable to get information on how long the thread was running.
const PROCESS_UPTIME: i64 = 1000;
/// Checks how long the bot has been running
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn uptime(ctx: Context<'_>) -> Result<(), Error> {
let uptime = PROCESS_UPTIME;
let days = uptime / (24 * 60 * 60);
let hours = (uptime % (24 * 60 * 60)) / 3600;
let minutes = (uptime % 60 * 60) / 60;
let seconds = uptime % 60;
ctx.send(
CreateReply::default().embed(
embed(
ctx,
"I have been up and awake for",
&format!("{} seconds", uptime),
&format!(
"{} days, {} hours, {} minutes and {} seconds",
days, hours, minutes, seconds
),
)
.await
.unwrap(),
),
)
.await?;
Ok(())
}

View File

@@ -0,0 +1,78 @@
use crate::{
commands::embeds::{embed, error_embed},
Context, Error,
};
use poise::CreateReply;
use serde::{Deserialize, Serialize};
use url::form_urlencoded;
/// Reference Bible by verse
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn verse(
ctx: Context<'_>,
#[description = "Latin?"]
#[flag]
latin: bool,
#[description = "BOOK+CHAPTER:VERSE"]
#[rest]
verse: String,
) -> Result<(), Error> {
let data: String = form_urlencoded::byte_serialize(verse.as_bytes()).collect();
let translation = if latin { "clementine" } else { "web" };
let client = reqwest::Client::new();
let response = client
.get(format!(
"https://bible-api.com/{}?translation={}",
data, translation
))
.send()
.await
.unwrap();
match response.status() {
reqwest::StatusCode::OK => {
match response.json::<APIResponse>().await {
Ok(parsed) => {
if parsed.text.len() > 4000 {
ctx.send(
CreateReply::default()
.embed(error_embed(ctx, "Quoted text is too long!").await.unwrap()),
)
.await?;
return Ok(());
}
ctx.send(
CreateReply::default().embed(
embed(
ctx,
&parsed.translation_name,
&parsed.text,
&parsed.reference,
)
.await
.unwrap(),
),
)
.await?;
}
Err(err) => println!("Something is messed up! {:?}", err),
};
}
reqwest::StatusCode::UNAUTHORIZED => {
println!("Unauthorized.. Uoops!!");
}
error => {
println!("Something went wrong: {:?}", error);
}
}
Ok(())
}
#[derive(Serialize, Deserialize, Debug)]
struct APIResponse {
reference: String,
text: String,
translation_name: String,
translation_note: String,
}

View File

@@ -0,0 +1,17 @@
use poise::CreateReply;
use crate::{commands::embeds::embed, Context, Error};
/// Shows weather for provided location
#[poise::command(prefix_command, slash_command, category = "Tools")]
pub async fn weather(
ctx: Context<'_>,
#[description = "Provide a city name"]
#[rest]
_location: String,
) -> Result<(), Error> {
ctx.send(CreateReply::default().embed(embed(ctx, "", "", "").await.unwrap()))
.await?;
Ok(())
}

View File

@@ -1,5 +1,5 @@
use reqwest::Client as HttpClient;
use poise::serenity_prelude::prelude::TypeMapKey;
use reqwest::Client as HttpClient;
pub struct HttpKey;

View File

@@ -1,9 +1,9 @@
use poise::serenity_prelude::{self as serenity, ActivityData};
use reqwest::Client as HttpClient;
use songbird::SerenityInit;
use std::sync::Arc;
use std::time::Duration;
use tracing::{info, warn, error};
use poise::serenity_prelude::{self as serenity, ActivityData};
use songbird::SerenityInit;
use reqwest::Client as HttpClient;
use tracing::{error, info, warn};
mod commands;
mod http;
@@ -37,7 +37,8 @@ async fn main() {
tracing_subscriber::fmt::init();
dotenv::dotenv().expect("Failed to load .env file.");
let token = std::env::var("DISCORD_TOKEN").expect("Environment variable `DISCORD_TOKEN` not found!");
let token =
std::env::var("DISCORD_TOKEN").expect("Environment variable `DISCORD_TOKEN` not found!");
let prefix = std::env::var("PREFIX").expect("Environment variable `PREFIX` not found!");
let commands = vec![
@@ -45,17 +46,34 @@ async fn main() {
music::deafen(),
music::join(),
music::leave(),
music::repeat(),
music::mute(),
music::pause(),
music::play(),
music::queue(),
music::repeat(),
music::resume(),
music::seek(),
music::shuffle(),
music::skip(),
music::stop(),
tools::ping(),
tools::register(),
music::volume(),
music::soundboard::effect(),
music::soundboard::stream(),
tools::ai(),
tools::dice(),
tools::dictionary(),
tools::help(),
tools::ip(),
tools::metar(),
tools::owoify(),
tools::ping(),
tools::posix(),
tools::qr(),
tools::register(),
tools::taf(),
// tools::uptime(),
tools::verse(),
tools::weather(),
];
let options = poise::FrameworkOptions {
@@ -95,7 +113,10 @@ async fn main() {
skip_checks_for_owners: false,
event_handler: |_ctx, event, _framework, _data| {
Box::pin(async move {
info!("Got an event in event handler: {:?}", event.snake_case_name());
info!(
"Got an event in event handler: {:?}",
event.snake_case_name()
);
Ok(())
})
},
@@ -105,7 +126,10 @@ async fn main() {
let framework = poise::Framework::builder()
.setup(move |ctx, ready, _framework| {
Box::pin(async move {
info!("{} [{}] connected successfully!", ready.user.name, ready.user.id);
info!(
"{} [{}] connected successfully!",
ready.user.name, ready.user.id
);
ctx.set_activity(Some(ActivityData::listening(prefix + "help")));
// poise::builtins::register_globally(ctx, &framework.options().commands).await?;
@@ -115,7 +139,8 @@ async fn main() {
.options(options)
.build();
let intents = serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT;
let intents =
serenity::GatewayIntents::non_privileged() | serenity::GatewayIntents::MESSAGE_CONTENT;
let mut client = serenity::ClientBuilder::new(token, intents)
.framework(framework)

Submodule src/spotify deleted from ea246e9ed2

1
src/spotify-parser Submodule

Submodule src/spotify-parser added at e3b3c0fb6e