vkteams-bot 0.11.5

High-performance VK Teams Bot API toolkit with CLI and MCP server support
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
//! API types
use crate::error::{ApiError, BotError, Result};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::borrow::Cow;
use std::fmt::*;
use std::time::Duration;
#[cfg(feature = "templates")]
use tera::{Context, Tera};
use tracing::debug;

/// Environment variable name for bot API URL
pub const VKTEAMS_BOT_API_URL: &str = "VKTEAMS_BOT_API_URL";
/// Environment variable name for bot API token
pub const VKTEAMS_BOT_API_TOKEN: &str = "VKTEAMS_BOT_API_TOKEN";
/// Environment variable name for bot Proxy URL
pub const VKTEAMS_PROXY: &str = "VKTEAMS_PROXY";
/// Timeout for long polling
pub const POLL_TIME: u64 = 30;
/// Global timeout for [`reqwest::Client`]
/// [`reqwest::Client`]: https://docs.rs/reqwest/latest/reqwest/struct.Client.html
pub const POLL_DURATION: &Duration = &Duration::from_secs(POLL_TIME + 10);

pub const SERVICE_NAME: &str = "BOT";
/// Supported API versions
#[derive(Debug)]
pub enum APIVersionUrl {
    /// default V1
    V1,
}
/// Supported API HTTP methods
#[derive(Debug, Default)]
pub enum HTTPMethod {
    #[default]
    GET,
    POST,
}

#[derive(Debug, Default)]
pub enum HTTPBody {
    // JSON,
    MultiPart(MultipartName),
    #[default]
    None,
}
/// Bot request trait
pub trait BotRequest {
    type Args;

