This commit is contained in:
Akulij 2025-04-03 04:57:46 +09:00
parent 30117624c4
commit 5cadb2bd76
4 changed files with 92 additions and 56 deletions

View File

@ -1,16 +1,20 @@
use teloxide::{dispatching::dialogue::GetChatId, payloads::SendMessageSetters, prelude::*, types::InputFile, utils::{command::BotCommands, render::RenderMessageTextHelper}}; use teloxide::{
dispatching::dialogue::GetChatId,
payloads::SendMessageSetters,
prelude::*,
types::InputFile,
utils::{command::BotCommands, render::RenderMessageTextHelper},
};
use crate::db::DB;
use crate::LogMsg; use crate::LogMsg;
use crate::db::DB;
// These are should not appear in /help // These are should not appear in /help
#[derive(BotCommands, Clone)] #[derive(BotCommands, Clone)]
#[command(rename_rule = "lowercase")] #[command(rename_rule = "lowercase")]
pub enum SecretCommands { pub enum SecretCommands {
/// Activate admin mode /// Activate admin mode
Secret { Secret { pass: String },
pass: String
},
} }
#[derive(BotCommands, Clone)] #[derive(BotCommands, Clone)]
@ -34,20 +38,28 @@ pub async fn admin_command_handler(
println!("MSG: {}", msg.html_text().unwrap()); println!("MSG: {}", msg.html_text().unwrap());
match cmd { match cmd {
AdminCommands::MyId => { AdminCommands::MyId => {
bot.send_message(msg.chat.id, format!("Your ID is: {}", tguser.id)).log().await?; bot.send_message(msg.chat.id, format!("Your ID is: {}", tguser.id))
.log()
.await?;
Ok(()) Ok(())
}, }
AdminCommands::Pin => { AdminCommands::Pin => {
if let Some(msg_to_pin) = msg.reply_to_message() { if let Some(msg_to_pin) = msg.reply_to_message() {
bot.pin_chat_message(msg.chat.id, msg_to_pin.id).await?; bot.pin_chat_message(msg.chat.id, msg_to_pin.id).await?;
} else { } else {
bot.send_message(msg.chat.id, "you need to reply to some message with this command").log().await?; bot.send_message(
msg.chat.id,
"you need to reply to some message with this command",
)
.log()
.await?;
} }
Ok(()) Ok(())
}, }
AdminCommands::Deop => { AdminCommands::Deop => {
db.set_admin(tguser.id.0 as i64, false).await; db.set_admin(tguser.id.0 as i64, false).await;
bot.send_message(msg.chat.id, "You are not an admin anymore").await?; bot.send_message(msg.chat.id, "You are not an admin anymore")
.await?;
Ok(()) Ok(())
} }
} }
@ -59,20 +71,24 @@ pub async fn secret_command_handler(
bot: Bot, bot: Bot,
msg: Message, msg: Message,
cmd: SecretCommands, cmd: SecretCommands,
admin_password: String admin_password: String,
) -> Result<(), teloxide::RequestError> { ) -> Result<(), teloxide::RequestError> {
println!("Admin Pass: {}", admin_password); println!("Admin Pass: {}", admin_password);
let user = db.get_or_init_user(msg.from.clone().unwrap().id.0 as i64).await; let user = db
.get_or_init_user(msg.from.clone().unwrap().id.0 as i64)
.await;
println!("MSG: {}", msg.html_text().unwrap()); println!("MSG: {}", msg.html_text().unwrap());
match cmd { match cmd {
SecretCommands::Secret { pass } => { SecretCommands::Secret { pass } => {
if user.is_admin == true { if user.is_admin == true {
bot.send_message(msg.from.unwrap().id, "You are an admin already").await?; bot.send_message(msg.from.unwrap().id, "You are an admin already")
.await?;
} else if pass == admin_password { } else if pass == admin_password {
db.set_admin(user.id, true).await; db.set_admin(user.id, true).await;
bot.send_message(msg.from.unwrap().id, "You are admin now!").await?; bot.send_message(msg.from.unwrap().id, "You are admin now!")
.await?;
} }
Ok(()) Ok(())
}, }
} }
} }

View File

