Skip to main content

InlineKeyboardButton

Struct InlineKeyboardButton 

Source
pub struct InlineKeyboardButton {
    pub type: String,
    pub text: String,
    pub payload: Option<String>,
    pub url: Option<String>,
    pub quick: Option<bool>,
    pub web_app: Option<String>,
    pub contact_id: Option<i64>,
    pub app_payload: Option<String>,
    pub message_text: Option<String>,
}
Expand description

Кнопка inline‑клавиатуры.

Может быть различных типов, определяемых полем type. Подробнее о типах кнопок смотрите в документации API MAX.

Fields§

§type: String

Тип кнопки: "callback", "link", "request_geo_location", "open_app", "message", "clipboard".

§text: String

Текст, отображаемый на кнопке.

§payload: Option<String>

Полезная нагрузка для callback‑кнопок.

§url: Option<String>

URL для кнопок‑ссылок.

§quick: Option<bool>

Флаг быстрой кнопки (обычно true для запросов контакта или геолокации).

§web_app: Option<String>

URL веб‑приложения для кнопок типа "open_app".

§contact_id: Option<i64>

Идентификатор контакта для кнопок "open_app".

§app_payload: Option<String>

Полезная нагрузка для кнопок "open_app".

§message_text: Option<String>

Текст сообщения, которое будет отправлено при нажатии на кнопку типа "message".

Implementations§

Source§

impl InlineKeyboardButton

Source

pub fn callback(text: impl Into<String>, payload: impl Into<String>) -> Self

Создаёт кнопку типа "callback".

При нажатии бот получит callback_query с указанным payload.

