vaegram 0.3.0

Telegram MTProto client library for users and bots
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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
mod support;

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

#[cfg(feature = "unstable-raw")]
use vaegram::connection::{Options, Proxy, Transport};
use vaegram::enums::{
    MessageEntityType, MessagesFilter, ParseMode, PollType, ProfileTab, StickerType, StoriesPrivacyRules,
    TopChatCategory,
};
#[cfg(feature = "unstable-raw")]
use vaegram::raw::Serializable;
use vaegram::raw::{base, functions, types};
#[cfg(feature = "unstable-raw")]
use vaegram::session::{Dc, Session};
use vaegram::storage::{FileStorage, Storage};
use vaegram::types::{
    ButtonStyle, Chat, FileSource, Folder, InlineKeyboardButton, InlineKeyboardMarkup, InlineQueryResultArticle,
    InputMedia, InputPollMedia, InputPollOption, InputRichMessage, InputSticker, InputStoryContent, Json,
    KeyboardButton, Media, Message, ReplyKeyboardMarkup, ReplyKeyboardRemove, RichBlock, Text, Upload,
};
use vaegram::utils::get_channel_id;
use vaegram::{Client, filters};

#[cfg(feature = "unstable-raw")]
#[tokio::test]
#[ignore = "connects to Telegram"]
async fn creates_auth_key_and_pings() {
    let dc = Dc::production(2).unwrap();
    let (session, _updates) = Session::connect(dc, None, &Options::default(), Arc::default(), None).await.unwrap();
    let base::Pong::Pong(pong) = session.invoke(&functions::Ping { ping_id: 42 }).await.unwrap();
    assert_eq!(pong.ping_id, 42);
}

#[cfg(feature = "unstable-raw")]
#[tokio::test]
#[ignore = "connects to Telegram's test servers"]
async fn creates_auth_key_on_test_server() {
    let dc = Dc::test_server(2).unwrap();
    let (session, _updates) = Session::connect(dc, None, &Options::default(), Arc::default(), None).await.unwrap();
    let base::Pong::Pong(pong) = session.invoke(&functions::Ping { ping_id: 7 }).await.unwrap();
    assert_eq!(pong.ping_id, 7);
}

#[cfg(feature = "unstable-raw")]
#[tokio::test]
#[ignore = "connects to Telegram's test servers"]
async fn binds_temp_key_on_test_server() {
    let dc = Dc::test_server(2).unwrap();
    let init = Some(functions::help::GetNearestDc {}.to_bytes());
    let (session, _updates) = Session::connect(dc, None, &Options::default(), Arc::default(), init).await.unwrap();
    // Requests wait for auth.bindTempAuthKey to succeed, so an answer means it did.
    let base::Pong::Pong(pong) = session.invoke(&functions::Ping { ping_id: 11 }).await.unwrap();
    assert_eq!(pong.ping_id, 11);
}

#[cfg(feature = "unstable-raw")]
#[tokio::test]
#[ignore = "connects to Telegram"]
async fn handshakes_over_every_transport() {
    let dc = Dc::production(2).unwrap();
    for transport in [Transport::Abridged, Transport::Intermediate, Transport::PaddedIntermediate] {
        for obfuscated in [false, true] {
            let options = Options::new().transport(transport).obfuscated(obfuscated);
            let (session, _updates) = Session::connect(dc, None, &options, Arc::default(), None).await.unwrap();
            let base::Pong::Pong(pong) = session.invoke(&functions::Ping { ping_id: 7 }).await.unwrap();
            assert_eq!(pong.ping_id, 7, "{options:?}");
        }
    }
}

#[cfg(feature = "unstable-raw")]
#[tokio::test]
#[ignore = "connects through VAEGRAM_SOCKS5 (host:port[:user:pass]) and VAEGRAM_MTPROXY (host:port:secret)"]
async fn handshakes_through_proxies() {
    let dc = Dc::production(2).unwrap();
    let mut proxies = Vec::new();
    if let Ok(s) = std::env::var("VAEGRAM_SOCKS5") {
        let parts: Vec<&str> = s.split(':').collect();
        let auth = parts.get(2).zip(parts.get(3)).map(|(u, p)| ((*u).into(), (*p).into()));
        proxies.push(Proxy::Socks5 { host: parts[0].into(), port: parts[1].parse().unwrap(), auth });
    }
    if let Ok(s) = std::env::var("VAEGRAM_MTPROXY") {
        let parts: Vec<&str> = s.split(':').collect();
        proxies.push(Proxy::MtProxy {
            host: parts[0].into(),
            port: parts[1].parse().unwrap(),
            secret: parts[2].parse().unwrap(),
        });
    }
    if proxies.is_empty() {
        eprintln!("skipped: set VAEGRAM_SOCKS5 or VAEGRAM_MTPROXY");
        return;
    }
    for proxy in proxies {
        let options = Options::new().proxy(proxy);
        let (session, _updates) = Session::connect(dc, None, &options, Arc::default(), None).await.unwrap();
        let base::Pong::Pong(pong) = session.invoke(&functions::Ping { ping_id: 9 }).await.unwrap();
        assert_eq!(pong.ping_id, 9, "{options:?}");
    }
}