@ -8,14 +8,14 @@ use diesel::prelude::*;
//use diesel::query_dsl::methods::FilterDsl; //use diesel::query_dsl::methods::FilterDsl;
//use diesel::{prelude::*, r2d2::{ConnectionManager, Pool}}; //use diesel::{prelude::*, r2d2::{ConnectionManager, Pool}};
use diesel_async::AsyncPgConnection; use diesel_async::AsyncPgConnection;
use diesel_async::RunQueryDsl;
use diesel_async::pooled_connection::AsyncDieselConnectionManager; use diesel_async::pooled_connection::AsyncDieselConnectionManager;
use diesel_async::pooled_connection::bb8::Pool; use diesel_async::pooled_connection::bb8::Pool;
use diesel_async::RunQueryDsl;
#[derive(Clone)] #[derive(Clone)]
pub struct DB { pub struct DB {
//pool: Pool<ConnectionManager<AsyncPgConnection>> //pool: Pool<ConnectionManager<AsyncPgConnection>>
pool: diesel_async::pooled_connection::bb8::Pool<AsyncPgConnection> pool: diesel_async::pooled_connection::bb8::Pool<AsyncPgConnection>,
} }
impl DB { impl DB {
@ -34,7 +34,11 @@ impl DB {
use self::schema::users::dsl::*; use self::schema::users::dsl::*;
let mut conn = self.pool.get().await.unwrap(); let mut conn = self.pool.get().await.unwrap();
//let mut conn = AsyncPgConnection::establish(&std::env::var("DATABASE_URL").unwrap()).await.unwrap(); //let mut conn = AsyncPgConnection::establish(&std::env::var("DATABASE_URL").unwrap()).await.unwrap();
users.filter(id.gt(0)).load::<User>(&mut conn).await.unwrap() users
.filter(id.gt(0))
.load::<User>(&mut conn)
.await
.unwrap()
} }
pub async fn set_admin(&mut self, userid: i64, isadmin: bool) { pub async fn set_admin(&mut self, userid: i64, isadmin: bool) {
@ -45,20 +49,29 @@ impl DB {
diesel::update(users) diesel::update(users)
.filter(id.eq(userid)) .filter(id.eq(userid))
.set(is_admin.eq(isadmin)) .set(is_admin.eq(isadmin))
.execute(connection).await.unwrap(); .execute(connection)
.await
.unwrap();
} }
pub async fn get_or_init_user(&mut self, userid: i64) -> User { pub async fn get_or_init_user(&mut self, userid: i64) -> User {
use self::schema::users::dsl::*; use self::schema::users::dsl::*;
let connection = &mut self.pool.get().await.unwrap(); let connection = &mut self.pool.get().await.unwrap();
let user = users.filter(id.eq(userid)).first::<User>(connection).await.optional().unwrap(); let user = users
.filter(id.eq(userid))
.first::<User>(connection)
.await
.optional()
.unwrap();
match user { match user {
Some(existing_user) => existing_user, Some(existing_user) => existing_user,
None => { None => diesel::insert_into(users)
diesel::insert_into(users).values((id.eq(userid as i64), is_admin.eq(false))).get_result(connection).await.unwrap() .values((id.eq(userid as i64), is_admin.eq(false)))
} .get_result(connection)
.await
.unwrap(),
} }
} }
} }

View File

@ -3,7 +3,6 @@
#![allow(unused)] #![allow(unused)]
#![allow(clippy::all)] #![allow(clippy::all)]
use diesel::prelude::*; use diesel::prelude::*;
#[derive(Queryable, Debug)] #[derive(Queryable, Debug)]
#[diesel(table_name = users)] #[diesel(table_name = users)]
@ -11,4 +10,3 @@ pub struct User {
pub id: i64, pub id: i64,
pub is_admin: bool, pub is_admin: bool,
} }

View File