    const METHOD: &'static str;
    const HTTP_METHOD: HTTPMethod = HTTPMethod::GET;
    type RequestType: Serialize + Debug + Default;
    type ResponseType: Serialize + DeserializeOwned + Debug + Default;
    fn get_multipart(&self) -> &MultipartName;
    fn new(args: Self::Args) -> Self;
    fn get_chat_id(&self) -> Option<&ChatId>;
}
/// API event id type
pub type EventId = u32;
/// Message text struct
#[derive(Serialize, Clone, Debug)]
pub enum MessageTextFormat {
    /// Plain text
    Plain(String),
    /// Bold text
    Bold(String),
    /// Italic text
    Italic(String),
    /// Underline text
    Underline(String),
    /// Strikethrough text
    Strikethrough(String),
    /// Inline URL
    Link(String, String),
    /// Inline mention of a user
    Mention(ChatId),
    /// Code formatted text
    Code(String),
    /// Pre-formatted fixed-width test block
    Pre(String, Option<String>),
    /// Ordered list
    OrderedList(Vec<String>),
    /// Unordered list
    UnOrderedList(Vec<String>),
    /// Quote text
    Quote(String),
    None,
}
/// Message text parse struct
#[derive(Default, Clone, Debug)]
pub struct MessageTextParser {
    /// Array of text formats
    pub text: Vec<MessageTextFormat>,
    // Context for templates
    #[cfg(feature = "templates")]
    pub ctx: Context,
    // Template name
    #[cfg(feature = "templates")]
    pub name: String,
    // Tera template engine
    #[cfg(feature = "templates")]
    pub tmpl: Tera,
    /// ## Parse mode
    /// - `HTML` - HTML
    /// - `MarkdownV2` - Markdown
    pub parse_mode: ParseMode,
}
/// Keyboard for send message methods
/// One of variants must be set:
/// - {`text`: String,`url`: String,`style`: [`ButtonStyle`]} - simple buttons
/// - {`text`: String,`callback_data`: String,`style`: [`ButtonStyle`]} - buttons with callback
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ButtonKeyboard {
    pub text: String, // formatting is not supported
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub callback_data: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub style: Option<ButtonStyle>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
/// Array of keyboard buttons
pub struct Keyboard {
    pub buttons: Vec<Vec<ButtonKeyboard>>,
}
/// Keyboard buttons style
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum ButtonStyle {
    Primary,
    Attention,
    #[default]
    Base,
}
/// Message text format parse mode
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ParseMode {
    MarkdownV2,
    #[default]
    HTML,
    #[cfg(feature = "templates")]
    Template,
}
/// Event message
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EventMessage {
    pub event_id: EventId,
    #[serde(flatten)]
    pub event_type: EventType,
}
/// Event types
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase", tag = "type", content = "payload")]
pub enum EventType {
    NewMessage(Box<EventPayloadNewMessage>),
    EditedMessage(Box<EventPayloadEditedMessage>),
    DeleteMessage(Box<EventPayloadDeleteMessage>),
    PinnedMessage(Box<EventPayloadPinnedMessage>),
    UnpinnedMessage(Box<EventPayloadUnpinnedMessage>),
    NewChatMembers(Box<EventPayloadNewChatMembers>),
    LeftChatMembers(Box<EventPayloadLeftChatMembers>),
    CallbackQuery(Box<EventPayloadCallbackQuery>),
    #[default]
    None,
}
/// Message payload event type newMessage
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EventPayloadNewMessage {
    pub msg_id: MsgId,
    #[serde(default)]
    pub text: String,
    pub chat: Chat,
    pub from: From,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<MessageFormat>,
    #[serde(default)]
    pub parts: Vec<MessageParts>,
    pub timestamp: Timestamp,
}
/// Message payload event type editedMessage
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EventPayloadEditedMessage {
    pub msg_id: MsgId,
    pub text: String,
    pub timestamp: Timestamp,
    pub chat: Chat,
    pub from: From,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<MessageFormat>,
    pub edited_timestamp: Timestamp,
}
/// Message payload event type deleteMessage
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EventPayloadDeleteMessage {
    pub msg_id: MsgId,
    pub chat: Chat,
    pub timestamp: Timestamp,
}
/// Message payload event type pinnedMessage
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EventPayloadPinnedMessage {
    pub msg_id: MsgId,
    pub chat: Chat,
    pub from: From,
    #[serde(default)]
    pub text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<MessageFormat>,
    #[serde(default)]
    pub parts: Vec<MessageParts>,
    pub timestamp: Timestamp,
}
/// Message payload event type unpinnedMessage
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EventPayloadUnpinnedMessage {
    pub msg_id: MsgId,
    pub chat: Chat,
    pub timestamp: Timestamp,
}
/// Message payload event type newChatMembers
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EventPayloadNewChatMembers {
    pub chat: Chat,
    pub new_members: Vec<From>,
    pub added_by: From,
}
/// Message payload event type leftChatMembers
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EventPayloadLeftChatMembers {
    pub chat: Chat,
    pub left_members: Vec<From>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub removed_by: Option<From>,
}
/// Callback query event type
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EventPayloadCallbackQuery {
    pub query_id: QueryId,
    pub from: From,
    #[serde(default)]
    pub chat: Chat,
    pub message: EventPayloadNewMessage,
    pub callback_data: String,
}
/// Message parts
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessageParts {
    #[serde(rename = "type", flatten)]
    pub part_type: MessagePartsType,
    // pub payload: MessagePartsPayload,
}
/// Message parts type
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase", tag = "type", content = "payload")]
pub enum MessagePartsType {
    Sticker(MessagePartsPayloadSticker),
    Mention(MessagePartsPayloadMention),
    Voice(MessagePartsPayloadVoice),
    File(Box<MessagePartsPayloadFile>),
    Forward(Box<MessagePartsPayloadForward>),
    Reply(Box<MessagePartsPayloadReply>),
    InlineKeyboardMarkup(Vec<Vec<MessagePartsPayloadInlineKeyboard>>),
}
/// Message parts payload sticker
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessagePartsPayloadSticker {
    pub file_id: FileId,
}
/// Message parts payload mention
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessagePartsPayloadMention {
    #[serde(flatten)]
    pub user_id: From,
}
/// Message parts payload voice
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessagePartsPayloadVoice {
    pub file_id: FileId,
}
/// Message parts payload file
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessagePartsPayloadFile {
    pub file_id: FileId,
    #[serde(rename = "type", default)]
    pub file_type: String,
    #[serde(default)]
    pub caption: String,
    #[serde(default)]
    pub format: MessageFormat,
}
/// Message parts payload forward
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessagePartsPayloadForward {
    message: MessagePayload,
}
/// Message parts payload reply
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessagePartsPayloadReply {
    message: MessagePayload,
}
/// Message parts payload inline keyboard
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessagePartsPayloadInlineKeyboard {
    #[serde(default)]
    pub callback_data: String,
    pub style: ButtonStyle,
    pub text: String,
    #[serde(default)]
    pub url: String,
}
/// Array of message formats
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessageFormat {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bold: Option<Vec<MessageFormatStruct>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub italic: Option<Vec<MessageFormatStruct>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub underline: Option<Vec<MessageFormatStruct>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strikethrough: Option<Vec<MessageFormatStruct>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub link: Option<Vec<MessageFormatStructLink>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mention: Option<Vec<MessageFormatStruct>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inline_code: Option<Vec<MessageFormatStruct>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pre: Option<Vec<MessageFormatStructPre>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ordered_list: Option<Vec<MessageFormatStruct>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quote: Option<Vec<MessageFormatStruct>>,
}
/// Message format struct
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessageFormatStruct {
    pub offset: i32,
    pub length: i32,
}
/// Message format struct for link
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessageFormatStructLink {
    pub offset: i32,
    pub length: i32,
    pub url: String,
}
/// Message format struct
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessageFormatStructPre {
    pub offset: i32,
    pub length: i32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
}
/// Event message payload
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MessagePayload {
    pub from: From,
    pub msg_id: MsgId,
    #[serde(default)]
    pub text: String,
    pub timestamp: u64,
    #[serde(default)]
    pub parts: Vec<MessageParts>,
}
/// Chat id struct
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Hash, Eq)]
pub struct ChatId(pub Cow<'static, str>);
/// Message id struct
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Hash, Eq)]
pub struct MsgId(pub String);
/// User id struct
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Hash, Eq)]
pub struct UserId(pub String);
/// File id struct
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Hash, Eq)]
pub struct FileId(pub String);
/// Query id struct
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Hash, Eq)]
pub struct QueryId(pub String);
/// Timestamp struct
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Hash, Eq)]
pub struct Timestamp(pub u32);
/// Chat struct
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Chat {
    pub chat_id: ChatId,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(rename = "type")]
    pub chat_type: String,
}
/// From struct
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct From {
    pub first_name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_name: Option<String>, //if its a bot, then it will be EMPTY
    pub user_id: UserId,
}
/// Languages
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum Languages {
    #[default]
    Ru,
    En,
}
/// Chat types
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub enum ChatType {
    #[default]
    Private,
    Group,
    Channel,
}
/// Chat actions
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum ChatActions {
    Looking,
    #[default]
    Typing,
}
/// Multipart name
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
pub enum MultipartName {
    FilePath(String),
    ImagePath(String),
    FileContent {
        filename: String,
        content: Vec<u8>,
    },
    ImageContent {
        filename: String,
        content: Vec<u8>,
    },
    #[default]
    None,
}
/// Admin struct
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Admin {
    pub user_id: UserId,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub creator: Option<bool>,
}
/// User struct
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Users {
    pub user_id: UserId,
}
/// Member struct
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Member {
    pub user_id: UserId,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub creator: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub admin: Option<bool>,
}
/// Sn struct for members
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Sn {
    pub sn: String,
    pub user_id: UserId,
}
/// Photo url struct
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct PhotoUrl {
    pub url: String,
}
// Intermediate structure for deserializing API responses with the "ok" field
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum ApiResponseWrapper<T> {
    PayloadWithOk {
        ok: bool,
        #[serde(flatten)]
        payload: T,
    },
    PayloadOnly(T),
    Error {
        ok: bool,
        description: String,
    },
}

