Formatting code

This commit is contained in:
Benjamin Sherriff
2024-05-12 09:05:59 -04:00
parent c971c55aa3
commit 1de68f86ae
46 changed files with 1109 additions and 609 deletions

View File

@@ -4,7 +4,9 @@ use log::{debug, warn};
use reqwest::Url;
use serenity::client::Cache;
use serenity::model::application::interaction::{InteractionResponseType, application_command::ApplicationCommandInteraction};
use serenity::model::application::interaction::{
InteractionResponseType, application_command::ApplicationCommandInteraction,
};
use serenity::model::prelude::{GuildId, ChannelId};
use serenity::model::user::User;
use serenity::prelude::*;
@@ -21,33 +23,60 @@ pub mod skip;
pub mod stop;
pub mod volume;
pub async fn join_by_user(cache: &Arc<Cache>, manager: Arc<Songbird>, guild_id_option: &Option<GuildId>, user: &User) -> Result<(), ServiceError> {
pub async fn join_by_user(
cache: &Arc<Cache>,
manager: Arc<Songbird>,
guild_id_option: &Option<GuildId>,
user: &User,
) -> Result<(), ServiceError> {
let guild_id = match guild_id_option {
Some(g) => g,
None => return Err(ServiceError { status: 422, message: format!("{}", "No guild ID set") })
None => {
return Err(ServiceError {
status: 422,
message: format!("{}", "No guild ID set"),
})
}
};
let channel_id = match find_voice_channel(cache, &guild_id, &user) {
Ok(channel) => channel,
Err(err) => return Err(ServiceError { status: 500, message: err.to_string() })
Err(err) => {
return Err(ServiceError {
status: 500,
message: err.to_string(),
})
}
};
join(manager, guild_id, &channel_id).await
}
pub async fn join(manager: Arc<Songbird>, guild_id: &GuildId, channel_id: &ChannelId) -> Result<(), ServiceError> {
pub async fn join(
manager: Arc<Songbird>,
guild_id: &GuildId,
channel_id: &ChannelId,
) -> Result<(), ServiceError> {
debug!("<{}> Joining channel {}", guild_id.0, channel_id.0);
let (_handle_lock, success) = manager.join(guild_id.to_owned(), channel_id.to_owned()).await;
let (_handle_lock, success) = manager
.join(guild_id.to_owned(), channel_id.to_owned())
.await;
match success {
Ok(s) => Ok(s),
Err(err) => {
warn!("Failed to join channel: {:?}", err);
Err(ServiceError { status: 500, message: err.to_string() })
Err(ServiceError {
status: 500,
message: err.to_string(),
})
}
}
}
pub async fn leave(manager: Arc<Songbird>, guild_id_option: &Option<GuildId>) -> Result<(), String> {
pub async fn leave(
manager: Arc<Songbird>,
guild_id_option: &Option<GuildId>,
) -> Result<(), String> {
let guild_id = match guild_id_option {
Some(g) => g,
None => {
@@ -58,39 +87,72 @@ pub async fn leave(manager: Arc<Songbird>, guild_id_option: &Option<GuildId>) ->
if manager.get(*guild_id).is_some() {
debug!("<{}> Disconnecting from channel", guild_id.0);
if let Err(e) = manager.remove(*guild_id).await {
return Err(format!("{}", e))
return Err(format!("{}", e));
}
}
Ok(())
}
fn find_voice_channel(cache: &Arc<Cache>, guild_id: &GuildId, user: &User) -> Result<ChannelId, String> {
fn find_voice_channel(
cache: &Arc<Cache>,
guild_id: &GuildId,
user: &User,
) -> Result<ChannelId, String> {
let guild = match guild_id.to_guild_cached(cache.to_owned()) {
Some(g) => g,
None => return Err(format!("Guild not found"))
None => return Err(format!("Guild not found")),
};
match guild.voice_states.get(&user.id).and_then(|voice_state| voice_state.channel_id) {
match guild
.voice_states
.get(&user.id)
.and_then(|voice_state| voice_state.channel_id)
{
Some(channel) => Ok(channel),
None => return Err(format!("User is not in a voice channel"))
None => return Err(format!("User is not in a voice channel")),
}
}
pub async fn create_response(ctx: &Context, command: &ApplicationCommandInteraction, content: String) -> Result<(), SerenityError> {
command.create_interaction_response(&ctx.http, |response: &mut serenity::builder::CreateInteractionResponse<'_>| {
response
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|message: &mut serenity::builder::CreateInteractionResponseData<'_>| message.content(content))
}).await
pub async fn create_response(
ctx: &Context,
command: &ApplicationCommandInteraction,
content: String,
) -> Result<(), SerenityError> {
command
.create_interaction_response(
&ctx.http,
|response: &mut serenity::builder::CreateInteractionResponse<'_>| {
response
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(
|message: &mut serenity::builder::CreateInteractionResponseData<'_>| {
message.content(content)
},
)
},
)
.await
}
pub async fn edit_response(ctx: &Context, command: &ApplicationCommandInteraction, content: String) -> Result<serenity::model::channel::Message, SerenityError> {
command.edit_original_interaction_response(&ctx.http, |response: &mut serenity::builder::EditInteractionResponse| {
response.content(content)
}).await
pub async fn edit_response(
ctx: &Context,
command: &ApplicationCommandInteraction,
content: String,
) -> Result<serenity::model::channel::Message, SerenityError> {
command
.edit_original_interaction_response(
&ctx.http,
|response: &mut serenity::builder::EditInteractionResponse| response.content(content),
)
.await
}
pub async fn add_song(call: Arc<Mutex<Call>>, url: &str, lazy: bool, volume: Option<f32>) -> Result<Metadata, SongbirdError> {
pub async fn add_song(
call: Arc<Mutex<Call>>,
url: &str,
lazy: bool,
volume: Option<f32>,
) -> Result<Metadata, SongbirdError> {
let source = Restartable::ytdl(url.to_owned(), lazy).await?;
let mut handler = call.lock().await;
let track: Input = source.into();
@@ -115,9 +177,10 @@ pub fn get_playlist_urls(url: &str) -> Result<Vec<PlaylistItem>, ServiceError> {
None
} else {
Some(
serde_json::from_slice::<PlaylistItem>(line.as_bytes()).map_err(
|err| ServiceError { status: 500, message: err.to_string() }
)
serde_json::from_slice::<PlaylistItem>(line.as_bytes()).map_err(|err| ServiceError {
status: 500,
message: err.to_string(),
}),
)
}
})
@@ -134,11 +197,16 @@ pub fn get_playlist_urls(url: &str) -> Result<Vec<PlaylistItem>, ServiceError> {
fn is_valid_url(url: &str) -> (bool, bool) {
Url::parse(url).ok().map_or((false, false), |valid_url| {
let is_playlist: bool = valid_url.query_pairs().find(|(key, _)| key == "list").map_or(false, |_| true);
let is_playlist: bool = valid_url
.query_pairs()
.find(|(key, _)| key == "list")
.map_or(false, |_| true);
(true, is_playlist)
})
}
pub async fn get_songbird(ctx: &Context) -> Arc<Songbird> {
songbird::get(ctx).await.expect("Songbird Voice client placed in at initialization")
songbird::get(ctx)
.await
.expect("Songbird Voice client placed in at initialization")
}

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -40,4 +42,4 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("pause").description("Pause the current track")
}
}

View File

@@ -10,7 +10,10 @@ use siren::ServiceError;
use songbird::{EventHandler, Songbird};
use crate::bot::ytdlp::PlaylistItem;
use crate::bot::{guilds::QueryGuild, commands::audio::{leave, get_playlist_urls, add_song, get_songbird}};
use crate::bot::{
guilds::QueryGuild,
commands::audio::{leave, get_playlist_urls, add_song, get_songbird},
};
use super::{create_response, edit_response, is_valid_url, join_by_user};
@@ -22,20 +25,23 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
Some(s) => s.to_owned(),
None => {
warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await {
if let Err(why) =
create_response(&ctx, &command, format!("Track option is missing")).await
{
error!("Failed to create response message: {}", why);
}
return;
}
}
},
None => {
warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await {
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await
{
error!("Failed to create response message: {}", why);
}
return;
}
}
},
None => {
warn!("Missing track option");
if let Err(why) = create_response(&ctx, &command, format!("Track option is missing")).await {
@@ -52,12 +58,14 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}
let manager = get_songbird(ctx).await;
match join_by_user(&ctx.cache, manager,&command.guild_id, &command.user).await {
match join_by_user(&ctx.cache, manager, &command.guild_id, &command.user).await {
Ok(_) => {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -76,15 +84,17 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
if let Err(why) = edit_response(&ctx, &command, message).await {
error!("Failed to edit response message: {}", why);
}
},
}
Err(err) => {
warn!("Failed to play track: {}", err);
if let Err(why) = edit_response(&ctx, &command, format!("Failed to play track: {}", err)).await {
if let Err(why) =
edit_response(&ctx, &command, format!("Failed to play track: {}", err)).await
{
error!("Failed to edit response message: {}", why);
}
}
};
},
}
Err(err) => {
warn!("{}", err);
if let Err(why) = edit_response(&ctx, &command, format!("{}", err)).await {
@@ -94,7 +104,11 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}
}
pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: String) -> Result<i32, ServiceError> {
pub async fn play_track(
manager: Arc<Songbird>,
guild_id: GuildId,
track_url: String,
) -> Result<i32, ServiceError> {
let mut track_count = 0;
if let Some(handler_lock) = manager.get(guild_id) {
let is_queue_empty = {
@@ -105,7 +119,10 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
let valid = is_valid_url(&track_url);
if !valid.0 {
warn!("Invalid track url: {}", track_url);
return Err(ServiceError { status: 422, message: format!("Invalid track url: {}", track_url) })
return Err(ServiceError {
status: 422,
message: format!("Invalid track url: {}", track_url),
});
}
let mut playlist_items: Vec<PlaylistItem> = Vec::new();
if valid.1 {
@@ -113,7 +130,10 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
Ok(items) => items,
Err(err) => {
warn!("Failed to get playlist urls: {}", err);
return Err(ServiceError { status: 422, message: err.to_string() })
return Err(ServiceError {
status: 422,
message: err.to_string(),
});
}
};
} else {
@@ -122,26 +142,42 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
url: track_url,
title: "".to_string(),
duration: 0,
playlist_index: 0
playlist_index: 0,
};
playlist_items.push(playlist_item);
}
for item in playlist_items {
match add_song(handler_lock.clone(), &item.url, is_queue_empty, Some(guild.volume as f32 / 100.0)).await {
match add_song(
handler_lock.clone(),
&item.url,
is_queue_empty,
Some(guild.volume as f32 / 100.0),
)
.await
{
Ok(added_song) => {
let track_title = added_song.title.unwrap();
debug!("Added track: {}", track_title);
let mut handler = handler_lock.lock().await;
handler.remove_all_global_events();
handler.add_global_event(songbird::Event::Track(songbird::TrackEvent::End), TrackEndNotifier { guild_id, call: manager.clone() });
handler.add_global_event(
songbird::Event::Track(songbird::TrackEvent::End),
TrackEndNotifier {
guild_id,
call: manager.clone(),
},
);
track_count += 1;
},
}
Err(err) => {
warn!("Failed to add song: {}", err);
if let Err(why) = leave(manager, &Some(guild_id)).await {
error!("Failed to leave voice channel: {}", why);
}
return Err(ServiceError { status: 422, message: err.to_string() })
return Err(ServiceError {
status: 422,
message: err.to_string(),
});
}
}
}
@@ -150,17 +186,21 @@ pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: St
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("play").description("Plays the given track").create_option(|option| { option
.name("track")
.description("The track to be played")
.kind(serenity::model::prelude::command::CommandOptionType::String)
.required(true)
})
command
.name("play")
.description("Plays the given track")
.create_option(|option| {
option
.name("track")
.description("The track to be played")
.kind(serenity::model::prelude::command::CommandOptionType::String)
.required(true)
})
}
struct TrackEndNotifier {
pub call: std::sync::Arc<songbird::Songbird>,
pub guild_id: serenity::model::id::GuildId
pub guild_id: serenity::model::id::GuildId,
}
#[async_trait]

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -39,5 +41,7 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("resume").description("Resume the current track")
}
command
.name("resume")
.description("Resume the current track")
}

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -40,4 +42,4 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("skip").description("Skip the current track")
}
}