@ -1,12 +1,18 @@
pub mod db;
pub mod admin; pub mod admin;
pub mod db;
use crate::db::DB;
use crate::admin::{AdminCommands, admin_command_handler}; use crate::admin::{AdminCommands, admin_command_handler};
use crate::admin::{secret_command_handler, SecretCommands}; use crate::admin::{SecretCommands, secret_command_handler};
use crate::db::DB;
use teloxide::{dispatching::dialogue::GetChatId, payloads::SendMessageSetters, prelude::*, types::InputFile, utils::{command::BotCommands, render::RenderMessageTextHelper}};
use envconfig::Envconfig; use envconfig::Envconfig;
use teloxide::{
dispatching::dialogue::GetChatId,
payloads::SendMessageSetters,
prelude::*,
types::InputFile,
utils::{command::BotCommands, render::RenderMessageTextHelper},
};
#[derive(Envconfig)] #[derive(Envconfig)]
struct Config { struct Config {
@ -39,7 +45,7 @@ impl LogMsg for <teloxide::Bot as teloxide::prelude::Requester>::SendMessage {
} }
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>>{ async fn main() -> Result<(), Box<dyn std::error::Error>> {
dotenvy::dotenv()?; dotenvy::dotenv()?;
let config = Config::init_from_env()?; let config = Config::init_from_env()?;
@ -52,25 +58,28 @@ async fn main() -> Result<(), Box<dyn std::error::Error>>{
}) })
.branch( .branch(
Update::filter_message() Update::filter_message()
.branch( .branch(
dptree::entry().filter_command::<UserCommands>().endpoint(user_command_handler) dptree::entry()
) .filter_command::<UserCommands>()
.branch( .endpoint(user_command_handler),
dptree::entry().filter_command::<SecretCommands>() )
.map(move || config.admin_password.clone()) .branch(
.endpoint(secret_command_handler) dptree::entry()
) .filter_command::<SecretCommands>()
.branch( .map(move || config.admin_password.clone())
dptree::entry().filter_async(async |msg: Message, mut db: DB| { .endpoint(secret_command_handler),
let user = db.get_or_init_user(msg.from.unwrap().id.0 as i64).await; )
user.is_admin .branch(
}).filter_command::<AdminCommands>().endpoint(admin_command_handler) dptree::entry()
) .filter_async(async |msg: Message, mut db: DB| {
let user = db.get_or_init_user(msg.from.unwrap().id.0 as i64).await;
user.is_admin
})
.filter_command::<AdminCommands>()
.endpoint(admin_command_handler),
),
) )
.branch( .branch(Update::filter_message().endpoint(echo));
Update::filter_message().endpoint(echo)
)
;
Dispatcher::builder(bot, handler) Dispatcher::builder(bot, handler)
.dependencies(dptree::deps![db]) .dependencies(dptree::deps![db])
@ -94,11 +103,12 @@ async fn user_command_handler(
UserCommands::Start => { UserCommands::Start => {
bot.send_photo(msg.chat.id, InputFile::file_id("AgACAgIAAxkBAANRZ-2EJWUdkgwG4tfJfNwut4bssVkAAunyMRvTJ2FLn4FTtVdyfOoBAAMCAANzAAM2BA")).await?; bot.send_photo(msg.chat.id, InputFile::file_id("AgACAgIAAxkBAANRZ-2EJWUdkgwG4tfJfNwut4bssVkAAunyMRvTJ2FLn4FTtVdyfOoBAAMCAANzAAM2BA")).await?;
Ok(()) Ok(())
}, }
UserCommands::Help => { UserCommands::Help => {
bot.send_message(msg.chat.id, UserCommands::descriptions().to_string()).await?; bot.send_message(msg.chat.id, UserCommands::descriptions().to_string())
.await?;
Ok(()) Ok(())
}, }
_ => { _ => {
bot.send_message(msg.chat.id, "Not yet implemented").await?; bot.send_message(msg.chat.id, "Not yet implemented").await?;
Ok(()) Ok(())
@ -106,13 +116,12 @@ async fn user_command_handler(
} }
} }
async fn echo( async fn echo(bot: Bot, msg: Message) -> Result<(), teloxide::RequestError> {
bot: Bot,
msg: Message,
) -> Result<(), teloxide::RequestError> {
if let Some(photo) = msg.photo() { if let Some(photo) = msg.photo() {
println!("File ID: {}", photo[0].file.id); println!("File ID: {}", photo[0].file.id);
} }
bot.send_message(msg.chat.id, msg.html_text().unwrap_or("UNWRAP".into())).parse_mode(teloxide::types::ParseMode::Html).await?; bot.send_message(msg.chat.id, msg.html_text().unwrap_or("UNWRAP".into()))
.parse_mode(teloxide::types::ParseMode::Html)
.await?;
Ok(()) Ok(())
} }