Examples found in repository?
examples/fruits-bot.rs (line 30)
29fn btn_stand() -> InlineKeyboardButton {
30    InlineKeyboardButton::callback("Встать", "stand")
31}
32
33/// Кнопки выбора фруктов (🍏 🍐 🍊 🍅).
34fn fruit_buttons() -> Result<InlineKeyboard, maxbot::KeyboardValidationError> {
35    make_keyboard(vec![
36        InlineKeyboardButton::callback("🍏", "fruit:apple"),
37        InlineKeyboardButton::callback("🍐", "fruit:pear"),
38        InlineKeyboardButton::callback("🍊", "fruit:orange"),
39        InlineKeyboardButton::callback("🍅", "fruit:tomato"),
40    ])
41}
42
43/// Кнопка «Начать заново» (для томата).
44fn btn_restart() -> Result<InlineKeyboard, maxbot::KeyboardValidationError> {
45    make_keyboard(vec![InlineKeyboardButton::callback("Начать заново", "stand")])
46}
More examples
Hide additional examples
examples/simple-methods-demo.rs (line 29)
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let client = MaxClient::from_env().expect("MAXBOT_TOKEN not set");
8    let chat_id = std::env::var("CHAT_ID")
9        .expect("CHAT_ID not set")
10        .parse::<i64>()?;
11
12    client.send_plain_text_to_chat(chat_id, "Hello from simple method!").await?;
13    client.send_markdown_to_chat(chat_id, "**Bold** text").await?;
14    client.send_html_to_chat(chat_id, "<b>Bold</b> text").await?;
15    client.send_sticker_to_chat(chat_id, "154ed15bb").await?;
16    client.send_location_to_chat(chat_id, 55.7558, 37.6176).await?;
17
18    let contact = ContactData {
19        name: Some("Max Bot".to_string()),
20        contact_id: Some(client.get_me().await?.user.user_id),
21        vcf_info: None,
22        vcf_phone: None,
23    };
24    client.send_contact_to_chat(chat_id, contact).await?;
25
26    client.send_share_to_chat(chat_id, "https://dev.max.ru", Some("API MAX")).await?;
27
28    let keyboard = InlineKeyboardBuilder::new()
29        .button(InlineKeyboardButton::callback("Нажми", "data"))
30        .build()?;
31    client.send_keyboard_to_chat(chat_id, "Кнопка:", keyboard).await?;
32
33    Ok(())
34}
examples/combined-attachments-demo.rs (line 91)
17async fn main() -> Result<(), Box<dyn std::error::Error>> {
18    let token = std::env::var("MAXBOT_TOKEN").expect("Missing MAXBOT_TOKEN");
19    let chat_id = std::env::var("CHAT_ID")
20        .expect("Missing CHAT_ID")
21        .parse::<i64>()?;
22    if let Ok(proxy_url) = std::env::var("MAXBOT_PROXY") {
23        maxbot::set_global_base_url(proxy_url);
24    }
25
26    let client = MaxClient::new(token);
27
28    // 1. Стикер (отдельное сообщение без текста)
29    println!("Отправляем стикер...");
30    let builder = SendMessageParamsBuilder::new()
31        .chat_id(chat_id)
32        .attachment(Attachment::sticker("154ed15bb")); // реальный код стикера
33    match client.send_message_builder(builder).await {
34        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
35        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
36    }
37
38    // 2. Контакт (требуется contact_id)
39    println!("Отправляем контакт...");
40    // Здесь нужно указать реальный user_id пользователя MAX
41    // Можно взять из участников чата или использовать свой собственный ID бота
42    let me = client.get_me().await?;
43    let contact = ContactData {
44        name: Some("Мой бот".to_string()),
45        contact_id: Some(me.user.user_id),
46        vcf_info: None,
47        vcf_phone: None,
48    };
49    let builder = SendMessageParamsBuilder::new()
50        .text("Контакт:")
51        .chat_id(chat_id)
52        .attachment(Attachment::contact(contact));
53    match client.send_message_builder(builder).await {
54        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
55        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
56    }
57
58    // 3. Геолокация
59    println!("Отправляем геолокацию...");
60    let builder = SendMessageParamsBuilder::new()
61        .text("Геолокация:")
62        .chat_id(chat_id)
63        .attachment(Attachment::location(55.7558, 37.6176)); // Москва
64    match client.send_message_builder(builder).await {
65        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
66        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
67    }
68
69    // 4. Share (ссылка)
70    println!("Отправляем share (ссылку)...");
71    let share = ShareData {
72        url: Some("https://dev.max.ru".to_string()),
73        token: None,
74    };
75    let builder = SendMessageParamsBuilder::new()
76        .text("Полезная ссылка:")
77        .chat_id(chat_id)
78        .attachment(Attachment::share(share));
79    match client.send_message_builder(builder).await {
80        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
81        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
82    }
83
84    // 5. Inline-клавиатура
85    println!("Отправляем inline-клавиатуру...");
86    let keyboard = InlineKeyboardBuilder::new()
87        // Первая строка с кнопками
88        .button(InlineKeyboardButton::link("Последние новости…", "https://www.e1.ru"))
89        // Новая строка с кнопками
90        .row(vec![InlineKeyboardButton::clipboard("Скопировать код", "SECRET_2026")])
91        .button(InlineKeyboardButton::callback("Кнопка", "demo_payload"))
92        // Результат
93        .build()?;
94    let builder = SendMessageParamsBuilder::new()
95        .text("Клавиатура:")
96        .chat_id(chat_id)
97        .attachment(Attachment::inline_keyboard(keyboard));
98    match client.send_message_builder(builder).await {
99        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
100        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
101    }
102
103    // 6. Inline-клавиатура с автоматическим заполнением кнопок по строкам
104    println!("Отправляем inline-клавиатуру в 3 строки…");
105    let keyboard = InlineKeyboardBuilder::new()
106        .push_button(InlineKeyboardButton::callback("1", "1"))
107        .push_button(InlineKeyboardButton::callback("2", "2"))
108        .push_button(InlineKeyboardButton::callback("3", "3"))
109        .push_button(InlineKeyboardButton::callback("4", "4"))
110        .push_button(InlineKeyboardButton::callback("5", "5"))
111        .push_button(InlineKeyboardButton::callback("6", "6"))
112        .push_button(InlineKeyboardButton::callback("7", "7"))
113        .push_button(InlineKeyboardButton::callback("8", "8"))
114        .push_button(InlineKeyboardButton::callback("9", "9"))
115        .push_button(InlineKeyboardButton::callback("10", "10"))
116        .push_button(InlineKeyboardButton::callback("11", "11"))
117        .push_button(InlineKeyboardButton::callback("12", "12"))
118        .push_button(InlineKeyboardButton::callback("13", "13"))
119        .push_button(InlineKeyboardButton::callback("14", "14"))
120        .push_button(InlineKeyboardButton::callback("15", "15"))
121        .build()?;
122    let builder = SendMessageParamsBuilder::new()
123        .text("Автозаполняемая клавиатура 1:")
124        .chat_id(chat_id)
125        .attachment(Attachment::inline_keyboard(keyboard));
126    match client.send_message_builder(builder).await {
127        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
128        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
129    }
130
131    // 7. Inline-клавиатура с автоматическим заполнением кнопок по строкам
132    println!("Отправляем inline-клавиатуру в 2 строки…");
133    let keyboard = InlineKeyboardBuilder::new()
134        .push_button(InlineKeyboardButton::callback("A", "a"))
135        .push_button(InlineKeyboardButton::callback("B", "b"))
136        .push_button(InlineKeyboardButton::callback("C", "c"))
137        .push_button(InlineKeyboardButton::callback("D", "d"))         // Уже 4 кнопки, строка заполнена (макс 7)
138        .push_button(InlineKeyboardButton::link("Я", "https://ya.ru")) // Новая строка (спец-кнопка)
139        .push_button(InlineKeyboardButton::callback("E", "e"))         // Идёт в строку со спец-кнопкой
140        .build()?;
141    let builder = SendMessageParamsBuilder::new()
142        .text("Автозаполняемая клавиатура 2:")
143        .chat_id(chat_id)
144        .attachment(Attachment::inline_keyboard(keyboard));
145    match client.send_message_builder(builder).await {
146        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
147        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
148    }
149
150    Ok(())
151}