View File

@@ -16,7 +16,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -34,5 +36,7 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("stop").description("Stop the current track and clear the queue")
}
command
.name("stop")
.description("Stop the current track and clear the queue")
}

View File

@@ -19,20 +19,23 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
Some(p) => p as i32,
None => {
warn!("Unable to get volume option as a string");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await {
if let Err(why) =
create_response(&ctx, &command, format!("Volume option is missing")).await
{
error!("Failed to create response message: {}", why);
}
return;
}
}
},
None => {
warn!("Missing volume option value");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await {
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await
{
error!("Failed to create response message: {}", why);
}
return;
}
}
},
None => {
warn!("Missing volume option");
if let Err(why) = create_response(&ctx, &command, format!("Volume option is missing")).await {
@@ -51,7 +54,9 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
let guild_id = match command.guild_id {
Some(g) => g,
None => {
if let Err(why) = edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await {
if let Err(why) =
edit_response(&ctx, &command, "Unable to join voice channel".to_string()).await
{
error!("Failed to edit response message: {}", why);
}
return;
@@ -59,7 +64,8 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
};
let manager = get_songbird(ctx).await;
set_volume(manager, guild_id, volume).await;
if let Err(why) = edit_response(&ctx, &command, format!("Setting the volume to {}", volume)).await {
if let Err(why) = edit_response(&ctx, &command, format!("Setting the volume to {}", volume)).await
{
error!("Failed to set the volume: {}", why);
}
}
@@ -79,10 +85,14 @@ pub async fn set_volume(manager: Arc<Songbird>, guild_id: GuildId, volume: i32)
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("volume").description("Set the audio player volume").create_option(|option| { option
command
.name("volume")
.description("Volume between 0 and 100")
.kind(serenity::model::prelude::command::CommandOptionType::Integer)
.required(true)
})
}
.description("Set the audio player volume")
.create_option(|option| {
option
.name("volume")
.description("Volume between 0 and 100")
.kind(serenity::model::prelude::command::CommandOptionType::Integer)
.required(true)
})
}

View File

@@ -26,31 +26,34 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
},
];
match QueryMessage::get_all(&QueryFilters {
by_guild_id: Some(guild_id.0 as i64),
by_channel_id: Some(channel_id.0 as i64),
by_user_id: Some(author_id.0 as i64),
..Default::default()
}, 100, 1) {
match QueryMessage::get_all(
&QueryFilters {
by_guild_id: Some(guild_id.0 as i64),
by_channel_id: Some(channel_id.0 as i64),
by_user_id: Some(author_id.0 as i64),
..Default::default()
},
100,
1,
) {
Ok(m) => {
for message in m {
messages.push(
ChatCompletionMessage {
role: GPTRole::User,
content: format!("{}", message.request)
}
);
messages.push(
ChatCompletionMessage {
role: GPTRole::Assistant,
content: format!("{}", message.response)
}
);
messages.push(ChatCompletionMessage {
role: GPTRole::User,
content: format!("{}", message.request),
});
messages.push(ChatCompletionMessage {
role: GPTRole::Assistant,
content: format!("{}", message.response),
});
}
},
Err(err) => warn!("Could not load previous messages: {}", err)
}
Err(err) => warn!("Could not load previous messages: {}", err),
};
messages.push(ChatCompletionMessage { role: GPTRole::User, content: parsed_content.clone() });
messages.push(ChatCompletionMessage {
role: GPTRole::User,
content: parsed_content.clone(),
});
let request = ChatCompletionRequest {
model: oai.default_model.clone(),
@@ -61,14 +64,18 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
max_tokens: Some(oai.max_tokens),
presence_penalty: Some(0.6),
frequency_penalty: Some(0.0),
user: Some(msg.author.name.clone())
user: Some(msg.author.name.clone()),
};
// Get the thread channel ID
let thread_name = generate_thread_name(oai, &parsed_content, 99).await;
let response_channel = match msg.channel_id.create_private_thread(&ctx.http, |thread| {
thread.name(thread_name).kind(ChannelType::PublicThread)
}).await {
let response_channel = match msg
.channel_id
.create_private_thread(&ctx.http, |thread| {
thread.name(thread_name).kind(ChannelType::PublicThread)
})
.await
{
Ok(c) => {
let allow = Permissions::SEND_MESSAGES;
let deny = Permissions::SEND_TTS_MESSAGES | Permissions::ATTACH_FILES;
@@ -80,9 +87,7 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
let _ = c.create_permission(&ctx.http, &overwrite).await;
c.id
}
Err(_) => {
channel_id
}
Err(_) => channel_id,
};
let typing = response_channel.start_typing(&ctx.http).unwrap();
@@ -144,7 +149,10 @@ pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
async fn generate_thread_name(oai: &OAI, s: &str, max_chars: usize) -> String {
let message = ChatCompletionMessage {
role: GPTRole::User,
content: format!("---\n{}\n---\nSummarize the message above into a concise Discord thread title", s)
content: format!(
"---\n{}\n---\nSummarize the message above into a concise Discord thread title",
s
),
};
let request = ChatCompletionRequest {
model: oai.default_model.clone(),
@@ -155,13 +163,14 @@ async fn generate_thread_name(oai: &OAI, s: &str, max_chars: usize) -> String {
max_tokens: Some(oai.max_tokens),
presence_penalty: Some(0.6),
frequency_penalty: Some(0.0),
user: None
user: None,
};
// Truncate the response to the max number of characters
let mut response = match s.char_indices().nth(max_chars) {
None => s,
Some((idx, _)) => &s[..idx]
}.to_string();
Some((idx, _)) => &s[..idx],
}
.to_string();
// Set the response to the OAI response
match oai.chat_completion(request).await {
Ok(r) => {

View File

@@ -0,0 +1 @@

View File

@@ -1,6 +1,6 @@
pub mod audio;
pub mod help;
pub mod chat;
pub mod help;
pub mod ping;
pub mod schedule;
pub mod roll;
pub mod schedule;

View File

@@ -1,5 +1,8 @@
use log::debug;
use serenity::{model::prelude::interaction::application_command::CommandDataOption, builder::CreateApplicationCommand};
use serenity::{
model::prelude::interaction::application_command::CommandDataOption,
builder::CreateApplicationCommand,
};
pub fn run(_options: &[CommandDataOption]) -> String {
debug!("Ping command executed");
@@ -8,4 +11,4 @@ pub fn run(_options: &[CommandDataOption]) -> String {
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("ping").description("Replies with pong")
}
}

View File

@@ -1,6 +1,12 @@
use log::{error, warn};
use rand::Rng;
use serenity::{builder::CreateApplicationCommand, client::Context, model::application::{command::CommandOptionType, interaction::application_command::ApplicationCommandInteraction}};
use serenity::{
builder::CreateApplicationCommand,
client::Context,
model::application::{
command::CommandOptionType, interaction::application_command::ApplicationCommandInteraction,
},
};
use crate::bot::commands::audio::edit_response;
@@ -49,10 +55,17 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
total += roll;
rolls.push(roll);
}
let response = format!("{}d{}{} = {}",
let response = format!(
"{}d{}{} = {}",
count,
sides,
if modifier > 0 { format!("+{}", modifier) } else if modifier < 0 { format!("-{}", modifier) } else { "".to_string() },
sides,
if modifier > 0 {
format!("+{}", modifier)
} else if modifier < 0 {
format!("-{}", modifier)
} else {
"".to_string()
},
total + (modifier as u32)
);
if let Err(why) = edit_response(&ctx, &command, response).await {
@@ -60,13 +73,12 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
}
}
Err(why) => {
if let Err(why) = edit_response(&ctx, &command, format!("Invalid dice string: {}", why)).await {
if let Err(why) = edit_response(&ctx, &command, format!("Invalid dice string: {}", why)).await
{
error!("Failed to create response message: {}", why);
}
}
}
}
fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
@@ -74,9 +86,9 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
let count = match parts.next() {
Some(c) => match c.parse::<u32>() {
Ok(n) => n,
Err(_) => return Err(format!("Invalid dice count: {}", c))
Err(_) => return Err(format!("Invalid dice count: {}", c)),
},
None => return Err(format!("Invalid dice string: {}", dice))
None => return Err(format!("Invalid dice string: {}", dice)),
};
let mut positive_modifier = true;
let mut parts = match parts.next() {
@@ -91,8 +103,8 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
} else {
p.split("+")
}
},
None => return Err(format!("Invalid dice string: {}", dice))
}
None => return Err(format!("Invalid dice string: {}", dice)),
};
let sides = match parts.next() {
Some(s) => match s.parse::<u32>() {
@@ -103,9 +115,9 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
return Err(format!("Invalid dice sides: {}", s));
}
}
Err(_) => return Err(format!("Invalid dice sides: {}", s))
Err(_) => return Err(format!("Invalid dice sides: {}", s)),
},
None => return Err(format!("Invalid dice string: {}", dice))
None => return Err(format!("Invalid dice string: {}", dice)),
};
let modifier = match parts.next() {
Some(m) => match m.parse::<i32>() {
@@ -115,20 +127,23 @@ fn parse_dice(dice: &str) -> Result<(u32, u32, i32), String> {
} else {
n * -1
}
},
Err(_) => return Err(format!("Invalid dice modifier: {}", m))
}
Err(_) => return Err(format!("Invalid dice modifier: {}", m)),
},
None => 0
None => 0,
};
Ok((count, sides, modifier))
}
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
command.name("roll").description("Rolls D&D dice").create_option(|option| {
option
.name("dice")
.description("Dice to roll")
.kind(CommandOptionType::String)
.required(true)
})
}
command
.name("roll")
.description("Rolls D&D dice")
.create_option(|option| {
option
.name("dice")
.description("Dice to roll")
.kind(CommandOptionType::String)
.required(true)
})
}

