Harmonise naming convention across the examples

This commit is contained in:
Hirrolot 2022-02-02 15:40:22 +06:00
parent c7bbfcccfa
commit 62934f29bd
8 changed files with 83 additions and 85 deletions

View file

@ -66,14 +66,14 @@ fn calc_restrict_time(time: u64, unit: UnitOfTime) -> Duration {
type MyBot = AutoSend<Bot>; type MyBot = AutoSend<Bot>;
// Kick a user with a replied message. // Kick a user with a replied message.
async fn kick_user(bot: MyBot, mes: Message) -> Result<(), Box<dyn Error + Send + Sync>> { async fn kick_user(bot: MyBot, msg: Message) -> Result<(), Box<dyn Error + Send + Sync>> {
match mes.reply_to_message() { match msg.reply_to_message() {
Some(replied) => { Some(replied) => {
// bot.unban_chat_member can also kicks a user from a group chat. // bot.unban_chat_member can also kicks a user from a group chat.
bot.unban_chat_member(mes.chat_id(), replied.from().unwrap().id).await?; bot.unban_chat_member(msg.chat_id(), replied.from().unwrap().id).await?;
} }
None => { None => {
bot.send_message(mes.chat_id(), "Use this command in reply to another message").await?; bot.send_message(msg.chat_id(), "Use this command in reply to another message").await?;
} }
} }
Ok(()) Ok(())
@ -82,24 +82,24 @@ async fn kick_user(bot: MyBot, mes: Message) -> Result<(), Box<dyn Error + Send
// Mute a user with a replied message. // Mute a user with a replied message.
async fn mute_user( async fn mute_user(
bot: MyBot, bot: MyBot,
mes: Message, msg: Message,
time: Duration, time: Duration,
) -> Result<(), Box<dyn Error + Send + Sync>> { ) -> Result<(), Box<dyn Error + Send + Sync>> {
match mes.reply_to_message() { match msg.reply_to_message() {
Some(replied) => { Some(replied) => {
bot.restrict_chat_member( bot.restrict_chat_member(
mes.chat_id(), msg.chat_id(),
replied.from().expect("Must be MessageKind::Common").id, replied.from().expect("Must be MessageKind::Common").id,
ChatPermissions::default(), ChatPermissions::default(),
) )
.until_date( .until_date(
DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(mes.date as i64, 0), Utc) DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(msg.date as i64, 0), Utc)
+ time, + time,
) )
.await?; .await?;
} }
None => { None => {
bot.send_message(mes.chat_id(), "Use this command in a reply to another message!") bot.send_message(msg.chat_id(), "Use this command in a reply to another message!")
.await?; .await?;
} }
} }
@ -109,23 +109,23 @@ async fn mute_user(
// Ban a user with replied message. // Ban a user with replied message.
async fn ban_user( async fn ban_user(
bot: MyBot, bot: MyBot,
mes: Message, msg: Message,
time: Duration, time: Duration,
) -> Result<(), Box<dyn Error + Send + Sync>> { ) -> Result<(), Box<dyn Error + Send + Sync>> {
match mes.reply_to_message() { match msg.reply_to_message() {
Some(replied) => { Some(replied) => {
bot.kick_chat_member( bot.kick_chat_member(
mes.chat_id(), msg.chat_id(),
replied.from().expect("Must be MessageKind::Common").id, replied.from().expect("Must be MessageKind::Common").id,
) )
.until_date( .until_date(
DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(mes.date as i64, 0), Utc) DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(msg.date as i64, 0), Utc)
+ time, + time,
) )
.await?; .await?;
} }
None => { None => {
bot.send_message(mes.chat_id(), "Use this command in a reply to another message!") bot.send_message(msg.chat_id(), "Use this command in a reply to another message!")
.await?; .await?;
} }
} }
@ -134,16 +134,16 @@ async fn ban_user(
async fn action( async fn action(
bot: MyBot, bot: MyBot,
mes: Message, msg: Message,
command: Command, command: Command,
) -> Result<(), Box<dyn Error + Send + Sync>> { ) -> Result<(), Box<dyn Error + Send + Sync>> {
match command { match command {
Command::Help => { Command::Help => {
bot.send_message(mes.chat_id(), Command::descriptions()).await?; bot.send_message(msg.chat_id(), Command::descriptions()).await?;
} }
Command::Kick => kick_user(bot, mes).await?, Command::Kick => kick_user(bot, msg).await?,
Command::Ban { time, unit } => ban_user(bot, mes, calc_restrict_time(time, unit)).await?, Command::Ban { time, unit } => ban_user(bot, msg, calc_restrict_time(time, unit)).await?,
Command::Mute { time, unit } => mute_user(bot, mes, calc_restrict_time(time, unit)).await?, Command::Mute { time, unit } => mute_user(bot, msg, calc_restrict_time(time, unit)).await?,
}; };
Ok(()) Ok(())

View file

@ -19,7 +19,7 @@ use teloxide::{
prelude2::*, prelude2::*,
}; };
type BotDialogue = Dialogue<State, SqliteStorage<Json>>; type MyDialogue = Dialogue<State, SqliteStorage<Json>>;
#[derive(DialogueState, Clone, serde::Serialize, serde::Deserialize)] #[derive(DialogueState, Clone, serde::Serialize, serde::Deserialize)]
#[handler_out(anyhow::Result<()>)] #[handler_out(anyhow::Result<()>)]
@ -71,37 +71,37 @@ async fn main() {
async fn handle_start( async fn handle_start(
bot: AutoSend<Bot>, bot: AutoSend<Bot>,
mes: Message, msg: Message,
dialogue: BotDialogue, dialogue: MyDialogue,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
bot.send_message(mes.chat_id(), "Let's start! What's your full name?").await?; bot.send_message(msg.chat_id(), "Let's start! What's your full name?").await?;
dialogue.update(State::ReceiveFullName).await?; dialogue.update(State::ReceiveFullName).await?;
Ok(()) Ok(())
} }
async fn handle_receive_full_name( async fn handle_receive_full_name(
bot: AutoSend<Bot>, bot: AutoSend<Bot>,
mes: Message, msg: Message,
dialogue: BotDialogue, dialogue: MyDialogue,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
bot.send_message(mes.chat_id(), "How old are you?").await?; bot.send_message(msg.chat_id(), "How old are you?").await?;
dialogue.update(State::ReceiveAge(mes.text().unwrap().into())).await?; dialogue.update(State::ReceiveAge(msg.text().unwrap().into())).await?;
Ok(()) Ok(())
} }
async fn handle_receive_age( async fn handle_receive_age(
bot: AutoSend<Bot>, bot: AutoSend<Bot>,
mes: Message, msg: Message,
dialogue: BotDialogue, dialogue: MyDialogue,
full_name: String, full_name: String,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
match mes.text().unwrap().parse::<u8>() { match msg.text().unwrap().parse::<u8>() {
Ok(age) => { Ok(age) => {
bot.send_message(mes.chat_id(), "What's your location?").await?; bot.send_message(msg.chat_id(), "What's your location?").await?;
dialogue.update(State::ReceiveLocation(ReceiveLocation { full_name, age })).await?; dialogue.update(State::ReceiveLocation(ReceiveLocation { full_name, age })).await?;
} }
_ => { _ => {
bot.send_message(mes.chat_id(), "Send me a number.").await?; bot.send_message(msg.chat_id(), "Send me a number.").await?;
} }
} }
Ok(()) Ok(())
@ -109,14 +109,14 @@ async fn handle_receive_age(
async fn handle_receive_location( async fn handle_receive_location(
bot: AutoSend<Bot>, bot: AutoSend<Bot>,
mes: Message, msg: Message,
dialogue: BotDialogue, dialogue: MyDialogue,
state: ReceiveLocation, state: ReceiveLocation,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let location = mes.text().unwrap(); let location = msg.text().unwrap();
let message = let message =
format!("Full name: {}\nAge: {}\nLocation: {}", state.full_name, state.age, location); format!("Full name: {}\nAge: {}\nLocation: {}", state.full_name, state.age, location);
bot.send_message(mes.chat_id(), message).await?; bot.send_message(msg.chat_id(), message).await?;
dialogue.exit().await?; dialogue.exit().await?;
Ok(()) Ok(())
} }

View file

@ -25,12 +25,12 @@ async fn main() {
// Filter allow you to filter updates by some condition. // Filter allow you to filter updates by some condition.
dptree::filter( dptree::filter(
// Note that `async move` is obligatory. // Note that `async move` is obligatory.
|mes: Message| async move { mes.chat.is_group() || mes.chat.is_supergroup() }, |msg: Message| async move { msg.chat.is_group() || msg.chat.is_supergroup() },
) )
// Endpoint is a last message handler. // Endpoint is a last message handler.
.endpoint(|mes: Message, bot: AutoSend<Bot>| async move { .endpoint(|msg: Message, bot: AutoSend<Bot>| async move {
log::info!("Received message from the group chat."); log::info!("Received message from the group chat.");
bot.send_message(mes.chat.id, "This is a group chat.").await?; bot.send_message(msg.chat.id, "This is a group chat.").await?;
respond(()) respond(())
}), }),
) )
@ -39,9 +39,9 @@ async fn main() {
.branch( .branch(
// There are some `filter` functions on message, that filters events. This // There are some `filter` functions on message, that filters events. This
// filter will filter only messages with dices. // filter will filter only messages with dices.
Message::filter_dice().endpoint(|mes: Message, bot: AutoSend<Bot>| async move { Message::filter_dice().endpoint(|msg: Message, bot: AutoSend<Bot>| async move {
bot.send_message(mes.chat.id, "This is a dice!") bot.send_message(msg.chat.id, "This is a dice!")
.reply_to_message_id(mes.id) .reply_to_message_id(msg.id)
.await?; .await?;
Ok(()) Ok(())
}), }),
@ -60,19 +60,19 @@ async fn main() {
) )
.branch( .branch(
// Filter maintainer by used ID. // Filter maintainer by used ID.
dptree::filter(|mes: Message, cfg: ConfigParameters| async move { dptree::filter(|msg: Message, cfg: ConfigParameters| async move {
mes.from().map(|user| user.id == cfg.bot_maintainer).unwrap_or_default() msg.from().map(|user| user.id == cfg.bot_maintainer).unwrap_or_default()
}) })
.add_command::<MaintainerCommands>() .add_command::<MaintainerCommands>()
.endpoint( .endpoint(
|mes: Message, bot: AutoSend<Bot>, cmd: MaintainerCommands| async move { |msg: Message, bot: AutoSend<Bot>, cmd: MaintainerCommands| async move {
match cmd { match cmd {
MaintainerCommands::Rand { from, to } => { MaintainerCommands::Rand { from, to } => {
let mut rng = rand::rngs::OsRng::default(); let mut rng = rand::rngs::OsRng::default();
let value: u64 = rng.gen_range(from..=to); let value: u64 = rng.gen_range(from..=to);
std::mem::drop(rng); std::mem::drop(rng);
bot.send_message(mes.chat.id, value.to_string()).await?; bot.send_message(msg.chat.id, value.to_string()).await?;
Ok(()) Ok(())
} }
@ -130,21 +130,21 @@ enum MaintainerCommands {
} }
async fn simple_commands_handler( async fn simple_commands_handler(
mes: Message, msg: Message,
bot: AutoSend<Bot>, bot: AutoSend<Bot>,
cmd: SimpleCommand, cmd: SimpleCommand,
cfg: ConfigParameters, cfg: ConfigParameters,
) -> Result<(), teloxide::RequestError> { ) -> Result<(), teloxide::RequestError> {
let text = match cmd { let text = match cmd {
SimpleCommand::Help => { SimpleCommand::Help => {
if mes.from().unwrap().id == cfg.bot_maintainer { if msg.from().unwrap().id == cfg.bot_maintainer {
format!("{}\n{}", SimpleCommand::descriptions(), MaintainerCommands::descriptions()) format!("{}\n{}", SimpleCommand::descriptions(), MaintainerCommands::descriptions())
} else { } else {
SimpleCommand::descriptions() SimpleCommand::descriptions()
} }
} }
SimpleCommand::Maintainer => { SimpleCommand::Maintainer => {
if mes.from().unwrap().id == cfg.bot_maintainer { if msg.from().unwrap().id == cfg.bot_maintainer {
"Maintainer is you!".into() "Maintainer is you!".into()
} else { } else {
if let Some(username) = cfg.maintainer_username { if let Some(username) = cfg.maintainer_username {
@ -155,10 +155,10 @@ async fn simple_commands_handler(
} }
} }
SimpleCommand::MyId => { SimpleCommand::MyId => {
format!("{}", mes.from().unwrap().id) format!("{}", msg.from().unwrap().id)
} }
}; };
bot.send_message(mes.chat.id, text).await?; bot.send_message(msg.chat.id, text).await?;
Ok(()) Ok(())
} }

View file

@ -26,8 +26,8 @@ async fn main() {
teloxide::repls2::repl_with_listener( teloxide::repls2::repl_with_listener(
bot.clone(), bot.clone(),
|mes: Message, bot: AutoSend<Bot>| async move { |msg: Message, bot: AutoSend<Bot>| async move {
bot.send_message(mes.chat.id, "pong").await?; bot.send_message(msg.chat.id, "pong").await?;
respond(()) respond(())
}, },
webhook(bot).await, webhook(bot).await,

View file

@ -26,8 +26,8 @@ async fn main() {
teloxide::repls2::repl_with_listener( teloxide::repls2::repl_with_listener(
bot.clone(), bot.clone(),
|mes: Message, bot: AutoSend<Bot>| async move { |msg: Message, bot: AutoSend<Bot>| async move {
bot.send_message(mes.chat.id, "pong").await?; bot.send_message(msg.chat.id, "pong").await?;
respond(()) respond(())
}, },
webhook(bot).await, webhook(bot).await,

View file

@ -5,7 +5,7 @@ use teloxide::{
}; };
use thiserror::Error; use thiserror::Error;
type BotDialogue = Dialogue<DialogueState, RedisStorage<Bincode>>; type MyDialogue = Dialogue<DialogueState, RedisStorage<Bincode>>;
type StorageError = <RedisStorage<Bincode> as Storage<DialogueState>>::Error; type StorageError = <RedisStorage<Bincode> as Storage<DialogueState>>::Error;
#[derive(Debug, Error)] #[derive(Debug, Error)]
@ -30,12 +30,12 @@ impl Default for DialogueState {
async fn handle_message( async fn handle_message(
bot: AutoSend<Bot>, bot: AutoSend<Bot>,
mes: Message, msg: Message,
dialogue: BotDialogue, dialogue: MyDialogue,
) -> Result<(), Error> { ) -> Result<(), Error> {
match mes.text() { match msg.text() {
None => { None => {
bot.send_message(mes.chat.id, "Send me a text message.").await?; bot.send_message(msg.chat.id, "Send me a text message.").await?;
} }
Some(ans) => { Some(ans) => {
let state = dialogue.get_or_default().await?; let state = dialogue.get_or_default().await?;
@ -44,23 +44,23 @@ async fn handle_message(
if let Ok(number) = ans.parse() { if let Ok(number) = ans.parse() {
dialogue.update(DialogueState::HaveNumber(number)).await?; dialogue.update(DialogueState::HaveNumber(number)).await?;
bot.send_message( bot.send_message(
mes.chat.id, msg.chat.id,
format!("Remembered number {}. Now use /get or /reset", number), format!("Remembered number {}. Now use /get or /reset", number),
) )
.await?; .await?;
} else { } else {
bot.send_message(mes.chat.id, "Please, send me a number").await?; bot.send_message(msg.chat.id, "Please, send me a number").await?;
} }
} }
DialogueState::HaveNumber(num) => { DialogueState::HaveNumber(num) => {
if ans.starts_with("/get") { if ans.starts_with("/get") {
bot.send_message(mes.chat.id, format!("Here is your number: {}", num)) bot.send_message(msg.chat.id, format!("Here is your number: {}", num))
.await?; .await?;
} else if ans.starts_with("/reset") { } else if ans.starts_with("/reset") {
dialogue.reset().await?; dialogue.reset().await?;
bot.send_message(mes.chat.id, "Resetted number").await?; bot.send_message(msg.chat.id, "Resetted number").await?;
} else { } else {
bot.send_message(mes.chat.id, "Please, send /get or /reset").await?; bot.send_message(msg.chat.id, "Please, send /get or /reset").await?;
} }
} }
} }

View file

@ -17,9 +17,9 @@ async fn main() {
let bot = Bot::from_env().auto_send(); let bot = Bot::from_env().auto_send();
let handler = Update::filter_message().branch(dptree::endpoint( let handler = Update::filter_message().branch(dptree::endpoint(
|mes: Message, bot: AutoSend<Bot>| async move { |msg: Message, bot: AutoSend<Bot>| async move {
let previous = MESSAGES_TOTAL.fetch_add(1, Ordering::Relaxed); let previous = MESSAGES_TOTAL.fetch_add(1, Ordering::Relaxed);
bot.send_message(mes.chat.id, format!("I received {} messages in total.", previous)) bot.send_message(msg.chat.id, format!("I received {} messages in total.", previous))
.await?; .await?;
respond(()) respond(())
}, },

View file

@ -5,10 +5,8 @@ use teloxide::{
}; };
use thiserror::Error; use thiserror::Error;
type Store = SqliteStorage<Json>; type MyDialogue = Dialogue<DialogueState, SqliteStorage<Json>>;
// FIXME: naming type StorageError = <SqliteStorage<Json> as Storage<DialogueState>>::Error;
type MyDialogue = Dialogue<BotDialogue, Store>;
type StorageError = <SqliteStorage<Json> as Storage<BotDialogue>>::Error;
#[derive(Debug, Error)] #[derive(Debug, Error)]
enum Error { enum Error {
@ -19,12 +17,12 @@ enum Error {
} }
#[derive(serde::Serialize, serde::Deserialize)] #[derive(serde::Serialize, serde::Deserialize)]
pub enum BotDialogue { pub enum DialogueState {
Start, Start,
GotNumber(i32), GotNumber(i32),
} }
impl Default for BotDialogue { impl Default for DialogueState {
fn default() -> Self { fn default() -> Self {
Self::Start Self::Start
} }
@ -32,37 +30,37 @@ impl Default for BotDialogue {
async fn handle_message( async fn handle_message(
bot: AutoSend<Bot>, bot: AutoSend<Bot>,
mes: Message, msg: Message,
dialogue: MyDialogue, dialogue: MyDialogue,
) -> Result<(), Error> { ) -> Result<(), Error> {
match mes.text() { match msg.text() {
None => { None => {
bot.send_message(mes.chat.id, "Send me a text message.").await?; bot.send_message(msg.chat.id, "Send me a text message.").await?;
} }
Some(ans) => { Some(ans) => {
let state = dialogue.get_or_default().await?; let state = dialogue.get_or_default().await?;
match state { match state {
BotDialogue::Start => { DialogueState::Start => {
if let Ok(number) = ans.parse() { if let Ok(number) = ans.parse() {
dialogue.update(BotDialogue::GotNumber(number)).await?; dialogue.update(DialogueState::GotNumber(number)).await?;
bot.send_message( bot.send_message(
mes.chat.id, msg.chat.id,
format!("Remembered number {}. Now use /get or /reset", number), format!("Remembered number {}. Now use /get or /reset", number),
) )
.await?; .await?;
} else { } else {
bot.send_message(mes.chat.id, "Please, send me a number").await?; bot.send_message(msg.chat.id, "Please, send me a number").await?;
} }
} }
BotDialogue::GotNumber(num) => { DialogueState::GotNumber(num) => {
if ans.starts_with("/get") { if ans.starts_with("/get") {
bot.send_message(mes.chat.id, format!("Here is your number: {}", num)) bot.send_message(msg.chat.id, format!("Here is your number: {}", num))
.await?; .await?;
} else if ans.starts_with("/reset") { } else if ans.starts_with("/reset") {
dialogue.reset().await?; dialogue.reset().await?;
bot.send_message(mes.chat.id, "Resetted number").await?; bot.send_message(msg.chat.id, "Resetted number").await?;
} else { } else {
bot.send_message(mes.chat.id, "Please, send /get or /reset").await?; bot.send_message(msg.chat.id, "Please, send /get or /reset").await?;
} }
} }
} }
@ -77,7 +75,7 @@ async fn main() {
let storage = SqliteStorage::open("db.sqlite", Json).await.unwrap(); let storage = SqliteStorage::open("db.sqlite", Json).await.unwrap();
let handler = dptree::entry() let handler = dptree::entry()
.add_dialogue::<Message, Store, BotDialogue>() .add_dialogue::<Message, SqliteStorage<Json>, DialogueState>()
.branch(dptree::endpoint(handle_message)); .branch(dptree::endpoint(handle_message));
DispatcherBuilder::new(bot, handler) DispatcherBuilder::new(bot, handler)