Создаёт кнопку‑ссылку типа "link".

Examples found in repository?
examples/combined-attachments-demo.rs (line 88)
17async fn main() -> Result<(), Box<dyn std::error::Error>> {
18    let token = std::env::var("MAXBOT_TOKEN").expect("Missing MAXBOT_TOKEN");
19    let chat_id = std::env::var("CHAT_ID")
20        .expect("Missing CHAT_ID")
21        .parse::<i64>()?;
22    if let Ok(proxy_url) = std::env::var("MAXBOT_PROXY") {
23        maxbot::set_global_base_url(proxy_url);
24    }
25
26    let client = MaxClient::new(token);
27
28    // 1. Стикер (отдельное сообщение без текста)
29    println!("Отправляем стикер...");
30    let builder = SendMessageParamsBuilder::new()
31        .chat_id(chat_id)
32        .attachment(Attachment::sticker("154ed15bb")); // реальный код стикера
33    match client.send_message_builder(builder).await {
34        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
35        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
36    }
37
38    // 2. Контакт (требуется contact_id)
39    println!("Отправляем контакт...");
40    // Здесь нужно указать реальный user_id пользователя MAX
41    // Можно взять из участников чата или использовать свой собственный ID бота
42    let me = client.get_me().await?;
43    let contact = ContactData {
44        name: Some("Мой бот".to_string()),
45        contact_id: Some(me.user.user_id),
46        vcf_info: None,
47        vcf_phone: None,
48    };
49    let builder = SendMessageParamsBuilder::new()
50        .text("Контакт:")
51        .chat_id(chat_id)
52        .attachment(Attachment::contact(contact));
53    match client.send_message_builder(builder).await {
54        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
55        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
56    }
57
58    // 3. Геолокация
59    println!("Отправляем геолокацию...");
60    let builder = SendMessageParamsBuilder::new()
61        .text("Геолокация:")
62        .chat_id(chat_id)
63        .attachment(Attachment::location(55.7558, 37.6176)); // Москва
64    match client.send_message_builder(builder).await {
65        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
66        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
67    }
68
69    // 4. Share (ссылка)
70    println!("Отправляем share (ссылку)...");
71    let share = ShareData {
72        url: Some("https://dev.max.ru".to_string()),
73        token: None,
74    };
75    let builder = SendMessageParamsBuilder::new()
76        .text("Полезная ссылка:")
77        .chat_id(chat_id)
78        .attachment(Attachment::share(share));
79    match client.send_message_builder(builder).await {
80        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
81        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
82    }
83
84    // 5. Inline-клавиатура
85    println!("Отправляем inline-клавиатуру...");
86    let keyboard = InlineKeyboardBuilder::new()
87        // Первая строка с кнопками
88        .button(InlineKeyboardButton::link("Последние новости…", "https://www.e1.ru"))
89        // Новая строка с кнопками
90        .row(vec![InlineKeyboardButton::clipboard("Скопировать код", "SECRET_2026")])
91        .button(InlineKeyboardButton::callback("Кнопка", "demo_payload"))
92        // Результат
93        .build()?;
94    let builder = SendMessageParamsBuilder::new()
95        .text("Клавиатура:")
96        .chat_id(chat_id)
97        .attachment(Attachment::inline_keyboard(keyboard));
98    match client.send_message_builder(builder).await {
99        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
100        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
101    }
102
103    // 6. Inline-клавиатура с автоматическим заполнением кнопок по строкам
104    println!("Отправляем inline-клавиатуру в 3 строки…");
105    let keyboard = InlineKeyboardBuilder::new()
106        .push_button(InlineKeyboardButton::callback("1", "1"))
107        .push_button(InlineKeyboardButton::callback("2", "2"))
108        .push_button(InlineKeyboardButton::callback("3", "3"))
109        .push_button(InlineKeyboardButton::callback("4", "4"))
110        .push_button(InlineKeyboardButton::callback("5", "5"))
111        .push_button(InlineKeyboardButton::callback("6", "6"))
112        .push_button(InlineKeyboardButton::callback("7", "7"))
113        .push_button(InlineKeyboardButton::callback("8", "8"))
114        .push_button(InlineKeyboardButton::callback("9", "9"))
115        .push_button(InlineKeyboardButton::callback("10", "10"))
116        .push_button(InlineKeyboardButton::callback("11", "11"))
117        .push_button(InlineKeyboardButton::callback("12", "12"))
118        .push_button(InlineKeyboardButton::callback("13", "13"))
119        .push_button(InlineKeyboardButton::callback("14", "14"))
120        .push_button(InlineKeyboardButton::callback("15", "15"))
121        .build()?;
122    let builder = SendMessageParamsBuilder::new()
123        .text("Автозаполняемая клавиатура 1:")
124        .chat_id(chat_id)
125        .attachment(Attachment::inline_keyboard(keyboard));
126    match client.send_message_builder(builder).await {
127        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
128        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
129    }
130
131    // 7. Inline-клавиатура с автоматическим заполнением кнопок по строкам
132    println!("Отправляем inline-клавиатуру в 2 строки…");
133    let keyboard = InlineKeyboardBuilder::new()
134        .push_button(InlineKeyboardButton::callback("A", "a"))
135        .push_button(InlineKeyboardButton::callback("B", "b"))
136        .push_button(InlineKeyboardButton::callback("C", "c"))
137        .push_button(InlineKeyboardButton::callback("D", "d"))         // Уже 4 кнопки, строка заполнена (макс 7)
138        .push_button(InlineKeyboardButton::link("Я", "https://ya.ru")) // Новая строка (спец-кнопка)
139        .push_button(InlineKeyboardButton::callback("E", "e"))         // Идёт в строку со спец-кнопкой
140        .build()?;
141    let builder = SendMessageParamsBuilder::new()
142        .text("Автозаполняемая клавиатура 2:")
143        .chat_id(chat_id)
144        .attachment(Attachment::inline_keyboard(keyboard));
145    match client.send_message_builder(builder).await {
146        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
147        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
148    }
149
150    Ok(())
151}
Source