View File

@@ -0,0 +1 @@

View File

@@ -2,4 +2,4 @@ mod model;
mod routes;
pub use model::*;
pub use routes::init_routes;
pub use routes::init_routes;

View File

@@ -9,7 +9,7 @@ use crate::storage::{schema::guilds, connection};
pub struct QueryGuild {
pub id: i64,
pub bot_id: i64,
pub volume: i32
pub volume: i32,
}
impl QueryGuild {
@@ -25,19 +25,23 @@ impl QueryGuild {
pub struct InsertGuild {
pub id: i64,
pub bot_id: i64,
pub volume: i32
pub volume: i32,
}
impl InsertGuild {
pub fn insert(guild: Self) -> Result<QueryGuild, ServiceError> {
let mut conn = connection()?;
let guild = diesel::insert_into(guilds::table).values(guild).get_result(&mut conn)?;
let guild = diesel::insert_into(guilds::table)
.values(guild)
.get_result(&mut conn)?;
Ok(guild)
}
pub fn update_audio(id: i64, volume: i32) -> Result<QueryGuild, ServiceError> {
let mut conn = connection()?;
let guild = diesel::update(guilds::table.filter(guilds::id.eq(id))).set(guilds::volume.eq(volume)).get_result(&mut conn)?;
let guild = diesel::update(guilds::table.filter(guilds::id.eq(id)))
.set(guilds::volume.eq(volume))
.get_result(&mut conn)?;
Ok(guild)
}
}

View File

@@ -5,74 +5,104 @@ use serde::{Serialize, Deserialize};
use serenity::model::prelude::{GuildChannel, ChannelType};
use siren::{ServiceError, Response};
use crate::{AppState, bot::commands::audio::{play::play_track, join}, bot::guilds::QueryGuild, auth::{Auth, verify_role}};
use crate::{
AppState,
bot::commands::audio::{play::play_track, join},
bot::guilds::QueryGuild,
auth::{Auth, verify_role},
};
#[get("/guilds")]
async fn get_guilds(data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err)
return ResponseError::error_response(&err);
};
let guild_results = &data.http.get_guilds(None, None).await;
let guilds = match guild_results {
Ok(guilds) => guilds,
Err(err) => return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
}
};
HttpResponse::Ok().json(Response {
data: guilds,
metadata: None
metadata: None,
})
}
#[get("/{id}/text")]
async fn get_text_channels(id: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
async fn get_text_channels(
id: web::Path<String>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err)
return ResponseError::error_response(&err);
};
let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await;
let channels = match channel_results {
Ok(channels) => channels.iter().filter(|c| c.kind == ChannelType::Text).collect::<Vec<&GuildChannel>>(),
Err(err) => return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
Ok(channels) => channels
.iter()
.filter(|c| c.kind == ChannelType::Text)
.collect::<Vec<&GuildChannel>>(),
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
}
};
HttpResponse::Ok().json(Response {
data: channels,
metadata: None
metadata: None,
})
}
#[get("/{id}/voice")]
async fn get_voice_channels(id: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
async fn get_voice_channels(
id: web::Path<String>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err)
return ResponseError::error_response(&err);
};
let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await;
let channels = match channel_results {
Ok(channels) => channels.iter().filter(|c| c.kind == ChannelType::Voice).collect::<Vec<&GuildChannel>>(),
Err(err) => return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
Ok(channels) => channels
.iter()
.filter(|c| c.kind == ChannelType::Voice)
.collect::<Vec<&GuildChannel>>(),
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
}
};
HttpResponse::Ok().json(Response {
data: channels,
metadata: None
metadata: None,
})
}
#[derive(Serialize, Deserialize)]
struct ChannelMessage {
message: String
message: String,
}
#[post("/{guild_id}/text/{channel_id}/message")]
async fn send_message(path: web::Path<(String, String)>, text: web::Json<ChannelMessage>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
async fn send_message(
path: web::Path<(String, String)>,
text: web::Json<ChannelMessage>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err)
return ResponseError::error_response(&err);
};
let (guild_id, channel_id) = path.into_inner();
let guild_id = match guild_id.parse::<u64>() {
@@ -80,7 +110,7 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json<Channel
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
message: err.to_string(),
})
}
};
@@ -89,7 +119,7 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json<Channel
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
message: err.to_string(),
})
}
};
@@ -99,26 +129,29 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json<Channel
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
message: err.to_string(),
})
}
};
let channel = match channels.iter().find(|c| c.id.0 == channel_id) {
Some(channel) => channel,
None => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: format!("Could not find channel with id {}", channel_id)
message: format!("Could not find channel with id {}", channel_id),
})
}
};
if let Err(err) = channel.say(&Pin::new(&data.http).get_ref(), &text.message).await {
if let Err(err) = channel
.say(&Pin::new(&data.http).get_ref(), &text.message)
.await
{
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
message: err.to_string(),
});
};
HttpResponse::Ok().finish()
@@ -126,38 +159,55 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json<Channel
#[derive(Serialize, Deserialize)]
struct PlayRequest {
track_url: String
track_url: String,
}
#[post("/{guild_id}/voice/{channel_id}/play")]
async fn play(path: web::Path<(String, String)>, play_request: web::Json<PlayRequest>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
async fn play(
path: web::Path<(String, String)>,
play_request: web::Json<PlayRequest>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err)
return ResponseError::error_response(&err);
};
let (guild_id, channel_id) = path.into_inner();
let guild_id = match guild_id.parse::<u64>() {
Ok(id) => id,
Err(err) => {
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
}
};
let channel_id = match channel_id.parse::<u64>() {
Ok(id) => id,
Err(err) => {
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
}
};
let http = Pin::new(&data.http).get_ref();
let guild = match http.get_guild(guild_id).await {
Ok(guild) => guild,
Err(err) => {
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
}
};
let channel = match http.get_channel(channel_id).await {
Ok(channel) => channel,
Err(err) => {
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
}
};
@@ -165,15 +215,22 @@ async fn play(path: web::Path<(String, String)>, play_request: web::Json<PlayReq
match join(Arc::clone(&manager), &guild.id, &channel.id()).await {
Ok(_) => {
match play_track(Arc::clone(&data.songbird), guild.id, play_request.track_url.to_string()).await {
match play_track(
Arc::clone(&data.songbird),
guild.id,
play_request.track_url.to_string(),
)
.await
{
Ok(_) => HttpResponse::Ok().finish(),
Err(err) => {
return ResponseError::error_response(&err)
}
Err(err) => return ResponseError::error_response(&err),
}
},
}
Err(err) => {
return ResponseError::error_response(&ServiceError { status: 500, message: err.to_string() })
return ResponseError::error_response(&ServiceError {
status: 500,
message: err.to_string(),
})
}
}
}
@@ -181,7 +238,7 @@ async fn play(path: web::Path<(String, String)>, play_request: web::Json<PlayReq
#[post("/{guild_id}/voice/stop")]
async fn stop(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err)
return ResponseError::error_response(&err);
};
let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() {
@@ -189,7 +246,7 @@ async fn stop(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Aut
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
message: err.to_string(),
})
}
};
@@ -203,9 +260,13 @@ async fn stop(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Aut
}
#[post("/{guild_id}/voice/resume")]
async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
async fn resume(
path: web::Path<String>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err)
return ResponseError::error_response(&err);
};
let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() {
@@ -213,7 +274,7 @@ async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: A
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
message: err.to_string(),
})
}
};
@@ -223,8 +284,8 @@ async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: A
if let Err(err) = handler.queue().resume() {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
message: err.to_string(),
});
}
}
@@ -232,9 +293,13 @@ async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: A
}
#[post("/{guild_id}/voice/pause")]
async fn pause(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
async fn pause(
path: web::Path<String>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err)
return ResponseError::error_response(&err);
};
let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() {
@@ -242,7 +307,7 @@ async fn pause(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Au
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
message: err.to_string(),
})
}
};
@@ -252,8 +317,8 @@ async fn pause(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Au
if let Err(err) = handler.queue().pause() {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
message: err.to_string(),
});
}
}
@@ -262,13 +327,13 @@ async fn pause(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Au
#[derive(Serialize, Deserialize)]
struct SetVolume {
volume: String
volume: String,
}
#[get("/{guild_id}/voice/volume")]
async fn get_volume(path: web::Path<String>, auth: Auth) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err)
return ResponseError::error_response(&err);
};
let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() {
@@ -276,7 +341,7 @@ async fn get_volume(path: web::Path<String>, auth: Auth) -> HttpResponse {
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
message: err.to_string(),
})
}
};
@@ -286,7 +351,7 @@ async fn get_volume(path: web::Path<String>, auth: Auth) -> HttpResponse {
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
message: err.to_string(),
})
}
};
@@ -295,9 +360,14 @@ async fn get_volume(path: web::Path<String>, auth: Auth) -> HttpResponse {
}
#[post("/{guild_id}/voice/volume")]
async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
async fn set_volume(
path: web::Path<String>,
volume: web::Json<SetVolume>,
data: web::Data<Arc<AppState>>,
auth: Auth,
) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err)
return ResponseError::error_response(&err);
};
let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() {
@@ -305,7 +375,7 @@ async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, dat
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
message: err.to_string(),
})
}
};
@@ -316,7 +386,10 @@ async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, dat
let guild = match http.get_guild(guild_id).await {
Ok(guild) => guild,
Err(err) => {
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
}
};
crate::bot::commands::audio::volume::set_volume(manager, guild.id, volume).await;
@@ -327,7 +400,7 @@ async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, dat
#[post("/{guild_id}/voice/skip")]
async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Auth) -> HttpResponse {
if let Err(err) = verify_role(&auth, "admin") {
return ResponseError::error_response(&err)
return ResponseError::error_response(&err);
};
let guild_id = path.into_inner();
let guild_id = match guild_id.parse::<u64>() {
@@ -335,7 +408,7 @@ async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Aut
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
message: err.to_string(),
})
}
};
@@ -345,8 +418,8 @@ async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Aut
if let Err(err) = handler.queue().skip() {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
message: err.to_string(),
});
}
}
@@ -354,9 +427,8 @@ async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Aut
}
pub fn init_routes(config: &mut web::ServiceConfig) {
config
.service(get_guilds)
.service(web::scope("guilds")
config.service(get_guilds).service(
web::scope("guilds")
.service(get_text_channels)
.service(get_voice_channels)
.service(send_message)
@@ -366,6 +438,6 @@ pub fn init_routes(config: &mut web::ServiceConfig) {
.service(pause)
.service(set_volume)
.service(get_volume)
.service(skip)
.service(skip),
);
}
}

View File

@@ -12,7 +12,7 @@ use super::commands::audio::create_response;
pub struct Handler {
// Open AI Config
pub oai: Option<oai::OAI>
pub oai: Option<oai::OAI>,
}
#[async_trait]
@@ -28,18 +28,21 @@ impl EventHandler for Handler {
Ok(mentioned) => {
let bot_in_thread = match msg.channel_id.get_thread_members(&ctx.http).await {
Ok(t) => {
match t.iter().find(|t| t.user_id.unwrap().0 == ctx.cache.current_user_id().0) {
match t
.iter()
.find(|t| t.user_id.unwrap().0 == ctx.cache.current_user_id().0)
{
Some(_) => true,
None => false
None => false,
}
}
Err(_) => false
Err(_) => false,
};
if mentioned || bot_in_thread {
commands::chat::generate_response(&ctx, &msg, oai).await;
}
}
Err(why) => warn!("Could not check mentions: {:?}", why)
Err(why) => warn!("Could not check mentions: {:?}", why),
};
}
None => {}
@@ -59,9 +62,9 @@ impl EventHandler for Handler {
_ => {
let content: String = match command.data.name.as_str() {
"ping" => commands::ping::run(&command.data.options),
_ => "Unknown command".to_string()
_ => "Unknown command".to_string(),
};
if let Err(why) = create_response(&ctx, &command, content).await {
warn!("Cannot respond to slash command: {}", why);
}
@@ -78,23 +81,61 @@ impl EventHandler for Handler {
let _ = InsertGuild::insert(InsertGuild {
id: (guild.id.0 as i64),
bot_id: ctx.cache.current_user().id.0 as i64,
volume: 100
volume: 100,
});
let commands = guild.id.set_application_commands(&ctx.http, |commands| {
commands
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::ping::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::roll::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::play::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::stop::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::pause::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::resume::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::skip::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::volume::register(command) })
}).await;
let commands = guild
.id
.set_application_commands(&ctx.http, |commands| {
commands
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::ping::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::roll::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::play::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::stop::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::pause::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::resume::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::skip::register(command)
},
)
.create_application_command(
|command: &mut serenity::builder::CreateApplicationCommand| {
commands::audio::volume::register(command)
},
)
})
.await;
match commands {
Ok(c) => info!("Registered {} commands for guild {}", c.len(), guild.id.0),
Err(why) => error!("Could not register commands for guild {}: {:?}", guild.id.0, why)
Err(why) => error!(
"Could not register commands for guild {}: {:?}",
guild.id.0, why
),
};
}
}
}
}

