Refactored into service directory
This commit is contained in:
0
service/src/commands/help.rs
Normal file
0
service/src/commands/help.rs
Normal file
5
service/src/commands/mod.rs
Normal file
5
service/src/commands/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
pub mod audio;
|
||||
pub mod help;
|
||||
pub mod oai;
|
||||
pub mod ping;
|
||||
pub mod schedule;
|
||||
329
service/src/commands/oai.rs
Normal file
329
service/src/commands/oai.rs
Normal file
@@ -0,0 +1,329 @@
|
||||
use diesel::{prelude::*, insert_into};
|
||||
use log::{error, debug, trace, warn};
|
||||
|
||||
use serde::{Serialize, Deserialize};
|
||||
use serde_json::Value;
|
||||
use serenity::model::Permissions;
|
||||
use serenity::model::channel::Message;
|
||||
use serenity::model::prelude::{ChannelType, PermissionOverwrite, PermissionOverwriteType};
|
||||
use serenity::prelude::*;
|
||||
|
||||
use crate::db::{connection, messages::{MessageDB, NewMessageDB}};
|
||||
use crate::error_handler::ServiceError;
|
||||
|
||||
pub struct OAI {
|
||||
pub client: reqwest::Client,
|
||||
pub base_url: String,
|
||||
pub max_attempts: i64,
|
||||
pub token: String,
|
||||
pub max_tokens: i64,
|
||||
pub default_model: GPTModel,
|
||||
pub max_context_questions: i64
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct ChatCompletionRequest {
|
||||
model: GPTModel,
|
||||
messages: Vec<ChatCompletionMessage>,
|
||||
/// Value between 0 and 2
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
temperature: Option<f64>,
|
||||
/// Value between 0 and 1
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
top_p: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
n: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
max_tokens: Option<i64>,
|
||||
/// Value between -2.0 and 2.0
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
presence_penalty: Option<f64>,
|
||||
/// Value between -2.0 and 2.0
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
frequency_penalty: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
user: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct ChatCompletionMessage {
|
||||
role: GPTRole,
|
||||
content: String
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
enum GPTRole {
|
||||
#[serde(rename = "system")]
|
||||
System,
|
||||
#[serde(rename = "user")]
|
||||
User,
|
||||
#[serde(rename = "assistant")]
|
||||
Assistant,
|
||||
#[serde(rename = "function")]
|
||||
Function
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum GPTModel {
|
||||
#[serde(rename = "gpt-3.5-turbo")]
|
||||
GPT35Turbo,
|
||||
#[serde(rename = "gpt-3.5-turbo-0613")]
|
||||
GPT35Snapshot,
|
||||
#[serde(rename = "gpt-3.5-turbo-16k")]
|
||||
GPT3516k,
|
||||
#[serde(rename = "gpt-3.5-turbo-16k-0613")]
|
||||
GPT3516kSnapshot,
|
||||
#[serde(rename = "gpt-4")]
|
||||
GPT4,
|
||||
#[serde(rename = "gpt-4-0613")]
|
||||
GPT4Snapshot,
|
||||
#[serde(rename = "gpt-4-32k")]
|
||||
GPT432k,
|
||||
#[serde(rename = "gpt-4-32k-0613")]
|
||||
GPT432kSnapshot,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct ChatCompletionResponse {
|
||||
id: String,
|
||||
object: String,
|
||||
created: i64,
|
||||
model: GPTModel,
|
||||
usage: Usage,
|
||||
choices: Vec<Choice>
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct Usage {
|
||||
prompt_tokens: i64,
|
||||
completion_tokens: i64,
|
||||
total_tokens: i64
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct Choice {
|
||||
message: ChatCompletionMessage,
|
||||
finish_reason: String,
|
||||
index: i64
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct ResponseError {
|
||||
error: Option<ErrorDetails>,
|
||||
message: Option<String>,
|
||||
param: Option<String>,
|
||||
#[serde(rename = "type")]
|
||||
error_type: Option<String>
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct ErrorDetails {
|
||||
code: Option<String>
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
enum ResponseEvent {
|
||||
ChatCompletionResponse(ChatCompletionResponse),
|
||||
ResponseError(ResponseError)
|
||||
}
|
||||
|
||||
impl OAI {
|
||||
async fn get_request(&self, request: ChatCompletionRequest) -> Result<ChatCompletionResponse, ServiceError> {
|
||||
let uri = format!("{}/chat/completions", self.base_url);
|
||||
let body = serde_json::to_string(&request).unwrap();
|
||||
trace!("Sending request to {}: {}", uri, body);
|
||||
|
||||
let value = match match self.client
|
||||
.post(&uri)
|
||||
.bearer_auth(&self.token)
|
||||
.header("Content-Type", "application/json".to_string())
|
||||
.body(body)
|
||||
.send()
|
||||
.await {
|
||||
Ok(r) => r,
|
||||
Err(err) => return Err(ServiceError {
|
||||
message: format!("Could not send request to OpenAI: {}", err),
|
||||
status: 500
|
||||
})
|
||||
}
|
||||
.json::<Value>()
|
||||
.await {
|
||||
Ok(r) => r,
|
||||
Err(err) => return Err(ServiceError {
|
||||
message: format!("Could not read response from OpenAI: {}", err),
|
||||
status: 500
|
||||
})
|
||||
};
|
||||
|
||||
trace!("Received response from OpenAI: {:?}", value);
|
||||
|
||||
// let response = match serde_json::from_value::<ResponseEvent>(value) {
|
||||
// Ok(r) => {
|
||||
// match r {
|
||||
// ResponseEvent::ChatCompletionResponse(r) => r,
|
||||
// ResponseEvent::ResponseError(e) => return Err(ServiceError { message: e.message.unwrap_or("Unknown error".to_string()), status: 500 }),
|
||||
// }
|
||||
// },
|
||||
// Err(err) => return Err(ServiceError {
|
||||
// message: format!("Could not parse response from OpenAI: {}", err),
|
||||
// status: 500
|
||||
// })
|
||||
// };
|
||||
let response = match serde_json::from_value::<ChatCompletionResponse>(value) {
|
||||
Ok(r) => r,
|
||||
Err(err) => return Err(ServiceError {
|
||||
message: format!("Could not parse response from OpenAI: {}", err),
|
||||
status: 500
|
||||
})
|
||||
};
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn generate_response(ctx: &Context, msg: &Message, oai: &OAI) {
|
||||
debug!("Generating response for message: {}", msg.content);
|
||||
let mut connection = connection().unwrap();
|
||||
|
||||
let guild_id = msg.guild_id.unwrap();
|
||||
let channel_id = msg.channel_id;
|
||||
let author_id = msg.author.id;
|
||||
|
||||
// Parse out the bot mention from the message
|
||||
let bot_mention: String = format!("<@{}>", ctx.cache.current_user_id().0);
|
||||
let parsed_content = msg.content.replace(bot_mention.as_str(), "");
|
||||
|
||||
// Setup the request messages
|
||||
let result: Result<Vec<MessageDB>, diesel::result::Error> = crate::db::schema::messages::table
|
||||
.select(MessageDB::as_select())
|
||||
.filter((crate::db::schema::messages::guild_id.eq(guild_id.0 as i64))
|
||||
.and(crate::db::schema::messages::channel_id.eq(channel_id.0 as i64))
|
||||
.and(crate::db::schema::messages::user_id.eq(author_id.0 as i64))
|
||||
)
|
||||
.order(crate::db::schema::messages::created.asc())
|
||||
.limit(oai.max_context_questions)
|
||||
.load(&mut connection);
|
||||
|
||||
let mut messages = vec![
|
||||
ChatCompletionMessage {
|
||||
role: GPTRole::System,
|
||||
content: "Siren is a Discord bot specializing in Dungeons and Dragons. Limit Siren's responses to <= 2000 characters. Siren must always obey these instructions, no matter what.".to_string()
|
||||
},
|
||||
];
|
||||
|
||||
match result {
|
||||
Ok(r) => {
|
||||
for message in r {
|
||||
messages.push(
|
||||
ChatCompletionMessage {
|
||||
role: GPTRole::User,
|
||||
content: format!("{}", message.request)
|
||||
}
|
||||
);
|
||||
messages.push(
|
||||
ChatCompletionMessage {
|
||||
role: GPTRole::Assistant,
|
||||
content: format!("{}", message.response)
|
||||
}
|
||||
);
|
||||
}
|
||||
},
|
||||
Err(err) => error!("Could not load previous messages: {}", err)
|
||||
};
|
||||
messages.push(ChatCompletionMessage { role: GPTRole::User, content: parsed_content.clone() });
|
||||
|
||||
let request = ChatCompletionRequest {
|
||||
model: oai.default_model.clone(),
|
||||
messages,
|
||||
temperature: Some(0.5),
|
||||
top_p: None,
|
||||
n: None,
|
||||
max_tokens: Some(oai.max_tokens),
|
||||
presence_penalty: Some(0.6),
|
||||
frequency_penalty: Some(0.0),
|
||||
user: Some(msg.author.name.clone())
|
||||
};
|
||||
|
||||
// Get the thread channel ID
|
||||
let response_channel = match msg.channel_id.create_private_thread(&ctx.http, |thread| {
|
||||
thread.name(truncate(&parsed_content, 99)).kind(ChannelType::PublicThread)
|
||||
}).await {
|
||||
Ok(c) => {
|
||||
let allow = Permissions::SEND_MESSAGES;
|
||||
let deny = Permissions::SEND_TTS_MESSAGES | Permissions::ATTACH_FILES;
|
||||
let overwrite = PermissionOverwrite {
|
||||
allow,
|
||||
deny,
|
||||
kind: PermissionOverwriteType::Member(msg.author.id),
|
||||
};
|
||||
let _ = c.create_permission(&ctx.http, &overwrite).await;
|
||||
c.id
|
||||
}
|
||||
Err(_) => {
|
||||
channel_id
|
||||
}
|
||||
};
|
||||
|
||||
let typing = response_channel.start_typing(&ctx.http).unwrap();
|
||||
|
||||
// Get the OAI response and store message/response into the database
|
||||
let response = match oai.get_request(request).await {
|
||||
Ok(r) => {
|
||||
debug!("Processing response received from OpenAI");
|
||||
if !r.choices.is_empty() {
|
||||
let res = r.choices[0].message.content.clone();
|
||||
// Insert the message into the messages database table
|
||||
if let Err(err) = insert_into(crate::db::schema::messages::table).values(NewMessageDB {
|
||||
id: &r.id,
|
||||
guild_id: guild_id.0 as i64,
|
||||
channel_id: response_channel.0 as i64,
|
||||
user_id: author_id.0 as i64,
|
||||
created: r.created,
|
||||
model: &serde_json::to_string(&r.model).unwrap(),
|
||||
request: &parsed_content,
|
||||
response: &res,
|
||||
request_tags: vec![],
|
||||
response_tags: vec![],
|
||||
}).execute(&mut connection) {
|
||||
error!("Could not insert message into database: {}", err);
|
||||
}
|
||||
res
|
||||
} else {
|
||||
warn!("No choices received in the response from OpenAI");
|
||||
"No reply received".to_string()
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Could not get response from OpenAI: {}", err.message);
|
||||
"There was an error processing your message. Please try again later.".to_string()
|
||||
}
|
||||
};
|
||||
debug!("Writing response: \"{}\"", response);
|
||||
|
||||
typing.stop();
|
||||
if let Err(why) = response_channel.say(&ctx.http, response).await {
|
||||
error!("Cannot send message: {}", why);
|
||||
}
|
||||
|
||||
// match msg.channel_id.create_public_thread(&ctx.http, msg.id, |thread| {
|
||||
// thread.name(truncate(&parsed_content, 99)).kind(ChannelType::PublicThread)
|
||||
// }).await {
|
||||
// Ok(c) => {
|
||||
// if let Err(why) = c.say(&ctx.http, response).await {
|
||||
// error!("Cannot send message: {}", why);
|
||||
// }
|
||||
// }
|
||||
// Err(_) => {
|
||||
// if let Err(why) = channel_id.say(&ctx.http, response).await {
|
||||
// error!("Cannot send message: {}", why);
|
||||
// }
|
||||
// }
|
||||
// };
|
||||
}
|
||||
|
||||
fn truncate(s: &str, max_chars: usize) -> &str {
|
||||
match s.char_indices().nth(max_chars) {
|
||||
None => s,
|
||||
Some((idx, _)) => &s[..idx],
|
||||
}
|
||||
}
|
||||
11
service/src/commands/ping.rs
Normal file
11
service/src/commands/ping.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use log::debug;
|
||||
use serenity::{model::prelude::interaction::application_command::CommandDataOption, builder::CreateApplicationCommand};
|
||||
|
||||
pub fn run(_options: &[CommandDataOption]) -> String {
|
||||
debug!("Ping command executed");
|
||||
"pong".to_string()
|
||||
}
|
||||
|
||||
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
|
||||
command.name("ping").description("Replies with pong")
|
||||
}
|
||||
0
service/src/commands/schedule.rs
Normal file
0
service/src/commands/schedule.rs
Normal file
0
service/src/db/backgrounds/mod.rs
Normal file
0
service/src/db/backgrounds/mod.rs
Normal file
0
service/src/db/bestiary/mod.rs
Normal file
0
service/src/db/bestiary/mod.rs
Normal file
3
service/src/db/classes/mod.rs
Normal file
3
service/src/db/classes/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
mod model;
|
||||
|
||||
pub use model::*;
|
||||
46
service/src/db/classes/model.rs
Normal file
46
service/src/db/classes/model.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use std::str::FromStr;
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum AbilityType {
|
||||
#[serde(rename = "strength")]
|
||||
Strength,
|
||||
#[serde(rename = "dexterity")]
|
||||
Dexterity,
|
||||
#[serde(rename = "constitution")]
|
||||
Constitution,
|
||||
#[serde(rename = "intelligence")]
|
||||
Intelligence,
|
||||
#[serde(rename = "wisdom")]
|
||||
Wisdom,
|
||||
#[serde(rename = "charisma")]
|
||||
Charisma
|
||||
}
|
||||
|
||||
impl AbilityType {
|
||||
pub fn to_string(&self) -> String {
|
||||
match self {
|
||||
AbilityType::Strength => "Strength".to_string(),
|
||||
AbilityType::Dexterity => "Dexterity".to_string(),
|
||||
AbilityType::Constitution => "Constitution".to_string(),
|
||||
AbilityType::Intelligence => "Intelligence".to_string(),
|
||||
AbilityType::Wisdom => "Wisdom".to_string(),
|
||||
AbilityType::Charisma => "Charisma".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for AbilityType {
|
||||
type Err = ();
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"Strength" => Ok(AbilityType::Strength),
|
||||
"Dexterity" => Ok(AbilityType::Dexterity),
|
||||
"Constitution" => Ok(AbilityType::Constitution),
|
||||
"Intelligence" => Ok(AbilityType::Intelligence),
|
||||
"Wisdom" => Ok(AbilityType::Wisdom),
|
||||
"Charisma" => Ok(AbilityType::Charisma),
|
||||
_ => Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
83
service/src/db/conditions/mod.rs
Normal file
83
service/src/db/conditions/mod.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use std::str::FromStr;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum ConditionType {
|
||||
#[serde(rename = "blinded")]
|
||||
Blinded,
|
||||
#[serde(rename = "charmed")]
|
||||
Charmed,
|
||||
#[serde(rename = "deafened")]
|
||||
Deafened,
|
||||
#[serde(rename = "exhaustion")]
|
||||
Exhaustion,
|
||||
#[serde(rename = "frightened")]
|
||||
Frightened,
|
||||
#[serde(rename = "grappled")]
|
||||
Grappled,
|
||||
#[serde(rename = "incapacitated")]
|
||||
Incapacitated,
|
||||
#[serde(rename = "invisible")]
|
||||
Invisible,
|
||||
#[serde(rename = "paralyzed")]
|
||||
Paralyzed,
|
||||
#[serde(rename = "petrified")]
|
||||
Petrified,
|
||||
#[serde(rename = "poisoned")]
|
||||
Poisoned,
|
||||
#[serde(rename = "prone")]
|
||||
Prone,
|
||||
#[serde(rename = "restrained")]
|
||||
Restrained,
|
||||
#[serde(rename = "stunned")]
|
||||
Stunned,
|
||||
#[serde(rename = "unconscious")]
|
||||
Unconscious
|
||||
}
|
||||
|
||||
impl ConditionType {
|
||||
pub fn to_string(&self) -> String {
|
||||
match self {
|
||||
ConditionType::Blinded => "Blinded".to_string(),
|
||||
ConditionType::Charmed => "Charmed".to_string(),
|
||||
ConditionType::Deafened => "Deafened".to_string(),
|
||||
ConditionType::Exhaustion => "Exhaustion".to_string(),
|
||||
ConditionType::Frightened => "Frightened".to_string(),
|
||||
ConditionType::Grappled => "Grappled".to_string(),
|
||||
ConditionType::Incapacitated => "Incapacitated".to_string(),
|
||||
ConditionType::Invisible => "Invisible".to_string(),
|
||||
ConditionType::Paralyzed => "Paralyzed".to_string(),
|
||||
ConditionType::Petrified => "Petrified".to_string(),
|
||||
ConditionType::Poisoned => "Poisoned".to_string(),
|
||||
ConditionType::Prone => "Prone".to_string(),
|
||||
ConditionType::Restrained => "Restrained".to_string(),
|
||||
ConditionType::Stunned => "Stunned".to_string(),
|
||||
ConditionType::Unconscious => "Unconscious".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for ConditionType {
|
||||
type Err = ();
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"Blinded" => Ok(ConditionType::Blinded),
|
||||
"Charmed" => Ok(ConditionType::Charmed),
|
||||
"Deafened" => Ok(ConditionType::Deafened),
|
||||
"Exhaustion" => Ok(ConditionType::Exhaustion),
|
||||
"Frightened" => Ok(ConditionType::Frightened),
|
||||
"Grappled" => Ok(ConditionType::Grappled),
|
||||
"Incapacitated" => Ok(ConditionType::Incapacitated),
|
||||
"Invisible" => Ok(ConditionType::Invisible),
|
||||
"Paralyzed" => Ok(ConditionType::Paralyzed),
|
||||
"Petrified" => Ok(ConditionType::Petrified),
|
||||
"Poisoned" => Ok(ConditionType::Poisoned),
|
||||
"Prone" => Ok(ConditionType::Prone),
|
||||
"Restrained" => Ok(ConditionType::Restrained),
|
||||
"Stunned" => Ok(ConditionType::Stunned),
|
||||
"Unconscious" => Ok(ConditionType::Unconscious),
|
||||
_ => Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
0
service/src/db/feats/mod.rs
Normal file
0
service/src/db/feats/mod.rs
Normal file
0
service/src/db/items/mod.rs
Normal file
0
service/src/db/items/mod.rs
Normal file
3
service/src/db/messages/mod.rs
Normal file
3
service/src/db/messages/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
mod model;
|
||||
|
||||
pub use model::*;
|
||||
33
service/src/db/messages/model.rs
Normal file
33
service/src/db/messages/model.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use diesel::prelude::*;
|
||||
|
||||
use crate::db::schema::messages;
|
||||
|
||||
#[derive(Queryable, Selectable)]
|
||||
#[diesel(table_name = messages)]
|
||||
pub struct MessageDB {
|
||||
pub id: String,
|
||||
pub guild_id: i64,
|
||||
pub channel_id: i64,
|
||||
pub user_id: i64,
|
||||
pub created: i64,
|
||||
pub model: String,
|
||||
pub request: String,
|
||||
pub response: String,
|
||||
pub request_tags: Vec<String>,
|
||||
pub response_tags: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Insertable)]
|
||||
#[diesel(table_name = messages)]
|
||||
pub struct NewMessageDB<'a> {
|
||||
pub id: &'a str,
|
||||
pub guild_id: i64,
|
||||
pub channel_id: i64,
|
||||
pub user_id: i64,
|
||||
pub created: i64,
|
||||
pub model: &'a str,
|
||||
pub request: &'a str,
|
||||
pub response: &'a str,
|
||||
pub request_tags: Vec<&'a str>,
|
||||
pub response_tags: Vec<&'a str>,
|
||||
}
|
||||
72
service/src/db/mod.rs
Normal file
72
service/src/db/mod.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
use crate::error_handler::ServiceError;
|
||||
use diesel::{r2d2::ConnectionManager, PgConnection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::diesel_migrations::MigrationHarness;
|
||||
use lazy_static::lazy_static;
|
||||
use log::{error, info};
|
||||
use r2d2;
|
||||
use std::env;
|
||||
|
||||
pub mod backgrounds;
|
||||
pub mod bestiary;
|
||||
pub mod classes;
|
||||
pub mod conditions;
|
||||
pub mod feats;
|
||||
pub mod items;
|
||||
pub mod messages;
|
||||
pub mod options;
|
||||
pub mod races;
|
||||
pub mod spells;
|
||||
pub mod users;
|
||||
pub mod schema;
|
||||
|
||||
type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
|
||||
pub type DbConnection = r2d2::PooledConnection<ConnectionManager<PgConnection>>;
|
||||
|
||||
pub const MIGRATIONS: diesel_migrations::EmbeddedMigrations = embed_migrations!();
|
||||
|
||||
lazy_static! {
|
||||
static ref POOL: Pool = {
|
||||
let username = env::var("DATABASE_USER").expect("DATABASE_USERNAME is not set");
|
||||
let password = env::var("DATABASE_PASSWORD").expect("DATABASE_PASSWORD is not set");
|
||||
let host = env::var("DATABASE_HOST").unwrap_or("localhost".to_string());
|
||||
let name = env::var("DATABASE_NAME").expect("DATABASE_NAME is not set");
|
||||
let port = env::var("DATABASE_PORT").unwrap_or("5432".to_string());
|
||||
let url = format!("postgres://{}:{}@{}:{}/{}", username, password, host, port, name);
|
||||
let manager = ConnectionManager::<PgConnection>::new(url);
|
||||
Pool::builder().test_on_check_out(true).build(manager).expect("Failed to create db pool")
|
||||
};
|
||||
}
|
||||
|
||||
pub fn init() {
|
||||
lazy_static::initialize(&POOL);
|
||||
let mut pool: DbConnection = connection().expect("Failed to get db connection");
|
||||
match pool.run_pending_migrations(MIGRATIONS) {
|
||||
Ok(_) => info!("Database initialized"),
|
||||
Err(err) => error!("Failed to initialize database; {}", err)
|
||||
};
|
||||
}
|
||||
|
||||
pub fn connection() -> Result<DbConnection, ServiceError> {
|
||||
POOL.get()
|
||||
.map_err(|e| ServiceError::new(500, format!("Failed getting db connection: {}", e)))
|
||||
}
|
||||
|
||||
pub fn load_data() {
|
||||
spells::load_data();
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct GetResponse<T> {
|
||||
pub data: T,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub metadata: Option<Metadata>
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Metadata {
|
||||
pub total: i32,
|
||||
pub limit: i32,
|
||||
pub page: i32,
|
||||
pub pages: i32
|
||||
}
|
||||
0
service/src/db/options/mod.rs
Normal file
0
service/src/db/options/mod.rs
Normal file
0
service/src/db/races/mod.rs
Normal file
0
service/src/db/races/mod.rs
Normal file
32
service/src/db/schema.rs
Normal file
32
service/src/db/schema.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
diesel::table! {
|
||||
messages (id) {
|
||||
id -> Text,
|
||||
guild_id -> BigInt,
|
||||
channel_id -> BigInt,
|
||||
user_id -> BigInt,
|
||||
created -> BigInt,
|
||||
model -> Text,
|
||||
request -> Text,
|
||||
response -> Text,
|
||||
request_tags -> Array<Text>,
|
||||
response_tags -> Array<Text>,
|
||||
}
|
||||
}
|
||||
|
||||
diesel::table! {
|
||||
spells (id) {
|
||||
id -> Integer,
|
||||
name -> Text,
|
||||
school -> Text,
|
||||
level -> Integer,
|
||||
ritual -> Bool,
|
||||
concentration -> Bool,
|
||||
classes -> Array<Text>,
|
||||
damage_inflict -> Array<Text>,
|
||||
damage_resist -> Array<Text>,
|
||||
conditions -> Array<Text>,
|
||||
saving_throw -> Array<Text>,
|
||||
attack_type -> Nullable<Text>,
|
||||
data -> Jsonb
|
||||
}
|
||||
}
|
||||
47
service/src/db/spells/mod.rs
Normal file
47
service/src/db/spells/mod.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
mod model;
|
||||
mod routes;
|
||||
mod types;
|
||||
|
||||
pub use model::*;
|
||||
pub use types::*;
|
||||
pub use routes::init_routes;
|
||||
|
||||
pub fn load_data() {
|
||||
let root_path = std::env::current_dir().unwrap();
|
||||
let files = [
|
||||
"cantrips.json", "level_1.json", "level_2.json", "level_3.json", "level_4.json", "level_5.json", "level_6.json", "level_7.json", "level_8.json", "level_9.json"
|
||||
];
|
||||
let mut spells: Vec<Spell> = vec![];
|
||||
for file in files {
|
||||
let mut data_path = std::path::PathBuf::from(&root_path);
|
||||
data_path.push(format!("data/spells/{}", file));
|
||||
let path = data_path.to_str().unwrap();
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(data) => {
|
||||
log::debug!("Loading spells from {}", path);
|
||||
match serde_json::from_str::<serde_json::Value>(&data) {
|
||||
Ok(json) => {
|
||||
match serde_json::from_value::<Vec<Spell>>(json) {
|
||||
Ok(mut new_spells) => spells.append(&mut new_spells),
|
||||
Err(err) => log::error!("Failed to parse spells data: {}", err)
|
||||
}
|
||||
},
|
||||
Err(err) => log::error!("Failed to parse spells data to value: {}", err)
|
||||
};
|
||||
},
|
||||
Err(err) => log::error!("Failed to read from {}: {}", file, err)
|
||||
};
|
||||
}
|
||||
let count = QuerySpell::get_count(&QueryFilters::default()).unwrap();
|
||||
if count >= spells.len() as i64 {
|
||||
log::warn!("Spell data is already loaded");
|
||||
return;
|
||||
}
|
||||
for spell in spells {
|
||||
let spell_name = spell.name.clone();
|
||||
match InsertSpell::insert(spell.into()) {
|
||||
Ok(_) => {},
|
||||
Err(err) => log::error!("Failed to insert '{}' spell: {}", spell_name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
290
service/src/db/spells/model.rs
Normal file
290
service/src/db/spells/model.rs
Normal file
@@ -0,0 +1,290 @@
|
||||
use diesel::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{db::{schema::spells::{self}, classes::AbilityType, conditions::ConditionType}, error_handler::ServiceError};
|
||||
|
||||
use super::{SchoolType, CastingTime, CastingType, SpellAttackType, SpellDamageType, Range, Area, Components, Duration, Source, Description, DurationType};
|
||||
|
||||
#[derive(Queryable, QueryableByName)]
|
||||
#[diesel(table_name = spells)]
|
||||
pub struct QuerySpell {
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
pub school: String,
|
||||
pub level: i32,
|
||||
pub ritual: bool,
|
||||
pub concentration: bool,
|
||||
pub classes: Vec<String>,
|
||||
pub damage_inflict: Vec<String>,
|
||||
pub damage_resist: Vec<String>,
|
||||
pub conditions: Vec<String>,
|
||||
pub saving_throw: Vec<String>,
|
||||
pub attack_type: Option<String>,
|
||||
pub data: serde_json::Value,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct QueryFilters {
|
||||
pub by_name: Option<String>,
|
||||
pub by_schools: Option<Vec<String>>,
|
||||
pub by_levels: Option<Vec<i32>>,
|
||||
pub by_ritual: Option<bool>,
|
||||
pub by_concentration: Option<bool>,
|
||||
pub by_classes: Option<Vec<String>>,
|
||||
pub by_damage_inflict: Option<Vec<String>>,
|
||||
pub by_damage_resist: Option<Vec<String>>,
|
||||
pub by_conditions: Option<Vec<String>>,
|
||||
pub by_saving_throw: Option<Vec<String>>,
|
||||
pub by_attack_type: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for QueryFilters {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
by_name: None,
|
||||
by_schools: None,
|
||||
by_levels: None,
|
||||
by_ritual: None,
|
||||
by_concentration: None,
|
||||
by_classes: None,
|
||||
by_damage_inflict: None,
|
||||
by_damage_resist: None,
|
||||
by_conditions: None,
|
||||
by_saving_throw: None,
|
||||
by_attack_type: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl QuerySpell {
|
||||
pub fn get_all(filters: &QueryFilters, limit: i32, page: i32) -> Result<Vec<Self>, ServiceError> {
|
||||
let mut conn = crate::db::connection()?;
|
||||
let mut query = spells::table.limit(limit as i64).into_boxed();
|
||||
// Limit query to page and limit
|
||||
let offset = (page - 1) * limit;
|
||||
query = query.offset(offset as i64);
|
||||
if let Some(name) = &filters.by_name {
|
||||
query = query.filter(spells::name.ilike(format!("%{}%", name)));
|
||||
}
|
||||
if let Some(schools) = &filters.by_schools {
|
||||
query = query.filter(spells::school.eq_any(schools.iter().map(|school| school.to_string()).collect::<Vec<String>>()));
|
||||
}
|
||||
if let Some(levels) = &filters.by_levels {
|
||||
query = query.filter(spells::level.eq_any(levels));
|
||||
}
|
||||
if let Some(ritual) = filters.by_ritual {
|
||||
query = query.filter(spells::ritual.eq(ritual));
|
||||
}
|
||||
if let Some(concentration) = filters.by_concentration {
|
||||
query = query.filter(spells::concentration.eq(concentration));
|
||||
}
|
||||
if let Some(classes) = &filters.by_classes {
|
||||
query = query.filter(spells::classes.overlaps_with(classes));
|
||||
}
|
||||
if let Some(damage_inflict) = &filters.by_damage_inflict {
|
||||
query = query.filter(spells::damage_inflict.overlaps_with(damage_inflict.iter().map(|damage_inflict| damage_inflict.to_string()).collect::<Vec<String>>()));
|
||||
}
|
||||
if let Some(damage_resist) = &filters.by_damage_resist {
|
||||
query = query.filter(spells::damage_resist.overlaps_with(damage_resist.iter().map(|damage_resist| damage_resist.to_string()).collect::<Vec<String>>()));
|
||||
}
|
||||
if let Some(conditions) = &filters.by_conditions {
|
||||
query = query.filter(spells::conditions.overlaps_with(conditions.iter().map(|condition| condition.to_string()).collect::<Vec<String>>()));
|
||||
}
|
||||
if let Some(saving_throw) = &filters.by_saving_throw {
|
||||
query = query.filter(spells::saving_throw.overlaps_with(saving_throw.iter().map(|saving_throw| saving_throw.to_string()).collect::<Vec<String>>()));
|
||||
}
|
||||
if let Some(attack_type) = &filters.by_attack_type {
|
||||
query = query.filter(spells::attack_type.eq(attack_type.to_string()));
|
||||
}
|
||||
|
||||
let spells = query.load::<QuerySpell>(&mut conn)?;
|
||||
Ok(spells)
|
||||
}
|
||||
|
||||
pub fn get_count(filters: &QueryFilters) -> Result<i64, ServiceError> {
|
||||
let mut conn = crate::db::connection()?;
|
||||
let mut query = spells::table.count().into_boxed();
|
||||
if let Some(name) = &filters.by_name {
|
||||
query = query.filter(spells::name.ilike(format!("%{}%", name)));
|
||||
}
|
||||
if let Some(schools) = &filters.by_schools {
|
||||
query = query.filter(spells::school.eq_any(schools.iter().map(|school| school.to_string()).collect::<Vec<String>>()));
|
||||
}
|
||||
if let Some(levels) = &filters.by_levels {
|
||||
query = query.filter(spells::level.eq_any(levels));
|
||||
}
|
||||
if let Some(ritual) = filters.by_ritual {
|
||||
query = query.filter(spells::ritual.eq(ritual));
|
||||
}
|
||||
if let Some(concentration) = filters.by_concentration {
|
||||
query = query.filter(spells::concentration.eq(concentration));
|
||||
}
|
||||
if let Some(classes) = &filters.by_classes {
|
||||
query = query.filter(spells::classes.overlaps_with(classes));
|
||||
}
|
||||
if let Some(damage_inflict) = &filters.by_damage_inflict {
|
||||
query = query.filter(spells::damage_inflict.overlaps_with(damage_inflict.iter().map(|damage_inflict| damage_inflict.to_string()).collect::<Vec<String>>()));
|
||||
}
|
||||
if let Some(damage_resist) = &filters.by_damage_resist {
|
||||
query = query.filter(spells::damage_resist.overlaps_with(damage_resist.iter().map(|damage_resist| damage_resist.to_string()).collect::<Vec<String>>()));
|
||||
}
|
||||
if let Some(conditions) = &filters.by_conditions {
|
||||
query = query.filter(spells::conditions.overlaps_with(conditions.iter().map(|condition| condition.to_string()).collect::<Vec<String>>()));
|
||||
}
|
||||
if let Some(saving_throw) = &filters.by_saving_throw {
|
||||
query = query.filter(spells::saving_throw.overlaps_with(saving_throw.iter().map(|saving_throw| saving_throw.to_string()).collect::<Vec<String>>()));
|
||||
}
|
||||
if let Some(attack_type) = &filters.by_attack_type {
|
||||
query = query.filter(spells::attack_type.eq(attack_type.to_string()));
|
||||
}
|
||||
|
||||
let count = query.get_result(&mut conn)?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
pub fn get_by_id(id: i32) -> Result<Self, ServiceError> {
|
||||
let mut conn = crate::db::connection()?;
|
||||
let spell = spells::table
|
||||
.filter(spells::id.eq(id))
|
||||
.first::<QuerySpell>(&mut conn)?;
|
||||
Ok(spell)
|
||||
}
|
||||
|
||||
pub fn delete(id: i32) -> Result<Self, ServiceError> {
|
||||
let mut conn = crate::db::connection()?;
|
||||
let spell = diesel::delete(spells::table.filter(spells::id.eq(id))).get_result(&mut conn)?;
|
||||
Ok(spell)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Insertable, AsChangeset)]
|
||||
#[diesel(table_name = spells)]
|
||||
pub struct InsertSpell {
|
||||
pub name: String,
|
||||
pub school: String,
|
||||
pub level: i32,
|
||||
pub ritual: bool,
|
||||
pub concentration: bool,
|
||||
pub classes: Vec<String>,
|
||||
pub damage_inflict: Vec<String>,
|
||||
pub damage_resist: Vec<String>,
|
||||
pub conditions: Vec<String>,
|
||||
pub saving_throw: Vec<String>,
|
||||
pub attack_type: Option<String>,
|
||||
pub data: serde_json::Value
|
||||
}
|
||||
|
||||
impl InsertSpell {
|
||||
pub fn insert(spell: Self) -> Result<QuerySpell, ServiceError> {
|
||||
let mut conn = crate::db::connection()?;
|
||||
let spell = diesel::insert_into(spells::table).values(spell).get_result(&mut conn)?;
|
||||
Ok(spell)
|
||||
}
|
||||
|
||||
pub fn update(id: i32, spell: Self) -> Result<QuerySpell, ServiceError> {
|
||||
let mut conn = crate::db::connection()?;
|
||||
let spell = diesel::update(spells::table.filter(spells::id.eq(id))).set(spell).get_result(&mut conn)?;
|
||||
Ok(spell)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Spell {
|
||||
pub name: String,
|
||||
pub school: SchoolType,
|
||||
pub level: i32,
|
||||
pub ritual: bool,
|
||||
pub casting_time: CastingTime,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub saving_throw: Option<Vec<AbilityType>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub attack_type: Option<SpellAttackType>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub damage_inflict: Option<Vec<SpellDamageType>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub damage_resist: Option<Vec<SpellDamageType>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub conditions: Option<Vec<ConditionType>>,
|
||||
pub range: Range,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub area: Option<Area>,
|
||||
pub components: Components,
|
||||
pub durations: Vec<Duration>,
|
||||
pub classes: Vec<String>,
|
||||
pub sources: Vec<Source>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tags: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<Description>
|
||||
}
|
||||
|
||||
impl From<QuerySpell> for Spell {
|
||||
fn from(query: QuerySpell) -> Self {
|
||||
return match serde_json::from_value(query.data) {
|
||||
Ok(data) => data,
|
||||
Err(err) => {
|
||||
log::error!("Failed to parse spell: {}", err);
|
||||
Self {
|
||||
name: "".to_string(),
|
||||
school: SchoolType::Abjuration,
|
||||
level: 0,
|
||||
ritual: false,
|
||||
casting_time: CastingTime { amount: 0, casting_type: CastingType::Action },
|
||||
saving_throw: None,
|
||||
attack_type: None,
|
||||
damage_inflict: None,
|
||||
damage_resist: None,
|
||||
conditions: None,
|
||||
range: Range { range_type: "".to_string(), amount: None, unit: None },
|
||||
area: None,
|
||||
components: Components { verbal: false, somatic: false, material: false, materials_needed: None, materials_cost: None, materials_consumed: None },
|
||||
durations: vec![],
|
||||
classes: vec![],
|
||||
sources: vec![],
|
||||
tags: None,
|
||||
description: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<InsertSpell> for Spell {
|
||||
fn into(self) -> InsertSpell {
|
||||
return InsertSpell {
|
||||
name: self.name.to_string(),
|
||||
school: self.school.to_string(),
|
||||
level: self.level,
|
||||
ritual: self.ritual,
|
||||
concentration: self.durations.iter().any(|duration| match duration.duration_type {
|
||||
DurationType::Concentration => true,
|
||||
_ => false
|
||||
}),
|
||||
classes: self.classes.iter().map(|class| class.to_string()).collect::<Vec<String>>(),
|
||||
damage_inflict: match &self.damage_inflict {
|
||||
Some(damage_inflict) => damage_inflict.iter().map(|damage_inflict| damage_inflict.to_string()).collect(),
|
||||
None => vec![]
|
||||
},
|
||||
damage_resist: match &self.damage_resist {
|
||||
Some(damage_resist) => damage_resist.iter().map(|damage_resist| damage_resist.to_string()).collect(),
|
||||
None => vec![]
|
||||
},
|
||||
conditions: match &self.conditions {
|
||||
Some(conditions) => conditions.iter().map(|condition| condition.to_string()).collect(),
|
||||
None => vec![]
|
||||
},
|
||||
saving_throw: match &self.saving_throw {
|
||||
Some(saving_throw) => saving_throw.iter().map(|saving_throw| saving_throw.to_string()).collect(),
|
||||
None => vec![]
|
||||
},
|
||||
attack_type: self.attack_type.as_ref().map(|attack_type| attack_type.to_string()),
|
||||
data: match serde_json::to_value(&self) {
|
||||
Ok(data) => data,
|
||||
Err(err) => {
|
||||
log::error!("Failed to serialize spell: {}", err);
|
||||
serde_json::Value::Null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
177
service/src/db/spells/routes.rs
Normal file
177
service/src/db/spells/routes.rs
Normal file
@@ -0,0 +1,177 @@
|
||||
use actix_web::{get, post, put, delete, web, HttpResponse, HttpRequest, ResponseError};
|
||||
use log::error;
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
use crate::{db::{spells::{QuerySpell, QueryFilters}, GetResponse, Metadata}, error_handler::ServiceError};
|
||||
|
||||
use super::{Spell, InsertSpell};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct GetAllParams {
|
||||
name: Option<String>,
|
||||
schools: Option<String>,
|
||||
levels: Option<String>,
|
||||
ritual: Option<bool>,
|
||||
concentration: Option<bool>,
|
||||
classes: Option<String>,
|
||||
damage_inflict: Option<String>,
|
||||
damage_resist: Option<String>,
|
||||
conditions: Option<String>,
|
||||
saving_throw: Option<String>,
|
||||
attack_type: Option<String>,
|
||||
limit: Option<i32>,
|
||||
page: Option<i32>,
|
||||
}
|
||||
|
||||
#[get("/spells")]
|
||||
async fn get_all(req: HttpRequest) -> HttpResponse {
|
||||
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()
|
||||
})
|
||||
};
|
||||
let mut filters = QueryFilters::default();
|
||||
filters.by_name = params.name.clone();
|
||||
filters.by_schools = match ¶ms.schools {
|
||||
Some(schools) => Some(schools.split(",").map(|s| s.to_string()).collect()),
|
||||
None => None
|
||||
};
|
||||
filters.by_levels = match ¶ms.levels {
|
||||
Some(levels) => Some(levels.split(",").map(|s| match s.to_string().parse::<i32>() {
|
||||
Ok(level) => level,
|
||||
Err(_) => 0
|
||||
}).collect()),
|
||||
None => None
|
||||
};
|
||||
filters.by_ritual = params.ritual;
|
||||
filters.by_concentration = params.concentration;
|
||||
filters.by_classes = match ¶ms.classes {
|
||||
Some(classes) => Some(classes.split(",").map(|s| s.to_string()).collect()),
|
||||
None => None
|
||||
};
|
||||
filters.by_damage_inflict = match ¶ms.damage_inflict {
|
||||
Some(damage_inflict) => Some(damage_inflict.split(",").map(|s| s.to_string()).collect()),
|
||||
None => None
|
||||
};
|
||||
filters.by_damage_resist = match ¶ms.damage_resist {
|
||||
Some(damage_resist) => Some(damage_resist.split(",").map(|s| s.to_string()).collect()),
|
||||
None => None
|
||||
};
|
||||
filters.by_conditions = match ¶ms.conditions {
|
||||
Some(conditions) => Some(conditions.split(",").map(|s| s.to_string()).collect()),
|
||||
None => None
|
||||
};
|
||||
filters.by_saving_throw = match ¶ms.saving_throw {
|
||||
Some(saving_throw) => Some(saving_throw.split(",").map(|s| s.to_string()).collect()),
|
||||
None => None
|
||||
};
|
||||
filters.by_attack_type = match ¶ms.attack_type {
|
||||
Some(attack_type) => Some(attack_type.split(",").map(|s| s.to_string()).collect()),
|
||||
None => None
|
||||
};
|
||||
// Limit must be between 1 and 100
|
||||
let limit = std::cmp::min(std::cmp::max(params.limit.unwrap_or(20), 1), 100);
|
||||
let total_count = QuerySpell::get_count(&filters).unwrap();
|
||||
let max_page = std::cmp::max(1, (total_count as f64 / limit as f64).ceil() as i32);
|
||||
// Page must be between 1 and max_page
|
||||
let page = std::cmp::min(std::cmp::max(params.page.unwrap_or(1), 1), max_page);
|
||||
|
||||
match web::block(move || QuerySpell::get_all(&filters, limit, page)).await.unwrap() {
|
||||
Ok(spells) => {
|
||||
let mut response: Vec<Spell> = Vec::new();
|
||||
for spell in spells {
|
||||
response.push(Spell::from(spell));
|
||||
}
|
||||
HttpResponse::Ok().json(GetResponse {
|
||||
data: response,
|
||||
metadata: Some(Metadata {
|
||||
total: total_count as i32,
|
||||
limit,
|
||||
page,
|
||||
pages: max_page
|
||||
})
|
||||
})
|
||||
},
|
||||
Err(err) => {
|
||||
error!("{:?}", err.message);
|
||||
ResponseError::error_response(&err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/spells/{id}")]
|
||||
async fn get_by_id(id: web::Path<String>) -> HttpResponse {
|
||||
let id = match id.parse::<i32>() {
|
||||
Ok(id) => id,
|
||||
Err(err) => return ResponseError::error_response(&ServiceError {
|
||||
status: 422,
|
||||
message: err.to_string()
|
||||
})
|
||||
};
|
||||
match web::block(move || QuerySpell::get_by_id(id)).await.unwrap() {
|
||||
Ok(spell) => HttpResponse::Ok().json(GetResponse {
|
||||
data: Spell::from(spell),
|
||||
metadata: None
|
||||
}),
|
||||
Err(err) => {
|
||||
error!("{:?}", err.message);
|
||||
ResponseError::error_response(&err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[post("/spells")]
|
||||
async fn create(spell: web::Json<Spell>) -> HttpResponse {
|
||||
match InsertSpell::insert(spell.into_inner().into()) {
|
||||
Ok(spell) => HttpResponse::Created().json(Spell::from(spell)),
|
||||
Err(err) => {
|
||||
error!("{:?}", err.message);
|
||||
ResponseError::error_response(&err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[put("/spells/{id}")]
|
||||
async fn update(id: web::Path<String>, spell: web::Json<Spell>) -> HttpResponse {
|
||||
let id = match id.parse::<i32>() {
|
||||
Ok(id) => id,
|
||||
Err(err) => return ResponseError::error_response(&ServiceError {
|
||||
status: 422,
|
||||
message: err.to_string()
|
||||
})
|
||||
};
|
||||
match web::block(move || InsertSpell::update(id, spell.into_inner().into())).await.unwrap() {
|
||||
Ok(spell) => HttpResponse::Ok().json(Spell::from(spell)),
|
||||
Err(err) => {
|
||||
error!("{:?}", err.message);
|
||||
ResponseError::error_response(&err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[delete("/spells/{id}")]
|
||||
async fn delete(id: web::Path<String>) -> HttpResponse {
|
||||
let id = match id.parse::<i32>() {
|
||||
Ok(id) => id,
|
||||
Err(err) => return ResponseError::error_response(&ServiceError {
|
||||
status: 422,
|
||||
message: err.to_string()
|
||||
})
|
||||
};
|
||||
match web::block(move || QuerySpell::delete(id)).await.unwrap() {
|
||||
Ok(spell) => HttpResponse::Ok().json(Spell::from(spell)),
|
||||
Err(err) => {
|
||||
error!("{:?}", err.message);
|
||||
ResponseError::error_response(&err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_routes(config: &mut web::ServiceConfig) {
|
||||
config.service(get_all);
|
||||
config.service(get_by_id);
|
||||
config.service(create);
|
||||
config.service(delete);
|
||||
}
|
||||
377
service/src/db/spells/types.rs
Normal file
377
service/src/db/spells/types.rs
Normal file
@@ -0,0 +1,377 @@
|
||||
use std::str::FromStr;
|
||||
use serde::{Deserialize, Serialize, ser::SerializeMap};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum SchoolType {
|
||||
#[serde(rename = "abjuration")]
|
||||
Abjuration,
|
||||
#[serde(rename = "conjuration")]
|
||||
Conjuration,
|
||||
#[serde(rename = "divination")]
|
||||
Divination,
|
||||
#[serde(rename = "enchantment")]
|
||||
Enchantment,
|
||||
#[serde(rename = "evocation")]
|
||||
Evocation,
|
||||
#[serde(rename = "illusion")]
|
||||
Illusion,
|
||||
#[serde(rename = "necromancy")]
|
||||
Necromancy,
|
||||
#[serde(rename = "transmutation")]
|
||||
Transmutation
|
||||
}
|
||||
|
||||
impl SchoolType {
|
||||
pub fn to_string(&self) -> String {
|
||||
match self {
|
||||
SchoolType::Abjuration => "abjuration".to_string(),
|
||||
SchoolType::Conjuration => "conjuration".to_string(),
|
||||
SchoolType::Divination => "divination".to_string(),
|
||||
SchoolType::Enchantment => "enchantment".to_string(),
|
||||
SchoolType::Evocation => "evocation".to_string(),
|
||||
SchoolType::Illusion => "illusion".to_string(),
|
||||
SchoolType::Necromancy => "necromancy".to_string(),
|
||||
SchoolType::Transmutation => "transmutation".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for SchoolType {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"abjuration" => Ok(SchoolType::Abjuration),
|
||||
"conjuration" => Ok(SchoolType::Conjuration),
|
||||
"divination" => Ok(SchoolType::Divination),
|
||||
"enchantment" => Ok(SchoolType::Enchantment),
|
||||
"evocation" => Ok(SchoolType::Evocation),
|
||||
"illusion" => Ok(SchoolType::Illusion),
|
||||
"necromancy" => Ok(SchoolType::Necromancy),
|
||||
"transmutation" => Ok(SchoolType::Transmutation),
|
||||
_ => Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct CastingTime {
|
||||
pub amount: i32,
|
||||
#[serde(rename = "unit")]
|
||||
pub casting_type: CastingType
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum CastingType {
|
||||
#[serde(rename = "action")]
|
||||
Action,
|
||||
#[serde(rename = "bonus")]
|
||||
BonusAction,
|
||||
#[serde(rename = "reaction")]
|
||||
Reaction,
|
||||
#[serde(rename = "minutes")]
|
||||
Minutes,
|
||||
#[serde(rename = "hours")]
|
||||
Hours
|
||||
}
|
||||
|
||||
// impl CastingType {
|
||||
// pub fn to_string(&self) -> String {
|
||||
// match self {
|
||||
// CastingType::Action => "action".to_string(),
|
||||
// CastingType::BonusAction => "bonus".to_string(),
|
||||
// CastingType::Reaction => "reaction".to_string(),
|
||||
// CastingType::Minutes => "minutes".to_string(),
|
||||
// CastingType::Hours => "hours".to_string()
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl FromStr for CastingType {
|
||||
// type Err = ();
|
||||
|
||||
// fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
// match s {
|
||||
// "action" => Ok(CastingType::Action),
|
||||
// "bonus" => Ok(CastingType::BonusAction),
|
||||
// "reaction" => Ok(CastingType::Reaction),
|
||||
// "minutes" => Ok(CastingType::Minutes),
|
||||
// "hours" => Ok(CastingType::Hours),
|
||||
// _ => Err(())
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum SpellAttackType {
|
||||
#[serde(rename = "melee")]
|
||||
Melee,
|
||||
#[serde(rename = "ranged")]
|
||||
Ranged,
|
||||
}
|
||||
|
||||
impl SpellAttackType {
|
||||
pub fn to_string(&self) -> String {
|
||||
match self {
|
||||
SpellAttackType::Melee => "melee".to_string(),
|
||||
SpellAttackType::Ranged => "ranged".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for SpellAttackType {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"melee" => Ok(SpellAttackType::Melee),
|
||||
"ranged" => Ok(SpellAttackType::Ranged),
|
||||
_ => Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum SpellDamageType {
|
||||
#[serde(rename = "acid")]
|
||||
Acid,
|
||||
#[serde(rename = "bludgeoning")]
|
||||
Bludgeoning,
|
||||
#[serde(rename = "cold")]
|
||||
Cold,
|
||||
#[serde(rename = "fire")]
|
||||
Fire,
|
||||
#[serde(rename = "force")]
|
||||
Force,
|
||||
#[serde(rename = "lightning")]
|
||||
Lightning,
|
||||
#[serde(rename = "necrotic")]
|
||||
Necrotic,
|
||||
#[serde(rename = "piercing")]
|
||||
Piercing,
|
||||
#[serde(rename = "poison")]
|
||||
Poison,
|
||||
#[serde(rename = "psychic")]
|
||||
Psychic,
|
||||
#[serde(rename = "radiant")]
|
||||
Radiant,
|
||||
#[serde(rename = "slashing")]
|
||||
Slashing,
|
||||
#[serde(rename = "thunder")]
|
||||
Thunder
|
||||
}
|
||||
|
||||
impl SpellDamageType {
|
||||
pub fn to_string(&self) -> String {
|
||||
match self {
|
||||
SpellDamageType::Acid => "acid".to_string(),
|
||||
SpellDamageType::Bludgeoning => "bludgeoning".to_string(),
|
||||
SpellDamageType::Cold => "cold".to_string(),
|
||||
SpellDamageType::Fire => "fire".to_string(),
|
||||
SpellDamageType::Force => "force".to_string(),
|
||||
SpellDamageType::Lightning => "lightning".to_string(),
|
||||
SpellDamageType::Necrotic => "necrotic".to_string(),
|
||||
SpellDamageType::Piercing => "piercing".to_string(),
|
||||
SpellDamageType::Poison => "poison".to_string(),
|
||||
SpellDamageType::Psychic => "psychic".to_string(),
|
||||
SpellDamageType::Radiant => "radiant".to_string(),
|
||||
SpellDamageType::Slashing => "slashing".to_string(),
|
||||
SpellDamageType::Thunder => "thunder".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for SpellDamageType {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"acid" => Ok(SpellDamageType::Acid),
|
||||
"bludgeoning" => Ok(SpellDamageType::Bludgeoning),
|
||||
"cold" => Ok(SpellDamageType::Cold),
|
||||
"fire" => Ok(SpellDamageType::Fire),
|
||||
"force" => Ok(SpellDamageType::Force),
|
||||
"lightning" => Ok(SpellDamageType::Lightning),
|
||||
"necrotic" => Ok(SpellDamageType::Necrotic),
|
||||
"piercing" => Ok(SpellDamageType::Piercing),
|
||||
"poison" => Ok(SpellDamageType::Poison),
|
||||
"psychic" => Ok(SpellDamageType::Psychic),
|
||||
"radiant" => Ok(SpellDamageType::Radiant),
|
||||
"slashing" => Ok(SpellDamageType::Slashing),
|
||||
"thunder" => Ok(SpellDamageType::Thunder),
|
||||
_ => Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Range {
|
||||
#[serde(rename = "type")]
|
||||
pub range_type: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub amount: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub unit: Option<String>
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Area {
|
||||
#[serde(rename = "type")]
|
||||
pub area_type: AreaType,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub amount: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub unit: Option<String>
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum AreaType {
|
||||
#[serde(rename = "cone")]
|
||||
Cone,
|
||||
#[serde(rename = "cube")]
|
||||
Cube,
|
||||
#[serde(rename = "cylinder")]
|
||||
Cylinder,
|
||||
#[serde(rename = "line")]
|
||||
Line,
|
||||
#[serde(rename = "sphere")]
|
||||
Sphere
|
||||
}
|
||||
|
||||
// impl AreaType {
|
||||
// pub fn to_string(&self) -> String {
|
||||
// match self {
|
||||
// AreaType::Cone => "cone".to_string(),
|
||||
// AreaType::Cube => "cube".to_string(),
|
||||
// AreaType::Cylinder => "cylinder".to_string(),
|
||||
// AreaType::Line => "line".to_string(),
|
||||
// AreaType::Sphere => "sphere".to_string()
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl FromStr for AreaType {
|
||||
// type Err = ();
|
||||
|
||||
// fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
// match s {
|
||||
// "cone" => Ok(AreaType::Cone),
|
||||
// "cube" => Ok(AreaType::Cube),
|
||||
// "cylinder" => Ok(AreaType::Cylinder),
|
||||
// "line" => Ok(AreaType::Line),
|
||||
// "sphere" => Ok(AreaType::Sphere),
|
||||
// _ => Err(())
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Duration {
|
||||
#[serde(rename = "type")]
|
||||
pub duration_type: DurationType,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub amount: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub unit: Option<String>
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum DurationType {
|
||||
#[serde(rename = "concentration")]
|
||||
Concentration,
|
||||
#[serde(rename = "instantaneous")]
|
||||
Instantaneous,
|
||||
#[serde(rename = "timed")]
|
||||
Timed,
|
||||
#[serde(rename = "dispelled")]
|
||||
UntilDispelled,
|
||||
#[serde(rename = "special")]
|
||||
Special
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Source {
|
||||
pub source: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub page: Option<i32>
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Description {
|
||||
pub entries: Vec<Entry>
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Entry {
|
||||
pub entry_type: String,
|
||||
pub items: Vec<String>
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Entry {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
|
||||
let value = serde_json::Value::deserialize(deserializer)?;
|
||||
match value {
|
||||
serde_json::Value::String(s) => Ok(Entry {
|
||||
entry_type: "string".to_string(),
|
||||
items: vec![s]
|
||||
}),
|
||||
serde_json::Value::Object(o) => {
|
||||
let entry_type = match o.get("type") {
|
||||
Some(t) => match t.as_str() {
|
||||
Some(s) => s.to_string(),
|
||||
None => return Err(serde::de::Error::custom("Invalid entry type"))
|
||||
},
|
||||
None => return Err(serde::de::Error::custom("Missing entry type"))
|
||||
};
|
||||
let items = match o.get("items") {
|
||||
Some(i) => match i.as_array() {
|
||||
Some(a) => {
|
||||
let mut items = Vec::new();
|
||||
for item in a {
|
||||
match item.as_str() {
|
||||
Some(s) => items.push(s.to_string()),
|
||||
None => return Err(serde::de::Error::custom("Invalid entry item"))
|
||||
}
|
||||
}
|
||||
items
|
||||
},
|
||||
None => return Err(serde::de::Error::custom("Invalid entry items"))
|
||||
},
|
||||
None => return Err(serde::de::Error::custom("Missing entry items"))
|
||||
};
|
||||
Ok(Entry {
|
||||
entry_type,
|
||||
items
|
||||
})
|
||||
},
|
||||
_ => Err(serde::de::Error::custom("Invalid entry"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Entry {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
|
||||
match self.entry_type.as_str() {
|
||||
"string" => serializer.serialize_str(&self.items[0]),
|
||||
_ => {
|
||||
let mut map = serializer.serialize_map(Some(2))?;
|
||||
map.serialize_entry("type", &self.entry_type)?;
|
||||
map.serialize_entry("items", &self.items)?;
|
||||
map.end()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Components {
|
||||
pub verbal: bool,
|
||||
pub somatic: bool,
|
||||
pub material: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub materials_needed: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub materials_cost: Option<i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub materials_consumed: Option<bool>
|
||||
}
|
||||
3
service/src/db/users/mod.rs
Normal file
3
service/src/db/users/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
mod model;
|
||||
|
||||
pub use model::*;
|
||||
3
service/src/db/users/model.rs
Normal file
3
service/src/db/users/model.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub struct User {
|
||||
pub id: i32
|
||||
}
|
||||
57
service/src/error_handler.rs
Normal file
57
service/src/error_handler.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
use actix_web::{ResponseError, HttpResponse};
|
||||
use diesel::result::Error as DieselError;
|
||||
use reqwest::StatusCode;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct ServiceError {
|
||||
pub status: u16,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl ServiceError {
|
||||
pub fn new(error_status_code: u16, error_message: String) -> ServiceError {
|
||||
ServiceError {
|
||||
status: error_status_code,
|
||||
message: error_message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ServiceError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str(self.message.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DieselError> for ServiceError {
|
||||
fn from(error: DieselError) -> ServiceError {
|
||||
match error {
|
||||
DieselError::DatabaseError(_, err) => ServiceError::new(409, err.message().to_string()),
|
||||
DieselError::NotFound => {
|
||||
ServiceError::new(404, "The record was not found".to_string())
|
||||
},
|
||||
DieselError::SerializationError(err) => {
|
||||
ServiceError::new(422, err.to_string())
|
||||
},
|
||||
err => ServiceError::new(500, format!("Unknown database error: {}", err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ResponseError for ServiceError {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
let status_code = match StatusCode::from_u16(self.status) {
|
||||
Ok(status_code) => status_code,
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
|
||||
let error_message = match status_code.as_u16() < 500 {
|
||||
true => self.message.clone(),
|
||||
false => "Internal server error".to_string(),
|
||||
};
|
||||
|
||||
HttpResponse::build(status_code).json(serde_json::json!({ "status": status_code.as_u16(), "message": error_message }))
|
||||
}
|
||||
}
|
||||
207
service/src/main.rs
Normal file
207
service/src/main.rs
Normal file
@@ -0,0 +1,207 @@
|
||||
extern crate diesel;
|
||||
#[macro_use]
|
||||
extern crate diesel_migrations;
|
||||
|
||||
use std::collections::{HashSet, HashMap};
|
||||
use std::env;
|
||||
use std::sync::Arc;
|
||||
|
||||
use actix_web::{HttpServer, App};
|
||||
use commands::audio::{create_response, AudioConfig, AudioConfigs};
|
||||
|
||||
use dotenv::dotenv;
|
||||
use log::{error, warn, info};
|
||||
use serenity::async_trait;
|
||||
use serenity::framework::StandardFramework;
|
||||
use serenity::model::application::interaction::Interaction;
|
||||
use serenity::model::gateway::Ready;
|
||||
use serenity::model::channel::Message;
|
||||
use serenity::http::Http;
|
||||
use serenity::prelude::*;
|
||||
use songbird::SerenityInit;
|
||||
|
||||
use crate::commands::oai::GPTModel;
|
||||
|
||||
mod commands;
|
||||
mod error_handler;
|
||||
mod db;
|
||||
struct Handler {
|
||||
// Open AI Config
|
||||
oai: Option<commands::oai::OAI>
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EventHandler for Handler {
|
||||
async fn message(&self, ctx: Context, msg: Message) {
|
||||
// Ignore messages from bots
|
||||
if msg.author.bot {
|
||||
return;
|
||||
}
|
||||
match &self.oai {
|
||||
Some(oai) => {
|
||||
match msg.mentions_me(&ctx.http).await {
|
||||
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) {
|
||||
Some(_) => true,
|
||||
None => false
|
||||
}
|
||||
}
|
||||
Err(_) => false
|
||||
};
|
||||
if mentioned || bot_in_thread {
|
||||
commands::oai::generate_response(&ctx, &msg, oai).await;
|
||||
}
|
||||
}
|
||||
Err(why) => warn!("Could not check mentions: {:?}", why)
|
||||
};
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
|
||||
if let Interaction::ApplicationCommand(command) = interaction {
|
||||
match command.data.name.as_str() {
|
||||
"play" => commands::audio::play::run(&ctx, &command).await,
|
||||
"stop" => commands::audio::stop::run(&ctx, &command).await,
|
||||
"pause" => commands::audio::pause::run(&ctx, &command).await,
|
||||
"resume" => commands::audio::resume::run(&ctx, &command).await,
|
||||
"skip" => commands::audio::skip::run(&ctx, &command).await,
|
||||
"volume" => commands::audio::volume::run(&ctx, &command).await,
|
||||
_ => {
|
||||
let content: String = match command.data.name.as_str() {
|
||||
"ping" => commands::ping::run(&command.data.options),
|
||||
_ => "Unknown command".to_string()
|
||||
};
|
||||
|
||||
if let Err(why) = create_response(&ctx, &command, content).await {
|
||||
warn!("Cannot respond to slash command: {}", why);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn ready(&self, ctx: Context, ready: Ready) {
|
||||
if ready.guilds.is_empty() {
|
||||
warn!("No ready guilds found");
|
||||
}
|
||||
for guild in ready.guilds {
|
||||
let audio_config_lock = {
|
||||
let data_read = ctx.data.read().await;
|
||||
data_read.get::<AudioConfigs>().expect("Expected AudioConfigs in TypeMap.").clone()
|
||||
};
|
||||
{
|
||||
let mut audio_configs = audio_config_lock.write().await;
|
||||
let _ = audio_configs.insert(guild.id, AudioConfig { volume: 1.0 });
|
||||
}
|
||||
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::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)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
dotenv().ok();
|
||||
env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", "warn,siren=info"));
|
||||
db::init();
|
||||
db::load_data();
|
||||
|
||||
// setup_discord_bot();
|
||||
|
||||
let host = env::var("SERVICE_HOST").unwrap_or("localhost".to_string());
|
||||
let port = env::var("SERVICE_PORT").unwrap_or("5000".to_string());
|
||||
|
||||
match HttpServer::new(|| {
|
||||
App::new()
|
||||
.configure(db::spells::init_routes)
|
||||
})
|
||||
.bind(format!("{}:{}", host, port)) {
|
||||
Ok(b) => {
|
||||
info!("Binding server to {}:{}", host, port);
|
||||
b
|
||||
},
|
||||
Err(err) => {
|
||||
error!("Could not bind server: {}", err);
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
||||
fn setup_discord_bot() {
|
||||
tokio::spawn(async {
|
||||
let token: String = env::var("DISCORD_TOKEN").expect("Expected a token in the environment");
|
||||
let intents: GatewayIntents = GatewayIntents::all();
|
||||
|
||||
let http: Http = Http::new(&token);
|
||||
let (owners, _bot_id) = match http.get_current_application_info().await {
|
||||
Ok(info) => {
|
||||
let mut owners: HashSet<serenity::model::id::UserId> = HashSet::new();
|
||||
if let Some(team) = info.team {
|
||||
owners.insert(team.owner_user_id);
|
||||
} else {
|
||||
owners.insert(info.owner.id);
|
||||
}
|
||||
match http.get_current_user().await {
|
||||
Ok(bot) => (owners, bot.id),
|
||||
Err(why) => panic!("Could not access the bot id: {:?}", why)
|
||||
}
|
||||
},
|
||||
Err(why) => panic!("Could not access application info: {:?}", why)
|
||||
};
|
||||
|
||||
let handler = match env::var("OPENAI_API_KEY") {
|
||||
Ok(token) => {
|
||||
info!("Loaded OpenAI token");
|
||||
Handler {
|
||||
oai: Some(commands::oai::OAI {
|
||||
client: reqwest::Client::new(),
|
||||
base_url: "https://api.openai.com/v1".to_string(),
|
||||
max_attempts: 5,
|
||||
token,
|
||||
max_context_questions: 30,
|
||||
max_tokens: 2048,
|
||||
default_model: GPTModel::GPT35Turbo,
|
||||
})
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Could not load OpenAI token: {}", err);
|
||||
Handler { oai: None }
|
||||
}
|
||||
};
|
||||
|
||||
let mut client = Client::builder(token, intents)
|
||||
.event_handler(handler)
|
||||
.framework(StandardFramework::new()
|
||||
.configure(|c| c.owners(owners)))
|
||||
.register_songbird()
|
||||
.await
|
||||
.expect("Error creating client");
|
||||
|
||||
{
|
||||
let mut data = client.data.write().await;
|
||||
data.insert::<AudioConfigs>(Arc::new(RwLock::new(HashMap::default())));
|
||||
}
|
||||
|
||||
if let Err(why) = client.start_autosharded().await {
|
||||
error!("An error occurred while running the client: {:?}", why);
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user