pub fn request_contact(text: impl Into<String>) -> Self

Создаёт кнопку запроса контакта у пользователя.

Examples found in repository?
examples/ask-phone-bot.rs (line 33)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let token = env::var("MAXBOT_TOKEN").expect("MAXBOT_TOKEN not set");
11    let real_token = env::var("MAXBOT_REAL_TOKEN").unwrap_or_else(|_| token.clone());
12
13    let mut check_hash = true;
14    let mut client = MaxClient::new(token);
15    if let Ok(proxy_url) = env::var("MAXBOT_PROXY") {
16        client.set_base_url(proxy_url);
17        if real_token.starts_with("Basic ") {
18            check_hash = false;
19        }
20    }
21
22    if !check_hash {
23        println!("Токен бота подменён. Требуется указать MAXBOT_REAL_TOKEN для проверки номера телефона.");
24    }
25
26    let bot = client;
27    let mut dp = Dispatcher::new(bot);
28
29    // Команда /start – отправляем кнопку запроса контакта
30    dp.on_command("/start", |ctx| async move {
31        let chat_id = ctx.chat_id().unwrap();
32        let keyboard = InlineKeyboardBuilder::new()
33            .button(InlineKeyboardButton::request_contact("Передать 🔀"))
34            .build()?;
35        let body = SendMessageParamsBuilder::new()
36            .text("Предоставьте свои данные")
37            .chat_id(chat_id)
38            .attachment(Attachment::inline_keyboard(keyboard))
39            .build();
40        ctx.bot().send_message(body).await?;
41        Ok(())
42    });
43
44    // Подготовка токена проверки для передачи в замыкание
45    let check_bytes = real_token.into_bytes();
46
47    // Обработка входящего контакта
48    dp.on_message(move |ctx| {
49        let token_bytes = check_bytes.clone();
50        async move {
51            let msg = match ctx.message() {
52                Some(m) => m,
53                None => return Ok(()),
54            };
55            let attachments = match &msg.body {
56                Some(b) => &b.attachments,
57                None => return Ok(()),
58            };
59            for att in attachments {
60                if let maxbot::AttachmentData::Contact { payload } = att {
61                    let mut response = String::from("Вы предоставили следующую информацию:\n");
62                    let mut has_phone = false;
63
64                    // Разбор vCard, если есть
65                    if let Some(vcf) = &payload.vcf_info {
66                        match parse_vcard(vcf) {
67                            Ok(card) => {
68                                if let Some(fn_) = card.get_formatted_name() {
69                                    response.push_str(&format!("Имя: {}\n", fn_));
70                                }
71                                for phone in card.get_phone_numbers() {
72                                    response.push_str(&format!("Телефон: {}\n", phone));
73                                    has_phone = !phone.is_empty();
74                                }
75                                for email in card.get_emails() {
76                                    response.push_str(&format!("Email: {}\n", email));
77                                }
78                            }
79                            Err(e) => response.push_str(&format!("Ошибка чтения vCard: {}\n", e)),
80                        }
81                    } else {
82                        if let Some(name) = &payload.name {
83                            response.push_str(&format!("Имя: {}\n", name));
84                        }
85                        if let Some(phone) = &payload.vcf_phone {
86                            response.push_str(&format!("Телефон: {}\n", phone));
87                            has_phone = !phone.is_empty();
88                        }
89                    }
90
91                    // Проверка контрольной суммы
92                    if check_hash && has_phone {
93                        if payload.verify_hash(&token_bytes) {
94                            response.push_str("✅ Номер телефона подтверждён.\n");
95                        } else {
96                            response.push_str("❌ Номер телефона не подтверждён.\n");
97                        }
98                    }
99
100                    ctx.reply_text(&response).await?;
101                    return Ok(());
102                }
103            }
104            Ok(())
105        }
106    });
107
108    println!("Бот запущен. Отправьте команду /start для запроса контактных данных.");
109    dp.start_polling().await;
110    Ok(())
111}
Source

