twilight_validate/request.rs
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 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
//! Contains all other input validation functions.
//!
//! These functions are generally not related to a specific Discord model.
use std::{
error::Error,
fmt::{Display, Formatter, Result as FmtResult},
time::{SystemTime, UNIX_EPOCH},
};
use twilight_model::id::marker::{ChannelMarker, RoleMarker};
use twilight_model::id::Id;
use twilight_model::util::Timestamp;
/// The maximum audit log reason length in UTF-16 codepoints.
pub const AUDIT_REASON_MAX: usize = 512;
/// Maximum length of an auto moderation block action's custom message.
pub const AUTO_MODERATION_ACTION_BLOCK_CUSTOM_MESSAGE_LENGTH_MAX: usize = 150;
/// Maximum amount of mentions that triggers an auto moderation action.
pub const AUTO_MODERATION_METADATA_MENTION_TOTAL_LIMIT: u8 = 50;
/// Maximum amount of keywords allowed in the keyword filter.
pub const AUTO_MODERATION_METADATA_KEYWORD_FILTER_MAX: usize = 1000;
/// Maximum length of a keyword in the keyword filter.
pub const AUTO_MODERATION_METADATA_KEYWORD_FILTER_LENGTH_MAX: usize = 60;
/// Maximum amount of allowed keywords when using the custom keywords.
pub const AUTO_MODERATION_METADATA_KEYWORD_ALLOW_LIST_MAX: usize = 100;
/// Maximum amount of allowed keywords when using a keyword preset.
pub const AUTO_MODERATION_METADATA_PRESET_ALLOW_LIST_MAX: usize = 1000;
/// Maximum length of a keyword preset keyword.
pub const AUTO_MODERATION_METADATA_PRESET_ALLOW_LIST_LENGTH_MAX: usize = 60;
/// Maximum length of a allowed keyword.
pub const AUTO_MODERATION_METADATA_KEYWORD_ALLOW_LIST_LENGTH_MAX: usize = 60;
/// Maximum amount of regex patterns that trigger the auto moderation.
pub const AUTO_MODERATION_METADATA_REGEX_PATTERNS_MAX: usize = 10;
/// Maximum length of a regex pattern.
pub const AUTO_MODERATION_METADATA_REGEX_PATTERNS_LENGTH_MAX: usize = 260;
/// Maximum amount of seconds (`2_419_200` this is equivalent to `28` days) to disable communication for.
pub const AUTO_MODERATION_ACTION_METADATA_DURATION_SECONDS_MAX: u32 = 2_419_200;
/// Maximum amount of exempt roles for the auto moderation rule.
pub const AUTO_MODERATION_EXEMPT_ROLES_MAX: usize = 20;
/// Maximum amount of exempt channels for the auto moderation rule.
pub const AUTO_MODERATION_EXEMPT_CHANNELS_MAX: usize = 50;
/// Maximum amount of seconds (`604_800` this is equivalent to `7` days) for messages to be deleted upon ban.
pub const CREATE_GUILD_BAN_DELETE_MESSAGE_SECONDS_MAX: u32 = 604_800;
/// Maximum amount of time a member can be timed out for.
pub const COMMUNICATION_DISABLED_MAX_DURATION: i64 = 28 * 24 * 60 * 60;
/// Maximum amount of messages to get.
pub const GET_CHANNEL_MESSAGES_LIMIT_MAX: u16 = 100;
/// Minimum amount of messages to get.
pub const GET_CHANNEL_MESSAGES_LIMIT_MIN: u16 = 1;
/// Maximum amount of guilds to get.
pub const GET_CURRENT_USER_GUILDS_LIMIT_MAX: u16 = 200;
/// Minimum amount of guilds to get.
pub const GET_CURRENT_USER_GUILDS_LIMIT_MIN: u16 = 1;
/// Maximum amount of entitlements to get.
pub const GET_ENTITLEMENTS_LIMIT_MAX: u8 = 100;
/// Minimum amount of entitlements to get.
pub const GET_ENTITLEMENTS_LIMIT_MIN: u8 = 1;
/// Maximum amount of audit log entries to list.
pub const GET_GUILD_AUDIT_LOG_LIMIT_MAX: u16 = 100;
/// Minimum amount of audit log entries to list.
pub const GET_GUILD_AUDIT_LOG_LIMIT_MIN: u16 = 1;
/// Maximum amount of guild bans to list.
pub const GET_GUILD_BANS_LIMIT_MAX: u16 = 1000;
/// Maximum amount of guild members to list.
pub const GET_GUILD_MEMBERS_LIMIT_MAX: u16 = 1000;
/// Minimum amount of guild members to list.
pub const GET_GUILD_MEMBERS_LIMIT_MIN: u16 = 1;
/// Maximum amount of users to return when getting reactions.
pub const GET_REACTIONS_LIMIT_MIN: u16 = 1;
/// Minimum amount of users to return when getting reactions.
pub const GET_REACTIONS_LIMIT_MAX: u16 = 100;
/// Maximum length of a guild's name.
pub const GUILD_NAME_LENGTH_MAX: usize = 100;
/// Minimum length of a guild's name.
pub const GUILD_NAME_LENGTH_MIN: usize = 2;
/// Maximum amount of days to prune users from a guild.
pub const GUILD_PRUNE_DAYS_MAX: u16 = 30;
/// Minimum amount of days to prune users from a guild.
pub const GUILD_PRUNE_DAYS_MIN: u16 = 1;
/// Maximum length of an invite's age, in seconds.
pub const INVITE_AGE_MAX: u32 = 604_800;
/// Maximum uses of an invite, if not unlimited.
pub const INVITE_USES_MAX: u16 = 100;
/// Maximum length of a maximum.
pub const NICKNAME_LIMIT_MAX: usize = 32;
/// Minimum length of a nickname.
pub const NICKNAME_LIMIT_MIN: usize = 1;
/// Maximum length of a scheduled event's description.
pub const SCHEDULED_EVENT_DESCRIPTION_MAX: usize = 1000;
/// Minimum length of a scheduled event's description.
pub const SCHEDULED_EVENT_DESCRIPTION_MIN: usize = 1;
/// Maximum amount of scheduled event users to get.
pub const SCHEDULED_EVENT_GET_USERS_MAX: u16 = 100;
/// Minimum amount of scheduled event users to get.
pub const SCHEDULED_EVENT_GET_USERS_MIN: u16 = 1;
/// Maximum length of a scheduled event's name.
pub const SCHEDULED_EVENT_NAME_MAX: usize = 100;
/// Minimum length of a scheduled event's name.
pub const SCHEDULED_EVENT_NAME_MIN: usize = 1;
/// Maximum amount of guild members to search for.
pub const SEARCH_GUILD_MEMBERS_LIMIT_MAX: u16 = 1000;
/// Minimum amount of guild members to search for.
pub const SEARCH_GUILD_MEMBERS_LIMIT_MIN: u16 = 1;
/// Maximum stage instance topic length.
pub const STAGE_TOPIC_LENGTH_MAX: usize = 120;
/// Minimum stage instance topic length.
pub const STAGE_TOPIC_LENGTH_MIN: usize = 1;
/// Maximum length of a guild template description.
pub const TEMPLATE_DESCRIPTION_LENGTH_MAX: usize = 120;
/// Maximum length of a guild template name.
pub const TEMPLATE_NAME_LENGTH_MAX: usize = 100;
/// Minimum length of a guild template name.
pub const TEMPLATE_NAME_LENGTH_MIN: usize = 1;
/// Maximum length of a username.
pub const USERNAME_LIMIT_MAX: usize = 32;
/// Minimum length of a username.
pub const USERNAME_LIMIT_MIN: usize = 2;
/// Maximum length of a webhook username.
pub const WEBHOOK_USERNAME_LIMIT_MAX: usize = 80;
/// Minimum length of a webhook username.
pub const WEBHOOK_USERNAME_LIMIT_MIN: usize = 2;
/// Forbidden substrings in usernames.
const USERNAME_INVALID_SUBSTRINGS: [&str; 5] = ["@", "#", ":", "```", "discord"];
/// Forbidden usernames.
const USERNAME_INVALID_STRINGS: [&str; 2] = ["everyone", "here"];
/// Forbidden webhook usernames.
const WEBHOOK_INVALID_STRINGS: [&str; 1] = ["clyde"];
/// A field is not valid.
#[derive(Debug)]
pub struct ValidationError {
/// Type of error that occurred.
kind: ValidationErrorType,
}
impl ValidationError {
/// Immutable reference to the type of error that occurred.
#[must_use = "retrieving the type has no effect if left unused"]
pub const fn kind(&self) -> &ValidationErrorType {
&self.kind
}
/// Consume the error, returning the source error if there is any.
#[allow(clippy::unused_self)]
#[must_use = "consuming the error and retrieving the source has no effect if left unused"]
pub fn into_source(self) -> Option<Box<dyn Error + Send + Sync>> {
None
}
/// Consume the error, returning the owned error type and the source error.
#[must_use = "consuming the error into its parts has no effect if left unused"]
pub fn into_parts(self) -> (ValidationErrorType, Option<Box<dyn Error + Send + Sync>>) {
(self.kind, None)
}
}
impl Display for ValidationError {
#[allow(clippy::too_many_lines)]
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match &self.kind {
ValidationErrorType::AuditReason { len } => {
f.write_str("provided audit reason length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUDIT_REASON_MAX, f)
}
ValidationErrorType::AutoModerationBlockActionCustomMessageLimit { len } => {
f.write_str("provided auto moderation block action custom message length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_ACTION_BLOCK_CUSTOM_MESSAGE_LENGTH_MAX, f)
}
ValidationErrorType::AutoModerationMetadataMentionTotalLimit { limit } => {
f.write_str("provided auto moderation metadata mention_total_limit is ")?;
Display::fmt(limit, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_METADATA_MENTION_TOTAL_LIMIT, f)
}
ValidationErrorType::AutoModerationMetadataAllowList { len } => {
f.write_str("provided auto moderation metadata allow_list length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_METADATA_KEYWORD_ALLOW_LIST_MAX, f)
}
ValidationErrorType::AutoModerationMetadataAllowListItem { len, substring } => {
f.write_str("provided auto moderation metadata allow_list item ")?;
Display::fmt(substring, f)?;
f.write_str(" length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_METADATA_KEYWORD_ALLOW_LIST_LENGTH_MAX, f)
}
ValidationErrorType::AutoModerationMetadataKeywordFilter { len } => {
f.write_str("provided auto moderation metadata keyword_filter length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_METADATA_KEYWORD_FILTER_MAX, f)
}
ValidationErrorType::AutoModerationMetadataKeywordFilterItem { len, substring } => {
f.write_str("provided auto moderation metadata keyword_filter item ")?;
Display::fmt(substring, f)?;
f.write_str(" length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_METADATA_KEYWORD_FILTER_LENGTH_MAX, f)
}
ValidationErrorType::AutoModerationMetadataPresetAllowList { len } => {
f.write_str("provided auto moderation metadata allow_list length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_METADATA_PRESET_ALLOW_LIST_MAX, f)
}
ValidationErrorType::AutoModerationMetadataPresetAllowListItem { len, substring } => {
f.write_str("provided auto moderation metadata allow_list item ")?;
Display::fmt(substring, f)?;
f.write_str(" length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_METADATA_PRESET_ALLOW_LIST_LENGTH_MAX, f)
}
ValidationErrorType::AutoModerationActionMetadataDurationSeconds { seconds } => {
f.write_str("provided auto moderation action timeout duration is ")?;
Display::fmt(seconds, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_ACTION_METADATA_DURATION_SECONDS_MAX, f)
}
ValidationErrorType::AutoModerationMetadataRegexPatterns { len } => {
f.write_str("provided auto moderation metadata regex_patterns length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_METADATA_REGEX_PATTERNS_MAX, f)
}
ValidationErrorType::AutoModerationMetadataRegexPatternsItem { len, substring } => {
f.write_str("provided auto moderation metadata regex_patterns item ")?;
Display::fmt(substring, f)?;
f.write_str(" length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_METADATA_REGEX_PATTERNS_LENGTH_MAX, f)
}
ValidationErrorType::AutoModerationExemptRoles { len } => {
f.write_str("provided auto moderation exempt_roles length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_EXEMPT_ROLES_MAX, f)
}
ValidationErrorType::AutoModerationExemptChannels { len } => {
f.write_str("provided auto moderation exempt_channels length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&AUTO_MODERATION_EXEMPT_CHANNELS_MAX, f)
}
ValidationErrorType::CreateGuildBanDeleteMessageSeconds {
seconds: delete_message_seconds,
} => {
f.write_str("provided create guild ban delete_message_seconds is ")?;
Display::fmt(delete_message_seconds, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&CREATE_GUILD_BAN_DELETE_MESSAGE_SECONDS_MAX, f)
}
ValidationErrorType::CommunicationDisabledUntil { .. } => {
f.write_str("provided timestamp is too far in the future")
}
ValidationErrorType::GetChannelMessages { limit } => {
f.write_str("provided get guild members limit is ")?;
Display::fmt(limit, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&GET_CHANNEL_MESSAGES_LIMIT_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&GET_CHANNEL_MESSAGES_LIMIT_MAX, f)
}
ValidationErrorType::GetCurrentUserGuilds { limit } => {
f.write_str("provided get current user guilds limit is ")?;
Display::fmt(limit, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&GET_CURRENT_USER_GUILDS_LIMIT_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&GET_CURRENT_USER_GUILDS_LIMIT_MAX, f)
}
ValidationErrorType::GetEntitlements { limit } => {
f.write_str("provided get entitlements limit is ")?;
Display::fmt(limit, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&GET_ENTITLEMENTS_LIMIT_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&GET_ENTITLEMENTS_LIMIT_MAX, f)
}
ValidationErrorType::GetGuildAuditLog { limit } => {
f.write_str("provided get guild audit log limit is ")?;
Display::fmt(limit, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&GET_GUILD_MEMBERS_LIMIT_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&GET_GUILD_MEMBERS_LIMIT_MAX, f)
}
ValidationErrorType::GetGuildBans { limit } => {
f.write_str("provided get guild bans limit is ")?;
Display::fmt(limit, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&GET_GUILD_BANS_LIMIT_MAX, f)
}
ValidationErrorType::GetGuildMembers { limit } => {
f.write_str("provided get guild members limit is ")?;
Display::fmt(limit, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&GET_GUILD_MEMBERS_LIMIT_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&GET_GUILD_MEMBERS_LIMIT_MAX, f)
}
ValidationErrorType::GetReactions { limit } => {
f.write_str("provided get reactions limit is ")?;
Display::fmt(limit, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&GET_REACTIONS_LIMIT_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&GET_REACTIONS_LIMIT_MAX, f)
}
ValidationErrorType::GuildName { len } => {
f.write_str("provided guild name length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&GUILD_NAME_LENGTH_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&GUILD_NAME_LENGTH_MAX, f)
}
ValidationErrorType::GuildPruneDays { days } => {
f.write_str("provided prune days is ")?;
Display::fmt(days, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&GUILD_PRUNE_DAYS_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&GUILD_PRUNE_DAYS_MAX, f)
}
ValidationErrorType::InviteMaxAge { max_age } => {
f.write_str("provided invite max_age is ")?;
Display::fmt(max_age, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&INVITE_AGE_MAX, f)
}
ValidationErrorType::InviteMaxUses { max_uses } => {
f.write_str("provided invite max_uses is ")?;
Display::fmt(max_uses, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&INVITE_USES_MAX, f)
}
ValidationErrorType::Nickname { len } => {
f.write_str("provided nickname length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&NICKNAME_LIMIT_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&NICKNAME_LIMIT_MAX, f)
}
ValidationErrorType::ScheduledEventDescription { len } => {
f.write_str("provided scheduled event description is length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&SCHEDULED_EVENT_DESCRIPTION_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&SCHEDULED_EVENT_DESCRIPTION_MAX, f)
}
ValidationErrorType::ScheduledEventGetUsers { limit } => {
f.write_str("provided scheduled event get users limit is ")?;
Display::fmt(limit, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&SCHEDULED_EVENT_GET_USERS_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&SCHEDULED_EVENT_GET_USERS_MAX, f)
}
ValidationErrorType::ScheduledEventName { len } => {
f.write_str("provided scheduled event name is length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&SCHEDULED_EVENT_NAME_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&SCHEDULED_EVENT_NAME_MAX, f)
}
ValidationErrorType::SearchGuildMembers { limit } => {
f.write_str("provided search guild members limit is ")?;
Display::fmt(limit, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&SEARCH_GUILD_MEMBERS_LIMIT_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&SEARCH_GUILD_MEMBERS_LIMIT_MAX, f)
}
ValidationErrorType::StageTopic { len } => {
f.write_str("provided stage instance topic length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&STAGE_TOPIC_LENGTH_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&STAGE_TOPIC_LENGTH_MAX, f)
}
ValidationErrorType::TemplateDescription { len } => {
f.write_str("provided guild template description topic length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at most ")?;
Display::fmt(&TEMPLATE_DESCRIPTION_LENGTH_MAX, f)
}
ValidationErrorType::TemplateName { len } => {
f.write_str("provided guild template name length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&TEMPLATE_NAME_LENGTH_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&TEMPLATE_NAME_LENGTH_MAX, f)
}
ValidationErrorType::Username { len, substring }
| ValidationErrorType::WebhookUsername { len, substring } => {
f.write_str("provided username")?;
if let Some(len) = len {
f.write_str(" length is ")?;
Display::fmt(len, f)?;
f.write_str(", but it must be at least ")?;
Display::fmt(&USERNAME_LIMIT_MIN, f)?;
f.write_str(" and at most ")?;
Display::fmt(&USERNAME_LIMIT_MAX, f)?;
}
if let Some(substring) = substring {
if len.is_some() {
f.write_str(", and")?;
}
f.write_str(" cannot contain ")?;
Display::fmt(substring, f)?;
}
Ok(())
}
}
}
}
impl Error for ValidationError {}
/// Type of [`ValidationError`] that occurred.
#[derive(Debug)]
pub enum ValidationErrorType {
/// Provided audit reason was too large.
AuditReason {
/// Invalid length.
len: usize,
},
/// Provided block action custom message was too long.
AutoModerationBlockActionCustomMessageLimit {
/// Invalid limit.
len: usize,
},
/// Provided limit was too large.
AutoModerationMetadataMentionTotalLimit {
/// Invalid limit.
limit: u8,
},
/// Provided keyword filter was invalid.
AutoModerationMetadataKeywordFilter {
/// Invalid length.
len: usize,
},
/// Provided keyword was invalid.
AutoModerationMetadataKeywordFilterItem {
/// Invalid length.
len: usize,
/// Invalid substring.
substring: String,
},
/// Provided keyword allow list was invalid.
AutoModerationMetadataAllowList {
/// Invalid length.
len: usize,
},
/// Provided allow list item was invalid.
AutoModerationMetadataAllowListItem {
/// Invalid length.
len: usize,
/// Invalid substring.
substring: String,
},
/// Provided keyword preset allow list was invalid.
AutoModerationMetadataPresetAllowList {
/// Invalid length.
len: usize,
},
/// Provided keyword preset allow list item was invalid.
AutoModerationMetadataPresetAllowListItem {
/// Invalid length.
len: usize,
/// Invalid substring.
substring: String,
},
/// Provided seconds to disable communication was invalid.
AutoModerationActionMetadataDurationSeconds {
/// Invalid seconds.
seconds: u32,
},
/// Provided regex patterns was invalid.
AutoModerationMetadataRegexPatterns {
/// Invalid length.
len: usize,
},
/// Provided regex patterns item was invalid.
AutoModerationMetadataRegexPatternsItem {
/// Invalid length.
len: usize,
/// Invalid substring.
substring: String,
},
/// Provided exempt roles was invalid.
AutoModerationExemptRoles {
/// Invalid length.
len: usize,
},
/// Provided exempt channels was invalid.
AutoModerationExemptChannels {
/// Invalid length.
len: usize,
},
/// Provided create guild ban delete message seconds was invalid.
CreateGuildBanDeleteMessageSeconds {
/// Invalid seconds.
seconds: u32,
},
/// Provided timestamp is too far in the future.
CommunicationDisabledUntil {
/// Invalid timestamp.
timestamp: Timestamp,
},
/// Provided get channel messages limit was invalid.
GetChannelMessages {
/// Invalid limit.
limit: u16,
},
/// Provided get current user guilds limit was invalid.
GetCurrentUserGuilds {
/// Invalid limit.
limit: u16,
},
/// Provided get entitlements limit was invalid.
GetEntitlements {
/// Invalid limit.
limit: u8,
},
/// Provided get guild audit log limit was invalid.
GetGuildAuditLog {
/// Invalid limit.
limit: u16,
},
/// Provided get guild bans limit was invalid.
GetGuildBans {
/// Invalid limit.
limit: u16,
},
/// Provided get guild members limit was invalid.
GetGuildMembers {
/// Invalid limit.
limit: u16,
},
/// Provided get reactions limit was invalid.
GetReactions {
/// Invalid limit.
limit: u16,
},
/// Provided guild name was invalid.
GuildName {
/// Invalid length.
len: usize,
},
/// Provided guild prune days was invalid.
GuildPruneDays {
/// Invalid days.
days: u16,
},
/// Provided invite max age was invalid.
InviteMaxAge {
/// Invalid age.
max_age: u32,
},
/// Provided invite max uses was invalid.
InviteMaxUses {
/// Invalid age.
max_uses: u16,
},
/// Provided nickname length was invalid.
Nickname {
/// Invalid length.
len: usize,
},
/// Scheduled event description is invalid.
ScheduledEventDescription {
/// Invalid length.
len: usize,
},
/// Scheduled event get users limit is invalid.
ScheduledEventGetUsers {
/// Invalid limit.
limit: u16,
},
/// Scheduled event name is invalid.
ScheduledEventName {
/// Invalid length.
len: usize,
},
/// Provided search guild members limit was invalid.
SearchGuildMembers {
/// Invalid limit.
limit: u16,
},
/// Provided stage instance topic was invalid.
StageTopic {
/// Invalid length.
len: usize,
},
/// Provided guild template description was invalid.
TemplateDescription {
/// Invalid length.
len: usize,
},
/// Provided guild template name was invalid.
TemplateName {
/// Invalid length.
len: usize,
},
/// Provided username was invalid.
Username {
/// Invalid length.
len: Option<usize>,
/// Invalid substring.
substring: Option<&'static str>,
},
/// Provided webhook username was invalid.
WebhookUsername {
/// Invalid length.
len: Option<usize>,
/// Invalid substring.
substring: Option<&'static str>,
},
}
/// Ensure that an audit reason is correct.
///
/// The length must be at most [`AUDIT_REASON_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AuditReason`] if the length is invalid.
///
/// [`AuditReason`]: ValidationErrorType::AuditReason
/// [this documentation entry]: https://discord.com/developers/docs/resources/audit-log#audit-log-entry-object-audit-log-entry-structure
pub fn audit_reason(audit_reason: impl AsRef<str>) -> Result<(), ValidationError> {
let len = audit_reason.as_ref().chars().count();
if len <= AUDIT_REASON_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AuditReason { len },
})
}
}
/// Ensure that an auto moderation block action's `custom_message` is correct.
///
/// The length must be at most [`AUTO_MODERATION_ACTION_BLOCK_CUSTOM_MESSAGE_LENGTH_MAX`].
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationBlockActionCustomMessageLimit`] if the
/// length is invalid.
///
/// [`AutoModerationBlockActionCustomMessageLimit`]: ValidationErrorType::AutoModerationBlockActionCustomMessageLimit
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-action-object-action-metadata
pub fn auto_moderation_block_action_custom_message_limit(
custom_message: impl AsRef<str>,
) -> Result<(), ValidationError> {
let len = custom_message.as_ref().chars().count();
if len <= AUTO_MODERATION_ACTION_BLOCK_CUSTOM_MESSAGE_LENGTH_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationBlockActionCustomMessageLimit { len },
})
}
}
/// Ensure that an auto moderation rule's `mention_total_limit` is correct.
///
/// The length must be at most [`AUTO_MODERATION_METADATA_MENTION_TOTAL_LIMIT`].
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationMetadataMentionTotalLimit`] if the
/// length is invalid.
///
/// [`AutoModerationMetadataMentionTotalLimit`]: ValidationErrorType::AutoModerationMetadataMentionTotalLimit
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata
pub const fn auto_moderation_metadata_mention_total_limit(
limit: u8,
) -> Result<(), ValidationError> {
if limit <= AUTO_MODERATION_METADATA_MENTION_TOTAL_LIMIT {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationMetadataMentionTotalLimit { limit },
})
}
}
/// Ensure that an auto moderation rule's `keyword_filter` is correct.
///
/// The length must be at most [`AUTO_MODERATION_METADATA_KEYWORD_FILTER_LENGTH_MAX`].
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationMetadataKeywordFilter`] if the
/// length is invalid.
///
/// Returns an error of type [`AutoModerationMetadataKeywordFilterItem`] if any
/// of the keywords are invalid.
///
/// [`AutoModerationMetadataKeywordFilter`]: ValidationErrorType::AutoModerationMetadataKeywordFilter
/// [`AutoModerationMetadataKeywordFilterItem`]: ValidationErrorType::AutoModerationMetadataKeywordFilterItem
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata-field-limits
pub fn auto_moderation_metadata_keyword_filter(
keywords: &[impl AsRef<str>],
) -> Result<(), ValidationError> {
let len = keywords.len();
if len <= AUTO_MODERATION_METADATA_KEYWORD_FILTER_MAX {
for keyword in keywords {
auto_moderation_metadata_keyword_filter_item(keyword)?;
}
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationMetadataKeywordFilter { len },
})
}
}
/// Ensure that an auto moderation rule's `keyword_filter` item is correct.
///
/// The length must be at most [`AUTO_MODERATION_METADATA_KEYWORD_FILTER_LENGTH_MAX`].
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationMetadataKeywordFilterItem`] if the
/// length is invalid.
///
/// [`AutoModerationMetadataKeywordFilterItem`]: ValidationErrorType::AutoModerationMetadataKeywordFilterItem
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata-field-limits
pub fn auto_moderation_metadata_keyword_filter_item(
keyword: impl AsRef<str>,
) -> Result<(), ValidationError> {
let len = keyword.as_ref().chars().count();
if len <= AUTO_MODERATION_METADATA_KEYWORD_FILTER_LENGTH_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationMetadataKeywordFilterItem {
len,
substring: keyword.as_ref().to_string(),
},
})
}
}
/// Ensure that an auto moderation rule's `allow_list` is correct.
///
/// The length must be at most [`AUTO_MODERATION_METADATA_PRESET_ALLOW_LIST_MAX`].
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationMetadataAllowList`] if the
/// length is invalid.
///
/// Returns an error of type [`AutoModerationMetadataAllowListItem`] if any of
/// the items are invalid.
///
/// [`AutoModerationMetadataAllowList`]: ValidationErrorType::AutoModerationMetadataAllowList
/// [`AutoModerationMetadataAllowListItem`]: ValidationErrorType::AutoModerationMetadataAllowListItem
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata-field-limits
pub fn auto_moderation_metadata_keyword_allow_list(
keywords: &[impl AsRef<str>],
) -> Result<(), ValidationError> {
let len = keywords.len();
if len <= AUTO_MODERATION_METADATA_KEYWORD_ALLOW_LIST_MAX {
for keyword in keywords {
auto_moderation_metadata_keyword_allow_list_item(keyword)?;
}
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationMetadataAllowList { len },
})
}
}
/// Ensure that an auto moderation rule's `allow_list` item is correct.
///
/// The length must be at most [`AUTO_MODERATION_METADATA_PRESET_ALLOW_LIST_MAX`].
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationMetadataAllowListItem`] if the
/// length is invalid.
///
/// [`AutoModerationMetadataAllowListItem`]: ValidationErrorType::AutoModerationMetadataAllowListItem
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata-field-limits
pub fn auto_moderation_metadata_keyword_allow_list_item(
keyword: impl AsRef<str>,
) -> Result<(), ValidationError> {
let len = keyword.as_ref().chars().count();
if len <= AUTO_MODERATION_METADATA_KEYWORD_FILTER_LENGTH_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationMetadataAllowListItem {
len,
substring: keyword.as_ref().to_string(),
},
})
}
}
/// Ensure that an auto moderation rule's `allow_list` is correct when using presets.
///
/// The length must be at most [`AUTO_MODERATION_METADATA_PRESET_ALLOW_LIST_MAX`].
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationMetadataPresetAllowList`] if the
/// length is invalid.
///
/// Returns an error of type [`AutoModerationMetadataPresetAllowListItem`] if any of
/// the items are invalid.
///
/// [`AutoModerationMetadataPresetAllowList`]: ValidationErrorType::AutoModerationMetadataPresetAllowList
/// [`AutoModerationMetadataPresetAllowListItem`]: ValidationErrorType::AutoModerationMetadataPresetAllowListItem
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata-field-limits
pub fn auto_moderation_metadata_preset_allow_list(
keywords: &[impl AsRef<str>],
) -> Result<(), ValidationError> {
let len = keywords.len();
if len <= AUTO_MODERATION_METADATA_PRESET_ALLOW_LIST_MAX {
for keyword in keywords {
auto_moderation_metadata_preset_allow_list_item(keyword)?;
}
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationMetadataPresetAllowList { len },
})
}
}
/// Ensure that an auto moderation rule's `allow_list` item is correct when using presets.
///
/// The length must be at most [`AUTO_MODERATION_METADATA_PRESET_ALLOW_LIST_LENGTH_MAX`].
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationMetadataPresetAllowListItem`] if the
/// length is invalid.
///
/// [`AutoModerationMetadataPresetAllowListItem`]: ValidationErrorType::AutoModerationMetadataPresetAllowListItem
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata-field-limits
pub fn auto_moderation_metadata_preset_allow_list_item(
keyword: impl AsRef<str>,
) -> Result<(), ValidationError> {
let len = keyword.as_ref().chars().count();
if len <= AUTO_MODERATION_METADATA_PRESET_ALLOW_LIST_LENGTH_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationMetadataPresetAllowListItem {
len,
substring: keyword.as_ref().to_string(),
},
})
}
}
/// Ensure that an auto moderation rule's `regex_patterns` is correct.
///
/// The length must be at most [`AUTO_MODERATION_METADATA_REGEX_PATTERNS_MAX`].
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationMetadataRegexPatterns`] if the
/// length is invalid.
///
/// Returns an error of type [`AutoModerationMetadataRegexPatternsItem`] if any of
/// the items are invalid.
///
/// [`AutoModerationMetadataRegexPatterns`]: ValidationErrorType::AutoModerationMetadataRegexPatterns
/// [`AutoModerationMetadataRegexPatternsItem`]: ValidationErrorType::AutoModerationMetadataRegexPatternsItem
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata-field-limits
pub fn auto_moderation_metadata_regex_patterns(
patterns: &[impl AsRef<str>],
) -> Result<(), ValidationError> {
let len = patterns.len();
if len <= AUTO_MODERATION_METADATA_REGEX_PATTERNS_MAX {
for pattern in patterns {
auto_moderation_metadata_regex_patterns_item(pattern)?;
}
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationMetadataRegexPatterns { len },
})
}
}
/// Ensure that an auto moderation rule's `regex_patterns` item is correct.
///
/// The length must be at most [`AUTO_MODERATION_METADATA_REGEX_PATTERNS_LENGTH_MAX`].
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationMetadataRegexPatternsItem`] if the
/// length is invalid.
///
/// [`AutoModerationMetadataRegexPatternsItem`]: ValidationErrorType::AutoModerationMetadataRegexPatternsItem
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata-field-limits
pub fn auto_moderation_metadata_regex_patterns_item(
pattern: impl AsRef<str>,
) -> Result<(), ValidationError> {
let len = pattern.as_ref().chars().count();
if len <= AUTO_MODERATION_METADATA_REGEX_PATTERNS_LENGTH_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationMetadataRegexPatternsItem {
len,
substring: pattern.as_ref().to_string(),
},
})
}
}
/// Ensure that the `duration_seconds` field for an auto moderation action
/// metadata is correct.
///
/// The duration must be at most [`AUTO_MODERATION_ACTION_METADATA_DURATION_SECONDS_MAX`].
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationActionMetadataDurationSeconds`] if the
/// duration is invalid.
///
/// [`AutoModerationActionMetadataDurationSeconds`]: ValidationErrorType::AutoModerationActionMetadataDurationSeconds
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-action-object-action-metadata
pub const fn auto_moderation_action_metadata_duration_seconds(
seconds: u32,
) -> Result<(), ValidationError> {
if seconds <= AUTO_MODERATION_ACTION_METADATA_DURATION_SECONDS_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationActionMetadataDurationSeconds { seconds },
})
}
}
/// Ensure that the `exempt_roles` field for an auto moderation rule is correct.
///
/// The length must be at most [`AUTO_MODERATION_EXEMPT_ROLES_MAX`]. This is based
/// on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationExemptRoles`] if the length is
/// invalid.
///
/// [`AutoModerationExemptRoles`]: ValidationErrorType::AutoModerationExemptRoles
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-auto-moderation-rule-structure
pub const fn auto_moderation_exempt_roles(roles: &[Id<RoleMarker>]) -> Result<(), ValidationError> {
let len = roles.len();
if len <= AUTO_MODERATION_EXEMPT_ROLES_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationExemptRoles { len },
})
}
}
/// Ensure that the `exempt_channels` field for an auto moderation rule is correct.
///
/// The length must be at most [`AUTO_MODERATION_EXEMPT_CHANNELS_MAX`]. This is based
/// on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`AutoModerationExemptChannels`] if the length is
/// invalid.
///
/// [`AutoModerationExemptChannels`]: ValidationErrorType::AutoModerationExemptChannels
/// [this documentation entry]: https://discord.com/developers/docs/resources/auto-moderation#auto-moderation-rule-object-auto-moderation-rule-structure
pub const fn auto_moderation_exempt_channels(
channels: &[Id<ChannelMarker>],
) -> Result<(), ValidationError> {
let len = channels.len();
if len <= AUTO_MODERATION_EXEMPT_CHANNELS_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::AutoModerationExemptChannels { len },
})
}
}
/// Ensure that the delete message seconds amount for the Create Guild Ban request
/// is correct.
///
/// The seconds must be at most [`CREATE_GUILD_BAN_DELETE_MESSAGE_SECONDS_MAX`]. This
/// is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`CreateGuildBanDeleteMessageSeconds`] if the seconds is
/// invalid.
///
/// [`CreateGuildBanDeleteMessageSeconds`]: ValidationErrorType::CreateGuildBanDeleteMessageSeconds
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild#create-guild-ban
pub const fn create_guild_ban_delete_message_seconds(seconds: u32) -> Result<(), ValidationError> {
if seconds <= CREATE_GUILD_BAN_DELETE_MESSAGE_SECONDS_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::CreateGuildBanDeleteMessageSeconds { seconds },
})
}
}
/// Validate that a timeout time is not too far in the future.
///
/// The time must not be farther than 28 days in the future.
///
/// # Errors
#[allow(clippy::cast_possible_wrap)] // casting of unix timestamp should never wrap
pub fn communication_disabled_until(timestamp: Timestamp) -> Result<(), ValidationError> {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| ValidationError {
kind: ValidationErrorType::CommunicationDisabledUntil { timestamp },
})?;
let end = timestamp.as_secs();
if end - now.as_secs() as i64 <= COMMUNICATION_DISABLED_MAX_DURATION {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::CommunicationDisabledUntil { timestamp },
})
}
}
/// Ensure that the limit for the Get Channel Messages request is correct.
///
/// The limit must be at least [`GET_CHANNEL_MESSAGES_LIMIT_MIN`] and at most
/// [`GET_CHANNEL_MESSAGES_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetChannelMessages`] if the limit is invalid.
///
/// [`GetChannelMessages`]: ValidationErrorType::GetChannelMessages
/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#get-channel-messages
pub const fn get_channel_messages_limit(limit: u16) -> Result<(), ValidationError> {
if limit >= GET_CHANNEL_MESSAGES_LIMIT_MIN && limit <= GET_CHANNEL_MESSAGES_LIMIT_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::GetChannelMessages { limit },
})
}
}
/// Ensure that the limit for the Get Current User Guilds request is correct.
///
/// The limit must be at least [`GET_CURRENT_USER_GUILDS_LIMIT_MIN`] and at most
/// [`GET_CURRENT_USER_GUILDS_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetCurrentUserGuilds`] if the limit is invalid.
///
/// [`GetCurrentUserGuilds`]: ValidationErrorType::GetCurrentUserGuilds
/// [this documentation entry]: https://discord.com/developers/docs/resources/user#get-current-user-guilds
pub const fn get_current_user_guilds_limit(limit: u16) -> Result<(), ValidationError> {
if limit >= GET_CURRENT_USER_GUILDS_LIMIT_MIN && limit <= GET_CURRENT_USER_GUILDS_LIMIT_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::GetCurrentUserGuilds { limit },
})
}
}
/// Ensure that the limit for the Get Entitlements endpoint is correct.
///
/// The limit must be at least [`GET_ENTITLEMENTS_LIMIT_MIN`] and at most
/// [`GET_ENTITLEMENTS_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetEntitlements`] if the limit is invalid.
///
/// [`GetEntitlements`]: ValidationErrorType::GetEntitlements
/// [this documentation entry]: https://discord.com/developers/docs/monetization/entitlements#list-entitlements
pub const fn get_entitlements_limit(limit: u8) -> Result<(), ValidationError> {
if limit >= GET_ENTITLEMENTS_LIMIT_MIN && limit <= GET_ENTITLEMENTS_LIMIT_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::GetEntitlements { limit },
})
}
}
/// Ensure that the limit for the Get Guild Audit Log endpoint is correct.
///
/// The limit must be at least [`GET_GUILD_AUDIT_LOG_LIMIT_MIN`] and at most
/// [`GET_GUILD_AUDIT_LOG_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetGuildAuditLog`] if the limit is invalid.
///
/// [`GetGuildAuditLog`]: ValidationErrorType::GetGuildAuditLog
/// [this documentation entry]: https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log
pub const fn get_guild_audit_log_limit(limit: u16) -> Result<(), ValidationError> {
if limit >= GET_GUILD_AUDIT_LOG_LIMIT_MIN && limit <= GET_GUILD_AUDIT_LOG_LIMIT_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::GetGuildAuditLog { limit },
})
}
}
/// Ensure that the limit for the Get Guild Bans endpoint is correct.
///
/// The limit must be at most [`GET_GUILD_BANS_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetGuildBans`] if the limit is invalid.
///
/// [`GetGuildBans`]: ValidationErrorType::GetGuildBans
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild#get-guild-bans
pub const fn get_guild_bans_limit(limit: u16) -> Result<(), ValidationError> {
if limit <= GET_GUILD_BANS_LIMIT_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::GetGuildBans { limit },
})
}
}
/// Ensure that the limit for the Get Guild Members endpoint is correct.
///
/// The limit must be at least [`GET_GUILD_MEMBERS_LIMIT_MIN`] and at most
/// [`GET_GUILD_MEMBERS_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetGuildMembers`] if the limit is invalid.
///
/// [`GetGuildMembers`]: ValidationErrorType::GetGuildMembers
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild#list-guild-members
pub const fn get_guild_members_limit(limit: u16) -> Result<(), ValidationError> {
if limit >= GET_GUILD_MEMBERS_LIMIT_MIN && limit <= GET_GUILD_MEMBERS_LIMIT_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::GetGuildMembers { limit },
})
}
}
/// Ensure that the limit for the Get Reactions endpoint is correct.
///
/// The limit must be at least [`GET_REACTIONS_LIMIT_MIN`] and at most
/// [`GET_REACTIONS_LIMIT_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GetReactions`] if the limit is invalid.
///
/// [`GetReactions`]: ValidationErrorType::GetReactions
/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#get-reactions
pub const fn get_reactions_limit(limit: u16) -> Result<(), ValidationError> {
if limit >= GET_REACTIONS_LIMIT_MIN && limit <= GET_REACTIONS_LIMIT_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::GetReactions { limit },
})
}
}
/// Ensure that a guild name's length is correct.
///
/// The length must be at least [`GUILD_NAME_LENGTH_MIN`] and at most
/// [`GUILD_NAME_LENGTH_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GuildName`] if the length is invalid.
///
/// [`GuildName`]: ValidationErrorType::GuildName
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild#guild-object
pub fn guild_name(name: impl AsRef<str>) -> Result<(), ValidationError> {
let len = name.as_ref().chars().count();
if (GUILD_NAME_LENGTH_MIN..=GUILD_NAME_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::GuildName { len },
})
}
}
/// Ensure that the days to prune members from a guild is correct.
///
/// The days must be at least [`GUILD_PRUNE_DAYS_MIN`] and at most
/// [`GUILD_PRUNE_DAYS_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`GuildPruneDays`] if the days is invalid.
///
/// [`GuildPruneDays`]: ValidationErrorType::GuildPruneDays
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild#get-guild-prune-count
pub const fn guild_prune_days(days: u16) -> Result<(), ValidationError> {
if days >= GUILD_PRUNE_DAYS_MIN && days <= GUILD_PRUNE_DAYS_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::GuildPruneDays { days },
})
}
}
/// Ensure that the invite max age is correct.
///
/// The age must be at most [`INVITE_AGE_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`InviteMaxAge`] if the age is invalid.
///
/// [`InviteMaxAge`]: ValidationErrorType::InviteMaxAge
/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#create-channel-invite
pub const fn invite_max_age(max_age: u32) -> Result<(), ValidationError> {
if max_age <= INVITE_AGE_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::InviteMaxAge { max_age },
})
}
}
/// Ensure that the invite max uses is correct.
///
/// The age must be at most [`INVITE_USES_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`InviteMaxUses`] if the uses is invalid.
///
/// [`InviteMaxUses`]: ValidationErrorType::InviteMaxUses
/// [this documentation entry]: https://discord.com/developers/docs/resources/channel#create-channel-invite
pub const fn invite_max_uses(max_uses: u16) -> Result<(), ValidationError> {
if max_uses <= INVITE_USES_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::InviteMaxUses { max_uses },
})
}
}
/// Ensure that the nickname length is correct.
///
/// The length must be at least [`NICKNAME_LIMIT_MIN`] and at most
/// [`NICKNAME_LIMIT_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`Nickname`] if the length is invalid.
///
/// [`Nickname`]: ValidationErrorType::Nickname
/// [this documentation entry]: https://discord.com/developers/docs/resources/user#usernames-and-nicknames
pub fn nickname(nickname: impl AsRef<str>) -> Result<(), ValidationError> {
let len = nickname.as_ref().chars().count();
if (NICKNAME_LIMIT_MIN..=NICKNAME_LIMIT_MAX).contains(&len) {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::Nickname { len },
})
}
}
/// Ensure that a scheduled event's description is correct.
///
/// The length must be at least [`SCHEDULED_EVENT_DESCRIPTION_MIN`] and at most
/// [`SCHEDULED_EVENT_DESCRIPTION_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`ScheduledEventDescription`] if the length is
/// invalid.
///
/// [`ScheduledEventDescription`]: ValidationErrorType::ScheduledEventDescription
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-structure
pub fn scheduled_event_description(description: impl AsRef<str>) -> Result<(), ValidationError> {
let len = description.as_ref().chars().count();
if (SCHEDULED_EVENT_DESCRIPTION_MIN..=SCHEDULED_EVENT_DESCRIPTION_MAX).contains(&len) {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::ScheduledEventDescription { len },
})
}
}
/// Ensure that a scheduled event's get users limit amount is correct.
///
/// The length must be at least [`SCHEDULED_EVENT_GET_USERS_MIN`] and at most
/// [`SCHEDULED_EVENT_GET_USERS_MAX`]. This is based on [this documentation
/// entry].
///
/// # Errors
///
/// Returns an error of type [`ScheduledEventGetUsers`] if the limit is invalid.
///
/// [`ScheduledEventGetUsers`]: ValidationErrorType::ScheduledEventGetUsers
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event-users-query-string-params
pub const fn scheduled_event_get_users(limit: u16) -> Result<(), ValidationError> {
if limit >= SCHEDULED_EVENT_GET_USERS_MIN && limit <= SCHEDULED_EVENT_GET_USERS_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::ScheduledEventGetUsers { limit },
})
}
}
/// Ensure that a scheduled event's name is correct.
///
/// The length must be at least [`SCHEDULED_EVENT_NAME_MIN`] and at most
/// [`SCHEDULED_EVENT_NAME_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`ScheduledEventName`] if the length is invalid.
///
/// [`ScheduledEventName`]: ValidationErrorType::ScheduledEventName
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object-guild-scheduled-event-structure
pub fn scheduled_event_name(name: impl AsRef<str>) -> Result<(), ValidationError> {
let len = name.as_ref().chars().count();
if (SCHEDULED_EVENT_NAME_MIN..=SCHEDULED_EVENT_NAME_MAX).contains(&len) {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::ScheduledEventName { len },
})
}
}
/// Ensure that the limit for the Search Guild Members endpoint is correct.
///
/// The limit must be at least [`SEARCH_GUILD_MEMBERS_LIMIT_MIN`] and at most
/// [`SEARCH_GUILD_MEMBERS_LIMIT_MAX`]. This is based on
/// [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`SearchGuildMembers`] if the limit is invalid.
///
/// [`SearchGuildMembers`]: ValidationErrorType::SearchGuildMembers
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild#search-guild-members
pub const fn search_guild_members_limit(limit: u16) -> Result<(), ValidationError> {
if limit >= SEARCH_GUILD_MEMBERS_LIMIT_MIN && limit <= SEARCH_GUILD_MEMBERS_LIMIT_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::SearchGuildMembers { limit },
})
}
}
/// Ensure that the stage instance's topic length is correct.
///
/// The length must be at least [`STAGE_TOPIC_LENGTH_MIN`] and at most
/// [`STAGE_TOPIC_LENGTH_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`StageTopic`] if the length is invalid.
///
/// [`StageTopic`]: ValidationErrorType::StageTopic
/// [this documentation entry]: https://discord.com/developers/docs/resources/stage-instance#stage-instance-object
pub fn stage_topic(topic: impl AsRef<str>) -> Result<(), ValidationError> {
let len = topic.as_ref().chars().count();
if (STAGE_TOPIC_LENGTH_MIN..=STAGE_TOPIC_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::StageTopic { len },
})
}
}
/// Ensure that a guild template's description length is correct.
///
/// The length must be at most [`TEMPLATE_DESCRIPTION_LENGTH_MAX`]. This is
/// based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`TemplateDescription`] if the length is invalid.
///
/// [`TemplateDescription`]: ValidationErrorType::TemplateDescription
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild-template#guild-template-object-guild-template-structure
pub fn template_description(description: impl AsRef<str>) -> Result<(), ValidationError> {
let len = description.as_ref().chars().count();
if len <= TEMPLATE_DESCRIPTION_LENGTH_MAX {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::TemplateDescription { len },
})
}
}
/// Ensure that a guild template's name length is correct.
///
/// The length must be at least [`TEMPLATE_NAME_LENGTH_MIN`] and at most
/// [`TEMPLATE_NAME_LENGTH_MAX`]. This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`TemplateName`] if the length is invalid.
///
/// [`TemplateName`]: ValidationErrorType::TemplateName
/// [this documentation entry]: https://discord.com/developers/docs/resources/guild-template#guild-template-object-guild-template-structure
pub fn template_name(name: impl AsRef<str>) -> Result<(), ValidationError> {
let len = name.as_ref().chars().count();
if (TEMPLATE_NAME_LENGTH_MIN..=TEMPLATE_NAME_LENGTH_MAX).contains(&len) {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::TemplateName { len },
})
}
}
/// Ensure that a username is correct.
///
/// The length must be at least [`USERNAME_LIMIT_MIN`] and at most
/// [`USERNAME_LIMIT_MAX`]. It must also be free of certain substrings. This is
/// based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`Username`] if the length is invalid.
///
/// [`Username`]: ValidationErrorType::Username
/// [this documentation entry]: https://discord.com/developers/docs/resources/user#usernames-and-nicknames
pub fn username(value: impl AsRef<str>) -> Result<(), ValidationError> {
let value = value.as_ref();
let len = value.chars().count();
let range = USERNAME_LIMIT_MIN..=USERNAME_LIMIT_MAX;
let invalid_len = (!range.contains(&len)).then_some(len);
let invalid_substring = USERNAME_INVALID_SUBSTRINGS
.into_iter()
.find(|invalid_substring| value.contains(invalid_substring))
.or_else(|| {
USERNAME_INVALID_STRINGS
.into_iter()
.find(|invalid_string| value == *invalid_string)
});
if invalid_len.is_none() && invalid_substring.is_none() {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::Username {
len: invalid_len,
substring: invalid_substring,
},
})
}
}
/// Ensure that a webhook is correct.
///
/// The length must be at least [`WEBHOOK_USERNAME_LIMIT_MIN`] and at most
/// [`WEBHOOK_USERNAME_LIMIT_MAX`]. It must also be free of certain substrings.
/// This is based on [this documentation entry].
///
/// # Errors
///
/// Returns an error of type [`WebhookUsername`] if the length is invalid.
///
/// [`WebhookUsername`]: ValidationErrorType::WebhookUsername
/// [this documentation entry]: https://discord.com/developers/docs/resources/webhook#create-webhook
pub fn webhook_username(value: impl AsRef<str>) -> Result<(), ValidationError> {
let value = value.as_ref();
let len = value.chars().count();
let range = WEBHOOK_USERNAME_LIMIT_MIN..=WEBHOOK_USERNAME_LIMIT_MAX;
let invalid_len = (!range.contains(&len)).then_some(len);
let invalid_substring = WEBHOOK_INVALID_STRINGS
.into_iter()
.find(|invalid_string| value == *invalid_string);
if invalid_len.is_none() && invalid_substring.is_none() {
Ok(())
} else {
Err(ValidationError {
kind: ValidationErrorType::WebhookUsername {
len: invalid_len,
substring: invalid_substring,
},
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn username_variants() {
let expected = format!(
"provided username length is 200, but it must be at least {USERNAME_LIMIT_MIN} and at \
most {USERNAME_LIMIT_MAX}, and cannot contain :"
);
let actual = ValidationError {
kind: ValidationErrorType::Username {
len: Some(200),
substring: Some(":"),
},
};
assert_eq!(expected, actual.to_string());
let expected = format!(
"provided username length is 200, but it must be at least {USERNAME_LIMIT_MIN} and at \
most {USERNAME_LIMIT_MAX}",
);
let actual = ValidationError {
kind: ValidationErrorType::Username {
len: Some(200),
substring: None,
},
};
assert_eq!(expected, actual.to_string());
let expected = "provided username cannot contain :".to_string();
let actual = ValidationError {
kind: ValidationErrorType::Username {
len: None,
substring: Some(":"),
},
};
assert_eq!(expected, actual.to_string());
}
#[test]
fn audit_reason_length() {
assert!(audit_reason("").is_ok());
assert!(audit_reason("a").is_ok());
assert!(audit_reason("a".repeat(500)).is_ok());
assert!(audit_reason("a".repeat(512)).is_ok());
assert!(audit_reason("a".repeat(513)).is_err());
}
#[test]
fn auto_moderation_block_action_custom_message() {
assert!(auto_moderation_block_action_custom_message_limit("").is_ok());
assert!(auto_moderation_block_action_custom_message_limit("a".repeat(150)).is_ok());
assert!(matches!(
auto_moderation_block_action_custom_message_limit("a".repeat(151))
.unwrap_err()
.kind,
ValidationErrorType::AutoModerationBlockActionCustomMessageLimit { len: 151 }
));
}
#[test]
fn auto_moderation_metadata_mention_total() {
assert!(auto_moderation_metadata_mention_total_limit(0).is_ok());
assert!(auto_moderation_metadata_mention_total_limit(1).is_ok());
assert!(auto_moderation_metadata_mention_total_limit(50).is_ok());
assert!(auto_moderation_metadata_mention_total_limit(51).is_err());
}
#[test]
fn auto_moderation_metadata_keyword_filter_max() {
let mut keywords = (0..1000).map(|_| "a").collect::<Vec<_>>();
assert!(auto_moderation_metadata_keyword_filter(&[] as &[&str]).is_ok());
assert!(auto_moderation_metadata_keyword_filter(&["a".repeat(60)]).is_ok());
assert!(auto_moderation_metadata_keyword_filter(&keywords).is_ok());
keywords.push("a");
assert!(auto_moderation_metadata_keyword_filter(&["a".repeat(61)]).is_err());
assert!(auto_moderation_metadata_keyword_filter(&keywords).is_err());
}
#[test]
fn auto_moderation_metadata_keyword_allow_list_max() {
let mut allow_list = (0..100).map(|_| "a").collect::<Vec<_>>();
assert!(auto_moderation_metadata_keyword_allow_list(&[] as &[&str]).is_ok());
assert!(auto_moderation_metadata_keyword_allow_list(&["a".repeat(60)]).is_ok());
allow_list.push("a");
assert!(auto_moderation_metadata_keyword_allow_list(&["a".repeat(61)]).is_err());
assert!(auto_moderation_metadata_keyword_allow_list(&allow_list).is_err());
}
#[test]
fn auto_moderation_metadata_preset_allow_list_max() {
let mut allow_list = (0..1000).map(|_| "a").collect::<Vec<_>>();
assert!(auto_moderation_metadata_preset_allow_list(&[] as &[&str]).is_ok());
assert!(auto_moderation_metadata_preset_allow_list(&["a".repeat(60)]).is_ok());
allow_list.push("a");
assert!(auto_moderation_metadata_preset_allow_list(&["a".repeat(61)]).is_err());
assert!(auto_moderation_metadata_preset_allow_list(&allow_list).is_err());
}
#[test]
fn auto_moderation_metadata_regex_patterns_max() {
let mut patterns = (0..10).map(|_| "a").collect::<Vec<_>>();
assert!(auto_moderation_metadata_regex_patterns(&[] as &[&str]).is_ok());
assert!(auto_moderation_metadata_regex_patterns(&["a".repeat(260)]).is_ok());
patterns.push("a");
assert!(auto_moderation_metadata_regex_patterns(&["a".repeat(261)]).is_err());
assert!(auto_moderation_metadata_regex_patterns(&patterns).is_err());
}
#[test]
fn auto_moderation_exempt_roles_max() {
let mut roles = (1..=20).map(Id::new).collect::<Vec<_>>();
assert!(auto_moderation_exempt_roles(&[]).is_ok());
assert!(auto_moderation_exempt_roles(&roles).is_ok());
roles.push(Id::new(21));
assert!(auto_moderation_exempt_roles(&roles).is_err());
}
#[test]
fn auto_moderation_exempt_channels_max() {
let mut channels = (1..=50).map(Id::new).collect::<Vec<_>>();
assert!(auto_moderation_exempt_channels(&[]).is_ok());
assert!(auto_moderation_exempt_channels(&channels).is_ok());
channels.push(Id::new(51));
assert!(auto_moderation_exempt_channels(&channels).is_err());
}
#[test]
fn auto_moderation_action_metadata_duration_seconds_max() {
assert!(auto_moderation_action_metadata_duration_seconds(0).is_ok());
assert!(auto_moderation_action_metadata_duration_seconds(1).is_ok());
assert!(auto_moderation_action_metadata_duration_seconds(2_419_200).is_ok());
assert!(auto_moderation_action_metadata_duration_seconds(2_419_201).is_err());
}
#[test]
fn create_guild_ban_delete_message_seconds_max() {
assert!(create_guild_ban_delete_message_seconds(0).is_ok());
assert!(create_guild_ban_delete_message_seconds(1).is_ok());
assert!(create_guild_ban_delete_message_seconds(604_800).is_ok());
assert!(create_guild_ban_delete_message_seconds(604_801).is_err());
}
#[test]
fn communication_disabled_until_max() {
#[allow(clippy::cast_possible_wrap)]
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let ok_timestamp =
Timestamp::from_secs(now + COMMUNICATION_DISABLED_MAX_DURATION - 1000).unwrap();
assert!(communication_disabled_until(ok_timestamp).is_ok());
let err_timestamp =
Timestamp::from_secs(now + COMMUNICATION_DISABLED_MAX_DURATION + 1000).unwrap();
assert!(communication_disabled_until(err_timestamp).is_err());
}
#[test]
fn get_channel_messages_limit_count() {
assert!(get_channel_messages_limit(1).is_ok());
assert!(get_channel_messages_limit(100).is_ok());
assert!(get_channel_messages_limit(0).is_err());
assert!(get_channel_messages_limit(101).is_err());
}
#[test]
fn get_current_user_guilds_limit_count() {
assert!(get_current_user_guilds_limit(1).is_ok());
assert!(get_current_user_guilds_limit(200).is_ok());
assert!(get_current_user_guilds_limit(0).is_err());
assert!(get_current_user_guilds_limit(201).is_err());
}
#[test]
fn get_guild_log_limit_count() {
assert!(get_guild_audit_log_limit(1).is_ok());
assert!(get_guild_audit_log_limit(100).is_ok());
assert!(get_guild_audit_log_limit(0).is_err());
assert!(get_guild_audit_log_limit(101).is_err());
}
#[test]
fn get_guild_bans_limit_count() {
assert!(get_guild_bans_limit(0).is_ok());
assert!(get_guild_bans_limit(1000).is_ok());
assert!(get_guild_bans_limit(1001).is_err());
}
#[test]
fn get_guild_members_limit_count() {
assert!(get_guild_members_limit(1).is_ok());
assert!(get_guild_members_limit(1000).is_ok());
assert!(get_guild_members_limit(0).is_err());
assert!(get_guild_members_limit(1001).is_err());
}
#[test]
fn get_reactions_limit_count() {
assert!(get_reactions_limit(1).is_ok());
assert!(get_reactions_limit(100).is_ok());
assert!(get_reactions_limit(0).is_err());
assert!(get_reactions_limit(101).is_err());
}
#[test]
fn guild_name_length() {
assert!(guild_name("aa").is_ok());
assert!(guild_name("a".repeat(100)).is_ok());
assert!(guild_name("").is_err());
assert!(guild_name("a").is_err());
assert!(guild_name("a".repeat(101)).is_err());
}
#[test]
fn guild_prune_days_length() {
assert!(guild_prune_days(1).is_ok());
assert!(guild_prune_days(30).is_ok());
assert!(guild_prune_days(0).is_err());
assert!(guild_prune_days(31).is_err());
assert!(guild_prune_days(100).is_err());
}
#[test]
fn invite_max_age_length() {
assert!(invite_max_age(0).is_ok());
assert!(invite_max_age(86_400).is_ok());
assert!(invite_max_age(604_800).is_ok());
assert!(invite_max_age(604_801).is_err());
}
#[test]
fn invite_max_uses_count() {
assert!(invite_max_uses(0).is_ok());
assert!(invite_max_uses(100).is_ok());
assert!(invite_max_uses(101).is_err());
}
#[test]
fn nickname_length() {
assert!(nickname("a").is_ok());
assert!(nickname("a".repeat(32)).is_ok());
assert!(nickname("").is_err());
assert!(nickname("a".repeat(33)).is_err());
}
#[test]
fn scheduled_event_description_length() {
assert!(scheduled_event_description("a").is_ok());
assert!(scheduled_event_description("a".repeat(1000)).is_ok());
assert!(scheduled_event_description("").is_err());
assert!(scheduled_event_description("a".repeat(1001)).is_err());
}
#[test]
fn scheduled_event_get_users_length() {
assert!(scheduled_event_get_users(0).is_err());
assert!(scheduled_event_get_users(101).is_err());
assert!(scheduled_event_get_users(100).is_ok());
assert!(scheduled_event_get_users(1).is_ok());
}
#[test]
fn scheduled_event_name_length() {
assert!(scheduled_event_name("a").is_ok());
assert!(scheduled_event_name("a".repeat(100)).is_ok());
assert!(scheduled_event_name("").is_err());
assert!(scheduled_event_name("a".repeat(101)).is_err());
}
#[test]
fn search_guild_members_limit_count() {
assert!(search_guild_members_limit(1).is_ok());
assert!(search_guild_members_limit(1000).is_ok());
assert!(search_guild_members_limit(0).is_err());
assert!(search_guild_members_limit(1001).is_err());
}
#[test]
fn stage_topic_length() {
assert!(stage_topic("a").is_ok());
assert!(stage_topic("a".repeat(120)).is_ok());
assert!(stage_topic("").is_err());
assert!(stage_topic("a".repeat(121)).is_err());
}
#[test]
fn template_description_length() {
assert!(template_description("").is_ok());
assert!(template_description("a").is_ok());
assert!(template_description("a".repeat(120)).is_ok());
assert!(template_description("a".repeat(121)).is_err());
}
#[test]
fn template_name_length() {
assert!(template_name("a").is_ok());
assert!(template_name("a".repeat(100)).is_ok());
assert!(template_name("").is_err());
assert!(template_name("a".repeat(101)).is_err());
}
#[test]
fn username_length() {
assert!(username("aa").is_ok());
assert!(username("a".repeat(32)).is_ok());
assert!(username("a").is_err());
assert!(username("a".repeat(33)).is_err());
assert!(username("no @ in username").is_err());
assert!(username("no # in username").is_err());
assert!(username("no : in username").is_err());
assert!(username(r"no ``` in username").is_err());
assert!(username("no discord in username").is_err());
assert!(username("everyone").is_err());
assert!(username("here").is_err());
}
#[test]
fn webhook_username_length() {
assert!(webhook_username("aa").is_ok());
assert!(webhook_username("a".repeat(80)).is_ok());
assert!(webhook_username("a").is_err());
assert!(webhook_username("a".repeat(81)).is_err());
assert!(webhook_username("clyde").is_err());
}
}