make SqlitePool a dptree dependency, so handlers would have access to database

This commit is contained in:
mykola2312 2024-02-26 00:42:28 +02:00
parent f87834a4f4
commit 524b7970e0
2 changed files with 11 additions and 5 deletions

BIN
mk-dl-bot.db Normal file

Binary file not shown.

View file

@ -1,4 +1,5 @@
use anyhow; use anyhow;
use sqlx::migrate::MigrateDatabase;
use std::env; use std::env;
use std::fmt; use std::fmt;
use std::str; use std::str;
@ -9,7 +10,7 @@ use teloxide::dispatching::dialogue::InMemStorage;
use teloxide::dispatching::UpdateHandler; use teloxide::dispatching::UpdateHandler;
use teloxide::types::InputFile; use teloxide::types::InputFile;
use teloxide::{prelude::*, update_listeners::Polling, utils::command::BotCommands}; use teloxide::{prelude::*, update_listeners::Polling, utils::command::BotCommands};
use sqlx::SqlitePool; use sqlx::{Sqlite, SqlitePool};
use super::util::make_database_url; use super::util::make_database_url;
@ -36,8 +37,12 @@ where
} }
pub async fn bot_main() -> anyhow::Result<()> { pub async fn bot_main() -> anyhow::Result<()> {
let db_path = make_database_url(); let db_url = make_database_url();
let db = SqlitePool::connect(&db_path).await?; if !Sqlite::database_exists(&db_url).await.unwrap_or(false) {
Sqlite::create_database(&db_url).await.expect("failed to create database");
}
let db = SqlitePool::connect(&db_url).await?;
let bot = Bot::new(env::var("BOT_TOKEN")?); let bot = Bot::new(env::var("BOT_TOKEN")?);
let listener = Polling::builder(bot.clone()) let listener = Polling::builder(bot.clone())
@ -47,7 +52,7 @@ pub async fn bot_main() -> anyhow::Result<()> {
.build(); .build();
Dispatcher::builder(bot, schema()) Dispatcher::builder(bot, schema())
.dependencies(dptree::deps![db]) .dependencies(dptree::deps![db, InMemStorage::<State>::new()])
.enable_ctrlc_handler() .enable_ctrlc_handler()
.build() .build()
.dispatch_with_listener( .dispatch_with_listener(
@ -83,7 +88,8 @@ enum Command {
Download(String), Download(String),
} }
async fn cmd_test(bot: Bot, msg: Message) -> HandlerResult { async fn cmd_test(bot: Bot, msg: Message, db: SqlitePool) -> HandlerResult {
dbg!(db);
bot.send_message(msg.chat.id, "test response").await?; bot.send_message(msg.chat.id, "test response").await?;
Ok(()) Ok(())