// Implementation of From for automatic conversion from ApiResponseWrapper to Result
impl<T> std::convert::From<ApiResponseWrapper<T>> for Result<T>
where
    T: Default + Serialize + DeserializeOwned,
{
    fn from(wrapper: ApiResponseWrapper<T>) -> Self {
        match wrapper {
            ApiResponseWrapper::PayloadWithOk { ok, payload } => {
                if ok {
                    debug!("Answer is ok, payload received");
                    Ok(payload)
                } else {
                    debug!("Answer is not ok, but description is not provided");
                    Err(BotError::Api(ApiError {
                        description: "Unspecified error".to_string(),
                    }))
                }
            }
            ApiResponseWrapper::PayloadOnly(payload) => {
                debug!("Answer is ok, payload received");
                Ok(payload)
            }
            ApiResponseWrapper::Error { ok, description } => {
                if ok {
                    debug!("Answer is ok, BUT error description is provided");
                } else {
                    debug!("Answer is NOT ok and error description is provided");
                }
                Err(BotError::Api(ApiError { description }))
            }
        }
    }
}

/// Display trait for [`ChatId`]
impl Display for ChatId {
    /// Format [`ChatId`] to string
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// From trait implementations for [`ChatId`]
impl std::convert::From<String> for ChatId {
    fn from(s: String) -> Self {
        ChatId(Cow::Owned(s))
    }
}

impl std::convert::From<&'static str> for ChatId {
    /// Create ChatId from static string literal (zero-allocation)
    fn from(s: &'static str) -> Self {
        ChatId(Cow::Borrowed(s))
    }
}