pub fn request_location(text: impl Into<String>) -> Self

Создаёт кнопку запроса геолокации у пользователя.

Source

pub fn open_app( text: impl Into<String>, web_app_url: impl Into<String>, contact_id: i64, payload: Option<String>, ) -> Self

Создаёт кнопку открытия веб‑приложения (тип "open_app").

Source

pub fn message(text: impl Into<String>, message_text: impl Into<String>) -> Self

Создаёт кнопку отправки сообщения от имени пользователя (тип "message").

Source

pub fn clipboard(text: impl Into<String>, payload: impl Into<String>) -> Self

Создаёт кнопку типа "clipboard".

При нажатии текст payload копируется в буфер обмена пользователя. Эта кнопка не отправляет callback-запрос боту.

Examples found in repository?
examples/combined-attachments-demo.rs (line 90)
17async fn main() -> Result<(), Box<dyn std::error::Error>> {
18    let token = std::env::var("MAXBOT_TOKEN").expect("Missing MAXBOT_TOKEN");
19    let chat_id = std::env::var("CHAT_ID")
20        .expect("Missing CHAT_ID")
21        .parse::<i64>()?;
22    if let Ok(proxy_url) = std::env::var("MAXBOT_PROXY") {
23        maxbot::set_global_base_url(proxy_url);
24    }
25
26    let client = MaxClient::new(token);
27
28    // 1. Стикер (отдельное сообщение без текста)
29    println!("Отправляем стикер...");
30    let builder = SendMessageParamsBuilder::new()
31        .chat_id(chat_id)
32        .attachment(Attachment::sticker("154ed15bb")); // реальный код стикера
33    match client.send_message_builder(builder).await {
34        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
35        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
36    }
37
38    // 2. Контакт (требуется contact_id)
39    println!("Отправляем контакт...");
40    // Здесь нужно указать реальный user_id пользователя MAX
41    // Можно взять из участников чата или использовать свой собственный ID бота
42    let me = client.get_me().await?;
43    let contact = ContactData {
44        name: Some("Мой бот".to_string()),
45        contact_id: Some(me.user.user_id),
46        vcf_info: None,
47        vcf_phone: None,
48    };
49    let builder = SendMessageParamsBuilder::new()
50        .text("Контакт:")
51        .chat_id(chat_id)
52        .attachment(Attachment::contact(contact));
53    match client.send_message_builder(builder).await {
54        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
55        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
56    }
57
58    // 3. Геолокация
59    println!("Отправляем геолокацию...");
60    let builder = SendMessageParamsBuilder::new()
61        .text("Геолокация:")
62        .chat_id(chat_id)
63        .attachment(Attachment::location(55.7558, 37.6176)); // Москва
64    match client.send_message_builder(builder).await {
65        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
66        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
67    }
68
69    // 4. Share (ссылка)
70    println!("Отправляем share (ссылку)...");
71    let share = ShareData {
72        url: Some("https://dev.max.ru".to_string()),
73        token: None,
74    };
75    let builder = SendMessageParamsBuilder::new()
76        .text("Полезная ссылка:")
77        .chat_id(chat_id)
78        .attachment(Attachment::share(share));
79    match client.send_message_builder(builder).await {
80        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
81        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
82    }
83
84    // 5. Inline-клавиатура
85    println!("Отправляем inline-клавиатуру...");
86    let keyboard = InlineKeyboardBuilder::new()
87        // Первая строка с кнопками
88        .button(InlineKeyboardButton::link("Последние новости…", "https://www.e1.ru"))
89        // Новая строка с кнопками
90        .row(vec![InlineKeyboardButton::clipboard("Скопировать код", "SECRET_2026")])
91        .button(InlineKeyboardButton::callback("Кнопка", "demo_payload"))
92        // Результат
93        .build()?;
94    let builder = SendMessageParamsBuilder::new()
95        .text("Клавиатура:")
96        .chat_id(chat_id)
97        .attachment(Attachment::inline_keyboard(keyboard));
98    match client.send_message_builder(builder).await {
99        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
100        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
101    }
102
103    // 6. Inline-клавиатура с автоматическим заполнением кнопок по строкам
104    println!("Отправляем inline-клавиатуру в 3 строки…");
105    let keyboard = InlineKeyboardBuilder::new()
106        .push_button(InlineKeyboardButton::callback("1", "1"))
107        .push_button(InlineKeyboardButton::callback("2", "2"))
108        .push_button(InlineKeyboardButton::callback("3", "3"))
109        .push_button(InlineKeyboardButton::callback("4", "4"))
110        .push_button(InlineKeyboardButton::callback("5", "5"))
111        .push_button(InlineKeyboardButton::callback("6", "6"))
112        .push_button(InlineKeyboardButton::callback("7", "7"))
113        .push_button(InlineKeyboardButton::callback("8", "8"))
114        .push_button(InlineKeyboardButton::callback("9", "9"))
115        .push_button(InlineKeyboardButton::callback("10", "10"))
116        .push_button(InlineKeyboardButton::callback("11", "11"))
117        .push_button(InlineKeyboardButton::callback("12", "12"))
118        .push_button(InlineKeyboardButton::callback("13", "13"))
119        .push_button(InlineKeyboardButton::callback("14", "14"))
120        .push_button(InlineKeyboardButton::callback("15", "15"))
121        .build()?;
122    let builder = SendMessageParamsBuilder::new()
123        .text("Автозаполняемая клавиатура 1:")
124        .chat_id(chat_id)
125        .attachment(Attachment::inline_keyboard(keyboard));
126    match client.send_message_builder(builder).await {
127        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
128        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
129    }
130
131    // 7. Inline-клавиатура с автоматическим заполнением кнопок по строкам
132    println!("Отправляем inline-клавиатуру в 2 строки…");
133    let keyboard = InlineKeyboardBuilder::new()
134        .push_button(InlineKeyboardButton::callback("A", "a"))
135        .push_button(InlineKeyboardButton::callback("B", "b"))
136        .push_button(InlineKeyboardButton::callback("C", "c"))
137        .push_button(InlineKeyboardButton::callback("D", "d"))         // Уже 4 кнопки, строка заполнена (макс 7)
138        .push_button(InlineKeyboardButton::link("Я", "https://ya.ru")) // Новая строка (спец-кнопка)
139        .push_button(InlineKeyboardButton::callback("E", "e"))         // Идёт в строку со спец-кнопкой
140        .build()?;
141    let builder = SendMessageParamsBuilder::new()
142        .text("Автозаполняемая клавиатура 2:")
143        .chat_id(chat_id)
144        .attachment(Attachment::inline_keyboard(keyboard));
145    match client.send_message_builder(builder).await {
146        Ok(ids) => println!("  ✅ mid = {:?}", ids.first().unwrap()),
147        Err(e) => eprintln!("  ❌ Ошибка: {}", e),
148    }
149
150    Ok(())
151}

Trait Implementations§

Source§

impl Clone for InlineKeyboardButton

Source§

fn clone(&self) -> InlineKeyboardButton

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for InlineKeyboardButton

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Serialize for InlineKeyboardButton

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more