Skip to main content

echo_bot/
echo-bot.rs

1//! Простой эхо-бот с использованием диспетчера.
2//!
3//! Запуск:
4//! ```bash
5//! export MAXBOT_TOKEN="ваш_токен"
6//! cargo run --example echo-bot
7//! ```
8
9use maxbot::{
10    Attachment, AttachmentData, ContactData, Dispatcher, MaxClient, SendMessageParamsBuilder,
11};
12
13#[tokio::main]
14async fn main() -> Result<(), Box<dyn std::error::Error>> {
15    // Инициализируем клиент из переменной окружения MAXBOT_TOKEN
16    let bot = MaxClient::from_env().expect("MAXBOT_TOKEN not set");
17
18    // Создаём диспетчер
19    let mut dp = Dispatcher::new(bot);
20
21    // Обработчик команды /start
22    dp.on_command("/start", |ctx| async move {
23        ctx.reply_markdown("Привет! Я эхо-бот.\nОтправь мне любое сообщение, и я отвечу тем же.").await?;
24        Ok(())
25    });
26
27    // Обработчик любого сообщения (эхо)
28    dp.on_message(|ctx| async move {
29        let chat_id = ctx.chat_id().unwrap();
30
31        // 1. Текст
32        let text = ctx.text().unwrap_or("").to_string();
33
34        // 2. Вложения
35        let mut attachments = Vec::new();
36        if let Some(msg) = ctx.message() {
37            if let Some(body) = &msg.body {
38                // Обработка вложений
39                for att in &body.attachments {
40                    match att {
41                        AttachmentData::Image { payload } => {
42                            if let Some(token) = &payload.token {
43                                attachments.push(Attachment::image_token(token));
44                            }
45                        }
46                        AttachmentData::Video { payload } => {
47                            if let Some(token) = &payload.token {
48                                attachments.push(Attachment::video_token(token));
49                            }
50                        }
51                        AttachmentData::Audio { payload } => {
52                            if let Some(token) = &payload.token {
53                                attachments.push(Attachment::audio_token(token));
54                            }
55                        }
56                        AttachmentData::File { payload } => {
57                            if let Some(token) = &payload.token {
58                                attachments.push(Attachment::file_token(token));
59                            }
60                        }
61                        AttachmentData::Sticker { payload } => {
62                            attachments.push(Attachment::sticker(&payload.code));
63                        }
64                        AttachmentData::InlineKeyboard { .. } => {
65                            unimplemented!("Ignore keyboard");
66                        }
67                        AttachmentData::Location { payload } => {
68                            attachments.push(Attachment::location(payload.latitude, payload.longitude));
69                        }
70                        AttachmentData::Contact { payload } => {
71                            let contact_data = ContactData {
72                                name: payload.name.clone(),
73                                contact_id: payload.contact_id,
74                                vcf_info: payload.vcf_info.clone(),
75                                vcf_phone: payload.vcf_phone.clone(),
76                            };
77                            attachments.push(Attachment::contact(contact_data));
78                        }
79                        _ => {}
80                    }
81                }
82            }
83        }
84
85        let params = SendMessageParamsBuilder::new()
86            .text(&text)
87            .chat_id(chat_id)
88            .attachments(attachments)
89            .build();
90        ctx.bot().send_message(params).await?;
91        Ok(())
92    });
93
94    println!("Бот запущен. Нажмите Ctrl+C для остановки.");
95    dp.start_polling().await;
96
97    Ok(())
98}