Skip to content

Commit

Permalink
small updates
Browse files Browse the repository at this point in the history
  • Loading branch information
YegorDrozdov committed Jun 20, 2024
1 parent 9dce1fc commit 9769337
Show file tree
Hide file tree
Showing 6 changed files with 256 additions and 100 deletions.
16 changes: 16 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ pub struct Config {
pub headers: HeaderMap,
pub api_key: String,
pub api_model: String,
pub db_host: String,
pub db_port: String,
pub db_user: String,
pub db_password: String,
pub db_name: String,

}

impl Config {
Expand All @@ -16,6 +22,11 @@ impl Config {
let pexels_api_key: String = env::var("PEXELS_API_KEY")?;
let api_key = env::var("OPENAI_API_KEY_").expect("OPENAI_API_KEY not set");
let api_model = env::var("OPENAI_API_MODEL").unwrap_or_else(|_| "gpt-3.5-turbo".to_string());
let db_host = env::var("DB_HOST").expect("DB_HOST must be set");
let db_port = env::var("DB_PORT").expect("DB_PORT must be set");
let db_user = env::var("DB_USER").expect("DB_USER must be set");
let db_password = env::var("DB_PASSWORD").expect("DB_PASSWORD must be set");
let db_name = env::var("DB_NAME").expect("DB_NAME must be set");

let mut headers: HeaderMap = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_str(&pexels_api_key).unwrap());
Expand All @@ -29,6 +40,11 @@ impl Config {
headers,
api_key,
api_model,
db_host,
db_port,
db_user,
db_password,
db_name,
})
}
}
91 changes: 78 additions & 13 deletions src/database.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,79 @@
use diesel::r2d2::{self, ConnectionManager};
use diesel::pg::PgConnection;
use std::env;

pub(crate) type DbPool = r2d2::Pool<ConnectionManager<PgConnection>>;

pub fn establish_connection_pool() -> DbPool {
dotenv::dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let manager = ConnectionManager::<PgConnection>::new(database_url);
r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.")
use tokio_postgres::{NoTls, Error};
use crate::config::Config;
use std::sync::Arc;

async fn create_tables(config: Arc<Config>) -> Result<(), Error> {
let connection_string = format!(
"host={} port={} user={} password={} dbname={}",
config.db_host,
config.db_port,
config.db_user,
config.db_password,
config.db_name,
);

let (client, connection) = tokio_postgres::connect(&connection_string, NoTls).await?;

tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("connection error: {}", e);
}
});

client.execute(
"
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
user_data JSON NOT NULL,
chat_data JSON NOT NULL,
epoch_time INTEGER NOT NULL
)
",
&[],
).await?;

client.execute(
"
CREATE TABLE IF NOT EXISTS requests (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
command TEXT NOT NULL,
response TEXT NOT NULL,
request_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
",
&[],
).await?;

Ok(())
}

async fn create_user(client: &tokio_postgres::Client, user_data: &str, chat_data: &str, epoch_time: i32) -> Result<u64, Error> {
let stmt = "
INSERT INTO users (user_data, chat_data, epoch_time)
VALUES ($1, $2, $3)
";
let rows_affected = client.execute(stmt, &[&user_data, &chat_data, &epoch_time]).await?;
Ok(rows_affected)
}

async fn create_request(client: &tokio_postgres::Client, user_id: i32, command: &str, response: &str) -> Result<u64, Error> {
let stmt = "
INSERT INTO requests (user_id, command, response)
VALUES ($1, $2, $3)
";
let rows_affected = client.execute(stmt, &[&user_id, &command, &response]).await?;
Ok(rows_affected)
}

async fn find_user_by_id(client: &tokio_postgres::Client, user_id: &str) -> Result<Option<i32>, Error> {
let stmt = "
SELECT id FROM users WHERE user_data->>'id' = $1
";
let row = client.query_opt(stmt, &[&user_id]).await?;
if let Some(row) = row {
Ok(Some(row.get(0)))
} else {
Ok(None)
}
}
23 changes: 16 additions & 7 deletions src/keyboards.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,29 @@
use serde::Deserialize;
use regex::Regex;
use serde_yaml::Value;
use serde::Deserialize;
use std::fs;
use regex::Regex;
use std::collections::HashMap;
use teloxide::types::{KeyboardMarkup, KeyboardButton};
use teloxide::types::{KeyboardButton, KeyboardMarkup};
use std::collections::BTreeMap;

#[derive(Debug, Deserialize)]
pub struct Command {
pub name: String,
pub action: String,
pub error_msg: String,
}

#[derive(Deserialize)]
struct CommandWrapper {
commands: BTreeMap<String, CommandData>,
}

#[derive(Deserialize)]
struct CommandData {
error_msg: String,
}

pub fn load_commands_with_emoji(file_path: &str) -> Vec<Command> {
let yaml_data = fs::read_to_string(file_path).expect("Unable to read YAML file");
let all_commands: HashMap<String, HashMap<String, Value>> = serde_yaml::from_str(&yaml_data).expect("Unable to parse YAML");
let all_commands: BTreeMap<String, BTreeMap<String, Value>> = serde_yaml::from_str(&yaml_data).expect("Unable to parse YAML");

let emoji_regex = Regex::new(r"^\p{Emoji}\s*").unwrap();

Expand Down Expand Up @@ -48,5 +57,5 @@ pub fn extract_command_from_label(label: &str) -> String {
.to_string()
.trim()
.to_lowercase()
.replace("_", "")
// .replace(" ", "_")
}
17 changes: 12 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#[macro_use]
extern crate diesel;
// extern crate diesel;
extern crate dotenv;

mod config;
Expand All @@ -21,13 +21,13 @@ use teloxide::prelude::*;
use config::Config;
use logging::init_logger;
use std::sync::Arc;
use database::establish_connection_pool;
// use database::establish_connection_pool;

#[tokio::main]
async fn main() {
dotenv::dotenv().ok();
let _ = init_logger();
let pool = Arc::new(establish_connection_pool());
// let pool = Arc::new(establish_connection_pool());
let config = Arc::new(Config::from_env().expect("Failed to load configuration"));
let commands = Arc::new(keyboards::load_commands_with_emoji("commands.yaml"));
let openai_recognizer = Arc::new(
Expand All @@ -41,10 +41,17 @@ async fn main() {
let config = Arc::clone(&config);
let commands = Arc::clone(&commands);
let openai_recognizer = Arc::clone(&openai_recognizer);
let pool = Arc::clone(&pool);
// let pool = Arc::clone(&pool);

async move {
let _ = routes::handle_message(bot, message, config, commands, openai_recognizer, pool).await;
let _ = routes::handle_message(
bot,
message,
config,
commands,
openai_recognizer,
// pool
).await;
respond(())
}
})
Expand Down
Loading

0 comments on commit 9769337

Please sign in to comment.