impl std::convert::From<Cow<'static, str>> for ChatId {
    fn from(cow: Cow<'static, str>) -> Self {
        ChatId(cow)
    }
}

impl AsRef<str> for ChatId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl ChatId {
    /// Create a new ChatId from a static string (zero-allocation)
    ///
    /// This is equivalent to `ChatId::from(static_str)` but more explicit.
    pub fn from_static(s: &'static str) -> Self {
        ChatId::from(s)
    }

    /// Create a new ChatId from a borrowed string (requires allocation)
    ///
    /// Use this when you have a non-static &str that needs to be owned.
    pub fn from_borrowed_str(s: &str) -> Self {
        ChatId(Cow::Owned(s.to_string()))
    }

    /// Create a new ChatId from an owned string
    pub fn from_owned(s: String) -> Self {
        ChatId(Cow::Owned(s))
    }

    /// Get the string representation as a reference
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Convert to owned String
    pub fn into_string(self) -> String {
        self.0.into_owned()
    }
}

/// Link basse path for API version
impl Display for APIVersionUrl {
    /// Format [`APIVersionUrl`] to string
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match self {
            APIVersionUrl::V1 => write!(f, "bot/v1/"),
        }
    }
}
/// Display trait for [`MultipartName`] enum
impl Display for MultipartName {
    /// Format [`MultipartName`] to string
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match self {
            MultipartName::FilePath(..) | MultipartName::FileContent { .. } => write!(f, "file"),
            MultipartName::ImagePath(..) | MultipartName::ImageContent { .. } => write!(f, "image"),
            _ => write!(f, ""),
        }
    }
}

/// Default values for [`Keyboard`]
impl Default for Keyboard {
    /// Create new [`Keyboard`] with required params
    fn default() -> Self {
        Self {
            // Empty vector of [`KeyboardButton`]
            buttons: vec![vec![]],
        }
    }
}

