tgbotrs 0.1.4

A fully-featured, auto-generated Telegram Bot API library for Rust. All 285 types and 165 methods β€” strongly typed, fully async.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
<div align="center">

<img src="https://rustacean.net/assets/rustacean-orig-noshadow.svg" width="110" alt="Ferris the Crab"/>

<h1>tgbotrs</h1>

<p><strong>A fully-featured, auto-generated Telegram Bot API library for Rust πŸ¦€</strong></p>

[![Crates.io](https://img.shields.io/crates/v/tgbotrs?style=for-the-badge&logo=rust&color=f74c00&labelColor=1a1a2e)](https://crates.io/crates/tgbotrs)
[![docs.rs](https://img.shields.io/docsrs/tgbotrs?style=for-the-badge&logo=docs.rs&color=4a90d9&labelColor=1a1a2e)](https://docs.rs/tgbotrs)
[![CI](https://img.shields.io/github/actions/workflow/status/ankit-chaubey/tgbotrs/ci.yml?branch=main&style=for-the-badge&logo=github-actions&label=CI&color=2ea44f&labelColor=1a1a2e)](https://github.com/ankit-chaubey/tgbotrs/actions/workflows/ci.yml)
[![API Sync](https://img.shields.io/github/actions/workflow/status/ankit-chaubey/tgbotrs/auto-regenerate.yml?style=for-the-badge&logo=telegram&label=API+SYNC&color=0088cc&labelColor=1a1a2e)](https://github.com/ankit-chaubey/tgbotrs/actions/workflows/auto-regenerate.yml)

[![Bot API](https://img.shields.io/badge/Telegram%20Bot%20API-9.4-0088cc?style=flat-square&logo=telegram&logoColor=white)](https://core.telegram.org/bots/api)
[![Rust](https://img.shields.io/badge/Rust-1.75%2B-f74c00?style=flat-square&logo=rust)](https://www.rust-lang.org)
[![Types](https://img.shields.io/badge/Types-285-7c3aed?style=flat-square)](https://docs.rs/tgbotrs)
[![Methods](https://img.shields.io/badge/Methods-165-16a34a?style=flat-square)](https://docs.rs/tgbotrs)
[![Coverage](https://img.shields.io/badge/API%20Coverage-100%25-22c55e?style=flat-square)](https://github.com/ankit-chaubey/tgbotrs/actions)
[![Downloads](https://img.shields.io/crates/d/tgbotrs?style=flat-square&color=f97316&label=Downloads)](https://crates.io/crates/tgbotrs)
[![License](https://img.shields.io/badge/License-MIT-eab308?style=flat-square)](LICENSE)

<br/>

> All **285 types** and **165 methods** of the Telegram Bot API β€”  
> strongly typed, fully async, automatically kept in sync with every official release.

<br/>

[πŸ“¦ Install](#-installation) Β· [πŸš€ Quick Start](#-quick-start) Β· [πŸ“– Examples](#-examples) Β· [πŸ”§ API Reference](#-api-reference) Β· [πŸ”„ Auto-Codegen](#-auto-codegen) Β· [πŸ“š docs.rs](https://docs.rs/tgbotrs)

</div>

---

## ✨ Features

<table>
<tr>
<td width="50%">

**πŸ€– Complete API Coverage**
- All **285 types** β€” structs, enums, markers
- All **165 methods** β€” fully async
- All **21 union types** as Rust enums
- **100 optional params structs** with builder pattern

</td>
<td width="50%">

**πŸ”„ Auto-Generated & Always Fresh**
- Generated from the [official spec]https://github.com/ankit-chaubey/api-spec
- Daily automated check for API updates
- PR auto-opened on every new API version
- Zero manual work to stay up-to-date

</td>
</tr>
<tr>
<td>

**πŸ¦€ Idiomatic Rust**
- Fully `async/await` with **Tokio**
- `Into<ChatId>` β€” accepts `i64` or `"@username"`
- `Into<String>` on all text params
- `Option<T>` for all optional fields
- `Box<T>` to break recursive type cycles

</td>
<td>

**πŸ›‘οΈ Fully Type-Safe**
- `ChatId` β€” integer or username, no stringly typing
- `InputFile` β€” file_id / URL / raw bytes
- `ReplyMarkup` β€” unified enum for all 4 keyboard types
- `InputMedia` β€” typed enum for media groups
- Compile-time guarantees on every API call

</td>
</tr>
<tr>
<td>

**πŸ“‘ Flexible HTTP Layer**
- Custom API server support (local Bot API)
- Multipart file uploads built-in
- Configurable timeout
- Flood-wait aware error handling
- `reqwest` backend

</td>
<td>

**πŸ“¬ Built-in Polling**
- Long-polling dispatcher included
- Spawns a Tokio task per update
- Configurable timeout, limit, allowed\_updates
- Clean concurrent update processing

</td>
</tr>
</table>

---

## πŸ“¦ Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
tgbotrs = "0.1"
tokio   = { version = "1", features = ["full"] }
```

> **Requirements:** Rust `1.75+` Β· Tokio async runtime

---

## πŸš€ Quick Start

```rust
use tgbotrs::Bot;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let bot = Bot::new("YOUR_BOT_TOKEN").await?;

    println!("βœ… Running as @{}", bot.me.username.as_deref().unwrap_or("unknown"));
    println!("   ID: {}", bot.me.id);

    // chat_id accepts i64, negative group IDs, or "@username"
    let msg = bot.send_message(123456789i64, "Hello from tgbotrs! πŸ¦€", None).await?;
    println!("πŸ“¨ Sent message #{}", msg.message_id);

    Ok(())
}
```

---

## πŸ“– Examples

### πŸ” Echo Bot β€” Long Polling

The simplest possible bot. Receives every message and echoes it back.

```rust
use tgbotrs::{Bot, Poller, UpdateHandler};

#[tokio::main]
async fn main() {
    let bot = Bot::new(std::env::var("BOT_TOKEN").unwrap())
        .await
        .expect("Invalid token");

    println!("πŸ€– @{} is running...", bot.me.username.as_deref().unwrap_or(""));

    let handler: UpdateHandler = Box::new(|bot, update| {
        Box::pin(async move {
            let Some(msg) = update.message else { return };
            let Some(text) = msg.text else { return };
            let _ = bot.send_message(msg.chat.id, text, None).await;
        })
    });

    Poller::new(bot, handler)
        .timeout(30)
        .limit(100)
        .start()
        .await
        .unwrap();
}
```

---

### πŸ’¬ Formatted Messages

Send HTML or MarkdownV2 formatted messages with optional settings.

```rust
use tgbotrs::gen_methods::SendMessageParams;

let params = SendMessageParams::new()
    .parse_mode("HTML".to_string())
    .disable_notification(true);

bot.send_message(
    "@mychannel",
    "<b>Bold</b> Β· <i>Italic</i> Β· <code>code</code> Β· <a href='https://example.com'>Link</a>",
    Some(params),
).await?;
```

---

### 🎹 Inline Keyboards

Buttons embedded inside messages. Perfect for interactive menus.

```rust
use tgbotrs::{ReplyMarkup, gen_methods::SendMessageParams};
use tgbotrs::types::{InlineKeyboardButton, InlineKeyboardMarkup};

let keyboard = InlineKeyboardMarkup {
    inline_keyboard: vec![
        vec![
            InlineKeyboardButton {
                text: "βœ… Accept".into(),
                callback_data: Some("accept".into()),
                ..Default::default()
            },
            InlineKeyboardButton {
                text: "❌ Decline".into(),
                callback_data: Some("decline".into()),
                ..Default::default()
            },
        ],
        vec![
            InlineKeyboardButton {
                text: "🌐 Visit Website".into(),
                url: Some("https://ankitchaubey.in".into()),
                ..Default::default()
            },
        ],
    ],
};

let params = SendMessageParams::new()
    .parse_mode("HTML".to_string())
    .reply_markup(ReplyMarkup::InlineKeyboard(keyboard));

bot.send_message(chat_id, "<b>Make a choice:</b>", Some(params)).await?;
```

---

### ⚑ Callback Queries

Handle button taps from inline keyboards. Always acknowledge with `answer_callback_query`.

```rust
use tgbotrs::gen_methods::{AnswerCallbackQueryParams, EditMessageTextParams};
use tgbotrs::types::MaybeInaccessibleMessage;

let handler: UpdateHandler = Box::new(|bot, update| {
    Box::pin(async move {
        let Some(cq) = update.callback_query else { return };
        let data = cq.data.as_deref().unwrap_or("");

        // Always acknowledge β€” dismisses the loading spinner
        let _ = bot
            .answer_callback_query(
                cq.id.clone(),
                Some(
                    AnswerCallbackQueryParams::new()
                        .text(format!("You chose: {}", data))
                        .show_alert(false),
                ),
            )
            .await;

        // Edit the original message in-place
        if let Some(msg) = &cq.message {
            if let MaybeInaccessibleMessage::Message(m) = msg.as_ref() {
                let edit_params = EditMessageTextParams::new()
                    .chat_id(m.chat.id)
                    .message_id(m.message_id)
                    .parse_mode("HTML".to_string());

                let _ = bot
                    .edit_message_text(
                        format!("βœ… You selected: <b>{}</b>", data),
                        Some(edit_params),
                    )
                    .await;
            }
        }
    })
});
```

---

### ⌨️ Reply Keyboards

Custom keyboard shown at the bottom of the screen. Great for persistent menu buttons.

```rust
use tgbotrs::{ReplyMarkup, gen_methods::SendMessageParams};
use tgbotrs::types::{KeyboardButton, ReplyKeyboardMarkup};

let keyboard = ReplyKeyboardMarkup {
    keyboard: vec![
        vec![
            KeyboardButton {
                text: "πŸ“ Share Location".into(),
                request_location: Some(true),
                ..Default::default()
            },
            KeyboardButton {
                text: "πŸ“± Share Contact".into(),
                request_contact: Some(true),
                ..Default::default()
            },
        ],
        vec![
            KeyboardButton { text: "🏠 Home".into(), ..Default::default() },
            KeyboardButton { text: "βš™οΈ Settings".into(), ..Default::default() },
        ],
    ],
    resize_keyboard: Some(true),
    one_time_keyboard: Some(true),
    ..Default::default()
};

let params = SendMessageParams::new()
    .reply_markup(ReplyMarkup::ReplyKeyboard(keyboard));

bot.send_message(chat_id, "Use the keyboard below πŸ‘‡", Some(params)).await?;
```

---

### πŸ“Έ Send Photos & Files

Send files by file\_id, URL, or raw bytes from disk.

```rust
use tgbotrs::{InputFile, gen_methods::SendPhotoParams};

let params = SendPhotoParams::new()
    .caption("Look at this! πŸ“·".to_string())
    .parse_mode("HTML".to_string());

// Fastest β€” already on Telegram's servers
bot.send_photo(chat_id, "AgACAgIAAxkBAAI...", Some(params.clone())).await?;

// Let Telegram download from a URL
bot.send_photo(chat_id, "https://example.com/photo.jpg", Some(params.clone())).await?;

// Upload raw bytes from disk
let data = tokio::fs::read("photo.jpg").await?;
bot.send_photo(chat_id, InputFile::memory("photo.jpg", data), Some(params)).await?;
```

---

### 🎬 Media Groups

Send multiple photos or videos as an album in a single message.

```rust
use tgbotrs::InputMedia;
use tgbotrs::types::{InputMediaPhoto, InputMediaVideo};

let media = vec![
    InputMedia::Photo(InputMediaPhoto {
        r#type: "photo".into(),
        media: "AgACAgIAAxkBAAI...".into(),
        caption: Some("First photo πŸ“Έ".into()),
        ..Default::default()
    }),
    InputMedia::Video(InputMediaVideo {
        r#type: "video".into(),
        media: "BAACAgIAAxkBAAI...".into(),
        caption: Some("A video 🎬".into()),
        ..Default::default()
    }),
];

bot.send_media_group(chat_id, media, None).await?;
```

---

### πŸ“Š Polls

Send polls β€” regular or quiz style.

```rust
use tgbotrs::gen_methods::SendPollParams;
use tgbotrs::types::InputPollOption;

let options = vec![
    InputPollOption { text: "πŸ¦€ Rust".into(),   ..Default::default() },
    InputPollOption { text: "🐹 Go".into(),     ..Default::default() },
    InputPollOption { text: "🐍 Python".into(), ..Default::default() },
];

let params = SendPollParams::new().is_anonymous(false);

bot.send_poll(chat_id, "Best language for bots?", options, Some(params)).await?;
```

---

### πŸͺ Inline Queries

Handle `@yourbot query` inline mode from any chat.

```rust
use tgbotrs::types::{
    InlineQueryResult, InlineQueryResultArticle,
    InputMessageContent, InputTextMessageContent,
};

let results = vec![
    InlineQueryResult::Article(InlineQueryResultArticle {
        r#type: "article".into(),
        id: "1".into(),
        title: "Hello World".into(),
        input_message_content: InputMessageContent::Text(InputTextMessageContent {
            message_text: "Hello from inline mode! πŸ‘‹".into(),
            ..Default::default()
        }),
        description: Some("Send a greeting".into()),
        ..Default::default()
    }),
];

bot.answer_inline_query(query.id.clone(), results, None).await?;
```

---

### πŸ›’ Payments & Telegram Stars

Send invoices using Telegram Stars (`XTR`) or payment providers.

```rust
use tgbotrs::gen_methods::SendInvoiceParams;
use tgbotrs::types::LabeledPrice;

let prices = vec![
    LabeledPrice { label: "Premium Plan".into(), amount: 999 },
];

bot.send_invoice(
    chat_id,
    "Premium Access",
    "30 days of unlimited features",
    "payload_premium_30d",
    "XTR",   // Telegram Stars
    prices,
    None,
).await?;
```

---

### πŸ”” Webhooks

Register a webhook URL so Telegram pushes updates to your server instead of you polling.

```rust
use tgbotrs::gen_methods::SetWebhookParams;

// Register webhook
let params = SetWebhookParams::new()
    .max_connections(100i64)
    .allowed_updates(vec!["message".into(), "callback_query".into()])
    .secret_token("my_secret_token".to_string());

bot.set_webhook("https://mybot.example.com/webhook", Some(params)).await?;
```

**Full webhook server with [axum](https://github.com/tokio-rs/axum):**

```toml
# Cargo.toml
[dev-dependencies]
axum = "0.7"
```

```rust
use axum::{extract::State, http::StatusCode, routing::post, Json, Router};
use std::sync::Arc;
use tgbotrs::{gen_methods::SetWebhookParams, types::Update, Bot};

struct AppState { bot: Bot }

#[tokio::main]
async fn main() {
    let bot = Bot::new("YOUR_BOT_TOKEN").await.unwrap();

    bot.set_webhook(
        "https://yourdomain.com/webhook",
        Some(SetWebhookParams::new()),
    )
    .await
    .unwrap();

    let app = Router::new()
        .route("/webhook", post(handle_update))
        .with_state(Arc::new(AppState { bot }));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn handle_update(
    State(state): State<Arc<AppState>>,
    Json(update): Json<Update>,
) -> StatusCode {
    let bot = state.bot.clone();
    // Spawn immediately β€” return 200 fast or Telegram will retry
    tokio::spawn(async move {
        if let Some(msg) = update.message {
            let _ = bot
                .send_message(msg.chat.id, "Received via webhook! πŸš€", None)
                .await;
        }
    });
    StatusCode::OK
}
```

> For local testing: `ngrok http 8080` β†’ use the ngrok URL as your webhook

---

### 🌐 Local Bot API Server

Point the bot at a self-hosted [Telegram Bot API server](https://github.com/tdlib/telegram-bot-api) for higher file size limits and faster speeds.

```rust
let bot = Bot::with_api_url("YOUR_TOKEN", "http://localhost:8081").await?;
```

---

### πŸ› οΈ Error Handling

Structured errors with helpers for flood-wait and common API errors.

```rust
use tgbotrs::BotError;

match bot.send_message(chat_id, "Hello!", None).await {
    Ok(msg) => println!("βœ… Sent: #{}", msg.message_id),

    Err(BotError::Api { code: 403, .. }) => {
        eprintln!("🚫 Bot was blocked by user");
    }
    Err(BotError::Api { code: 400, description, .. }) => {
        eprintln!("⚠️  Bad request: {}", description);
    }
    Err(e) if e.is_api_error_code(429) => {
        if let Some(secs) = e.flood_wait_seconds() {
            println!("⏳ Flood wait: {} seconds", secs);
            tokio::time::sleep(std::time::Duration::from_secs(secs as u64)).await;
        }
    }
    Err(e) => eprintln!("❌ Unexpected error: {}", e),
}
```

---

## πŸ”§ API Reference

### `Bot` β€” Core Struct

```rust
pub struct Bot {
    pub token:   String,  // Bot token from @BotFather
    pub me:      User,    // Populated via getMe on creation
    pub api_url: String,  // Default: https://api.telegram.org
}
```

| Constructor | Description |
|---|---|
| `Bot::new(token)` | Create bot, calls `getMe`, verifies token |
| `Bot::with_api_url(token, url)` | Create with a custom/local API server |
| `Bot::new_unverified(token)` | Create without calling `getMe` |

---

### `ChatId` β€” Flexible Chat Identifier

Anywhere `ChatId` is expected, you can pass any of these:

```rust
bot.send_message(123456789i64,     "user by numeric id", None).await?;
bot.send_message(-100123456789i64, "group or channel",   None).await?;
bot.send_message("@channelname",   "by username",        None).await?;
bot.send_message(ChatId::Id(123),  "explicit wrapper",   None).await?;
```

---

### `InputFile` β€” File Sending

```rust
// Reference a file already on Telegram's servers (fastest)
InputFile::file_id("AgACAgIAAxkBAAI...")

// Let Telegram download from a URL
InputFile::url("https://example.com/image.png")

// Upload raw bytes directly
let data = tokio::fs::read("photo.jpg").await?;
InputFile::memory("photo.jpg", data)
```

---

### `ReplyMarkup` β€” All Keyboard Types

```rust
// Inline keyboard β€” buttons inside messages
ReplyMarkup::InlineKeyboard(InlineKeyboardMarkup { .. })

// Reply keyboard β€” custom keyboard at bottom of screen
ReplyMarkup::ReplyKeyboard(ReplyKeyboardMarkup { .. })

// Remove the reply keyboard
ReplyMarkup::ReplyKeyboardRemove(ReplyKeyboardRemove { remove_keyboard: true, .. })

// Force the user to reply to a message
ReplyMarkup::ForceReply(ForceReply { force_reply: true, .. })
```

---

### `Poller` β€” Long Polling Dispatcher

```rust
Poller::new(bot, handler)
    .timeout(30)           // Seconds to long-poll (0 = short poll)
    .limit(100)            // Max updates per request (1–100)
    .allowed_updates(vec![ // Filter which update types to receive
        "message".into(),
        "callback_query".into(),
        "inline_query".into(),
    ])
    .start()
    .await?;
```

---

### `BotError` β€” Error Variants

```rust
pub enum BotError {
    Http(reqwest::Error),       // Network / HTTP transport error
    Json(serde_json::Error),    // Serialization error
    Api {
        code: i64,                       // Telegram error code (400, 403, 429…)
        description: String,             // Human-readable message
        retry_after: Option<i64>,        // Flood-wait seconds (code 429)
        migrate_to_chat_id: Option<i64>, // Migration target (code 400)
    },
    InvalidToken,               // Token missing ':'
    Other(String),              // Catch-all
}

// Helper methods
error.is_api_error_code(429)   // β†’ bool
error.flood_wait_seconds()     // β†’ Option<i64>
```

---

### Builder Pattern for Optional Params

Every method with optional parameters has a `*Params` struct with a fluent builder API:

```rust
// Pattern: MethodNameParams::new().field(value).field(value)
let params = SendMessageParams::new()
    .parse_mode("HTML".to_string())
    .disable_notification(true)
    .protect_content(false)
    .message_thread_id(123i64)
    .reply_parameters(ReplyParameters { message_id: 42, ..Default::default() })
    .reply_markup(ReplyMarkup::ForceReply(ForceReply {
        force_reply: true,
        ..Default::default()
    }));
```

---

## πŸ“Š Coverage Statistics

| Category | Count | Status |
|:---|:---:|:---:|
| **Total Types** | **285** | βœ… 100% |
| ↳ Struct types | 257 | βœ… |
| ↳ Union / Enum types | 21 | βœ… |
| ↳ Marker types | 7 | βœ… |
| **Total Methods** | **165** | βœ… 100% |
| ↳ `set*` methods | 30 | βœ… |
| ↳ `get*` methods | 29 | βœ… |
| ↳ `send*` methods | 22 | βœ… |
| ↳ `edit*` methods | 12 | βœ… |
| ↳ `delete*` methods | 11 | βœ… |
| ↳ Other methods | 61 | βœ… |
| **Optional params structs** | 100 | βœ… |
| **Lines auto-generated** | ~11,258 | β€” |

---

## πŸ”„ Auto-Codegen

tgbotrs is the only Rust Telegram library that **automatically stays in sync** with the official API spec via GitHub Actions β€” no manual updates, no lag.

### How It Works

```
Every Day at 08:00 UTC
        β”‚
        β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  Fetch latest   β”‚  ← github.com/ankit-chaubey/api-spec
  β”‚  api.json spec  β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  Compare with   │── No change? ──► Stop βœ…
  β”‚  pinned version β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚ Changed!
           β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  diff_spec.py   β”‚  ← Semantic diff (added/removed types & methods)
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  codegen.py     β”‚  ← Pure Python, zero pip dependencies
  β”‚                 β”‚    Generates gen_types.rs + gen_methods.rs
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  validate.py    β”‚  ← Verify 100% coverage
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  Open PR with   β”‚  ← Rich report: summary table, per-field diff
  β”‚  full report    β”‚    New/removed items, checklist
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  On PR merge:   β”‚
  β”‚  β€’ Bump semver  β”‚
  β”‚  β€’ Git tag      β”‚
  β”‚  β€’ GitHub Releaseβ”‚
  β”‚  β€’ crates.io    β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### Regenerate Manually

```sh
# 1. Pull latest spec
curl -o api.json \
  https://raw.githubusercontent.com/ankit-chaubey/api-spec/main/api.json

# 2. Run codegen (no pip installs needed)
python3 codegen/codegen.py api.json tgbotrs/src/

# 3. Rebuild
cargo build
```

### GitHub Actions Workflows

| Workflow | Trigger | Purpose |
|:---|:---|:---|
| `auto-regenerate.yml` | ⏰ Daily 08:00 UTC + manual | Spec sync β†’ diff β†’ codegen β†’ PR |
| `ci.yml` | Every push / PR | Build, test, lint on 3 OS Γ— 2 Rust versions |
| `release.yml` | PR merged β†’ main | Semver bump β†’ tag β†’ crates.io publish |
| `notify.yml` | After regen | GitHub Issue with full change summary |

---

## 🀝 Contributing

Contributions are welcome!

**Report issues:**
- πŸ› Bug β†’ [open a bug report]https://github.com/ankit-chaubey/tgbotrs/issues/new?template=bug_report.md
- πŸ’‘ Feature β†’ [open a feature request]https://github.com/ankit-chaubey/tgbotrs/issues/new?template=feature_request.md
- πŸ”’ Security β†’ email [ankitchaubey.dev@gmail.com]mailto:ankitchaubey.dev@gmail.com directly

**Development workflow:**

```sh
git clone https://github.com/ankit-chaubey/tgbotrs && cd tgbotrs

cargo build --workspace                    # Build everything
cargo test --workspace                     # Run tests
cargo clippy --workspace -- -D warnings    # Lint
cargo fmt --all                            # Format

# Regenerate from latest spec
python3 codegen/codegen.py api.json tgbotrs/src/

# Validate 100% coverage
python3 .github/scripts/validate_generated.py \
  api.json tgbotrs/src/gen_types.rs tgbotrs/src/gen_methods.rs
```

**PR guidelines:**
- One concern per PR
- Always run `cargo fmt` and `cargo clippy` before submitting
- Never edit `gen_types.rs` or `gen_methods.rs` directly β€” edit `codegen.py` instead
- Add examples for any new helpers

---

## πŸ“œ Changelog

See [CHANGELOG.md](CHANGELOG.md) for the full release history.

---

### Developed by [Ankit Chaubey]https://github.com/ankit-chaubey

**tgbotrs** started as a personal tool.  
I was constantly running into limitations, missing features, and unsupported things,  
so in 2024 I decided to build my own solution.

After using **tgbotrs** for a long time (2024-26) and refining it along the way,  
I felt it could be useful for others too β€” so I made it public.

If this helps you in any way, feel free to ⭐ star it or 🍴 fork it 😁

Developed and maintained by Ankit Chaubey [(@ankit-chaubey)](https://github.com/ankit-chaubey)

<p align="center">
  <sub>
    Rust engineer Β· Open-source builder Β· Telegram & systems enthusiast
  </sub>
</p>

<p align="center">
  <a href="https://github.com/ankit-chaubey">
    <img src="https://img.shields.io/badge/GitHub-ankit--chaubey-181717?style=flat&logo=github" />
  </a>
  <a href="https://t.me/ankify">
    <img src="https://img.shields.io/badge/Telegram-@ankify-0088cc?style=flat&logo=telegram&logoColor=white" />
  </a>
  <a href="mailto:ankitchaubey.dev@gmail.com">
    <img src="https://img.shields.io/badge/Email-Contact-ea4335?style=flat&logo=gmail&logoColor=white" />
  </a>
  <a href="https://ankitchaubey.in">
    <img src="https://img.shields.io/badge/Website-ankitchaubey.in-4a90d9?style=flat&logo=google-chrome&logoColor=white" />
  </a>
</p>

<hr />

<p align="center">
  <a href="https://docs.rs/tgbotrs">
    <img src="https://img.shields.io/badge/docs.rs-tgbotrs-4a90d9?style=flat-square&logo=docs.rs" />
  </a>
  <a href="https://crates.io/crates/tgbotrs">
    <img src="https://img.shields.io/badge/crates.io-tgbotrs-f74c00?style=flat-square&logo=rust" />
  </a>
  <a href="https://github.com/ankit-chaubey/tgbotrs/stargazers">
    <img src="https://img.shields.io/github/stars/ankit-chaubey/tgbotrs?style=social" />
  </a>
  <a href="https://github.com/ankit-chaubey/tgbotrs/network/members">
    <img src="https://img.shields.io/github/forks/ankit-chaubey/tgbotrs?style=social" />
  </a>
</p>

---

## πŸ™ Thanks & Credits

Special thanks to **[Paul / PaulSonOfLars](https://github.com/PaulSonOfLars)** β€” the auto-generation approach at the heart of this library was directly inspired by his excellent Go library **[gotgbot](https://github.com/PaulSonOfLars/gotgbot)** and api-spec gen. Seeing how clean and maintainable a fully-generated, strongly-typed Telegram library can be was the spark for building tgbotrs.

| | |
|:---|:---|
| [**Telegram**]https://core.telegram.org/bots/api | The Bot API this library implements |
| [**PaulSonOfLars / gotgbot**]https://github.com/PaulSonOfLars/gotgbot | Inspiration for the codegen-first approach |
| [**ankit-chaubey / api-spec**]https://github.com/ankit-chaubey/api-spec | Machine-readable spec used as the codegen source |

---

## πŸ“„ License

MIT License Β© 2026 [Ankit Chaubey](https://github.com/ankit-chaubey)

---

<div align="center">

*If tgbotrs saved you time, a ⭐ on GitHub means a lot!*