deep_linking/
deep_linking.rs1use dptree::{case, deps};
14use teloxide::{
15 dispatching::dialogue::{self, InMemStorage},
16 macros::BotCommands,
17 prelude::*,
18 types::{BotFullInfo, ParseMode},
19};
20
21pub type MyDialogue = Dialogue<State, InMemStorage<State>>;
22pub type HandlerResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
23
24#[derive(Clone, PartialEq, Debug, Default)]
25pub enum State {
26 #[default]
27 Start,
28 WriteToSomeone {
29 id: ChatId,
30 },
31}
32
33#[derive(BotCommands, Clone, Debug)]
34#[command(rename_rule = "lowercase")]
35pub enum StartCommand {
36 Start(String),
37}
38
39#[tokio::main]
40async fn main() {
41 pretty_env_logger::init();
42 log::info!("Starting deep linking bot...");
43
44 let bot = Bot::from_env();
45
46 let handler = dialogue::enter::<Update, InMemStorage<State>, State, _>()
47 .branch(
48 Update::filter_message()
49 .filter_command::<StartCommand>()
50 .branch(case![StartCommand::Start(start)].endpoint(start)),
51 )
52 .branch(
53 Update::filter_message()
54 .branch(case![State::WriteToSomeone { id }].endpoint(send_message)),
55 );
56
57 Dispatcher::builder(bot, handler)
58 .dependencies(deps![InMemStorage::<State>::new()])
59 .enable_ctrlc_handler()
60 .build()
61 .dispatch()
62 .await;
63}
64
65pub async fn start(
66 bot: Bot,
67 dialogue: MyDialogue,
68 msg: Message,
69 start: String, me: BotFullInfo,
71) -> HandlerResult {
72 if start.is_empty() {
73 bot.send_message(format!(
75 "Hello!\n\nThis link allows anyone to message you secretly: {}?start={}",
76 me.tme_url().ok_or("The bot needs a public username for deep links")?,
77 msg.chat.id
78 ))
79 .chat_id(msg.chat.id)
80 .await?;
81 dialogue.exit().await?;
82 } else {
83 match start.parse::<i64>() {
86 Ok(id) => {
87 bot.send_message("Send your message:").chat_id(msg.chat.id).await?;
88 dialogue.update(State::WriteToSomeone { id: ChatId(id) }).await?;
89 }
90 Err(_) => {
91 bot.send_message("Bad link!").chat_id(msg.chat.id).await?;
92 dialogue.exit().await?;
93 }
94 }
95 }
96 Ok(())
97}
98
99pub async fn send_message(
100 bot: Bot,
101 id: ChatId, msg: Message,
103 dialogue: MyDialogue,
104 me: BotFullInfo,
105) -> HandlerResult {
106 match msg.text() {
107 Some(text) => {
108 let sent_result = bot
110 .send_message(format!("You have a new message!\n\n<i>{text}</i>"))
111 .chat_id(id)
112 .parse_mode(ParseMode::Html)
113 .await;
114
115 if sent_result.is_ok() {
117 bot.send_message(format!(
118 "Message sent!\n\nYour link is: {}?start={}",
119 me.tme_url().ok_or("The bot needs a public username for deep links")?,
120 msg.chat.id
121 ))
122 .chat_id(msg.chat.id)
123 .await?;
124 } else {
125 bot.send_message("Error sending message! Maybe user blocked the bot?")
126 .chat_id(msg.chat.id)
127 .await?;
128 }
129 dialogue.exit().await?;
130 }
131 None => {
132 bot.send_message("This bot can send only text.").chat_id(msg.chat.id).await?;
133 }
134 };
135 Ok(())
136}