impl std::fmt::Display for UserId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_chat_id_display() {
        let id = ChatId::from("test_id");
        assert_eq!(format!("{id}"), "test_id");
    }

    #[test]
    fn test_chat_id_from_implementations() {
        // Test From<&'static str> - should use Cow::Borrowed (zero allocation)
        let static_id = ChatId::from("static_chat_id");
        assert_eq!(static_id.as_str(), "static_chat_id");

        // Test from_borrowed_str for non-static strings - should use Cow::Owned
        let dynamic_string = format!("dynamic_{}", 123);
        let dynamic_id = ChatId::from_borrowed_str(&dynamic_string);
        assert_eq!(dynamic_id.as_str(), "dynamic_123");

        // Test From<String> - should use Cow::Owned
        let owned_id = ChatId::from("owned_string".to_string());
        assert_eq!(owned_id.as_str(), "owned_string");

        // Test from_static method
        let static_method_id = ChatId::from_static("static_method");
        assert_eq!(static_method_id.as_str(), "static_method");

        // Test that static strings create borrowed Cow
        let static_literal = ChatId::from("literal");
        match static_literal.0 {
            Cow::Borrowed(_) => (), // Expected for static strings
            Cow::Owned(_) => panic!("Expected Cow::Borrowed for static string literal"),
        }

        // Test that dynamic strings create owned Cow
        let dynamic = ChatId::from_borrowed_str("not_static");
        match dynamic.0 {
            Cow::Owned(_) => (), // Expected for dynamic strings
            Cow::Borrowed(_) => panic!("Expected Cow::Owned for dynamic string"),
        }
    }

    #[test]
    fn test_apiversionurl_display() {
        assert_eq!(format!("{}", APIVersionUrl::V1), "bot/v1/");
    }

    #[test]
    fn test_multipartname_display() {
        let f = MultipartName::FilePath("file.txt".to_string());
        let i = MultipartName::ImagePath("img.png".to_string());
        let n = MultipartName::None;
        assert_eq!(format!("{f}"), "file");
        assert_eq!(format!("{i}"), "image");
        assert_eq!(format!("{n}"), "");
    }

    #[test]
    fn test_keyboard_default() {
        let kb = Keyboard::default();
        assert_eq!(kb.buttons, vec![vec![]]);
    }

    #[test]
    fn test_userid_display() {
        let id = UserId("u123".to_string());
        assert_eq!(format!("{id}"), "u123");
    }

    #[test]
    fn test_parsemode_default_and_eq() {
        assert_eq!(ParseMode::default(), ParseMode::HTML);
        assert_eq!(ParseMode::HTML, ParseMode::HTML);
        assert_ne!(ParseMode::HTML, ParseMode::MarkdownV2);
    }

    #[test]
    fn test_buttonstyle_default_and_eq() {
        assert_eq!(ButtonStyle::default(), ButtonStyle::Base);
        assert_eq!(ButtonStyle::Primary, ButtonStyle::Primary);
        assert_ne!(ButtonStyle::Primary, ButtonStyle::Attention);
    }

    #[test]
    fn test_apiresponsewrapper_from_payloadonly() {
        let wrap = ApiResponseWrapper::PayloadOnly(42);
        let res: Result<i32> = wrap.into();
        assert_eq!(res.unwrap(), 42);
    }

    #[test]
    fn test_apiresponsewrapper_from_payloadwithok() {
        let wrap = ApiResponseWrapper::PayloadWithOk {
            ok: true,
            payload: 7,
        };
        let res: Result<i32> = wrap.into();
        assert_eq!(res.unwrap(), 7);
        let wrap = ApiResponseWrapper::PayloadWithOk {
            ok: false,
            payload: 0,
        };
        let res: Result<i32> = wrap.into();
        assert!(res.is_err());
    }

    #[test]
    fn test_apiresponsewrapper_from_error() {
        let wrap = ApiResponseWrapper::<i32>::Error {
            ok: false,
            description: "fail".to_string(),
        };
        let res: Result<i32> = wrap.into();
        assert!(res.is_err());
    }

    #[test]
    fn test_message_text_format_variants() {
        let _ = MessageTextFormat::Plain("text".to_string());
        let _ = MessageTextFormat::Bold("b".to_string());
        let _ = MessageTextFormat::Italic("i".to_string());
        let _ = MessageTextFormat::Underline("u".to_string());
        let _ = MessageTextFormat::Strikethrough("s".to_string());
        let _ = MessageTextFormat::Link("t".to_string(), "url".to_string());
        let _ = MessageTextFormat::Mention(ChatId::from("cid"));
        let _ = MessageTextFormat::Code("c".to_string());
        let _ = MessageTextFormat::Pre("p".to_string(), Some("lang".to_string()));
        let _ = MessageTextFormat::OrderedList(vec!["1".to_string()]);
        let _ = MessageTextFormat::UnOrderedList(vec!["2".to_string()]);
        let _ = MessageTextFormat::Quote("q".to_string());
        let _ = MessageTextFormat::None;
    }

    #[test]
    fn test_eventtype_default() {
        assert_eq!(EventType::default(), EventType::None);
    }
}