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
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
//! The [`Bot`] builder and its runtime.
use crate::{
accounts::Accounts,
adapters,
command::{Command, Handler},
error::{Error, Result},
platform::{Platform, PlatformConfig},
ratelimit::{RateLimit, RateLimiter},
Ctx,
};
use futures::future::{self, BoxFuture};
use std::{collections::HashMap, future::Future, sync::Arc};
/// The main entry point.
///
/// Build one with [`Bot::new`], add platforms and commands with the
/// chainable methods, then call [`Bot::run`].
///
/// ```no_run
/// use foukoapi::{Bot, Platform};
///
/// # async fn run() -> foukoapi::Result<()> {
/// Bot::new()
/// .add_platform(Platform::telegram("123:abc"))
/// .command("/help", |ctx| async move {
/// ctx.reply("hi").await
/// })
/// .run()
/// .await
/// # }
/// ```
#[must_use = "a Bot does nothing until you call .run().await on it"]
pub struct Bot {
platforms: Vec<Platform>,
commands: HashMap<String, CommandSlot>,
/// Plain-text triggers (no leading `/`). Matched case-insensitively in
/// registration order.
text_commands: Vec<TextSlot>,
fallback: Option<Handler>,
/// Runs for every incoming message (after command dispatch), useful for
/// XP counters and logging. It never answers the user - just observes.
on_message: Vec<Handler>,
/// Handle to the account helper. When set, built-in helpers like
/// [`Bot::with_default_lang_command`] and the i18n-aware
/// [`Bot::with_default_help`] can read/write per-user language.
accounts: Option<Accounts>,
/// Per-user rate limiter. `None` means no limiting. Defaults to a
/// relaxed policy so a fresh bot is spam-resistant without any setup;
/// override with [`Bot::rate_limit`] or disable with
/// [`Bot::no_rate_limit`].
rate_limiter: Option<Arc<RateLimiter>>,
/// Optional hook run when a user trips the rate limit, so a bot can
/// tell them to slow down instead of silently dropping the message.
on_rate_limited: Option<Handler>,
/// Drop updates older than this on startup, so a bot that was offline
/// doesn't reply to a backlog of stale commands all at once. `None`
/// keeps every update. Only adapters that expose an update timestamp
/// (Telegram) honour it.
max_update_age: Option<std::time::Duration>,
/// Optional flood watchdog: counts every incoming update before the
/// per-user rate limit and fires a handler when the total for the
/// current minute crosses a threshold. Set with [`Bot::on_flood`].
on_flood: Option<FloodHook>,
/// Optional outbound handle. When set, adapters register their sender
/// into it on startup so background tasks can push messages.
notifier: Option<crate::notifier::Notifier>,
/// Optional Mini App menu button: `(label, url)`. When set, the
/// Telegram adapter publishes it via `setChatMenuButton` on startup,
/// so private chats show an app button next to the message box.
menu_web_app: Option<(String, String)>,
/// Optional presence (activity + online status). Applied by the
/// Discord adapter when the gateway is ready; platforms without a
/// presence concept ignore it.
presence: Option<crate::platform::Presence>,
}
#[derive(Clone)]
struct TextSlot {
pattern: String,
matcher: TextMatch,
handler: Handler,
}
/// How a text-trigger matches an incoming message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextMatch {
/// The whole message (trimmed) equals the pattern, case-insensitive.
Exact,
/// The message starts with the pattern (trimmed, case-insensitive).
Prefix,
/// The pattern appears anywhere in the message, case-insensitive.
Contains,
}
#[derive(Clone)]
struct CommandSlot {
handler: Handler,
/// `None` means "runs on every platform".
platforms: Option<Vec<crate::PlatformKind>>,
/// Default-language description. Shown by the auto-generated `/help`
/// when nothing else matches the user's language.
description: Option<String>,
/// Per-language descriptions keyed by lang code (e.g. `"en"`, `"ru"`).
/// Populated by [`Bot::command_described_i18n`].
descriptions_i18n: HashMap<String, String>,
/// Optional group heading used by the auto-generated `/help` to sort
/// commands into sections. `None` lands the command in a default
/// bucket. Set with [`Bot::category`].
category: Option<String>,
/// When `true`, the Discord adapter adds a native USER option to this
/// slash command so the client offers a member picker. The picked
/// user's id is prepended to the command's args. Set with
/// [`Bot::user_option`].
takes_user: bool,
}
impl Bot {
/// Start a fresh, empty bot.
pub fn new() -> Self {
Self {
platforms: Vec::new(),
commands: HashMap::new(),
text_commands: Vec::new(),
fallback: None,
on_message: Vec::new(),
accounts: None,
rate_limiter: Some(Arc::new(RateLimiter::new(RateLimit::relaxed()))),
on_rate_limited: None,
max_update_age: Some(std::time::Duration::from_secs(60)),
on_flood: None,
notifier: None,
menu_web_app: None,
presence: None,
}
}
/// Attach a [`Notifier`](crate::Notifier) so background tasks can push
/// messages into chats. Adapters register their delivery function into
/// it as they connect. Keep a clone of the notifier before calling
/// this to use it later.
pub fn with_notifier(mut self, notifier: crate::notifier::Notifier) -> Self {
self.notifier = Some(notifier);
self
}
/// Show a Mini App button in Telegram private chats (the button next
/// to the message box, like BotFather's "Open"). Published via
/// `setChatMenuButton` when the Telegram adapter starts. Other
/// platforms ignore it.
///
/// For the app to also appear on the bot's profile, additionally set
/// the Main Mini App URL in BotFather (/mybots -> Bot Settings ->
/// Main Mini App) - Telegram offers no API for that part.
pub fn menu_web_app(mut self, label: impl Into<String>, url: impl Into<String>) -> Self {
self.menu_web_app = Some((label.into(), url.into()));
self
}
/// What the bot appears to be doing - "Playing X", "Streaming Y with
/// a link", plus the online dot. Discord shows it in the member list
/// and on the bot's profile; platforms without presence (Telegram)
/// ignore it. Applied when the gateway connects, and re-applied on
/// every reconnect.
///
/// ```no_run
/// use foukoapi::{Bot, Presence};
///
/// Bot::new().presence(Presence::streaming("bot.fouko.xyz", "https://bot.fouko.xyz"));
/// ```
pub fn presence(mut self, presence: crate::platform::Presence) -> Self {
self.presence = Some(presence);
self
}
/// Replace the per-user rate-limit policy.
///
/// By default a bot throttles each user to a relaxed 5 actions / 3
/// seconds. Pass your own [`RateLimit`] to make it looser or tighter.
pub fn rate_limit(mut self, policy: RateLimit) -> Self {
self.rate_limiter = Some(Arc::new(RateLimiter::new(policy)));
self
}
/// Turn per-user rate limiting off entirely. Not recommended for a
/// public bot, but handy for tests or trusted single-user setups.
pub fn no_rate_limit(mut self) -> Self {
self.rate_limiter = None;
self
}
/// Run `handler` when a user trips the rate limit, e.g. to reply
/// "you're going too fast". Without one, throttled updates are simply
/// dropped. The handler sees the same [`Ctx`] the update would have
/// reached, so it can answer in the right chat and language.
pub fn on_rate_limited<F, Fut>(mut self, handler: F) -> Self
where
F: Fn(Ctx) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.on_rate_limited = Some(Handler::new(handler));
self
}
/// Install a watchdog over the *total* incoming update flow, across
/// all users and platforms. Every update is counted before the
/// per-user rate limit; when more than `per_minute` land inside one
/// 60-second window, `handler` fires with the current count. It fires
/// at most once per `cooldown`, so an ongoing flood pages you once,
/// not once per message. Use it to detect a spam wave or a DDoS-style
/// burst and alert an operator.
///
/// ```no_run
/// use foukoapi::{Bot, Notifier, PlatformKind, Reply};
/// use std::time::Duration;
///
/// let notifier = Notifier::new();
/// let alerts = notifier.clone();
/// Bot::new()
/// .with_notifier(notifier)
/// .on_flood(600, Duration::from_secs(300), move |count| {
/// let alerts = alerts.clone();
/// async move {
/// let msg = format!("flood: {count} updates in the last minute");
/// let _ = alerts
/// .send(PlatformKind::Telegram, "123456", Reply::text(msg))
/// .await;
/// }
/// });
/// ```
pub fn on_flood<F, Fut>(
mut self,
per_minute: u32,
cooldown: std::time::Duration,
handler: F,
) -> Self
where
F: Fn(u64) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
self.on_flood = Some(FloodHook {
window: FloodWindow::new(per_minute, cooldown),
handler: Arc::new(move |count| Box::pin(handler(count))),
});
self
}
/// Ignore updates older than `age` when they arrive. This is the
/// "don't spew a backlog after downtime" guard: if the bot was offline
/// and a platform delivers a pile of queued messages, anything older
/// than `age` is skipped. Pass a very large duration (or build your
/// own dispatch) to keep everything.
pub fn max_update_age(mut self, age: std::time::Duration) -> Self {
self.max_update_age = Some(age);
self
}
/// Process every update regardless of age (opposite of
/// [`Bot::max_update_age`]).
pub fn process_all_updates(mut self) -> Self {
self.max_update_age = None;
self
}
/// Hand the bot a ready-made [`Accounts`] so that built-in helpers
/// (like [`Bot::with_default_lang_command`] and i18n in
/// [`Bot::with_default_help`]) can read per-user preferences.
///
/// You typically still keep your own clone of `Accounts` for your
/// handlers - this call is just `.clone()` under the hood.
pub fn with_accounts(mut self, accounts: Accounts) -> Self {
self.accounts = Some(accounts);
self
}
/// Attach another platform to this bot. Every registered command runs
/// on every attached platform.
pub fn add_platform(mut self, platform: Platform) -> Self {
self.platforms.push(platform);
self
}
/// Register a command handler.
///
/// `name` is the trigger including the leading slash (`"/help"`, `"/roll"`).
/// The handler is any async closure taking a [`Ctx`]. Names are stored
/// lowercase and matched case-insensitively, so `/Help` finds `/help`.
pub fn command<F, Fut>(mut self, name: impl Into<String>, handler: F) -> Self
where
F: Fn(Ctx) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.commands.insert(
normalize_command_name(&name.into()),
CommandSlot {
handler: Handler::new(handler),
platforms: None,
description: None,
descriptions_i18n: HashMap::new(),
category: None,
takes_user: false,
},
);
self
}
/// Register a command and attach a short human description (used by
/// the auto-generated `/help`).
pub fn command_described<F, Fut>(
mut self,
name: impl Into<String>,
description: impl Into<String>,
handler: F,
) -> Self
where
F: Fn(Ctx) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.commands.insert(
normalize_command_name(&name.into()),
CommandSlot {
handler: Handler::new(handler),
platforms: None,
description: Some(description.into()),
descriptions_i18n: HashMap::new(),
category: None,
takes_user: false,
},
);
self
}
/// Register a command with per-language descriptions.
///
/// `descriptions` maps a lang code (e.g. `"en"`, `"ru"`) to the short
/// description that [`Bot::with_default_help`] should show when the
/// user is on that language. The first entry is also used as the
/// default description (shown when the user's language isn't in the
/// map).
///
/// ```no_run
/// use foukoapi::Bot;
/// use std::collections::HashMap;
///
/// let mut descs = HashMap::new();
/// descs.insert("en".to_string(), "flip a coin".to_string());
/// descs.insert("ru".to_string(), "подбросить монетку".to_string());
///
/// Bot::new().command_described_i18n("/coin", descs, |ctx| async move {
/// ctx.reply("heads").await
/// });
/// ```
pub fn command_described_i18n<F, Fut>(
mut self,
name: impl Into<String>,
descriptions: HashMap<String, String>,
handler: F,
) -> Self
where
F: Fn(Ctx) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
// Pick a default: prefer "en", otherwise any value in the map.
let default = descriptions
.get("en")
.cloned()
.or_else(|| descriptions.values().next().cloned());
self.commands.insert(
normalize_command_name(&name.into()),
CommandSlot {
handler: Handler::new(handler),
platforms: None,
description: default,
descriptions_i18n: descriptions,
category: None,
takes_user: false,
},
);
self
}
/// Restrict the last registered command to only run on `platforms`.
pub fn only_on(mut self, name: &str, platforms: &[crate::PlatformKind]) -> Self {
if let Some(slot) = self.commands.get_mut(&normalize_command_name(name)) {
slot.platforms = Some(platforms.to_vec());
}
self
}
/// Put a command under a heading in the auto-generated `/help`.
///
/// Categories are entirely optional: commands without one fall into a
/// default group. When *no* command has a category, `/help` renders a
/// single flat list, exactly as before. `name` is the command's
/// trigger (e.g. `"/roll"`), `category` is any label you like
/// (`"Fun"`, `"Economy"`, ...).
pub fn category(mut self, name: &str, category: impl Into<String>) -> Self {
if let Some(slot) = self.commands.get_mut(&normalize_command_name(name)) {
slot.category = Some(category.into());
}
self
}
/// Mark a command as taking a user argument. On Discord the slash
/// command gets a native USER option (the client shows a member
/// picker); the chosen user's id arrives as the first token of
/// [`Ctx::args`]. On platforms without such pickers (Telegram) this
/// changes nothing - users keep typing an id or @mention as text.
pub fn user_option(mut self, name: &str) -> Self {
if let Some(slot) = self.commands.get_mut(&normalize_command_name(name)) {
slot.takes_user = true;
}
self
}
/// Run `handler` on every incoming message, regardless of command.
/// Useful for XP counters and audit logging.
pub fn on_message<F, Fut>(mut self, handler: F) -> Self
where
F: Fn(Ctx) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.on_message.push(Handler::new(handler));
self
}
/// Register a text-trigger (no leading `/`). Matches run after slash
/// commands: if the user typed `/help`, slash dispatch wins. Only when
/// the message isn't a slash command do text triggers fire.
pub fn text_command<F, Fut>(
mut self,
pattern: impl Into<String>,
matcher: TextMatch,
handler: F,
) -> Self
where
F: Fn(Ctx) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.text_commands.push(TextSlot {
pattern: pattern.into().to_lowercase(),
matcher,
handler: Handler::new(handler),
});
self
}
/// Register a built-in `/help` that lists every described command.
///
/// When an [`Accounts`] has been attached via
/// [`Bot::with_accounts`], the generated help picks a per-language
/// description for each command (from
/// [`Bot::command_described_i18n`]) and a localised header, so a
/// Russian user sees `команды:` and Russian summaries while an
/// English user keeps the default.
pub fn with_default_help(self) -> Self {
// Snapshot (name, default_desc, i18n_map, category, platforms) for
// every described command, so the `/help` closure can render at
// dispatch time without holding a lock on `self`.
type HelpEntry = (
String,
Option<String>,
HashMap<String, String>,
Option<String>,
Option<Vec<crate::PlatformKind>>,
);
let snapshot: Vec<HelpEntry> = self
.commands
.iter()
.filter(|(_, slot)| slot.description.is_some() || !slot.descriptions_i18n.is_empty())
.map(|(name, slot)| {
(
name.clone(),
slot.description.clone(),
slot.descriptions_i18n.clone(),
slot.category.clone(),
slot.platforms.clone(),
)
})
.collect();
let accounts = self.accounts.clone();
self.command("/help", move |ctx| {
let snapshot = snapshot.clone();
let accounts = accounts.clone();
async move {
// Figure out the user's language. Falls back to "en" when
// we have no accounts handle or the lookup fails.
let lang = match &accounts {
Some(a) => a
.lang_for(ctx.platform(), ctx.user_id())
.await
.unwrap_or_else(|_| "en".to_owned()),
None => "en".to_owned(),
};
let (title, intro) = match lang.as_str() {
"ru" => ("\u{1F4D6} Команды", "Вот что я умею:"),
_ => ("\u{1F4D6} Commands", "Here's what I can do:"),
};
let mut sorted = snapshot;
sorted.sort_by(|a, b| a.0.cmp(&b.0));
// Resolve each command's line and its group. Commands that
// don't run on this platform are skipped entirely - no
// point advertising /avatar to Telegram users. Groups keep
// first-seen order so a bot controls layout by the order it
// assigns categories, not alphabetically.
let mut groups: Vec<(String, String)> = Vec::new();
let has_categories = sorted.iter().any(|(_, _, _, cat, _)| cat.is_some());
for (name, default_desc, i18n, category, platforms) in sorted {
if let Some(allowed) = &platforms {
if !allowed.contains(&ctx.platform()) {
continue;
}
}
let desc = i18n
.get(&lang)
.cloned()
.or(default_desc)
.unwrap_or_default();
let line = if desc.is_empty() {
format!("{name}\n")
} else {
format!("{name} - {desc}\n")
};
// Without categories everything shares one bucket.
let group = category.unwrap_or_default();
match groups.iter_mut().find(|(g, _)| g == &group) {
Some((_, body)) => body.push_str(&line),
None => groups.push((group, line)),
}
}
let mut em = crate::Embed::new().title(title).color(0x5B8DEF);
if has_categories {
em = em.description(intro);
for (group, body) in groups {
let heading = if group.is_empty() {
match lang.as_str() {
"ru" => "Прочее".to_owned(),
_ => "Other".to_owned(),
}
} else {
group
};
em = em.field(heading, body.trim_end().to_owned());
}
} else {
// Flat list: one description block, no field headings.
let body = groups.into_iter().map(|(_, b)| b).collect::<String>();
em = em.description(format!("{intro}\n\n{}", body.trim_end()));
}
ctx.reply_with(crate::Reply::embed(em)).await
}
})
}
/// Register a built-in `/lang` command with inline buttons.
///
/// No argument: shows the current language plus a button for every
/// language in `supported`. Tapping a button switches instantly -
/// no typing `/lang ru` needed. Typing `/lang ru` still works for
/// users on clients without inline keyboards.
///
/// Callback ids used: `foukoapi:lang:<code>`. They don't clash with
/// anything the bot defines itself.
///
/// Requires [`Bot::with_accounts`] to have been called - without an
/// [`Accounts`] the command politely says so.
pub fn with_default_lang_command<I, S>(self, supported: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
// `foukoapi:lang:<invoker>:<code>` - we glue the invoker user id
// into the callback so only the person who ran `/lang` can press
// a button that was meant for them.
const CB_PREFIX: &str = "foukoapi:lang:";
let supported: Vec<String> = supported
.into_iter()
.map(|s| s.into().to_ascii_lowercase())
.collect();
let accounts = self.accounts.clone();
self.command_described(
"/lang",
"switch language, e.g. /lang ru",
move |ctx| {
let accounts = accounts.clone();
let supported = supported.clone();
async move {
let Some(accounts) = accounts else {
return ctx
.reply(
"language switching is not wired up on this bot (the author forgot to call Bot::with_accounts)",
)
.await;
};
// Button press: `foukoapi:lang:<invoker>:<code>`.
// Parse out both parts and, if we have an invoker id,
// make sure it matches the tapping user.
let (requested, invoker): (Option<String>, Option<String>) =
if let Some(data) = ctx.callback_data() {
if let Some(rest) = data.strip_prefix(CB_PREFIX) {
let mut parts = rest.splitn(2, ':');
let invoker = parts.next().map(|s| s.to_owned());
let code = parts.next().map(|s| s.to_ascii_lowercase());
(code, invoker)
} else {
(None, None)
}
} else {
let arg = ctx.args().trim().to_ascii_lowercase();
if arg.is_empty() {
(None, None)
} else {
(Some(arg), None)
}
};
// Invoker guard: if this is a button press and the
// tap came from someone else, reject quietly. The
// "someone else" case is common in group chats.
if let Some(inv) = invoker.as_deref() {
if !inv.is_empty() && inv != ctx.user_id() {
let lang_now = accounts
.lang_for(ctx.platform(), ctx.user_id())
.await
.unwrap_or_else(|_| "en".into());
let msg = match lang_now.as_str() {
"ru" => "эта кнопка не для тебя",
_ => "this button isn't for you",
};
return ctx.reply(msg).await;
}
}
let current = accounts
.lang_for(ctx.platform(), ctx.user_id())
.await
.unwrap_or_else(|_| "en".into());
match requested {
None => {
// Show the picker. Embed the invoker id in
// every callback id so follow-up taps can be
// gated to the same user.
let body = match current.as_str() {
"ru" => format!(
"текущий язык: {current}\nвыбери язык:"
),
_ => format!(
"current language: {current}\npick a language:"
),
};
if supported.is_empty() {
return ctx.reply(body).await;
}
let invoker_id = ctx.user_id().to_owned();
let kb =
build_lang_keyboard(&supported, ¤t, &invoker_id, CB_PREFIX);
ctx.reply_with(crate::Reply::text(body).keyboard(kb)).await
}
Some(code) => {
if !supported.is_empty() && !supported.contains(&code) {
let list = supported.join(", ");
let msg = match current.as_str() {
"ru" => format!("поддерживаемые языки: {list}"),
_ => format!("supported languages: {list}"),
};
return ctx.reply(msg).await;
}
accounts
.set_lang(ctx.platform(), ctx.user_id(), &code)
.await?;
// Re-render the picker with the new pick
// marked. When this is a button press we
// edit the original message; when it was a
// typed `/lang ru`, edit_reply falls back
// to a fresh message.
let invoker_id = ctx.user_id().to_owned();
let body = match code.as_str() {
"ru" => format!(
"язык: {code} \u{2705}\nвыбери другой:"
),
_ => format!(
"language set to {code} \u{2705}\npick another:"
),
};
if supported.is_empty() {
return ctx.edit_reply(body).await;
}
let kb =
build_lang_keyboard(&supported, &code, &invoker_id, CB_PREFIX);
ctx.edit_reply(crate::Reply::text(body).keyboard(kb)).await
}
}
}
},
)
}
/// Register a built-in `/link` command with inline buttons.
///
/// What the user gets:
///
/// - `/link` with no arguments, not linked yet: issues a 6-char code
/// and shows a **cancel** button.
/// - `/link` when already linked: shows both identities + current
/// primary, with **pick primary** and **unlink** buttons.
/// - `/link CODE`: redeems a code issued on another platform (through
/// [`Accounts::redeem_link`]) and shows the primary-picker buttons.
/// - Button presses are routed back through the same `/link` handler,
/// so the whole dance lives on one command.
///
/// Works in English and Russian out of the box. The button-callback
/// ids used internally start with `foukoapi:link:` so they don't clash
/// with anything the bot defines itself.
///
/// Requires [`Bot::with_accounts`] to have been called.
pub fn with_default_link_command(self) -> Self {
const CB_UNLINK: &str = "foukoapi:link:unlink";
const CB_CANCEL: &str = "foukoapi:link:cancel";
const CB_PRIMARY_ME: &str = "foukoapi:link:primary_me";
const CB_PRIMARY_PARTNER: &str = "foukoapi:link:primary_partner";
let mut descs = HashMap::new();
descs.insert(
"en".to_owned(),
"Link or unlink accounts across platforms".to_owned(),
);
descs.insert(
"ru".to_owned(),
"Связать или отвязать аккаунты между платформами".to_owned(),
);
let accounts = self.accounts.clone();
self.command_described_i18n("/link", descs, move |ctx| {
let accounts = accounts.clone();
async move {
let Some(accounts) = accounts else {
return ctx
.reply(
"account linking is not wired up on this bot (the author forgot to call Bot::with_accounts)",
)
.await;
};
let lang = accounts
.lang_for(ctx.platform(), ctx.user_id())
.await
.unwrap_or_else(|_| "en".into());
// DM-only guard. `/link` juggles short-lived codes tied
// to a specific account; running it in a public chat
// would splash the code to every onlooker, which is a
// recipe for someone else hijacking the link. Refuse
// outside of direct messages.
if !ctx.is_dm() {
let body = match lang.as_str() {
"ru" => "команда /link работает только в личке с ботом. открой переписку и попробуй снова.",
_ => "/link only works in a private chat with the bot. open the bot's DM and try again.",
};
return ctx.reply(body).await;
}
if let Some(data) = ctx.callback_data() {
return handle_link_callback(
&ctx,
&accounts,
data,
&lang,
CB_UNLINK,
CB_CANCEL,
CB_PRIMARY_ME,
CB_PRIMARY_PARTNER,
)
.await;
}
let arg = ctx.args().trim().to_owned();
if arg.starts_with("foukoapi:link:") {
return handle_link_callback(
&ctx,
&accounts,
&arg,
&lang,
CB_UNLINK,
CB_CANCEL,
CB_PRIMARY_ME,
CB_PRIMARY_PARTNER,
)
.await;
}
if arg.is_empty() {
return link_status_reply(&ctx, &accounts, &lang, CB_UNLINK, CB_CANCEL)
.await;
}
match accounts
.redeem_link(&arg, ctx.platform(), ctx.user_id())
.await
{
Ok(res) => {
let (title, body, footer) = match lang.as_str() {
"ru" => (
"\u{2705} Аккаунты связаны",
format!(
"**{}** \u{2194} **{}**",
platform_title(platform_of(&res.primary)),
platform_title(platform_of(&res.partner))
),
"Выбери основной аккаунт. На нём остаются XP, монеты и настройки. Выбор делается **один раз** - потом поменять нельзя, можно только /link -> Отвязать.",
),
_ => (
"\u{2705} Accounts Linked",
format!(
"**{}** \u{2194} **{}**",
platform_title(platform_of(&res.primary)),
platform_title(platform_of(&res.partner))
),
"Pick the primary - XP, coins and settings live there. You can only pick **once**; after that, /link -> Unlink is the only reset.",
),
};
let me = format!("{}:{}", ctx.platform(), ctx.user_id());
let em = crate::Embed::new()
.title(title)
.description(body)
.footer(footer)
.color(LINK_COLOR);
let kb = primary_picker_keyboard(
&lang,
&me,
&res.partner,
CB_PRIMARY_ME,
CB_PRIMARY_PARTNER,
);
ctx.reply_with(crate::Reply::embed(em).keyboard(kb)).await
}
Err(e) => {
let (title, desc) = match lang.as_str() {
"ru" => ("\u{274C} Не получилось", format!("{e}")),
_ => ("\u{274C} Link Failed", format!("{e}")),
};
let em = crate::Embed::new()
.title(title)
.description(desc)
.color(ERROR_COLOR);
ctx.reply_with(crate::Reply::embed(em)).await
}
}
}
})
}
/// Handler invoked when an incoming message starts with `/` but doesn't
/// match any registered command. Optional.
pub fn fallback<F, Fut>(mut self, handler: F) -> Self
where
F: Fn(Ctx) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
self.fallback = Some(Handler::new(handler));
self
}
/// List registered commands as `Command` values.
pub fn commands(&self) -> Vec<Command> {
self.commands
.iter()
.map(|(name, slot)| Command::new(name.clone(), slot.handler.clone()))
.collect()
}
/// Snapshot `(name, description, takes_user)` for every registered
/// command. Used by adapters (e.g. Discord) to register native
/// slash-command metadata on the platform side.
#[doc(hidden)]
pub fn command_snapshot(&self) -> Vec<(String, Option<String>, bool)> {
self.commands
.iter()
.map(|(name, slot)| (name.clone(), slot.description.clone(), slot.takes_user))
.collect()
}
/// Run the bot until every platform stops or the task is cancelled.
pub async fn run(self) -> Result<()> {
if self.platforms.is_empty() {
return Err(Error::NoPlatforms);
}
// Snapshot the command metadata before we move `self.commands`
// into the router - Discord adapter uses it to register native
// slash commands with the platform so `/help` shows up in the
// client's autocomplete list.
let commands_meta: Vec<(String, Option<String>, bool)> = self
.commands
.iter()
.map(|(name, slot)| (name.clone(), slot.description.clone(), slot.takes_user))
.collect();
let router = Arc::new(Router {
commands: self
.commands
.into_iter()
.map(|(k, v)| {
(
k,
RouterSlot {
handler: v.handler,
platforms: v.platforms,
},
)
})
.collect(),
text_commands: self
.text_commands
.into_iter()
.map(|t| RouterTextSlot {
pattern: t.pattern,
matcher: t.matcher,
handler: t.handler,
})
.collect(),
fallback: self.fallback,
on_message: self.on_message,
rate_limiter: self.rate_limiter,
on_rate_limited: self.on_rate_limited,
max_update_age: self.max_update_age,
on_flood: self.on_flood,
});
let mut tasks: Vec<BoxFuture<'static, Result<()>>> = Vec::new();
for platform in self.platforms {
let router = Arc::clone(&router);
let name = platform.kind.to_string();
let notifier = self.notifier.clone();
match platform.config {
#[cfg(feature = "telegram")]
PlatformConfig::Telegram { token } => {
let cmds = commands_meta.clone();
let menu_app = self.menu_web_app.clone();
tasks.push(Box::pin(async move {
adapters::telegram::run(token, router, cmds, notifier, menu_app).await
}));
}
#[cfg(not(feature = "telegram"))]
PlatformConfig::Telegram { .. } => {
tracing::warn!(
"Telegram platform configured but the `telegram` feature is off; skipping"
);
}
#[cfg(feature = "discord")]
PlatformConfig::Discord { token } => {
let cmds = commands_meta.clone();
let presence = self.presence.clone();
tasks.push(Box::pin(async move {
adapters::discord::run(token, router, cmds, notifier, presence).await
}));
}
#[cfg(not(feature = "discord"))]
PlatformConfig::Discord { .. } => {
tracing::warn!(
"Discord platform configured but the `discord` feature is off; skipping"
);
}
}
tracing::info!(platform = %name, "adapter registered");
}
if tasks.is_empty() {
return Err(Error::NoPlatforms);
}
// Run every adapter concurrently. The whole bot stops as soon as one
// of them returns - successfully or otherwise.
let (result, _, _rest) = future::select_all(tasks).await;
result
}
}
impl Default for Bot {
fn default() -> Self {
Self::new()
}
}
/// Lowercase a command trigger so registration and dispatch agree on the
/// key. `/Help` and `/help` are the same command.
fn normalize_command_name(name: &str) -> String {
name.to_lowercase()
}
/// Turn a callback-button id into the slash-command name that should
/// handle it.
///
/// Convention:
/// - `foukoapi:<cmd>:<rest>` -> `/<cmd>` (built-in API commands)
/// - `<cmd>:<rest>` -> `/<cmd>` (bot-defined commands)
/// - anything else -> `None`
///
/// Returning `None` just means "I don't know, let the router fall
/// through to the usual text/fallback paths".
fn callback_to_command(data: &str) -> Option<String> {
let first = data.split(':').next()?;
// Unwrap the API-owned prefix so `foukoapi:link:me` also resolves to
// `/link`, not to `/foukoapi`.
let cmd = if first == "foukoapi" {
data.split(':').nth(1)?
} else {
first
};
if cmd.is_empty() {
return None;
}
Some(normalize_command_name(&format!("/{cmd}")))
}
/// Build the `/lang` inline keyboard: one row of up to 3 buttons per
/// chunk, the current language marked with a star.
fn build_lang_keyboard(
supported: &[String],
current: &str,
invoker_id: &str,
cb_prefix: &str,
) -> crate::Keyboard {
let mut kb = crate::Keyboard::new();
for chunk in supported.chunks(3) {
let row: Vec<crate::Button> = chunk
.iter()
.map(|code| {
let marker = if code == current { "\u{2B50} " } else { "" };
let label = format!("{marker}{}", lang_label(code));
crate::Button::callback(label, format!("{cb_prefix}{invoker_id}:{code}"))
})
.collect();
kb = kb.row(row);
}
kb
}
/// Pretty label for a language code, with a flag-ish prefix.
///
/// Covers the handful of codes most bots care about; anything unknown
/// falls back to the upper-cased code so the picker still shows
/// *something*.
fn lang_label(code: &str) -> String {
match code {
"en" => "\u{1F1FA}\u{1F1F8} English".to_owned(),
"ru" => "\u{1F1F7}\u{1F1FA} Русский".to_owned(),
"uk" => "\u{1F1FA}\u{1F1E6} Українська".to_owned(),
"de" => "\u{1F1E9}\u{1F1EA} Deutsch".to_owned(),
"fr" => "\u{1F1EB}\u{1F1F7} Français".to_owned(),
"es" => "\u{1F1EA}\u{1F1F8} Español".to_owned(),
"it" => "\u{1F1EE}\u{1F1F9} Italiano".to_owned(),
"pt" => "\u{1F1F5}\u{1F1F9} Português".to_owned(),
"pl" => "\u{1F1F5}\u{1F1F1} Polski".to_owned(),
"tr" => "\u{1F1F9}\u{1F1F7} Türkçe".to_owned(),
"ja" => "\u{1F1EF}\u{1F1F5} 日本語".to_owned(),
"zh" => "\u{1F1E8}\u{1F1F3} 中文".to_owned(),
"ko" => "\u{1F1F0}\u{1F1F7} 한국어".to_owned(),
other => other.to_ascii_uppercase(),
}
}
// ---------------------------------------------------------------------------
// Built-in `/link` helpers, shared by `with_default_link_command`.
// ---------------------------------------------------------------------------
/// Accent colours used by the built-in `/link` embeds on Discord.
/// Ignored on Telegram/Matrix where there's nothing to paint.
const LINK_COLOR: u32 = 0x5B8DEF;
const ERROR_COLOR: u32 = 0xE74C3C;
/// Pretty platform name for an identity of the form `"platform:id"`.
///
/// Used by `/link` and friends to surface "telegram" / "discord" in
/// place of raw numeric ids, so the user doesn't have to squint at
/// `560024252393455645` to figure out which account is which.
fn platform_of(ident: &str) -> &str {
ident.split(':').next().unwrap_or(ident)
}
/// Render the "linked or not" status screen with an unlink button.
async fn link_status_reply(
ctx: &Ctx,
accounts: &Accounts,
lang: &str,
cb_unlink: &str,
cb_cancel: &str,
) -> Result<()> {
let me = format!("{}:{}", ctx.platform(), ctx.user_id());
let partner = accounts.partner_for(ctx.platform(), ctx.user_id()).await?;
match partner {
Some(p) => {
let (title, platforms_label, foot) = match lang {
"ru" => (
"\u{1F517} Связанные аккаунты",
"Платформы",
"Отвязать можно один раз. После отвязки у партнёрской платформы будет чистый профиль.",
),
_ => (
"\u{1F517} Linked Accounts",
"Platforms",
"You can unlink once. After that the other side starts with a fresh profile.",
),
};
let em = crate::Embed::new()
.title(title)
.field(
platforms_label,
format!(
"**{}** \u{2194} **{}**",
platform_title(platform_of(&me)),
platform_title(platform_of(&p))
),
)
.footer(foot)
.color(LINK_COLOR);
let kb = crate::Keyboard::new().row([crate::Button::callback(
match lang {
"ru" => "\u{1F494} Отвязать",
_ => "\u{1F494} Unlink",
},
cb_unlink,
)]);
ctx.reply_with(crate::Reply::embed(em).keyboard(kb)).await
}
None => {
let code = accounts.start_link(ctx.platform(), ctx.user_id()).await?;
let (title, code_label, how_label, how_value, foot) = match lang {
"ru" => (
"\u{1F517} Код привязки",
"Код",
"Как использовать",
format!("Открой бота на другой платформе и отправь:\n`/link {code}`"),
"Код живёт 5 минут.",
),
_ => (
"\u{1F517} Link Code",
"Code",
"How To Use",
format!("Open the bot on another platform and send:\n`/link {code}`"),
"The code expires in 5 minutes.",
),
};
let em = crate::Embed::new()
.title(title)
.field(code_label, format!("`{code}`"))
.field(how_label, how_value)
.footer(foot)
.color(LINK_COLOR);
let kb = crate::Keyboard::new().row([crate::Button::callback(
match lang {
"ru" => "\u{274C} Отмена",
_ => "\u{274C} Cancel",
},
cb_cancel,
)]);
ctx.reply_with(crate::Reply::embed(em).keyboard(kb)).await
}
}
}
/// Pretty, capitalised form of a platform id ("telegram" -> "Telegram").
fn platform_title(raw: &str) -> String {
let mut chars = raw.chars();
match chars.next() {
Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
None => String::new(),
}
}
/// Two "pick primary" buttons shown once, right after `/link CODE`.
fn primary_picker_keyboard(
lang: &str,
me: &str,
partner: &str,
cb_me: &str,
cb_partner: &str,
) -> crate::Keyboard {
let (me_label, partner_label) = match lang {
"ru" => (
format!("\u{1F4CD} Эта ({})", platform_title(platform_of(me))),
format!(
"\u{1F517} Другая ({})",
platform_title(platform_of(partner))
),
),
_ => (
format!("\u{1F4CD} This ({})", platform_title(platform_of(me))),
format!("\u{1F517} Other ({})", platform_title(platform_of(partner))),
),
};
crate::Keyboard::new().row([
crate::Button::callback(me_label, cb_me),
crate::Button::callback(partner_label, cb_partner),
])
}
/// Shared handler for every `foukoapi:link:*` button.
#[allow(clippy::too_many_arguments)]
async fn handle_link_callback(
ctx: &Ctx,
accounts: &Accounts,
data: &str,
lang: &str,
cb_unlink: &str,
cb_cancel: &str,
cb_primary_me: &str,
cb_primary_partner: &str,
) -> Result<()> {
if data == cb_cancel {
let (title, desc) = match lang {
"ru" => (
"\u{274C} Отменено",
"Запусти /link ещё раз, когда будешь готов.",
),
_ => (
"\u{274C} Cancelled",
"Run /link again whenever you're ready.",
),
};
let em = crate::Embed::new()
.title(title)
.description(desc)
.color(ERROR_COLOR);
return ctx.edit_reply(crate::Reply::embed(em)).await;
}
if data == cb_primary_me || data == cb_primary_partner {
let me = format!("{}:{}", ctx.platform(), ctx.user_id());
let partner = match accounts.partner_for(ctx.platform(), ctx.user_id()).await? {
Some(p) => p,
None => {
let (title, desc) = match lang {
"ru" => ("\u{2753} Нет связки", "Сначала выполни /link CODE."),
_ => ("\u{2753} No Link", "Redeem a /link CODE first."),
};
let em = crate::Embed::new()
.title(title)
.description(desc)
.color(ERROR_COLOR);
return ctx.edit_reply(crate::Reply::embed(em)).await;
}
};
// One-shot guard: once primary is picked, the lock key disables
// further presses from either side. set_nx makes claiming the
// lock atomic, so two racing taps can't both win.
let lock_key = format!("foukoapi:link:primary_locked:{me}");
let partner_lock = format!("foukoapi:link:primary_locked:{partner}");
let partner_already = accounts
.storage_ref()
.get(&partner_lock)
.await
.ok()
.flatten()
.is_some();
let claimed = if partner_already {
false
} else {
match accounts.storage_ref().set_nx(&lock_key, "1").await {
Ok(won) => won,
Err(e) => {
tracing::warn!(error = %e, "link: could not claim primary lock");
let (title, desc) = match lang {
"ru" => (
"\u{274C} Ошибка",
"Не получилось сохранить выбор. Попробуй ещё раз.",
),
_ => ("\u{274C} Error", "Could not save your choice. Try again."),
};
let em = crate::Embed::new()
.title(title)
.description(desc)
.color(ERROR_COLOR);
return ctx.edit_reply(crate::Reply::embed(em)).await;
}
}
};
if !claimed {
let (title, desc) = match lang {
"ru" => (
"\u{1F512} Уже выбрано",
"Основная платформа уже зафиксирована. Поменять можно только через /link -> Отвязать.",
),
_ => (
"\u{1F512} Already Locked",
"The primary is already locked in. You can only change it via /link -> Unlink.",
),
};
let em = crate::Embed::new()
.title(title)
.description(desc)
.color(ERROR_COLOR);
return ctx.edit_reply(crate::Reply::embed(em)).await;
}
let chosen = if data == cb_primary_me {
me.clone()
} else {
partner.clone()
};
accounts
.set_primary(ctx.platform(), ctx.user_id(), &chosen)
.await?;
if let Err(e) = accounts.storage_ref().set(&partner_lock, "1").await {
tracing::warn!(error = %e, "link: could not set partner primary lock");
}
let (title, desc) = match lang {
"ru" => (
"\u{2705} Основная выбрана",
format!(
"Основной аккаунт: **{}**. Поменять больше нельзя - только через /link -> Отвязать.",
platform_title(platform_of(&chosen))
),
),
_ => (
"\u{2705} Primary Locked",
format!(
"Primary: **{}**. It can't be changed anymore - use /link -> Unlink to reset.",
platform_title(platform_of(&chosen))
),
),
};
let em = crate::Embed::new()
.title(title)
.description(desc)
.color(LINK_COLOR);
return ctx.edit_reply(crate::Reply::embed(em)).await;
}
if data == cb_unlink {
let me = format!("{}:{}", ctx.platform(), ctx.user_id());
let partner_before = accounts.partner_for(ctx.platform(), ctx.user_id()).await?;
return match accounts.unlink(ctx.platform(), ctx.user_id()).await? {
Some(partner) => {
// Release the primary-lock markers on both sides.
let _ = accounts
.storage_ref()
.del(&format!("foukoapi:link:primary_locked:{me}"))
.await;
if let Some(p) = partner_before.as_deref() {
let _ = accounts
.storage_ref()
.del(&format!("foukoapi:link:primary_locked:{p}"))
.await;
}
let (title, desc) = match lang {
"ru" => (
"\u{1F494} Отвязано",
format!(
"Больше не связан с **{}**. Основная платформа сохраняет свой профиль, остальные - получают чистый.",
platform_title(platform_of(&partner))
),
),
_ => (
"\u{1F494} Unlinked",
format!(
"No longer linked to **{}**. The primary keeps its profile; the other side starts fresh.",
platform_title(platform_of(&partner))
),
),
};
let em = crate::Embed::new()
.title(title)
.description(desc)
.color(LINK_COLOR);
ctx.edit_reply(crate::Reply::embed(em)).await
}
None => {
let (title, desc) = match lang {
"ru" => ("\u{2753} Нечего отвязывать", "Связанного аккаунта нет."),
_ => ("\u{2753} Nothing To Unlink", "No partner was set."),
};
let em = crate::Embed::new()
.title(title)
.description(desc)
.color(ERROR_COLOR);
ctx.reply_with(crate::Reply::embed(em)).await
}
};
}
Ok(())
}
/// Router used by platform adapters to dispatch incoming updates.
///
/// Not part of the public API surface end-users should rely on - it exists
/// mainly so adapters in [`crate::adapters`] can hold a typed handle to the
/// bot's commands. Treat it as semver-exempt.
#[doc(hidden)]
#[derive(Clone)]
pub struct Router {
pub(crate) commands: HashMap<String, RouterSlot>,
pub(crate) text_commands: Vec<RouterTextSlot>,
pub(crate) fallback: Option<Handler>,
pub(crate) on_message: Vec<Handler>,
pub(crate) rate_limiter: Option<Arc<RateLimiter>>,
pub(crate) on_rate_limited: Option<Handler>,
pub(crate) max_update_age: Option<std::time::Duration>,
pub(crate) on_flood: Option<FloodHook>,
}
impl Router {
/// How stale an update may be before an adapter should drop it, if a
/// limit was configured. Adapters that carry an update timestamp
/// (Telegram) consult this to avoid replaying a backlog after downtime.
#[doc(hidden)]
pub fn max_update_age(&self) -> Option<std::time::Duration> {
self.max_update_age
}
}
#[doc(hidden)]
#[derive(Clone)]
pub(crate) struct RouterSlot {
pub(crate) handler: Handler,
pub(crate) platforms: Option<Vec<crate::PlatformKind>>,
}
#[doc(hidden)]
#[derive(Clone)]
pub(crate) struct RouterTextSlot {
pub(crate) pattern: String,
pub(crate) matcher: TextMatch,
pub(crate) handler: Handler,
}
/// Boxed flood-alert callback: gets the update count for the window.
pub(crate) type FloodHandler = Arc<dyn Fn(u64) -> BoxFuture<'static, ()> + Send + Sync + 'static>;
/// The flood watchdog wiring carried from [`Bot::on_flood`] to the router.
#[derive(Clone)]
pub(crate) struct FloodHook {
pub(crate) window: FloodWindow,
pub(crate) handler: FloodHandler,
}
/// A fixed 60-second counting window with a fire cooldown.
///
/// Every incoming update calls [`FloodWindow::hit`]; when the count inside
/// the current window crosses the threshold, `hit` returns `Some(count)` -
/// but at most once per cooldown, so an ongoing flood alerts once instead
/// of on every message. Clones share state, matching how the router is
/// cloned per adapter.
#[derive(Clone)]
pub(crate) struct FloodWindow {
inner: Arc<FloodWindowInner>,
}
struct FloodWindowInner {
/// Alert threshold: strictly more than this many hits per window fires.
per_minute: u64,
/// Minimum gap between two alerts.
cooldown: std::time::Duration,
/// Hits in the current window.
count: std::sync::atomic::AtomicU64,
/// Window start and last-alert bookkeeping.
state: std::sync::Mutex<FloodState>,
}
struct FloodState {
window_start: std::time::Instant,
last_fired: Option<std::time::Instant>,
}
/// Length of the counting window.
const FLOOD_WINDOW: std::time::Duration = std::time::Duration::from_secs(60);
impl FloodWindow {
pub(crate) fn new(per_minute: u32, cooldown: std::time::Duration) -> Self {
Self {
inner: Arc::new(FloodWindowInner {
per_minute: u64::from(per_minute),
cooldown,
count: std::sync::atomic::AtomicU64::new(0),
state: std::sync::Mutex::new(FloodState {
window_start: std::time::Instant::now(),
last_fired: None,
}),
}),
}
}
/// Count one update at `now`. Returns `Some(count)` when the window
/// total just crossed the threshold and the cooldown allows an alert.
pub(crate) fn hit(&self, now: std::time::Instant) -> Option<u64> {
let mut state = match self.inner.state.lock() {
Ok(s) => s,
// A poisoned lock must not wedge dispatch; skip the check.
Err(poisoned) => poisoned.into_inner(),
};
if now.duration_since(state.window_start) >= FLOOD_WINDOW {
state.window_start = now;
self.inner
.count
.store(0, std::sync::atomic::Ordering::Relaxed);
}
let count = self
.inner
.count
.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
+ 1;
if count <= self.inner.per_minute {
return None;
}
let cooled = match state.last_fired {
Some(t) => now.duration_since(t) >= self.inner.cooldown,
None => true,
};
if !cooled {
return None;
}
state.last_fired = Some(now);
Some(count)
}
}
impl Router {
/// Dispatch an incoming message. First runs every `on_message` hook
/// (errors are logged, not propagated), then tries slash commands,
/// then plain-text triggers, then the fallback.
///
/// Button presses land here too: adapters populate
/// [`Ctx::callback_data`] with the id of the pressed button. We route
/// those to a command by convention - a callback id that looks like
/// `foukoapi:link:me` or `something:xyz` is mapped to the command
/// that "owns" it (`/link` and `/something`), so a single handler
/// serves both typed text and inline taps.
#[doc(hidden)]
pub async fn dispatch(&self, ctx: Ctx) -> Result<()> {
// Flood watchdog first, before any per-user limiting, so the count
// reflects the raw incoming flow. The alert handler is spawned so
// a slow one (posting to an ops channel, say) can't stall dispatch.
if let Some(flood) = &self.on_flood {
if let Some(count) = flood.window.hit(std::time::Instant::now()) {
let handler = Arc::clone(&flood.handler);
tokio::spawn(async move {
handler(count).await;
});
}
}
// Rate limit before anything else - including the on_message hooks
// - so a flood can't farm XP, hammer handlers, or pile up work. We
// key on platform + user so one noisy user can't throttle everyone
// else. On the first deny of a window we optionally let a handler
// tell them to slow down; further denials in the same window are
// dropped silently so the bot doesn't answer every flood message.
if let Some(limiter) = &self.rate_limiter {
let key = format!("{}:{}", ctx.platform(), ctx.user_id());
if let crate::ratelimit::Decision::Deny { first, .. } = limiter.check(&key) {
if first {
if let Some(hook) = &self.on_rate_limited {
// Best effort: a failure here must not escalate.
if let Err(e) = hook.call(ctx).await {
tracing::debug!(error = %e, "on_rate_limited hook error");
}
}
}
return Ok(());
}
}
for hook in &self.on_message {
if let Err(e) = hook.call(ctx.clone()).await {
tracing::debug!(error = %e, "on_message hook error");
}
}
// Button-callback path: try to find a command whose name matches
// the callback prefix. Supports `<cmd>:<rest>` and the API-owned
// `foukoapi:<cmd>:<rest>`. If we find a match, run its handler
// and return; otherwise fall through to text dispatch.
if let Some(data) = ctx.callback_data() {
if let Some(cmd_name) = callback_to_command(data) {
if let Some(slot) = self.commands.get(&cmd_name) {
if let Some(allowed) = &slot.platforms {
if !allowed.contains(&ctx.platform()) {
return Ok(());
}
}
return slot.handler.call(ctx).await;
}
}
}
let text = ctx.text().trim();
// Slash commands first. Match case-insensitively so `/Help` from a
// phone keyboard's auto-capitalisation still lands on `/help`.
if text.starts_with('/') {
let cmd_word = text.split_whitespace().next().unwrap_or("");
let cmd_clean = cmd_word.split('@').next().unwrap_or(cmd_word);
let cmd_key = normalize_command_name(cmd_clean);
if let Some(slot) = self.commands.get(&cmd_key) {
if let Some(allowed) = &slot.platforms {
if !allowed.contains(&ctx.platform()) {
return Ok(());
}
}
return slot.handler.call(ctx).await;
}
if let Some(fallback) = &self.fallback {
return fallback.call(ctx).await;
}
return Ok(());
}
// Plain-text triggers.
let lower = text.to_lowercase();
for slot in &self.text_commands {
let hit = match slot.matcher {
TextMatch::Exact => lower == slot.pattern,
TextMatch::Prefix => lower.starts_with(&slot.pattern),
TextMatch::Contains => lower.contains(&slot.pattern),
};
if hit {
return slot.handler.call(ctx).await;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::FloodWindow;
use std::time::{Duration, Instant};
#[test]
fn under_the_threshold_stays_quiet() {
let w = FloodWindow::new(5, Duration::from_secs(60));
let now = Instant::now();
for _ in 0..5 {
assert_eq!(w.hit(now), None);
}
}
#[test]
fn crossing_the_threshold_fires_with_the_count() {
let w = FloodWindow::new(3, Duration::from_secs(60));
let now = Instant::now();
for _ in 0..3 {
assert_eq!(w.hit(now), None);
}
assert_eq!(w.hit(now), Some(4));
}
#[test]
fn cooldown_suppresses_repeat_alerts() {
let w = FloodWindow::new(2, Duration::from_secs(60));
let now = Instant::now();
w.hit(now);
w.hit(now);
assert_eq!(w.hit(now), Some(3));
// Still flooding, but within cooldown: quiet.
assert_eq!(w.hit(now), None);
assert_eq!(w.hit(now), None);
}
#[test]
fn cooldown_expiry_allows_another_alert() {
let w = FloodWindow::new(1, Duration::from_secs(10));
let now = Instant::now();
w.hit(now);
assert_eq!(w.hit(now), Some(2));
assert_eq!(w.hit(now), None);
// 10s later: same window (60s), still over threshold, cooldown over.
let later = now + Duration::from_secs(10);
assert_eq!(w.hit(later), Some(4));
}
#[test]
fn a_new_window_resets_the_count() {
let w = FloodWindow::new(2, Duration::from_secs(0));
let now = Instant::now();
w.hit(now);
w.hit(now);
assert_eq!(w.hit(now), Some(3));
// Next minute: counting starts over.
let next = now + Duration::from_secs(60);
assert_eq!(w.hit(next), None);
assert_eq!(w.hit(next), None);
assert_eq!(w.hit(next), Some(3));
}
}