View File

@@ -2,7 +2,10 @@ use diesel::prelude::*;
use serde::{Deserialize, Serialize};
use siren::ServiceError;
use crate::storage::{schema::messages::{self}, connection};
use crate::storage::{
schema::messages::{self},
connection,
};
#[derive(Queryable, Selectable, Insertable, AsChangeset, Serialize, Deserialize)]
#[diesel(table_name = messages)]
@@ -28,7 +31,7 @@ pub struct QueryFilters {
pub by_request: Option<String>,
pub by_response: Option<String>,
pub by_request_tags: Option<Vec<String>>,
pub by_response_tags: Option<Vec<String>>
pub by_response_tags: Option<Vec<String>>,
}
impl Default for QueryFilters {
@@ -42,7 +45,7 @@ impl Default for QueryFilters {
by_request: None,
by_response: None,
by_request_tags: None,
by_response_tags: None
by_response_tags: None,
}
}
}
@@ -50,7 +53,10 @@ impl Default for QueryFilters {
impl QueryMessage {
pub fn get_all(filters: &QueryFilters, limit: i32, page: i32) -> Result<Vec<Self>, ServiceError> {
let mut conn = connection()?;
let mut query = messages::table.limit(limit as i64).order(messages::created.asc()).into_boxed();
let mut query = messages::table
.limit(limit as i64)
.order(messages::created.asc())
.into_boxed();
// Limit query to page and limit
let offset = (page - 1) * limit;
query = query.offset(offset as i64);

View File

@@ -3,7 +3,10 @@ use log::error;
use serde::{Serialize, Deserialize};
use siren::{Response, Metadata, ServiceError};
use crate::{bot::messages::{QueryMessage, QueryFilters}, auth::{Auth, verify_role}};
use crate::{
bot::messages::{QueryMessage, QueryFilters},
auth::{Auth, verify_role},
};
#[derive(Serialize, Deserialize)]
struct GetAllParams {
@@ -23,15 +26,17 @@ struct GetAllParams {
#[get("/messages")]
async fn get_all(req: HttpRequest, auth: Auth) -> HttpResponse {
let _ = match verify_role(&auth, "admin") {
Ok(_) => {},
Err(err) => return ResponseError::error_response(&err)
Ok(_) => {}
Err(err) => return ResponseError::error_response(&err),
};
let params = match web::Query::<GetAllParams>::from_query(req.query_string()) {
Ok(params) => params,
Err(err) => return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
Err(err) => {
return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string(),
})
}
};
let mut filters = QueryFilters::default();
filters.by_id = params.id.clone();
@@ -47,19 +52,17 @@ async fn get_all(req: HttpRequest, auth: Auth) -> HttpResponse {
let total_count = QueryMessage::get_count(&filters).unwrap();
let max_page = std::cmp::max((total_count as f64 / limit as f64).ceil() as i32, 1);
let page = std::cmp::min(std::cmp::max(params.page.unwrap_or(1), 1), max_page);
match QueryMessage::get_all(&filters, limit, page) {
Ok(messages) => {
HttpResponse::Ok().json(Response {
data: messages,
metadata: Some(Metadata {
total: total_count as i32,
limit,
page,
pages: max_page
})
})
},
Ok(messages) => HttpResponse::Ok().json(Response {
data: messages,
metadata: Some(Metadata {
total: total_count as i32,
limit,
page,
pages: max_page,
}),
}),
Err(err) => {
error!("{:?}", err.message);
ResponseError::error_response(&err)
@@ -70,8 +73,8 @@ async fn get_all(req: HttpRequest, auth: Auth) -> HttpResponse {
#[post("/messages")]
async fn create(message: web::Json<QueryMessage>, auth: Auth) -> HttpResponse {
let _ = match verify_role(&auth, "admin") {
Ok(_) => {},
Err(err) => return ResponseError::error_response(&err)
Ok(_) => {}
Err(err) => return ResponseError::error_response(&err),
};
match QueryMessage::insert(message.into_inner()) {
Ok(message) => HttpResponse::Created().json(message),
@@ -85,4 +88,4 @@ async fn create(message: web::Json<QueryMessage>, auth: Auth) -> HttpResponse {
pub fn init_routes(config: &mut web::ServiceConfig) {
config.service(get_all);
config.service(create);
}
}

View File

@@ -11,7 +11,7 @@ pub enum GPTRole {
#[serde(rename = "assistant")]
Assistant,
#[serde(rename = "function")]
Function
Function,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -41,7 +41,7 @@ pub struct ChatCompletionRequest {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatCompletionMessage {
pub role: GPTRole,
pub content: String
pub content: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -52,14 +52,14 @@ pub struct ChatCompletionResponse {
pub created: i64,
pub model: String,
pub usage: Usage,
pub choices: Vec<Choice>
pub choices: Vec<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Usage {
pub prompt_tokens: i64,
pub completion_tokens: i64,
pub total_tokens: i64
pub total_tokens: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -67,13 +67,13 @@ pub struct Choice {
pub message: ChatCompletionMessage,
pub finish_reason: String,
pub index: i64,
pub logprobs: Option<String>
pub logprobs: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
enum ResponseEvent {
ChatCompletionResponse(ChatCompletionResponse),
ResponseError(ResponseError)
ResponseError(ResponseError),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -82,13 +82,13 @@ struct ResponseError {
message: Option<String>,
param: Option<String>,
#[serde(rename = "type")]
error_type: Option<String>
error_type: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ErrorDetails {
code: Option<String>,
message: Option<String>
message: Option<String>,
}
pub struct OAI {
@@ -99,13 +99,18 @@ pub struct OAI {
pub token: String,
pub max_tokens: i64,
pub default_model: String,
pub max_context_questions: i64
pub max_context_questions: i64,
}
impl OAI {
pub async fn chat_completion(&self, request: ChatCompletionRequest) -> Result<ChatCompletionResponse, ServiceError> {
pub async fn chat_completion(
&self,
request: ChatCompletionRequest,
) -> Result<ChatCompletionResponse, ServiceError> {
let url = format!("{}/chat/completions", self.base_url);
let response = self.client.post(&url)
let response = self
.client
.post(&url)
.bearer_auth(&self.token)
.header("Content-Type", "application/json".to_string())
.json(&request)
@@ -121,8 +126,13 @@ impl OAI {
// }
let res = serde_json::from_value::<ChatCompletionResponse>(value)?;
return Ok(res);
},
Err(err) => return Err(ServiceError { status: 500, message: format!("Error: {}", err) })
}
Err(err) => {
return Err(ServiceError {
status: 500,
message: format!("Error: {}", err),
})
}
}
}
}

View File

@@ -4,7 +4,6 @@ use std::process::{Child, Command, Output, Stdio};
pub use model::*;
const YOUTUBE_DL_COMMAND: &str = "yt-dlp";
pub struct YtDlp {
@@ -15,7 +14,8 @@ pub struct YtDlp {
impl YtDlp {
pub fn new() -> Self {
let mut cmd = Command::new(YOUTUBE_DL_COMMAND);
cmd.env("LC_ALL", "en_US.UTF-8")
cmd
.env("LC_ALL", "en_US.UTF-8")
.stdout(Stdio::piped())
.stdin(Stdio::piped())
.stderr(Stdio::piped());
@@ -31,9 +31,10 @@ impl YtDlp {
}
pub fn execute(&mut self) -> std::io::Result<Output> {
self.command
self
.command
.args(self.args.clone())
.spawn()
.and_then(Child::wait_with_output)
}
}
}

View File

@@ -1,6 +1,5 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct PlaylistItem {
pub id: String,
@@ -8,4 +7,4 @@ pub struct PlaylistItem {
pub title: String,
pub duration: i32,
pub playlist_index: i32,
}
}