Skip to main content

deep_linking/
deep_linking.rs

1//! This example demonstrates how to use deep linking in Telegram
2//! by making a simple anonymous message bot.
3//!
4//! Deep linking (links like https://t.me/some_bot?start=123456789)
5//! is handled by telegram in the same way as just sending /start {argument}.
6//! So, in the StartCommand enum we need to write Start(String)
7//! to get the argument, just like in command.rs example.
8//!
9//! Also, deep linking is only supported with /start command!
10//! "https://t.me/some_bot?argument=123456789" will not work
11//!
12//! https://core.telegram.org/bots/features#deep-linking
13use 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, // Available from `case![StartCommand::Start(start)]`
70    me: BotFullInfo,
71) -> HandlerResult {
72    if start.is_empty() {
73        // This means that it is just a regular link like https://t.me/some_bot, or a /start command
74        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        // And this means that the link is like this: https://t.me/some_bot?start=123456789,
84        // or a /start 123456789 command
85        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, // Available from `State::WriteToSomeone`
102    msg: Message,
103    dialogue: MyDialogue,
104    me: BotFullInfo,
105) -> HandlerResult {
106    match msg.text() {
107        Some(text) => {
108            // Trying to send a message to the user
109            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            // And if no error is returned, success!
116            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}