#[tokio::test]
#[ignore = "logs in as a bot and sends a message"]
async fn bot_sends_and_edits_messages() {
    if std::env::var("VAEGRAM_BOT_TOKEN").is_err() {
        eprintln!("skipped: set VAEGRAM_API_ID, VAEGRAM_API_HASH, VAEGRAM_BOT_TOKEN and VAEGRAM_CHAT_ID");
        return;
    }
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let app =
        Client::builder("target/vaegram-live-test", env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
            .bot_token(env("VAEGRAM_BOT_TOKEN"))
            .start()
            .await
            .unwrap();

    let me = app.get_me().await.unwrap();
    assert!(me.is_bot);

    let chat_id = env("VAEGRAM_CHAT_ID").parse().unwrap();
    let hello = app.send_message(chat_id, "hello from vaegram").await.unwrap();
    assert_eq!((hello.chat.id, hello.text(), hello.outgoing), (chat_id, "hello from vaegram", true));
    assert_eq!(hello.from_user.as_ref().map(|u| u.id), Some(me.id));

    let sent = app.send_message(chat_id, "<b>bold</b>, <i>italic</i> and <code>code</code>").html().await.unwrap();
    assert_eq!((sent.text(), entities(&sent)), ("bold, italic and code", 3));
    let sent =
        app.send_message(chat_id, "**bold**, __italic__ and [a link](https://github.com)").markdown().await.unwrap();
    assert_eq!((sent.text(), entities(&sent)), ("bold, italic and a link", 3));

    let keyboard = InlineKeyboardMarkup::new([
        vec![
            InlineKeyboardButton::callback("Yes", "yes").style(ButtonStyle::Success),
            InlineKeyboardButton::callback("No", "no").style(ButtonStyle::Danger),
        ],
        vec![InlineKeyboardButton::url("Source", "https://github.com/rjriajul/vaegram")],
    ]);
    let asked = app.send_message(chat_id, "Do buttons work?").reply_markup(keyboard).await.unwrap();
    assert!(asked.reply_markup().is_some());

    let edited = asked.edit_text("Buttons work, <b>edited</b>.").html().await.unwrap();
    assert_eq!((edited.id, edited.text(), entities(&edited)), (asked.id, "Buttons work, edited.", 1));
    assert!(edited.edit_date.is_some());
    assert!(edited.reply_markup().is_none());

    // updateShortSentMessage has no rich_message field; this shows whether Telegram answers with it.
    let rich = app.send_rich_message(chat_id, InputRichMessage::html("<b>rich</b> hello")).await.unwrap();
    assert!(rich.rich_message.is_some());
    let rich =
        rich.edit_text(InputRichMessage::blocks([RichBlock::paragraph(Text::new().bold("edited"))])).await.unwrap();
    assert!(rich.rich_message.is_some() && rich.text().contains("edited"));
    rich.delete().await.unwrap();

    let reply = app.send_message(chat_id, "a reply").reply_to(hello.id).await.unwrap();
    assert_eq!(reply.reply_to_message_id, Some(hello.id));

    let keyboard = ReplyKeyboardMarkup::new([vec![KeyboardButton::new("One"), KeyboardButton::new("Two")]]);
    app.send_message(chat_id, "a reply keyboard").reply_markup(keyboard).await.unwrap();
    let removed = app.send_message(chat_id, "keyboard removed").reply_markup(ReplyKeyboardRemove::default()).await;
    removed.unwrap().delete().await.unwrap();
    reply.delete().await.unwrap();

    let again = Client::builder("unused", env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
        .session_string(app.export_session_string())
        .start()
        .await
        .unwrap();
    let me_again = again.get_me().await.unwrap();
    assert_eq!(me_again.id, me.id);
}

fn entities(message: &Message) -> usize {
    message.entities().map_or(0, <[_]>::len)
}

#[tokio::test]
#[ignore = "logs in as a bot and sends polls, dice, venues, contacts and locations"]
async fn bot_sends_polls_and_media() {
    if std::env::var("VAEGRAM_BOT_TOKEN").is_err() {
        eprintln!("skipped: set VAEGRAM_API_ID, VAEGRAM_API_HASH, VAEGRAM_BOT_TOKEN and VAEGRAM_CHAT_ID");
        return;
    }
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let app =
        Client::builder("target/vaegram-live-sends", env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
            .bot_token(env("VAEGRAM_BOT_TOKEN"))
            .start()
            .await
            .unwrap();
    let chat_id: i64 = env("VAEGRAM_CHAT_ID").parse().unwrap();

    let dice = app.send_dice(chat_id).emoji("🎯").disable_notification().await.unwrap();
    let Some(Media::Dice(d)) = &dice.media else { panic!("no dice in {dice:?}") };
    assert_eq!(d.emoji, "🎯");
    let venue = app.send_venue(chat_id, 51.5007, -0.1246, "Big Ben", "London SW1A 0AA").await.unwrap();
    assert!(matches!(venue.media, Some(Media::Venue(_))));
    let contact = app.send_contact(chat_id, "+15555550100", "Vae").last_name("Gram").await.unwrap();
    assert!(matches!(contact.media, Some(Media::Contact(_))));
    let location = app.send_location(chat_id, 51.5007, -0.1246).reply_to(contact.id).await.unwrap();
    assert_eq!(location.reply_to_message_id, Some(contact.id));

    let quiz = app
        .send_poll(chat_id, "2 + 2?", ["3", "4"])
        .quiz([1])
        .explanation("<b>Basic</b> math")
        .explanation_parse_mode(ParseMode::Html)
        .await
        .unwrap();
    let stopped = app.stop_poll(chat_id, quiz.id).await.unwrap();
    let Some(Media::Poll(poll)) = &stopped.media else { panic!("no poll") };
    assert!(poll.is_closed && poll.kind == PollType::Quiz);

    for message in [dice, venue, contact, location, stopped] {
        message.delete().await.unwrap();
    }
}

#[tokio::test]
#[ignore = "logs in as a bot and uploads a file"]
async fn bot_uploads_and_downloads_a_document() {
    if std::env::var("VAEGRAM_BOT_TOKEN").is_err() {
        eprintln!("skipped: set VAEGRAM_API_ID, VAEGRAM_API_HASH, VAEGRAM_BOT_TOKEN and VAEGRAM_CHAT_ID");
        return;
    }
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let app =
        Client::builder("target/vaegram-live-files", env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
            .bot_token(env("VAEGRAM_BOT_TOKEN"))
            .start()
            .await
            .unwrap();
    let chat_id: i64 = env("VAEGRAM_CHAT_ID").parse().unwrap();

    let data: Vec<u8> = (0..3_000_000u32).map(|i| (i * 7 + i / 251) as u8).collect();
    let sent = app.send_document(chat_id, Upload::bytes("vaegram.bin", &data)).caption("a file").await.unwrap();
    let document = sent.document().expect("the message has the document");
    assert_eq!((document.file_name.as_deref(), document.file_size), (Some("vaegram.bin"), data.len() as i64));

    assert!(sent.download().await.unwrap() == data);
    let path = std::path::Path::new("target/vaegram-live-download/vaegram.bin");
    app.download_media(document).save(path).await.unwrap();
    assert!(std::fs::read(path).unwrap() == data);

    let (mut reported, mut streamed) = (0, Vec::new());
    let mut stream = sent.download().progress(|done, _| reported = done).stream();
    while let Some(chunk) = stream.next().await.unwrap() {
        streamed.extend_from_slice(&chunk);
    }
    drop(stream);
    assert!(streamed == data);
    assert_eq!(reported, data.len() as u64);

    let again = app.send_document(chat_id, FileSource::file_id(&document.file_id).unwrap()).await.unwrap();
    let copy = again.document().expect("the copy has the document");
    assert_eq!((copy.id, copy.file_unique_id.as_str()), (document.id, document.file_unique_id.as_str()));
    assert!(app.download_media(&copy.file_id).await.unwrap() == data);
    again.delete().await.unwrap();
    sent.delete().await.unwrap();
}

#[tokio::test]
#[ignore = "logs in as a bot and uploads a photo and a video; the chat must be a channel the bot posts in"]
async fn bot_sends_live_photos_paid_media_and_poll_media() {
    if std::env::var("VAEGRAM_PHOTO").is_err() || std::env::var("VAEGRAM_VIDEO").is_err() {
        eprintln!("skipped: set the bot variables plus VAEGRAM_PHOTO (a JPEG) and VAEGRAM_VIDEO (a short MP4)");
        return;
    }
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let app =
        Client::builder("target/vaegram-live-photo", env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
            .bot_token(env("VAEGRAM_BOT_TOKEN"))
            .start()
            .await
            .unwrap();
    let chat_id: i64 = env("VAEGRAM_CHAT_ID").parse().unwrap();
    let (photo, video) = (env("VAEGRAM_PHOTO"), env("VAEGRAM_VIDEO"));

    let sent = app.send_live_photo(chat_id, photo.as_str(), video.as_str()).caption("live").await.unwrap();
    let live = sent.live_photo().expect("the message has the live photo");
    assert!(live.photo.is_some() && live.file_size > 0);
    sent.delete().await.unwrap();

    let media = [
        InputMedia::photo(photo.as_str()),
        InputMedia::video(video.as_str()),
        InputMedia::live_photo(photo.as_str(), video.as_str()),
    ];
    let sent = app.send_paid_media(chat_id, 5, media).payload("order-7").caption("paid").await.unwrap();
    assert!(matches!(sent.media, Some(Media::PaidMedia(ref m)) if m.star_count == 5));
    sent.delete().await.unwrap();

    // A link goes only on an option, so the description gets the photo.
    let options = [
        InputPollOption::new("Here").media(InputPollMedia::location(48.85, 2.35)),
        InputPollOption::new("This").media(InputPollMedia::link("https://telegram.org")),
    ];
    let poll = app.send_poll(chat_id, "Where?", options).description_media(InputMedia::photo(photo.as_str()));
    let sent = match poll.await {
        Ok(sent) => sent,
        // Telegram's answer while it has no preview of the link at hand; the same request passes at other times.
        Err(e) if e.is("WEBPAGE_NOT_FOUND") => {
            eprintln!("skipped the poll: Telegram has no preview of the link for now (WEBPAGE_NOT_FOUND)");
            return;
        }
        Err(e) => panic!("sending the poll failed: {e:?}"),
    };
    assert!(sent.poll().is_some());
    sent.delete().await.unwrap();
}

#[tokio::test]
#[ignore = "logs in as a bot and sends audio, voice, an album and a media edit"]
async fn bot_sends_typed_files_and_albums() {
    if std::env::var("VAEGRAM_BOT_TOKEN").is_err() {
        eprintln!("skipped: set VAEGRAM_API_ID, VAEGRAM_API_HASH, VAEGRAM_BOT_TOKEN and VAEGRAM_CHAT_ID");
        return;
    }
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let app =
        Client::builder("target/vaegram-live-media", env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
            .bot_token(env("VAEGRAM_BOT_TOKEN"))
            .start()
            .await
            .unwrap();
    let chat_id: i64 = env("VAEGRAM_CHAT_ID").parse().unwrap();
    let data: Vec<u8> = (0..200_000u32).map(|i| (i * 13 + i / 7) as u8).collect();

    let song = Upload::bytes("song.mp3", &data);
    let song = app.send_audio(chat_id, song).duration(3).performer("vaegram").title("Song").await.unwrap();
    let audio = song.audio().expect("the song is audio");
    assert_eq!((audio.performer.as_deref(), audio.title.as_deref()), (Some("vaegram"), Some("Song")));

    let voice = app.send_voice(chat_id, Upload::bytes("voice.ogg", &data)).duration(3).await.unwrap();
    assert!(voice.voice().is_some());

    let album = [
        InputMedia::document(Upload::bytes("a.bin", &data)).caption("<b>first</b>").html(),
        InputMedia::document(Upload::bytes("b.bin", &data)),
    ];
    let album = app.send_media_group(chat_id, album).await.unwrap();
    assert_eq!(album.len(), 2);
    assert!(album[0].id < album[1].id && album[0].media_group_id.is_some());
    assert_eq!(album[0].caption(), Some("first"));

    let replaced = InputMedia::document(Upload::bytes("c.bin", &data)).caption("replaced");
    let edited = app.edit_message_media(chat_id, album[1].id, replaced).await.unwrap();
    let name = edited.document().and_then(|d| d.file_name.as_deref());
    assert_eq!((edited.caption(), name), (Some("replaced"), Some("c.bin")));

    let first = album[0].document().expect("the album has documents");
    let again = app.send_document(chat_id, first).await.unwrap();
    assert_eq!(again.document().map(|d| d.id), Some(first.id));

    app.delete_messages(chat_id, &[song.id, voice.id, album[0].id, album[1].id, again.id]).await.unwrap();
}

#[tokio::test]
#[ignore = "logs in as a bot and manages a sticker set"]
async fn bot_manages_a_sticker_set() {
    let (Ok(_), Ok(owner), Ok(file)) = (
        std::env::var("VAEGRAM_BOT_TOKEN"),
        std::env::var("VAEGRAM_STICKER_OWNER"),
        std::env::var("VAEGRAM_STICKER_FILE"),
    ) else {
        eprintln!(
            "skipped: set VAEGRAM_API_ID, VAEGRAM_API_HASH, VAEGRAM_BOT_TOKEN, VAEGRAM_STICKER_OWNER (a user who \
             started the bot) and VAEGRAM_STICKER_FILE (a 512 px .webp or .png)"
        );
        return;
    };
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let app =
        Client::builder("target/vaegram-live-sets", env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
            .bot_token(env("VAEGRAM_BOT_TOKEN"))
            .start()
            .await
            .unwrap();
    let (owner, file) = (owner.parse::<i64>().unwrap(), file.as_str());
    let me = app.get_me().await.unwrap();
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
    let name = format!("vaegram_{now}_by_{}", me.username.expect("bots have a username"));

    let uploaded = app.upload_sticker_file(owner, file).await.unwrap();
    let first = vec![InputSticker::existing(&uploaded, "😀")];
    let set = app.create_new_sticker_set(owner, &name, "vaegram test", first).await.unwrap();
    assert_eq!((set.name.as_str(), set.sticker_type, set.stickers.len()), (name.as_str(), StickerType::Regular, 1));

    let party = InputSticker::new(file, "🎉").keywords(["party", "fun"]);
    let set = app.add_sticker_to_set(owner, &name, party).await.unwrap();
    let added = set.stickers[1].clone();
    let set = app.set_sticker_position_in_set(&added, 0).await.unwrap();
    assert_eq!(set.stickers[0].id, added.id);
    app.set_sticker_emoji_list(&added, "😎🔥").await.unwrap();
    app.set_sticker_keywords(&added, ["cool"]).await.unwrap();
    let set = app.set_sticker_set_title(&name, "vaegram renamed").await.unwrap();
    assert_eq!(set.title, "vaegram renamed");

    let set = app.replace_sticker_in_set(owner, &set.stickers[1], InputSticker::new(file, "🙂")).await.unwrap();
    assert_eq!(set.stickers.len(), 2);
    let set = app.delete_sticker_from_set(&set.stickers[1]).await.unwrap();
    assert_eq!(set.stickers.len(), 1);
    app.set_sticker_set_thumbnail(&name, owner, None).await.unwrap();
    let fetched = app.get_sticker_set(&name).await.unwrap();
    assert_eq!((fetched.id, fetched.stickers[0].id), (set.id, added.id));
    app.delete_sticker_set(&name).await.unwrap();
    assert!(app.get_sticker_set(&name).await.is_err());

    let icons = app.get_forum_topic_icon_stickers().await.unwrap();
    let ids: Vec<i64> = icons.iter().map(|icon| icon.id).take(3).collect();
    let emoji = app.get_custom_emoji_stickers(&ids).await.unwrap();
    assert_eq!(emoji.len(), ids.len());
    for sticker in &emoji {
        assert_eq!(sticker.kind, StickerType::CustomEmoji);
        assert!(sticker.custom_emoji_id.is_some_and(|id| ids.contains(&id)));
    }
}

#[tokio::test]
#[ignore = "connects to Telegram"]
async fn telegram_errors_come_back_as_rpc_errors() {
    match Client::builder("target/vaegram-live-bad-id", 0, "").start().await {
        Err(vaegram::Error::Rpc(e)) => assert_eq!(e.name, "CONNECTION_API_ID_INVALID"),
        other => panic!("expected CONNECTION_API_ID_INVALID, got {:?}", other.err()),
    }
}

#[tokio::test]
#[ignore = "uses a logged-in user session and a bot"]
async fn user_account_talks_to_bot() {
    let (Ok(session), Ok(token)) = (std::env::var("VAEGRAM_USER_SESSION"), std::env::var("VAEGRAM_BOT_TOKEN")) else {
        eprintln!("skipped: set VAEGRAM_USER_SESSION (a logged-in session name) and VAEGRAM_BOT_TOKEN");
        return;
    };
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let (api_id, api_hash): (i32, String) = (env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"));
    let user = Client::builder(session, api_id, api_hash.clone()).connect().await.unwrap();
    let me = user.get_me().await.unwrap();
    assert!(!me.is_bot);

    let saved = user.send_message(me.id, "**saved** by vaegram").markdown().await.unwrap();
    assert_eq!((saved.chat.id, saved.text(), entities(&saved)), (me.id, "saved by vaegram", 1));
    let saved = saved.edit_text("edited by vaegram").await.unwrap();
    assert_eq!(saved.text(), "edited by vaegram");
    saved.delete().await.unwrap();

    let again = Client::builder("unused", api_id, api_hash.clone())
        .session_string(user.export_session_string())
        .connect()
        .await
        .unwrap();
    let me_again = again.get_me().await.unwrap();
    assert_eq!(me_again.id, me.id);

    // Without catch-up, `run` starts from now instead of replaying what the saved sessions missed, so the handlers
    // below don't answer other tests' old messages.
    let bot = Client::builder("target/vaegram-live-bot-chat", api_id, api_hash)
        .bot_token(token)
        .catch_up(false)
        .start()
        .await
        .unwrap();
    let bot_me = bot.get_me().await.unwrap();
    let bot_id = user.resolve_username(bot_me.username.as_deref().unwrap()).await.unwrap();
    assert_eq!(bot_id, bot_me.id);

    let mention =
        user.send_message(me.id, format!("hi <a href=\"tg://user?id={bot_id}\">bot</a>")).html().await.unwrap();
    assert!(matches!(mention.entities(), Some([e]) if e.kind == MessageEntityType::TextMention));
    mention.delete().await.unwrap();

    let raw_updates = Arc::new(AtomicUsize::new(0));
    let counter = raw_updates.clone();
    bot.on_raw_update(move |_, _| {
        counter.fetch_add(1, Ordering::Relaxed);
        async { Ok(()) }
    });
    // Incoming only: a bot also gets the messages its other sessions send.
    bot.on_message(filters::private() & filters::text() & filters::incoming(), |msg| async move {
        let tap = InlineKeyboardMarkup::new([vec![InlineKeyboardButton::callback("Tap", "tap")]]);
        msg.reply(format!("pong: {}", msg.text())).reply_markup(tap).await?;
        Ok(())
    });
    bot.on_edited_message(filters::private() & filters::incoming(), |msg| async move {
        msg.reply(format!("edited: {}", msg.text())).await?;
        Ok(())
    });
    bot.on_callback_query(filters::data("tap"), |query| async move {
        query.answer().text("tapped").await?;
        query.edit_message_text("tapped!").await?;
        Ok(())
    });
    bot.on_inline_query(filters::all(), |query| async move {
        let result = InlineQueryResultArticle::new("Result", format!("inline: {}", query.query));
        query.answer([result]).cache_time(0).await?;
        Ok(())
    });

    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
    let from_bot = filters::private() & filters::user(bot_id) & filters::incoming();
    let sent = tx.clone();
    user.on_message(from_bot.clone(), move |msg| {
        let tx = sent.clone();
        async move {
            let _ = tx.send(("new", msg));
            Ok(())
        }
    });
    user.on_edited_message(from_bot, move |msg| {
        let tx = tx.clone();
        async move {
            let _ = tx.send(("edit", msg));
            Ok(())
        }
    });
    let (bot_runner, user_runner) = (bot.clone(), user.clone());
    tokio::spawn(async move { bot_runner.run().await });
    tokio::spawn(async move { user_runner.run().await });
    let _disconnect = support::Disconnect(vec![bot.clone(), user.clone()]);
    tokio::time::sleep(Duration::from_secs(2)).await;

    // Each wait takes only the bot's answer to this test's message, newer than it: the chat may also bring older
    // messages that the user's saved session missed.
    let ping = user.send_message(bot_id, "ping").await.unwrap();
    let pong = next(&mut rx, "new", |m| m.id > ping.id && m.reply_to_message_id == Some(ping.id)).await;
    assert_eq!(pong.text(), "pong: ping");
    assert!(pong.reply_markup().is_some());

    let ping = ping.edit_text("ping 2").await.unwrap();
    let edited = next(&mut rx, "new", |m| m.id > pong.id && m.reply_to_message_id == Some(ping.id)).await;
    assert_eq!(edited.text(), "edited: ping 2");

    let peer = user.resolve_peer(bot_id).await.unwrap();
    let request = functions::messages::GetBotCallbackAnswer {
        game: false,
        peer: peer.clone(),
        msg_id: pong.id,
        data: Some(b"tap".to_vec()),
        password: None,
    };
    let base::messages::BotCallbackAnswer::BotCallbackAnswer(answer) = user.invoke(&request).await.unwrap();
    assert_eq!(answer.message.as_deref(), Some("tapped"));
    let tapped = next(&mut rx, "edit", |m| m.id == pong.id).await;
    assert_eq!((tapped.id, tapped.text()), (pong.id, "tapped!"));

    let base::InputPeer::InputPeerUser(bot_peer) = &peer else { panic!("the bot is not a user peer") };
    let bot_user =
        base::InputUser::InputUser(Box::new(types::InputUser { user_id: bot_id, access_hash: bot_peer.access_hash }));
    let request = functions::messages::GetInlineBotResults {
        bot: bot_user,
        peer,
        geo_point: None,
        query: "hi".into(),
        offset: String::new(),
    };
    match user.invoke(&request).await {
        Err(e) if e.is("BOT_INLINE_DISABLED") => {
            eprintln!("skipped the inline query: turn on inline mode for the bot with /setinline in @BotFather")
        }
        results => {
            let base::messages::BotResults::BotResults(results) = results.unwrap();
            assert!(
                matches!(results.results.first(), Some(base::BotInlineResult::BotInlineResult(r)) if r.title.as_deref() == Some("Result"))
            );
        }
    }

    assert!(raw_updates.load(Ordering::Relaxed) >= 3);
    user.delete_messages(bot_id, &[ping.id, pong.id]).await.unwrap();
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_keeps_peers_across_restarts() {
    let Ok(session) = std::env::var("VAEGRAM_USER_SESSION") else {
        eprintln!("skipped: set VAEGRAM_USER_SESSION (a logged-in session name)");
        return;
    };
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let (api_id, api_hash): (i32, String) = (env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"));
    let name = "target/vaegram-live-restart";
    std::fs::copy(format!("{session}.session"), format!("{name}.session")).unwrap();

    let user = Client::builder(name, api_id, api_hash.clone()).connect().await.unwrap();
    let id = user.resolve_username("BotFather").await.unwrap();
    let resolved = user.resolve_peer(id).await.unwrap();
    drop(user);

    let stored = FileStorage::new(name).get_peer_by_id(id).await.unwrap().expect("BotFather was saved on drop");
    let user = Client::builder(name, api_id, api_hash).connect().await.unwrap();
    assert_eq!(user.resolve_peer(id).await.unwrap(), resolved);
    assert_eq!(stored.id, id);
    drop(user);
    std::fs::remove_file(format!("{name}.session")).unwrap();
}

#[tokio::test]
#[ignore = "uses a logged-in user session and a bot"]
async fn user_gets_the_bots_reply_through_the_kit() {
    let Some(kit) = support::Kit::from_env().await else { return };
    kit.bot.on_message(filters::private() & filters::text() & filters::incoming(), |m| async move {
        m.reply(format!("echo: {}", m.text())).await?;
        Ok(())
    });
    let reply = kit.user.send_and_wait_reply(&kit.bot, "hi from the kit").await.unwrap();
    assert_eq!((reply.text(), reply.outgoing), ("echo: hi from the kit", false));
}

/// The next `kind` message on `rx` that `wanted` accepts; the others are skipped.
async fn next(
    rx: &mut tokio::sync::mpsc::UnboundedReceiver<(&'static str, Message)>,
    kind: &str,
    wanted: impl Fn(&Message) -> bool,
) -> Message {
    loop {
        let (k, msg) = tokio::time::timeout(Duration::from_secs(30), rx.recv())
            .await
            .unwrap_or_else(|_| panic!("no {kind} message from the bot within 30s"))
            .unwrap();
        if k == kind && wanted(&msg) {
            return msg;
        }
    }
}

#[tokio::test]
#[ignore = "logs in as a bot and changes its own and a chat's photo"]
async fn bot_sets_and_removes_photos() {
    let vars = ["VAEGRAM_API_ID", "VAEGRAM_API_HASH", "VAEGRAM_BOT_TOKEN", "VAEGRAM_PHOTO_CHAT_ID", "VAEGRAM_PHOTO"];
    if vars.iter().any(|k| std::env::var(k).is_err()) {
        eprintln!("skipped: set {}; the bot must be an admin of the chat and the photo a JPEG", vars.join(", "));
        return;
    }
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let app =
        Client::builder("target/vaegram-live-photos", env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
            .bot_token(env("VAEGRAM_BOT_TOKEN"))
            .start()
            .await
            .unwrap();
    let (chat_id, photo) = (env("VAEGRAM_PHOTO_CHAT_ID").parse::<i64>().unwrap(), env("VAEGRAM_PHOTO"));

    app.set_profile_photo(photo.as_str()).await.unwrap();
    app.remove_profile_photo().await.unwrap();
    app.set_chat_photo(chat_id, photo.as_str()).await.unwrap();
    app.delete_chat_photo(chat_id).await.unwrap();
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_lists_active_sessions() {
    let Ok(session) = std::env::var("VAEGRAM_USER_SESSION") else {
        eprintln!("skipped: set VAEGRAM_USER_SESSION (a logged-in session name)");
        return;
    };
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let user = Client::builder(session, env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
        .device_model("vaegram live test")
        .connect()
        .await
        .unwrap();
    let sessions = user.get_active_sessions().await.unwrap();
    let current = sessions.active_sessions.iter().find(|s| s.is_current).expect("no current session listed");
    assert_eq!(current.device_model, "vaegram live test");
}

async fn user_client() -> Option<Client> {
    let Ok(session) = std::env::var("VAEGRAM_USER_SESSION") else {
        eprintln!("skipped: set VAEGRAM_USER_SESSION (a logged-in session name)");
        return None;
    };
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let client = Client::builder(session, env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"));
    Some(client.connect().await.unwrap())
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn account_settings_round_trip() {
    let Ok(session) = std::env::var("VAEGRAM_USER_SESSION") else {
        eprintln!("skipped: set VAEGRAM_USER_SESSION (a logged-in session name)");
        return;
    };
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let user = Client::builder(session, env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
        .connect()
        .await
        .unwrap();
    let me = user.get_me().await.unwrap();

    // Every call writes back what it read, so the account is left as it was.
    let days = user.get_account_ttl().await.unwrap();
    user.set_account_ttl(days).await.unwrap();
    let days = user.get_active_sessions().await.unwrap().inactive_session_ttl_days;
    match user.set_inactive_session_ttl(days).await {
        Err(e) if e.is("FRESH_RESET_AUTHORISATION_FORBIDDEN") => {
            eprintln!("skipped set_inactive_session_ttl: Telegram refuses it for 24 hours after a login")
        }
        result => result.unwrap(),
    }

    let key = vaegram::enums::PrivacyKey::Bio;
    let rules = user.get_privacy(key).await.unwrap();
    assert_eq!(user.set_privacy(key, &rules).await.unwrap(), rules);

    let global = user.get_global_privacy_settings().await.unwrap();
    assert_eq!(user.set_global_privacy_settings(global).await.unwrap(), global);

    let notify = user.get_chat_notifications(me.id).await.unwrap();
    user.update_chat_notifications(me.id).mute_until(notify.mute_until.unwrap_or(0)).await.unwrap();

    let first_name = me.first_name;
    assert_eq!(user.update_profile().first_name(first_name.as_str()).await.unwrap().first_name, first_name);
    user.update_status(false).await.unwrap();
}

#[tokio::test]
#[ignore = "creates and deletes a supergroup with a logged-in user session"]
async fn user_creates_and_manages_a_supergroup() {
    let Some(user) = user_client().await else { return };
    in_new_chat(&user, false, async |group| {
        assert_eq!(group.kind, vaegram::enums::ChatType::Supergroup);
        user.set_slow_mode(group.id, Some(10)).await?;
        user.set_chat_protected_content(group.id, true).await?;
        user.toggle_forum_topics(group.id, true).await?;
        user.delete_chat_history(group.id).revoke().await?;
        Ok(())
    })
    .await;
}

/// Creates a supergroup, or a channel if `broadcast`, runs `test` in it and deletes it again, also when `test`
/// returns an error or panics.
///
/// Telegram slows down accounts that create and change many groups in a row: calls on the new chats then answer
/// FLOOD_WAIT for about 15 minutes. That is the account's state rather than a vaegram failure, so the test is
/// skipped with the wait printed instead of sleeping it off.
async fn in_new_chat(user: &Client, broadcast: bool, test: impl AsyncFnOnce(Chat) -> vaegram::Result<()>) {
    let (title, about) = ("vaegram live test", "deleted right away");
    let created = match broadcast {
        true => user.create_channel(title, about).await,
        false => user.create_supergroup(title, about).await,
    };
    let Some(chat) = flood_skipped(created) else { return };
    let id = chat.id;
    // A failed assertion is caught here so the chat is still deleted, then goes on unwinding below.
    let mut step = std::pin::pin!(test(chat));
    let outcome = std::future::poll_fn(|cx| {
        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| step.as_mut().poll(cx))) {
            Ok(poll) => poll.map(Ok),
            Err(panic) => std::task::Poll::Ready(Err(panic)),
        }
    })
    .await;
    let deleted = match broadcast {
        true => user.delete_channel(id).await,
        false => user.delete_supergroup(id).await,
    };
    let result = match outcome {
        Ok(result) => result,
        Err(panic) => {
            if let Err(e) = deleted {
                eprintln!("chat {id} was left behind: {e}");
            }
            std::panic::resume_unwind(panic);
        }
    };
    if flood_skipped(result).is_some() {
        flood_skipped(deleted);
    } else if let Err(e) = deleted {
        eprintln!("chat {id} was left behind: {e}");
    }
}

/// Unwraps `result`, except that a flood wait prints why the test is skipped and gives `None`.
fn flood_skipped<T>(result: vaegram::Result<T>) -> Option<T> {
    match result {
        Err(e) if support::flood_limited(&e, "creating or changing a test chat") => None,
        result => Some(result.unwrap()),
    }
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_lists_dialogs_and_contacts() {
    let Ok(session) = std::env::var("VAEGRAM_USER_SESSION") else {
        eprintln!("skipped: set VAEGRAM_USER_SESSION (a logged-in session name)");
        return;
    };
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let user = Client::builder(session, env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
        .connect()
        .await
        .unwrap();
    let me = user.get_me().await.unwrap();

    let mut dialogs = user.get_dialogs().limit(150);
    let mut seen = Vec::new();
    while let Some(dialog) = dialogs.next().await.unwrap() {
        assert!(!seen.contains(&dialog.chat.id), "chat {} listed twice", dialog.chat.id);
        seen.push(dialog.chat.id);
    }
    let total = user.get_dialogs_count(false).await.unwrap();
    assert!(seen.len() <= 150 && seen.len() as i32 <= total);

    user.pin_chat(me.id).await.unwrap();
    user.unpin_chat(me.id).await.unwrap();
    user.mark_chat_unread(me.id).await.unwrap();
    let peer = types::InputDialogPeer { peer: user.resolve_peer(me.id).await.unwrap() };
    let peer = base::InputDialogPeer::InputDialogPeer(Box::new(peer));
    user.invoke(&functions::messages::MarkDialogUnread { unread: false, parent_peer: None, peer }).await.unwrap();
    assert!(user.get_chat_history_count(me.id).await.unwrap() >= 0);

    let contacts = user.get_contacts().await.unwrap();
    assert_eq!(contacts.len() as i32, user.get_contacts_count().await.unwrap());
    user.search_contacts("telegram", 5).await.unwrap();
    user.get_blocked_message_senders().limit(10).await.unwrap();
    if let Some(phone) = &me.phone_number {
        assert_eq!(user.resolve_phone(phone).await.unwrap(), me.id);
    }

    let botfather = user.resolve_username("BotFather").await.unwrap();
    user.block_user(botfather).await.unwrap();
    let blocked = user.get_blocked_message_senders().await;
    // Unblock before asserting so a failure doesn't leave BotFather blocked.
    user.unblock_user(botfather).await.unwrap();
    assert!(blocked.unwrap().iter().any(|c| c.id == botfather));
    user.get_common_chats(botfather).await.unwrap();
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_reads_stories() {
    let Some(user) = user_client().await else { return };
    let stories = user.get_all_stories(false).await.unwrap();
    let Some(story) = stories.first() else { return };
    let chat_id = story.chat.id;
    let fetched = user.get_stories(chat_id, &[story.id]).await.unwrap();
    assert_eq!(fetched.first().map(|s| s.id), Some(story.id));
    assert!(user.get_chat_stories(chat_id).await.unwrap().iter().any(|s| s.id == story.id));
    user.view_stories(chat_id, &[story.id]).await.unwrap();
    user.read_stories(chat_id, story.id).await.unwrap();
}

#[tokio::test]
#[ignore = "posts, edits, pins and deletes a story with a logged-in user session"]
async fn user_posts_and_edits_a_story() {
    let Ok(photo) = std::env::var("VAEGRAM_STORY_PHOTO") else {
        eprintln!("skipped: set VAEGRAM_STORY_PHOTO (a JPEG path) and VAEGRAM_USER_SESSION");
        return;
    };
    let Some(user) = user_client().await else { return };
    let me = user.get_me().await.unwrap();
    // Formatted story captions need Premium while Telegram's `stories_entities` setting is `premium`.
    let caption = if me.is_premium { "<b>vaegram</b>" } else { "vaegram" };
    if !me.is_premium {
        eprintln!("skipped the formatted caption: the VAEGRAM_USER_SESSION account has no Premium");
    }
    let sent = user
        .send_story(me.id, InputStoryContent::photo(photo.as_str()))
        .caption(caption)
        .html()
        .privacy(StoriesPrivacyRules::CloseFriends)
        .protect_content()
        .await;
    let story = match sent {
        // The account is at its `story_expiring_limit_*` of active stories (a few without Premium).
        Err(e) if support::story_limit_reached(&e) => return,
        sent => sent.unwrap(),
    };
    assert_eq!((story.chat.id, story.caption.as_deref(), story.is_close_friends), (me.id, Some("vaegram"), true));

    let edited = user.edit_story_caption(me.id, story.id, "edited").await.unwrap();
    assert_eq!(edited.caption.as_deref(), Some("edited"));
    let only_me = StoriesPrivacyRules::SelectedUsers(vec![me.id]);
    assert!(!user.edit_story_privacy(me.id, story.id, only_me).await.unwrap().is_close_friends);

    assert_eq!(user.pin_chat_stories(me.id, &[story.id]).await.unwrap(), [story.id]);
    assert_eq!(user.get_pinned_stories(me.id).limit(10).next().await.unwrap().map(|s| s.id), Some(story.id));
    assert_eq!(user.unpin_chat_stories(me.id, &[story.id]).await.unwrap(), [story.id]);
    assert_eq!(user.get_stories_archive(me.id).limit(10).next().await.unwrap().map(|s| s.id), Some(story.id));
    assert_eq!(user.delete_stories(me.id, &[story.id]).await.unwrap(), [story.id]);
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_manages_folders() {
    let Some(user) = user_client().await else { return };
    let me = user.get_me().await.unwrap();
    let folder = Folder::new("vaegram").included_chats([me.id]);
    let mut folder = user.create_folder(folder).await.unwrap();
    assert!(user.get_folders().await.unwrap().iter().any(|f| f.id == folder.id && f.title == "vaegram"));

    folder.title = "vaegram 2".into();
    user.edit_folder(&folder).await.unwrap();
    let ids: Vec<i32> = user.get_folders().await.unwrap().iter().map(|f| f.id).collect();
    user.reorder_folders(&ids).await.unwrap();
    user.delete_folder(folder.id).await.unwrap();
    assert!(!user.get_folders().await.unwrap().iter().any(|f| f.id == folder.id));
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_shares_a_folder() {
    let Ok(chat_id) = std::env::var("VAEGRAM_CHAT_ID") else {
        eprintln!("skipped: set VAEGRAM_CHAT_ID (a channel or supergroup you're in)");
        return;
    };
    let Some(user) = user_client().await else { return };
    let chat_id: i64 = chat_id.parse().unwrap();
    let folder = Folder::new("vaegram").included_chats([chat_id]);
    let folder = user.create_folder(folder).await.unwrap();

    let link = user.create_folder_invite_link(folder.id, [chat_id]).name("vaegram").await.unwrap();
    assert_eq!((link.name.as_str(), link.chat_ids.as_slice()), ("vaegram", [chat_id].as_slice()));
    let info = user.check_folder_invite_link(&link.invite_link).await.unwrap();
    assert_eq!((info.folder_id, info.added_chats.len()), (Some(folder.id), 1));
    let link = user.edit_folder_invite_link(folder.id, &link.invite_link).name("edited").await.unwrap();
    assert_eq!(link.name, "edited");
    assert!(user.get_folder_invite_links(folder.id).await.unwrap().iter().any(|l| l.invite_link == link.invite_link));
    user.delete_folder_invite_link(folder.id, &link.invite_link).await.unwrap();
    user.delete_folder(folder.id).await.unwrap();
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_reads_reaction_and_effect_lists() {
    let Ok(session) = std::env::var("VAEGRAM_USER_SESSION") else {
        eprintln!("skipped: set VAEGRAM_USER_SESSION (a logged-in session name)");
        return;
    };
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let user = Client::builder(session, env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
        .connect()
        .await
        .unwrap();

    let available = user.get_available_reactions().await.unwrap();
    assert!(available.iter().any(|r| r.emoji == "👍" && !r.is_premium));
    let effects = user.get_available_effects().await.unwrap();
    assert!(effects.iter().all(|e| e.id != 0 && !e.emoji.is_empty()));
    assert!(user.get_top_reactions(10).await.unwrap().len() <= 10);
    user.get_recent_reactions(10).await.unwrap();
    user.get_saved_reaction_tags().await.unwrap();
}

#[tokio::test]
#[ignore = "uses a logged-in user session and the public @gif bot"]
async fn user_uses_inline_bot() {
    let Ok(session) = std::env::var("VAEGRAM_USER_SESSION") else {
        eprintln!("skipped: set VAEGRAM_USER_SESSION (a logged-in session name)");
        return;
    };
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let user = Client::builder(session, env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
        .connect()
        .await
        .unwrap();
    let me = user.get_me().await.unwrap();
    let gif = user.resolve_username("gif").await.unwrap();

    let results = user.get_inline_bot_results(gif, "cat").await.unwrap();
    let id = results.results.first().expect("@gif found no cats").id.clone();
    let sent = user.send_inline_bot_result(me.id, results.query_id, id).await.unwrap();
    assert_eq!(sent.chat.id, me.id);
    sent.delete().await.unwrap();

    let started = user.start_bot(gif, gif, "vaegram").await.unwrap();
    assert_eq!((started.chat.id, started.outgoing), (gif, true));
    started.delete().await.unwrap();
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_searches_and_translates() {
    let Ok(session) = std::env::var("VAEGRAM_USER_SESSION") else {
        eprintln!("skipped: set VAEGRAM_USER_SESSION (a logged-in session name)");
        return;
    };
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let user = Client::builder(session, env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"))
        .connect()
        .await
        .unwrap();

    let marker = format!("vaegram search {}", std::process::id());
    let saved = user.send_message("me", marker.clone()).await.unwrap();
    // Search indexing lags a little behind sending, so counts and results may not include the marker yet.
    user.search_messages_count("me").query(marker.as_str()).await.unwrap();
    let mut found = user.search_global(marker.as_str()).limit(5);
    while let Some(message) = found.next().await.unwrap() {
        assert!(message.text().contains(&marker));
    }
    user.search_global_count("telegram", MessagesFilter::Url).await.unwrap();
    saved.delete().await.unwrap();

    // Translations keep their formatting only for Premium accounts.
    let premium = user.get_me().await.unwrap().is_premium;
    let spanish = user.translate_text("<b>Good morning</b>", "es").html().await.unwrap();
    assert_eq!((spanish.text.is_empty(), spanish.entities.map(|e| e.len())), (false, premium.then_some(1)));
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_reads_premium_and_boosts() {
    let Some(user) = user_client().await else { return };
    user.get_premium_promo().await.unwrap();
    let boosts = user.get_my_boosts().await.unwrap();
    assert!(boosts.iter().all(|b| b.expire_date >= b.date));
    let err = user.check_gift_code("https://t.me/giftcode/vaegram-no-such-code").await.unwrap_err();
    assert!(matches!(err, vaegram::Error::Rpc(_)), "{err}");
}

#[tokio::test]
#[ignore = "reads the admin log and statistics of a chat the user administers"]
async fn admin_reads_event_log_and_statistics() {
    let Some(user) = user_client().await else { return };
    let Ok(chat_id) = std::env::var("VAEGRAM_ADMIN_CHAT_ID") else {
        eprintln!("skipped: set VAEGRAM_ADMIN_CHAT_ID (a chat you administer)");
        return;
    };
    let chat_id: i64 = chat_id.parse().unwrap();

    let mut log = user.get_chat_event_log(chat_id).limit(150);
    let mut ids = Vec::new();
    while let Some(event) = log.next().await.unwrap() {
        ids.push(event.id);
    }
    assert!(ids.len() <= 150 && ids.windows(2).all(|w| w[0] > w[1]), "events come newest first, without repeats");

    // Chats too small for statistics are refused with CHAT_ADMIN_REQUIRED; big ones may live on another DC.
    let statistics = match user.get_channel_statistics(chat_id).await {
        Err(vaegram::Error::Rpc(e)) if e.name == "BROADCAST_REQUIRED" => {
            user.get_supergroup_statistics(chat_id).await.map(drop)
        }
        other => other.map(drop),
    };
    let refused = |e: &vaegram::Error| matches!(e, vaegram::Error::Rpc(e) if matches!(e.name.as_str(), "CHAT_ADMIN_REQUIRED" | "STATS_MIGRATE"));
    assert!(statistics.as_ref().err().is_none_or(refused), "{statistics:?}");
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_browses_app_bots() {
    let Ok(session) = std::env::var("VAEGRAM_USER_SESSION") else {
        eprintln!("skipped: set VAEGRAM_USER_SESSION (a logged-in session name), optionally VAEGRAM_BOT_APP=bot/app");
        return;
    };
    let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("set {k}"));
    let (api_id, api_hash): (i32, String) = (env("VAEGRAM_API_ID").parse().unwrap(), env("VAEGRAM_API_HASH"));
    let user = Client::builder(session, api_id, api_hash).connect().await.unwrap();

    let mut popular = user.get_popular_app_bots().limit(3);
    let mut bots = Vec::new();
    while let Some(bot) = popular.next().await.unwrap() {
        bots.push(bot);
    }
    assert_eq!((bots.len(), bots.iter().all(|b| b.is_bot)), (3, true));
    let similar = user.get_similar_bots(bots[0].id).await.unwrap();
    assert!(similar.iter().all(|b| b.is_bot && b.id != bots[0].id));

    if let Some(added) = user.get_attach_menu_bots().await.unwrap().first() {
        let again = user.get_attach_menu_bot(added.bot.id).await.unwrap();
        assert_eq!((again.bot.id, again.short_name.as_str()), (added.bot.id, added.short_name.as_str()));
    }

    if let Some((bot, short_name)) = std::env::var("VAEGRAM_BOT_APP").ok().as_deref().and_then(|l| l.split_once('/')) {
        let app = user.get_bot_app(bot, short_name).await.unwrap();
        assert_eq!(app.short_name, short_name);
    }
}

#[tokio::test]
#[ignore = "uses a logged-in user session with Telegram Business"]
async fn user_manages_business_links_and_quick_replies() {
    let Some(user) = user_client().await else { return };
    let replies = user.get_quick_replies().await.unwrap();
    assert!(replies.iter().all(|q| !q.shortcut.is_empty()));
    user.get_connected_bots().await.unwrap();
    if !user.get_me().await.unwrap().is_premium {
        eprintln!("skipped the business chat links: they need Telegram Premium on the VAEGRAM_USER_SESSION account");
        return;
    }

    let link = user.create_business_chat_link("**hi** from vaegram").markdown().title("vaegram").await.unwrap();
    let got = (link.text.as_str(), link.title.as_deref(), link.entities.as_ref().map(Vec::len));
    assert_eq!(got, ("hi from vaegram", Some("vaegram"), Some(1)));
    let link = user.edit_business_chat_link(link.slug(), "edited").await.unwrap();
    assert!(user.get_business_chat_links().await.unwrap().iter().any(|l| l.link == link.link && l.text == "edited"));
    assert_eq!(user.resolve_business_chat_link(link.slug()).await.unwrap().text, "edited");
    user.delete_business_chat_link(link.slug()).await.unwrap();
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_reads_app_config_and_languages() {
    let Some(user) = user_client().await else { return };
    assert!((1..=5).contains(&user.get_nearest_dc().await.unwrap().this_dc));
    assert!(matches!(user.get_app_config().await.unwrap(), Json::Object(_)));
    assert!(user.get_countries_list("en").await.unwrap().iter().any(|c| c.iso2 == "US"));
    assert!(!user.get_timezones_list().await.unwrap().is_empty());
    user.get_terms_of_service_update().await.unwrap();
    user.get_promo_data().await.unwrap();

    let languages = user.get_languages("android").await.unwrap();
    assert!(languages.iter().any(|l| l.lang_code == "en" && l.is_official));
    let en = user.get_language("android", "en").await.unwrap();
    assert_eq!((en.lang_code.as_str(), en.is_rtl), ("en", false));
    let pack = user.get_lang_pack("android", "en").await.unwrap();
    assert!(!pack.strings.is_empty());
    let diff = user.get_lang_pack_difference("android", "en", pack.version).await.unwrap();
    assert!(diff.version >= pack.version);
}

#[tokio::test]
#[ignore = "creates and deletes a supergroup with a logged-in user session"]
async fn user_lists_and_pins_forum_topics() {
    let Some(user) = user_client().await else { return };
    in_new_chat(&user, false, async |group| {
        user.toggle_forum_topics(group.id, true).await?;
        let first = user.create_forum_topic(group.id, "first").await?;
        let second = user.create_forum_topic(group.id, "second").await?;

        let mut topics = user.get_forum_topics(group.id).limit(10);
        let mut ids = Vec::new();
        while let Some(topic) = topics.next().await? {
            ids.push(topic.id);
        }
        assert!(ids.contains(&first.id) && ids.contains(&second.id), "{ids:?}");

        user.pin_forum_topic(group.id, first.id).await?;
        assert!(user.get_forum_topics_by_id(group.id, &[first.id]).await?[0].is_pinned);
        user.unpin_forum_topic(group.id, first.id).await?;
        assert!(!user.get_forum_topics_by_id(group.id, &[first.id]).await?[0].is_pinned);
        Ok(())
    })
    .await;
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_copies_and_forwards_an_album() {
    let Some(user) = user_client().await else { return };
    let data: Vec<u8> = (0..200_000u32).map(|i| (i * 13 + i / 7) as u8).collect();
    let album =
        [InputMedia::document(Upload::bytes("a.bin", &data)), InputMedia::document(Upload::bytes("b.bin", &data))];
    let album = user.send_media_group("me", album).await.unwrap();
    assert_eq!(user.get_media_group("me", album[1].id).await.unwrap().len(), 2);

    let forwarded = user.forward_media_group("me", "me", album[0].id).await.unwrap();
    assert_eq!(forwarded.len(), 2);
    assert!(forwarded[0].media_group_id.is_some() && forwarded[0].media_group_id == forwarded[1].media_group_id);
    assert_ne!(forwarded[0].media_group_id, album[0].media_group_id);

    let copied = user.copy_media_group("me", "me", album[0].id).caption(0, "copied").await.unwrap();
    assert_eq!((copied.len(), copied[0].caption()), (2, Some("copied")));

    let ids: Vec<i32> = [album, forwarded, copied].iter().flatten().map(|m| m.id).collect();
    user.delete_messages("me", &ids).await.unwrap();
}

#[tokio::test]
#[ignore = "creates and deletes a supergroup with a logged-in user session"]
async fn user_adds_and_deletes_poll_options() {
    let Some(user) = user_client().await else { return };
    in_new_chat(&user, false, async |group| {
        // Telegram lets members add options only to a poll that shows its voters.
        let sent = user.send_poll(group.id, "Lunch?", ["A", "B"]).public_voters().allow_adding_options().await?;
        user.add_poll_option(group.id, sent.id, "C").await?;
        let options = |messages: Vec<Option<Message>>| {
            messages[0].as_ref().and_then(Message::poll).map(|p| p.options.len()).expect("the poll is gone")
        };
        assert_eq!(options(user.get_messages(group.id, &[sent.id]).await?), 3);
        user.delete_poll_option(group.id, sent.id, 2).await?;
        assert_eq!(options(user.get_messages(group.id, &[sent.id]).await?), 2);
        Ok(())
    })
    .await;
}

#[tokio::test]
#[ignore = "creates and deletes a supergroup with a logged-in user session"]
async fn user_manages_invite_links() {
    let Some(user) = user_client().await else { return };
    let me = user.get_me().await.unwrap();
    in_new_chat(&user, false, async |group| {
        let link = user.create_chat_invite_link(group.id).name("t").await?.invite_link;

        assert_eq!(user.get_chat_invite_link(group.id, &link).await?.name.as_deref(), Some("t"));
        assert!(user.get_chat_invite_link_joiners(group.id, &link).await?.is_empty());
        assert_eq!(user.get_chat_invite_link_joiners_count(group.id, &link).await?, 0);

        let active = user.get_chat_admin_invite_links(group.id, "me").await?;
        assert!(active.iter().any(|l| l.invite_link == link));
        assert!(user.get_chat_admin_invite_links_count(group.id, "me", false).await? >= 1);
        let admins = user.get_chat_admins_with_invite_links(group.id).await?;
        assert!(admins.iter().any(|a| a.admin.id == me.id));

        user.revoke_chat_invite_link(group.id, &link).await?;
        let revoked = user.get_chat_admin_invite_links(group.id, "me").revoked().await?;
        assert!(revoked.iter().any(|l| l.invite_link == link));
        user.delete_chat_invite_link(group.id, &link).await?;
        user.delete_chat_admin_invite_links(group.id, "me").await?;
        Ok(())
    })
    .await;
}

async fn input_channel(user: &Client, chat_id: i64) -> base::InputChannel {
    let base::InputPeer::InputPeerChannel(p) = user.resolve_peer(chat_id).await.unwrap() else {
        panic!("{chat_id} is not a channel")
    };
    base::InputChannel::InputChannel(Box::new(types::InputChannel {
        channel_id: p.channel_id,
        access_hash: p.access_hash,
    }))
}

async fn channel_full(user: &Client, chat_id: i64) -> types::ChannelFull {
    let channel = input_channel(user, chat_id).await;
    let base::messages::ChatFull::ChatFull(full) =
        user.invoke(&functions::channels::GetFullChannel { channel }).await.unwrap();
    let base::ChatFull::ChannelFull(full) = full.full_chat else { panic!("{chat_id} has no channel info") };
    *full
}

async fn channel_info(user: &Client, chat_id: i64) -> types::Channel {
    let id = vec![input_channel(user, chat_id).await];
    let chats = match user.invoke(&functions::channels::GetChannels { id }).await.unwrap() {
        base::messages::Chats::Chats(c) => c.chats,
        base::messages::Chats::ChatsSlice(c) => c.chats,
    };
    chats
        .into_iter()
        .find_map(|c| match c {
            base::Chat::Channel(c) => Some(*c),
            _ => None,
        })
        .expect("the channel is gone")
}

#[tokio::test]
#[ignore = "creates and deletes a supergroup with a logged-in user session"]
async fn user_changes_supergroup_settings() {
    let Some(user) = user_client().await else { return };
    in_new_chat(&user, false, async |group| {
        let hidden = channel_full(&user, group.id).await.hidden_prehistory;
        user.toggle_pre_history_hidden(group.id, !hidden).await?;
        assert_eq!(channel_full(&user, group.id).await.hidden_prehistory, !hidden);
        user.toggle_pre_history_hidden(group.id, hidden).await?;
        assert_eq!(channel_full(&user, group.id).await.hidden_prehistory, hidden);

        user.set_chat_ttl(group.id, 86400).await?;
        assert_eq!(channel_full(&user, group.id).await.ttl_period, Some(86400));
        user.set_chat_ttl(group.id, 0).await?;
        assert_eq!(channel_full(&user, group.id).await.ttl_period.unwrap_or(0), 0);

        let first = user.send_message(group.id, "x").await?.id;
        let second = user.send_message(group.id, "x").await?.id;
        user.delete_user_history(group.id, "me").await?;
        assert!(user.get_messages(group.id, &[first, second]).await?.iter().all(Option::is_none));

        user.toggle_forum_topics(group.id, true).await?;
        user.toggle_view_forum_as_messages(group.id, true).await?;
        assert!(channel_full(&user, group.id).await.view_forum_as_messages);
        Ok(())
    })
    .await;
}

#[tokio::test]
#[ignore = "flips and restores the settings of a chat the user owns: anti-spam and hidden members in a supergroup, \
            sponsored messages and auto-translation in a channel with enough boosts"]
async fn owner_flips_and_restores_channel_toggles() {
    let Some(user) = user_client().await else { return };
    let Ok(chat) = std::env::var("VAEGRAM_OWNED_CHAT_ID") else {
        eprintln!("skipped: set VAEGRAM_OWNED_CHAT_ID (a chat the user owns)");
        return;
    };
    let chat: i64 = chat.parse().unwrap();
    // Anti-spam and hidden members are supergroup settings; sponsored messages and auto-translation are a broadcast
    // channel's, and Telegram answers CHANNEL_INVALID for them in a supergroup.
    if channel_info(&user, chat).await.megagroup {
        eprintln!("skipped sponsored messages and auto-translation: VAEGRAM_OWNED_CHAT_ID is a supergroup");
        let read = |full: types::ChannelFull| (full.antispam, full.participants_hidden);
        let (antispam, hidden) = read(channel_full(&user, chat).await);
        user.toggle_anti_spam(chat, !antispam).await.unwrap();
        // Hiding members needs `hidden_members_group_size_min` (100) of them, more than a test chat usually has.
        let hides = match user.toggle_participants_hidden(chat, !hidden).await {
            Err(e) if e.is("PARTICIPANTS_TOO_FEW") => {
                eprintln!("skipped toggle_participants_hidden: the chat has too few members to hide them");
                false
            }
            result => {
                result.unwrap();
                true
            }
        };
        assert_eq!(read(channel_full(&user, chat).await), (!antispam, hidden != hides));

        user.toggle_anti_spam(chat, antispam).await.unwrap();
        if hides {
            user.toggle_participants_hidden(chat, hidden).await.unwrap();
        }
        assert_eq!(read(channel_full(&user, chat).await), (antispam, hidden));
    } else {
        eprintln!("skipped anti-spam and hidden members: VAEGRAM_OWNED_CHAT_ID is a broadcast channel");
        let restricted = channel_full(&user, chat).await.restricted_sponsored;
        let translated = channel_info(&user, chat).await.autotranslation;
        user.restrict_sponsored_messages(chat, !restricted).await.unwrap();
        user.toggle_auto_translation(chat, !translated).await.unwrap();
        assert_eq!(channel_full(&user, chat).await.restricted_sponsored, !restricted);
        assert_eq!(channel_info(&user, chat).await.autotranslation, !translated);

        user.restrict_sponsored_messages(chat, restricted).await.unwrap();
        user.toggle_auto_translation(chat, translated).await.unwrap();
        assert_eq!(channel_full(&user, chat).await.restricted_sponsored, restricted);
        assert_eq!(channel_info(&user, chat).await.autotranslation, translated);
    }
}

#[tokio::test]
#[ignore = "creates and deletes a channel and a supergroup with a logged-in user session"]
async fn user_links_a_discussion_group() {
    let Some(user) = user_client().await else { return };
    in_new_chat(&user, true, async |channel| {
        in_new_chat(&user, false, async |group| {
            let suitable = user.get_suitable_discussion_chats().await?;
            assert!(suitable.iter().any(|c| c.id == group.id), "{suitable:?}");

            user.set_chat_discussion_group(channel.id, Some(group.id.into())).await?;
            assert_eq!(channel_full(&user, channel.id).await.linked_chat_id.map(get_channel_id), Some(group.id));
            // Telegram offers other senders only in public and discussion groups, so not in a new group alone.
            assert!(!user.get_send_as_chats(group.id).await?.is_empty());
            user.set_chat_discussion_group(channel.id, None).await?;
            assert_eq!(channel_full(&user, channel.id).await.linked_chat_id, None);
            Ok(())
        })
        .await;

        user.set_main_profile_tab(channel.id, ProfileTab::Media).await?;
        assert_eq!(channel_full(&user, channel.id).await.main_tab, Some(base::ProfileTab::ProfileTabMedia));
        user.get_personal_channels().await?;

        user.set_chat_direct_messages_group(channel.id, true, 0).await?;
        let info = channel_info(&user, channel.id).await;
        assert!(info.broadcast_messages_allowed);
        let monoforum = info.linked_monoforum_id.map(get_channel_id).expect("no direct messages chat");
        let me = user.get_me().await?;
        // Nobody has written to the new direct messages chat yet.
        assert!(user.get_direct_messages_topics_by_id(monoforum, &[me.id]).await?.is_empty());
        user.set_chat_direct_messages_group(channel.id, false, 0).await?;
        Ok(())
    })
    .await;
}

#[tokio::test]
#[ignore = "uses a logged-in user session"]
async fn user_reads_chat_settings_and_top_chats() {
    let Some(user) = user_client().await else { return };
    user.get_chat_settings("me").await.unwrap();
    assert!(user.get_top_chats(TopChatCategory::Users, 10).await.unwrap().len() <= 10);
    let base::messages::DialogFilters::DialogFilters(folders) =
        user.invoke(&functions::messages::GetDialogFilters {}).await.unwrap();
    // Writing the current value back changes nothing, so accounts without Premium pass while tags are off.
    user.toggle_folder_tags(folders.tags_enabled).await.unwrap();
}