1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2025-02-16 10:23:57 +00:00

Parse commands properly

This commit is contained in:
Steffo 2024-07-08 04:15:53 +02:00
parent b6d026cbd8
commit a8534c8d27
Signed by: steffo
GPG key ID: 5ADA3868646C3FC0
5 changed files with 63 additions and 35 deletions

21
Cargo.lock generated
View file

@ -300,7 +300,7 @@ checksum = "0892a17df262a24294c382f0d5997571006e7a4348b4327557c4ff1cd4a8bccc"
dependencies = [ dependencies = [
"darling 0.20.9", "darling 0.20.9",
"either", "either",
"heck", "heck 0.5.0",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.68", "syn 2.0.68",
@ -527,6 +527,12 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.5.0" version = "0.5.0"
@ -1385,6 +1391,7 @@ dependencies = [
"serde_json", "serde_json",
"serde_with_macros", "serde_with_macros",
"teloxide-core", "teloxide-core",
"teloxide-macros",
"thiserror", "thiserror",
"tokio", "tokio",
"tokio-stream", "tokio-stream",
@ -1423,6 +1430,18 @@ dependencies = [
"uuid", "uuid",
] ]
[[package]]
name = "teloxide-macros"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f1d653b093dba5e44cada57a516f572167df37b8a619443e59c8c517bb6d804"
dependencies = [
"heck 0.4.1",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]] [[package]]
name = "tempfile" name = "tempfile"
version = "3.10.1" version = "3.10.1"

View file

@ -11,5 +11,5 @@ log = "0.4.22"
micronfig = "0.3.0" micronfig = "0.3.0"
pretty_env_logger = "0.5.0" pretty_env_logger = "0.5.0"
rand = { version = "0.8.5", features = ["small_rng"] } rand = { version = "0.8.5", features = ["small_rng"] }
teloxide = { version = "0.12.2", features = ["ctrlc_handler", "native-tls"], default-features = false } teloxide = { version = "0.12.2", features = ["ctrlc_handler", "native-tls", "macros"], default-features = false }
tokio = { version = "1.38.0", features = ["macros", "rt-multi-thread"] } tokio = { version = "1.38.0", features = ["macros", "rt-multi-thread"] }

View file

@ -6,7 +6,7 @@ use rand::seq::SliceRandom;
use teloxide::Bot; use teloxide::Bot;
use teloxide::payloads::SendMessageSetters; use teloxide::payloads::SendMessageSetters;
use teloxide::prelude::{Message, Requester}; use teloxide::prelude::{Message, Requester};
use crate::telegram::commands::{CommandDialogue, CommandResult}; use crate::telegram::commands::{CommandResult};
// Tutte le fortune devono essere positive, o almeno neutrali, per poter essere aggiunte. // Tutte le fortune devono essere positive, o almeno neutrali, per poter essere aggiunte.
const FORTUNES: [&str; 160] = [ const FORTUNES: [&str; 160] = [
@ -187,7 +187,7 @@ impl Hash for FortuneKey {
} }
} }
pub(super) async fn handler(bot: Bot, _dialogue: CommandDialogue, message: Message) -> CommandResult { pub async fn handler(bot: Bot, message: Message) -> CommandResult {
let today = chrono::Local::now().date_naive(); let today = chrono::Local::now().date_naive();
let author = message.from() let author = message.from()

View file

@ -1,53 +1,62 @@
use anyhow::Error; // See the following link for an example of how to use this file:
// https://github.com/teloxide/teloxide/blob/master/crates/teloxide/examples/dispatching_features.rs
use std::sync::Arc;
use anyhow::{Context, Error};
use teloxide::{Bot, dptree}; use teloxide::{Bot, dptree};
use teloxide::dispatching::{DefaultKey, Dispatcher, HandlerExt, UpdateFilterExt}; use teloxide::dispatching::{DefaultKey, Dispatcher, HandlerExt, UpdateFilterExt};
use teloxide::dispatching::dialogue::{InMemStorage, TraceStorage}; use teloxide::dptree::entry;
use teloxide::payloads::SendMessageSetters;
use teloxide::requests::Requester;
use teloxide::types::{Message, Update}; use teloxide::types::{Message, Update};
use teloxide::utils::command::BotCommands;
mod start; mod start;
mod fortune; mod fortune;
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, BotCommands)]
enum State { #[command(rename_rule = "lowercase")]
#[default] enum Command {
Default, Start,
Fortune,
} }
type CommandDialogue = teloxide::dispatching::dialogue::Dialogue<State, TraceStorage<InMemStorage<State>>>; async fn handle_command(bot: Bot, command: Command, message: Message) -> CommandResult {
type CommandResult = anyhow::Result<()>; log::trace!("Received command: {command:?}");
async fn detect_command(bot: Bot, dialogue: CommandDialogue, message: Message) -> CommandResult { match command {
let text = message.text(); Command::Start => start::handler(bot, message).await,
if text.is_none() { Command::Fortune => fortune::handler(bot, message).await,
// Ignore non-textual messages
return Ok(())
}
let text = text.unwrap();
match text {
"/start" => start::handler(bot, dialogue, message).await,
"/fortune" => fortune::handler(bot, dialogue, message).await,
_ => anyhow::bail!("Unknown command"),
} }
} }
pub(super) fn dispatcher(bot: Bot) -> Dispatcher<Bot, Error, DefaultKey> { async fn unknown_command(bot: Bot, message: Message) -> CommandResult {
log::trace!("Received an unknown command.");
bot.send_message(message.chat.id, "⚠️ Comando sconosciuto.")
.reply_to_message_id(message.id)
.await
.context("Failed to send message")?;
Ok(())
}
pub fn dispatcher(bot: Bot) -> Dispatcher<Bot, Error, DefaultKey> {
Dispatcher::builder( Dispatcher::builder(
bot, bot,
Update::filter_message() Update::filter_message()
.enter_dialogue::<Message, TraceStorage<InMemStorage<State>>, State>()
.branch( .branch(
dptree::case![State::Default] entry()
.endpoint(detect_command) .filter_command::<Command>()
.endpoint(handle_command)
) )
.endpoint(unknown_command)
) )
.dependencies( .dependencies(
dptree::deps![ dptree::deps![] // No deps needed at the moment.
TraceStorage::new(
InMemStorage::<State>::new()
)
]
) )
.enable_ctrlc_handler() .enable_ctrlc_handler()
.build() .build()
} }
type CommandResult = anyhow::Result<()>;

View file

@ -3,9 +3,9 @@ use teloxide::Bot;
use teloxide::payloads::SendMessageSetters; use teloxide::payloads::SendMessageSetters;
use teloxide::requests::Requester; use teloxide::requests::Requester;
use teloxide::types::{Message}; use teloxide::types::{Message};
use super::{CommandDialogue, CommandResult}; use super::{CommandResult};
pub(super) async fn handler(bot: Bot, _dialogue: CommandDialogue, message: Message) -> CommandResult { pub async fn handler(bot: Bot, message: Message) -> CommandResult {
let author = message.from() let author = message.from()
.context("Failed to get the user who sent the original message")?; .context("Failed to get the user who sent the original message")?;