twilight_http/client/mod.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 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986
mod builder;
mod connector;
mod interaction;
pub use self::{builder::ClientBuilder, interaction::InteractionClient};
use crate::request::application::{
emoji::{
AddApplicationEmoji, DeleteApplicationEmoji, ListApplicationEmojis, UpdateApplicationEmoji,
},
monetization::{
CreateTestEntitlement, CreateTestEntitlementOwner, DeleteTestEntitlement, GetEntitlements,
GetSKUs,
},
};
#[allow(deprecated)]
use crate::{
client::connector::Connector,
error::{Error, ErrorType},
request::{
channel::{
invite::{CreateInvite, DeleteInvite, GetChannelInvites, GetInvite},
message::{
CreateMessage, CrosspostMessage, DeleteMessage, DeleteMessages, GetChannelMessages,
GetMessage, UpdateMessage,
},
reaction::{
delete_reaction::TargetUser, CreateReaction, DeleteAllReaction, DeleteAllReactions,
DeleteReaction, GetReactions, RequestReactionType,
},
stage::{
CreateStageInstance, DeleteStageInstance, GetStageInstance, UpdateStageInstance,
},
thread::{
AddThreadMember, CreateForumThread, CreateThread, CreateThreadFromMessage,
GetJoinedPrivateArchivedThreads, GetPrivateArchivedThreads,
GetPublicArchivedThreads, GetThreadMember, GetThreadMembers, JoinThread,
LeaveThread, RemoveThreadMember, UpdateThread,
},
webhook::{
CreateWebhook, DeleteWebhook, DeleteWebhookMessage, ExecuteWebhook,
GetChannelWebhooks, GetWebhook, GetWebhookMessage, UpdateWebhook,
UpdateWebhookMessage, UpdateWebhookWithToken,
},
CreatePin, CreateTypingTrigger, DeleteChannel, DeleteChannelPermission, DeletePin,
FollowNewsChannel, GetChannel, GetPins, UpdateChannel, UpdateChannelPermission,
},
guild::{
auto_moderation::{
CreateAutoModerationRule, DeleteAutoModerationRule, GetAutoModerationRule,
GetGuildAutoModerationRules, UpdateAutoModerationRule,
},
ban::{CreateBan, DeleteBan, GetBan, GetBans},
emoji::{CreateEmoji, DeleteEmoji, GetEmoji, GetEmojis, UpdateEmoji},
integration::{DeleteGuildIntegration, GetGuildIntegrations},
member::{
AddGuildMember, AddRoleToMember, GetGuildMembers, GetMember, RemoveMember,
RemoveRoleFromMember, SearchGuildMembers, UpdateGuildMember,
},
role::{CreateRole, DeleteRole, GetGuildRoles, UpdateRole, UpdateRolePositions},
sticker::{
CreateGuildSticker, DeleteGuildSticker, GetGuildSticker, GetGuildStickers,
UpdateGuildSticker,
},
update_guild_onboarding::{UpdateGuildOnboarding, UpdateGuildOnboardingFields},
user::{UpdateCurrentUserVoiceState, UpdateUserVoiceState},
CreateGuild, CreateGuildChannel, CreateGuildPrune, DeleteGuild, GetActiveThreads,
GetAuditLog, GetGuild, GetGuildChannels, GetGuildInvites, GetGuildOnboarding,
GetGuildPreview, GetGuildPruneCount, GetGuildVanityUrl, GetGuildVoiceRegions,
GetGuildWebhooks, GetGuildWelcomeScreen, GetGuildWidget, GetGuildWidgetSettings,
UpdateCurrentMember, UpdateGuild, UpdateGuildChannelPositions, UpdateGuildMfa,
UpdateGuildWelcomeScreen, UpdateGuildWidgetSettings,
},
poll::{EndPoll, GetAnswerVoters},
scheduled_event::{
CreateGuildScheduledEvent, DeleteGuildScheduledEvent, GetGuildScheduledEvent,
GetGuildScheduledEventUsers, GetGuildScheduledEvents, UpdateGuildScheduledEvent,
},
sticker::{GetNitroStickerPacks, GetSticker},
template::{
CreateGuildFromTemplate, CreateTemplate, DeleteTemplate, GetTemplate, GetTemplates,
SyncTemplate, UpdateTemplate,
},
user::{
CreatePrivateChannel, GetCurrentUser, GetCurrentUserConnections,
GetCurrentUserGuildMember, GetCurrentUserGuilds, GetUser, LeaveGuild,
UpdateCurrentUser,
},
GetCurrentAuthorizationInformation, GetGateway, GetUserApplicationInfo, GetVoiceRegions,
Method, Request, UpdateCurrentUserApplication,
},
response::ResponseFuture,
API_VERSION,
};
use http::header::{
HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT,
};
use http_body_util::Full;
use hyper::body::Bytes;
use hyper_util::client::legacy::Client as HyperClient;
use std::{
fmt::{Debug, Formatter, Result as FmtResult},
ops::Deref,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use tokio::time;
use twilight_http_ratelimiting::Ratelimiter;
use twilight_model::{
channel::{message::AllowedMentions, ChannelType},
guild::{
auto_moderation::AutoModerationEventType, scheduled_event::PrivacyLevel, MfaLevel,
RolePosition,
},
http::{channel_position::Position, permission_overwrite::PermissionOverwrite},
id::{
marker::{
ApplicationMarker, AutoModerationRuleMarker, ChannelMarker, EmojiMarker,
EntitlementMarker, GuildMarker, IntegrationMarker, MessageMarker, RoleMarker,
ScheduledEventMarker, SkuMarker, StickerMarker, UserMarker, WebhookMarker,
},
Id,
},
};
const TWILIGHT_USER_AGENT: &str = concat!(
"DiscordBot (",
env!("CARGO_PKG_HOMEPAGE"),
", ",
env!("CARGO_PKG_VERSION"),
") Twilight-rs",
);
/// Wrapper for an authorization token with a debug implementation that redacts
/// the string.
#[derive(Default)]
struct Token {
/// Authorization token that is redacted in the Debug implementation.
inner: Box<str>,
}
impl Token {
/// Create a new authorization wrapper.
const fn new(token: Box<str>) -> Self {
Self { inner: token }
}
}
impl Debug for Token {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str("<redacted>")
}
}
impl Deref for Token {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
/// Twilight's http client.
///
/// Almost all of the client methods require authentication, and as such, the client must be
/// supplied with a Discord Token. Get yours [here].
///
/// # Interactions
///
/// HTTP interaction requests may be accessed via the [`Client::interaction`]
/// method.
///
/// # OAuth2
///
/// To use Bearer tokens prefix the token with `"Bearer "`, including the space
/// at the end like so:
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use std::env;
/// use twilight_http::Client;
///
/// let bearer = env::var("BEARER_TOKEN")?;
/// let token = format!("Bearer {bearer}");
///
/// let client = Client::new(token);
/// # Ok(()) }
/// ```
///
/// # Using the client in multiple tasks
///
/// To use a client instance in multiple tasks, consider wrapping it in an
/// [`std::sync::Arc`] or [`std::rc::Rc`].
///
/// # Unauthorized behavior
///
/// When the client encounters an Unauthorized response it will take note that
/// the configured token is invalid. This may occur when the token has been
/// revoked or expired. When this happens, you must create a new client with the
/// new token. The client will no longer execute requests in order to
/// prevent API bans and will always return [`ErrorType::Unauthorized`].
///
/// # Examples
///
/// Create a client called `client`:
/// ```no_run
/// use twilight_http::Client;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
/// # Ok(()) }
/// ```
///
/// Use [`ClientBuilder`] to create a client called `client`, with a shorter
/// timeout:
/// ```no_run
/// use std::time::Duration;
/// use twilight_http::Client;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::builder()
/// .token("my token".to_owned())
/// .timeout(Duration::from_secs(5))
/// .build();
/// # Ok(()) }
/// ```
///
/// All the examples on this page assume you have already created a client, and have named it
/// `client`.
///
/// [here]: https://discord.com/developers/applications
#[derive(Debug)]
pub struct Client {
pub(crate) default_allowed_mentions: Option<AllowedMentions>,
default_headers: Option<HeaderMap>,
http: HyperClient<Connector, Full<Bytes>>,
proxy: Option<Box<str>>,
ratelimiter: Option<Box<dyn Ratelimiter>>,
timeout: Duration,
/// Whether the token has been invalidated.
///
/// Whether an invalid token is tracked can be configured via
/// [`ClientBuilder::remember_invalid_token`].
token_invalidated: Option<Arc<AtomicBool>>,
token: Option<Token>,
use_http: bool,
}
impl Client {
/// Create a new client with a token.
pub fn new(token: String) -> Self {
ClientBuilder::default().token(token).build()
}
/// Create a new builder to create a client.
///
/// Refer to its documentation for more information.
pub fn builder() -> ClientBuilder {
ClientBuilder::new()
}
/// Retrieve an immutable reference to the token used by the client.
///
/// If the initial token provided is not prefixed with `Bot `, it will be, and this method
/// reflects that.
pub fn token(&self) -> Option<&str> {
self.token.as_deref()
}
/// Create an interface for using interactions.
///
/// An application ID is required to be passed in to use interactions. The
/// ID may be retrieved via [`current_user_application`] and cached for use
/// with this method.
///
/// # Examples
///
/// Retrieve the application ID and then use an interaction request:
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use std::env;
/// use twilight_http::Client;
///
/// let client = Client::new(env::var("DISCORD_TOKEN")?);
///
/// // Cache the application ID for repeated use later in the process.
/// let application_id = {
/// let response = client.current_user_application().await?;
///
/// response.model().await?.id
/// };
///
/// // Later in the process...
/// let commands = client
/// .interaction(application_id)
/// .global_commands()
/// .await?
/// .models()
/// .await?;
///
/// println!("there are {} global commands", commands.len());
/// # Ok(()) }
/// ```
///
/// [`current_user_application`]: Self::current_user_application
pub const fn interaction(
&self,
application_id: Id<ApplicationMarker>,
) -> InteractionClient<'_> {
InteractionClient::new(self, application_id)
}
/// Get an immutable reference to the default [`AllowedMentions`] for sent
/// messages.
pub const fn default_allowed_mentions(&self) -> Option<&AllowedMentions> {
self.default_allowed_mentions.as_ref()
}
/// Get the Ratelimiter used by the client internally.
///
/// This will return `None` only if ratelimit handling
/// has been explicitly disabled in the [`ClientBuilder`].
pub fn ratelimiter(&self) -> Option<&dyn Ratelimiter> {
self.ratelimiter.as_ref().map(AsRef::as_ref)
}
/// Get an auto moderation rule in a guild.
///
/// Requires the [`MANAGE_GUILD`] permission.
///
/// [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
pub const fn auto_moderation_rule(
&self,
guild_id: Id<GuildMarker>,
auto_moderation_rule_id: Id<AutoModerationRuleMarker>,
) -> GetAutoModerationRule<'_> {
GetAutoModerationRule::new(self, guild_id, auto_moderation_rule_id)
}
/// Get the auto moderation rules in a guild.
///
/// Requires the [`MANAGE_GUILD`] permission.
///
/// [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
pub const fn auto_moderation_rules(
&self,
guild_id: Id<GuildMarker>,
) -> GetGuildAutoModerationRules<'_> {
GetGuildAutoModerationRules::new(self, guild_id)
}
/// Create an auto moderation rule within a guild.
///
/// Requires the [`MANAGE_GUILD`] permission.
///
/// # Examples
///
/// Create a rule that deletes messages that contain the word "darn":
///
/// ```no_run
/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use twilight_http::Client;
/// use twilight_model::{guild::auto_moderation::AutoModerationEventType, id::Id};
///
/// let client = Client::new("my token".to_owned());
///
/// let guild_id = Id::new(1);
/// client
/// .create_auto_moderation_rule(guild_id, "no darns", AutoModerationEventType::MessageSend)
/// .action_block_message()
/// .enabled(true)
/// .with_keyword(&["darn"], &["d(?:4|a)rn"], &["darn it"])
/// .await?;
/// # Ok(()) }
/// ```
///
/// [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
pub const fn create_auto_moderation_rule<'a>(
&'a self,
guild_id: Id<GuildMarker>,
name: &'a str,
event_type: AutoModerationEventType,
) -> CreateAutoModerationRule<'a> {
CreateAutoModerationRule::new(self, guild_id, name, event_type)
}
/// Delete an auto moderation rule in a guild.
///
/// Requires the [`MANAGE_GUILD`] permission.
///
/// [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
pub const fn delete_auto_moderation_rule(
&self,
guild_id: Id<GuildMarker>,
auto_moderation_rule_id: Id<AutoModerationRuleMarker>,
) -> DeleteAutoModerationRule<'_> {
DeleteAutoModerationRule::new(self, guild_id, auto_moderation_rule_id)
}
/// Update an auto moderation rule in a guild.
///
/// Requires the [`MANAGE_GUILD`] permission.
///
/// [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
pub const fn update_auto_moderation_rule(
&self,
guild_id: Id<GuildMarker>,
auto_moderation_rule_id: Id<AutoModerationRuleMarker>,
) -> UpdateAutoModerationRule<'_> {
UpdateAutoModerationRule::new(self, guild_id, auto_moderation_rule_id)
}
/// Get the audit log for a guild.
///
/// # Examples
///
/// ```no_run
/// # use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("token".to_owned());
/// let guild_id = Id::new(101);
/// let audit_log = client.audit_log(guild_id).await?;
/// # Ok(()) }
/// ```
pub const fn audit_log(&self, guild_id: Id<GuildMarker>) -> GetAuditLog<'_> {
GetAuditLog::new(self, guild_id)
}
/// Retrieve the bans for a guild.
///
/// # Examples
///
/// Retrieve the bans for guild `1`:
///
/// ```no_run
/// # use twilight_http::Client;
/// use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let guild_id = Id::new(1);
///
/// let bans = client.bans(guild_id).await?;
/// # Ok(()) }
/// ```
pub const fn bans(&self, guild_id: Id<GuildMarker>) -> GetBans<'_> {
GetBans::new(self, guild_id)
}
/// Get information about a ban of a guild.
///
/// Includes the user banned and the reason.
pub const fn ban(&self, guild_id: Id<GuildMarker>, user_id: Id<UserMarker>) -> GetBan<'_> {
GetBan::new(self, guild_id, user_id)
}
/// Bans a user from a guild, optionally with the number of seconds' worth of
/// messages to delete and the reason.
///
/// # Examples
///
/// Ban user `200` from guild `100`, deleting
/// `86_400` second's (this is equivalent to `1` day) worth of messages, for the reason `"memes"`:
///
/// ```no_run
/// # use twilight_http::{request::AuditLogReason, Client};
/// use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let guild_id = Id::new(100);
/// let user_id = Id::new(200);
/// client
/// .create_ban(guild_id, user_id)
/// .delete_message_seconds(86_400)
/// .reason("memes")
/// .await?;
/// # Ok(()) }
/// ```
pub const fn create_ban(
&self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>,
) -> CreateBan<'_> {
CreateBan::new(self, guild_id, user_id)
}
/// Remove a ban from a user in a guild.
///
/// # Examples
///
/// Unban user `200` from guild `100`:
///
/// ```no_run
/// # use twilight_http::Client;
/// use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let guild_id = Id::new(100);
/// let user_id = Id::new(200);
///
/// client.delete_ban(guild_id, user_id).await?;
/// # Ok(()) }
/// ```
pub const fn delete_ban(
&self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>,
) -> DeleteBan<'_> {
DeleteBan::new(self, guild_id, user_id)
}
/// Get a channel by its ID.
///
/// # Examples
///
/// Get channel `100`:
///
/// ```no_run
/// # use twilight_http::Client;
/// # use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let channel_id = Id::new(100);
/// #
/// let channel = client.channel(channel_id).await?;
/// # Ok(()) }
/// ```
pub const fn channel(&self, channel_id: Id<ChannelMarker>) -> GetChannel<'_> {
GetChannel::new(self, channel_id)
}
/// Delete a channel by ID.
pub const fn delete_channel(&self, channel_id: Id<ChannelMarker>) -> DeleteChannel<'_> {
DeleteChannel::new(self, channel_id)
}
/// Update a channel.
pub const fn update_channel(&self, channel_id: Id<ChannelMarker>) -> UpdateChannel<'_> {
UpdateChannel::new(self, channel_id)
}
/// Follows a news channel by [`Id<ChannelMarker>`].
///
/// The type returned is [`FollowedChannel`].
///
/// [`FollowedChannel`]: ::twilight_model::channel::FollowedChannel
pub const fn follow_news_channel(
&self,
channel_id: Id<ChannelMarker>,
webhook_channel_id: Id<ChannelMarker>,
) -> FollowNewsChannel<'_> {
FollowNewsChannel::new(self, channel_id, webhook_channel_id)
}
/// Get the invites for a guild channel.
///
/// Requires the [`MANAGE_CHANNELS`] permission. This method only works if
/// the channel is a guild channel.
///
/// [`MANAGE_CHANNELS`]: twilight_model::guild::Permissions::MANAGE_CHANNELS
pub const fn channel_invites(&self, channel_id: Id<ChannelMarker>) -> GetChannelInvites<'_> {
GetChannelInvites::new(self, channel_id)
}
/// Get channel messages, by [`Id<ChannelMarker>`].
///
/// Only one of [`after`], [`around`], and [`before`] can be specified at a time.
/// Once these are specified, the type returned is [`GetChannelMessagesConfigured`].
///
/// If [`limit`] is unspecified, the default set by Discord is 50.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
/// let channel_id = Id::new(123);
/// let message_id = Id::new(234);
/// let limit: u16 = 6;
///
/// let messages = client
/// .channel_messages(channel_id)
/// .before(message_id)
/// .limit(limit)
/// .await?;
///
/// # Ok(()) }
/// ```
///
/// # Errors
///
/// Returns an error of type [`ValidationErrorType::GetChannelMessages`] if
/// the amount is less than 1 or greater than 100.
///
/// [`GetChannelMessagesConfigured`]: crate::request::channel::message::GetChannelMessagesConfigured
/// [`ValidationErrorType::GetChannelMessages`]: twilight_validate::request::ValidationErrorType::GetChannelMessages
/// [`after`]: GetChannelMessages::after
/// [`around`]: GetChannelMessages::around
/// [`before`]: GetChannelMessages::before
/// [`limit`]: GetChannelMessages::limit
pub const fn channel_messages(&self, channel_id: Id<ChannelMarker>) -> GetChannelMessages<'_> {
GetChannelMessages::new(self, channel_id)
}
pub const fn delete_channel_permission(
&self,
channel_id: Id<ChannelMarker>,
) -> DeleteChannelPermission<'_> {
DeleteChannelPermission::new(self, channel_id)
}
/// Update the permissions for a role or a user in a channel.
///
/// # Examples:
///
/// Create permission overrides for a role to view the channel, but not send
/// messages:
///
/// ```no_run
/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # use twilight_http::Client;
/// # let client = Client::new("my token".to_owned());
/// #
/// use twilight_model::{
/// guild::Permissions,
/// http::permission_overwrite::{PermissionOverwrite, PermissionOverwriteType},
/// id::{marker::RoleMarker, Id},
/// };
///
/// let channel_id = Id::new(123);
/// let role_id: Id<RoleMarker> = Id::new(432);
/// let permission_overwrite = PermissionOverwrite {
/// allow: Some(Permissions::VIEW_CHANNEL),
/// deny: Some(Permissions::SEND_MESSAGES),
/// id: role_id.cast(),
/// kind: PermissionOverwriteType::Role,
/// };
///
/// client
/// .update_channel_permission(channel_id, &permission_overwrite)
/// .await?;
/// # Ok(()) }
/// ```
pub const fn update_channel_permission(
&self,
channel_id: Id<ChannelMarker>,
permission_overwrite: &PermissionOverwrite,
) -> UpdateChannelPermission<'_> {
UpdateChannelPermission::new(self, channel_id, permission_overwrite)
}
/// Get all the webhooks of a channel.
pub const fn channel_webhooks(&self, channel_id: Id<ChannelMarker>) -> GetChannelWebhooks<'_> {
GetChannelWebhooks::new(self, channel_id)
}
/// Get information about the current user.
pub const fn current_user(&self) -> GetCurrentUser<'_> {
GetCurrentUser::new(self)
}
/// Get information about the current user in a guild.
pub const fn current_user_guild_member(
&self,
guild_id: Id<GuildMarker>,
) -> GetCurrentUserGuildMember<'_> {
GetCurrentUserGuildMember::new(self, guild_id)
}
/// Get information about the current OAuth2 authorization.
pub const fn current_authorization(&self) -> GetCurrentAuthorizationInformation<'_> {
GetCurrentAuthorizationInformation::new(self)
}
/// Get information about the current bot application.
pub const fn current_user_application(&self) -> GetUserApplicationInfo<'_> {
GetUserApplicationInfo::new(self)
}
/// Update the current user's application.
pub const fn update_current_user_application(&self) -> UpdateCurrentUserApplication<'_> {
UpdateCurrentUserApplication::new(self)
}
/// Update the current user.
///
/// All parameters are optional. If the username is changed, it may cause the discriminator to
/// be randomized.
pub const fn update_current_user(&self) -> UpdateCurrentUser<'_> {
UpdateCurrentUser::new(self)
}
/// Update the current user's voice state.
///
/// All parameters are optional.
///
/// # Caveats
///
/// - `channel_id` must currently point to a stage channel.
/// - Current user must have already joined `channel_id`.
pub const fn update_current_user_voice_state(
&self,
guild_id: Id<GuildMarker>,
) -> UpdateCurrentUserVoiceState<'_> {
UpdateCurrentUserVoiceState::new(self, guild_id)
}
/// Get the current user's connections.
///
/// Requires the `connections` `OAuth2` scope.
pub const fn current_user_connections(&self) -> GetCurrentUserConnections<'_> {
GetCurrentUserConnections::new(self)
}
/// Returns a list of guilds for the current user.
///
/// # Examples
///
/// Get the first 25 guilds with an ID after `300` and before
/// `400`:
///
/// ```no_run
/// # use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let after = Id::new(300);
/// let before = Id::new(400);
/// let guilds = client
/// .current_user_guilds()
/// .after(after)
/// .before(before)
/// .limit(25)
/// .await?;
/// # Ok(()) }
/// ```
pub const fn current_user_guilds(&self) -> GetCurrentUserGuilds<'_> {
GetCurrentUserGuilds::new(self)
}
/// Get the emojis for a guild, by the guild's id.
///
/// # Examples
///
/// Get the emojis for guild `100`:
///
/// ```no_run
/// # use twilight_http::Client;
/// # use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let guild_id = Id::new(100);
///
/// client.emojis(guild_id).await?;
/// # Ok(()) }
/// ```
pub const fn emojis(&self, guild_id: Id<GuildMarker>) -> GetEmojis<'_> {
GetEmojis::new(self, guild_id)
}
/// Get the entitlements for an application.
///
/// # Examples
///
/// Get emojis for the application `100`:
///
/// ```no_run
/// # use twilight_http::Client;
/// # use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let application_id = Id::new(100);
///
/// client.entitlements(application_id).await?;
/// # Ok(()) }
/// ```
pub const fn entitlements(&self, application_id: Id<ApplicationMarker>) -> GetEntitlements<'_> {
GetEntitlements::new(self, application_id)
}
/// Get an emoji for a guild by the the guild's ID and emoji's ID.
///
/// # Examples
///
/// Get emoji `100` from guild `50`:
///
/// ```no_run
/// # use twilight_http::Client;
/// # use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let guild_id = Id::new(50);
/// let emoji_id = Id::new(100);
///
/// client.emoji(guild_id, emoji_id).await?;
/// # Ok(()) }
/// ```
pub const fn emoji(
&self,
guild_id: Id<GuildMarker>,
emoji_id: Id<EmojiMarker>,
) -> GetEmoji<'_> {
GetEmoji::new(self, guild_id, emoji_id)
}
/// Create an emoji in a guild.
///
/// The emoji must be a Data URI, in the form of
/// `data:image/{type};base64,{data}` where `{type}` is the image MIME type
/// and `{data}` is the base64-encoded image. See [Discord Docs/Image Data].
///
/// [Discord Docs/Image Data]: https://discord.com/developers/docs/reference#image-data
pub const fn create_emoji<'a>(
&'a self,
guild_id: Id<GuildMarker>,
name: &'a str,
image: &'a str,
) -> CreateEmoji<'a> {
CreateEmoji::new(self, guild_id, name, image)
}
/// Delete an emoji in a guild, by id.
pub const fn delete_emoji(
&self,
guild_id: Id<GuildMarker>,
emoji_id: Id<EmojiMarker>,
) -> DeleteEmoji<'_> {
DeleteEmoji::new(self, guild_id, emoji_id)
}
/// Update an emoji in a guild, by id.
pub const fn update_emoji(
&self,
guild_id: Id<GuildMarker>,
emoji_id: Id<EmojiMarker>,
) -> UpdateEmoji<'_> {
UpdateEmoji::new(self, guild_id, emoji_id)
}
/// Get information about the gateway, optionally with additional information detailing the
/// number of shards to use and sessions remaining.
///
/// # Examples
///
/// Get the gateway connection URL without bot information:
///
/// ```no_run
/// # use twilight_http::Client;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let info = client.gateway().await?;
/// # Ok(()) }
/// ```
///
/// Get the gateway connection URL with additional shard and session information, which
/// requires specifying a bot token:
///
/// ```no_run
/// # use twilight_http::Client;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let info = client.gateway().authed().await?.model().await?;
///
/// println!("URL: {}", info.url);
/// println!("Recommended shards to use: {}", info.shards);
/// # Ok(()) }
/// ```
pub const fn gateway(&self) -> GetGateway<'_> {
GetGateway::new(self)
}
/// Get information about a guild.
pub const fn guild(&self, guild_id: Id<GuildMarker>) -> GetGuild<'_> {
GetGuild::new(self, guild_id)
}
/// Create a new request to create a guild.
///
/// The minimum length of the name is 2 UTF-16 characters and the maximum is 100 UTF-16
/// characters. This endpoint can only be used by bots in less than 10 guilds.
///
/// # Errors
///
/// Returns a [`CreateGuildErrorType::NameInvalid`] error type if the name
/// length is too short or too long.
///
/// [`CreateGuildErrorType::NameInvalid`]: crate::request::guild::create_guild::CreateGuildErrorType::NameInvalid
pub fn create_guild(&self, name: String) -> CreateGuild<'_> {
CreateGuild::new(self, name)
}
/// Delete a guild permanently. The user must be the owner.
pub const fn delete_guild(&self, guild_id: Id<GuildMarker>) -> DeleteGuild<'_> {
DeleteGuild::new(self, guild_id)
}
/// Update a guild.
///
/// All endpoints are optional. See [Discord Docs/Modify Guild].
///
/// [Discord Docs/Modify Guild]: https://discord.com/developers/docs/resources/guild#modify-guild
pub const fn update_guild(&self, guild_id: Id<GuildMarker>) -> UpdateGuild<'_> {
UpdateGuild::new(self, guild_id)
}
/// Leave a guild by id.
pub const fn leave_guild(&self, guild_id: Id<GuildMarker>) -> LeaveGuild<'_> {
LeaveGuild::new(self, guild_id)
}
/// Get the channels in a guild.
pub const fn guild_channels(&self, guild_id: Id<GuildMarker>) -> GetGuildChannels<'_> {
GetGuildChannels::new(self, guild_id)
}
/// Create a new request to create a guild channel.
///
/// All fields are optional except for name. The minimum length of the name
/// is 1 UTF-16 character and the maximum is 100 UTF-16 characters.
///
/// # Errors
///
/// Returns an error of type [`NameInvalid`] when the length of the name is
/// either fewer than 1 UTF-16 character or more than 100 UTF-16 characters.
///
/// Returns an error of type [`RateLimitPerUserInvalid`] when the seconds of
/// the rate limit per user is more than 21600.
///
/// Returns an error of type [`TopicInvalid`] when the length of the topic
/// is more than 1024 UTF-16 characters.
///
/// [`NameInvalid`]: twilight_validate::channel::ChannelValidationErrorType::NameInvalid
/// [`RateLimitPerUserInvalid`]: twilight_validate::channel::ChannelValidationErrorType::RateLimitPerUserInvalid
/// [`TopicInvalid`]: twilight_validate::channel::ChannelValidationErrorType::TopicInvalid
pub fn create_guild_channel<'a>(
&'a self,
guild_id: Id<GuildMarker>,
name: &'a str,
) -> CreateGuildChannel<'a> {
CreateGuildChannel::new(self, guild_id, name)
}
/// Modify the guild onboarding flow.
pub const fn update_guild_onboarding(
&self,
guild_id: Id<GuildMarker>,
fields: UpdateGuildOnboardingFields,
) -> UpdateGuildOnboarding {
UpdateGuildOnboarding::new(self, guild_id, fields)
}
/// Modify the positions of the channels.
///
/// The minimum amount of channels to modify, is a swap between two channels.
pub const fn update_guild_channel_positions<'a>(
&'a self,
guild_id: Id<GuildMarker>,
channel_positions: &'a [Position],
) -> UpdateGuildChannelPositions<'a> {
UpdateGuildChannelPositions::new(self, guild_id, channel_positions)
}
/// Get a guild's widget.
///
/// See [Discord Docs/Get Guild Widget].
///
/// [Discord Docs/Get Guild Widget]: https://discord.com/developers/docs/resources/guild#get-guild-widget
pub const fn guild_widget(&self, guild_id: Id<GuildMarker>) -> GetGuildWidget<'_> {
GetGuildWidget::new(self, guild_id)
}
/// Get a guild's widget settings.
///
/// See [Discord Docs/Get Guild Widget Settings].
///
/// [Discord Docs/Get Guild Widget]: https://discord.com/developers/docs/resources/guild#get-guild-widget-settings
pub const fn guild_widget_settings(
&self,
guild_id: Id<GuildMarker>,
) -> GetGuildWidgetSettings<'_> {
GetGuildWidgetSettings::new(self, guild_id)
}
/// Modify a guild's widget.
///
/// See [Discord Docs/Modify Guild Widget].
///
/// [Discord Docs/Modify Guild Widget]: https://discord.com/developers/docs/resources/guild#modify-guild-widget
pub const fn update_guild_widget_settings(
&self,
guild_id: Id<GuildMarker>,
) -> UpdateGuildWidgetSettings<'_> {
UpdateGuildWidgetSettings::new(self, guild_id)
}
/// Get the guild's integrations.
pub const fn guild_integrations(&self, guild_id: Id<GuildMarker>) -> GetGuildIntegrations<'_> {
GetGuildIntegrations::new(self, guild_id)
}
/// Delete an integration for a guild, by the integration's id.
pub const fn delete_guild_integration(
&self,
guild_id: Id<GuildMarker>,
integration_id: Id<IntegrationMarker>,
) -> DeleteGuildIntegration<'_> {
DeleteGuildIntegration::new(self, guild_id, integration_id)
}
/// Get information about the invites of a guild.
///
/// Requires the [`MANAGE_GUILD`] permission.
///
/// [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
pub const fn guild_invites(&self, guild_id: Id<GuildMarker>) -> GetGuildInvites<'_> {
GetGuildInvites::new(self, guild_id)
}
/// Update a guild's MFA level.
pub const fn update_guild_mfa(
&self,
guild_id: Id<GuildMarker>,
level: MfaLevel,
) -> UpdateGuildMfa<'_> {
UpdateGuildMfa::new(self, guild_id, level)
}
/// Get the members of a guild, by id.
///
/// The upper limit to this request is 1000. If more than 1000 members are needed, the requests
/// must be chained. Discord defaults the limit to 1.
///
/// # Examples
///
/// Get the first 500 members of guild `100` after user ID `3000`:
///
/// ```no_run
/// # use twilight_http::Client;
/// use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let guild_id = Id::new(100);
/// let user_id = Id::new(3000);
/// let members = client
/// .guild_members(guild_id)
/// .after(user_id)
/// .limit(500)
/// .await?;
/// # Ok(()) }
/// ```
///
/// # Errors
///
/// Returns an error of type [`ValidationErrorType::GetGuildMembers`] if the
/// limit is invalid.
///
/// [`ValidationErrorType::GetGuildMembers`]: twilight_validate::request::ValidationErrorType::GetGuildMembers
pub const fn guild_members(&self, guild_id: Id<GuildMarker>) -> GetGuildMembers<'_> {
GetGuildMembers::new(self, guild_id)
}
/// Search the members of a specific guild by a query.
///
/// The upper limit to this request is 1000. Discord defaults the limit to 1.
///
/// # Examples
///
/// Get the first 10 members of guild `100` matching `Wumpus`:
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let guild_id = Id::new(100);
/// let members = client
/// .search_guild_members(guild_id, "Wumpus")
/// .limit(10)
/// .await?;
/// # Ok(()) }
/// ```
///
/// # Errors
///
/// Returns an error of type [`ValidationErrorType::SearchGuildMembers`] if
/// the limit is invalid.
///
/// [`GUILD_MEMBERS`]: twilight_model::gateway::Intents::GUILD_MEMBERS
/// [`ValidationErrorType::SearchGuildMembers`]: twilight_validate::request::ValidationErrorType::SearchGuildMembers
pub const fn search_guild_members<'a>(
&'a self,
guild_id: Id<GuildMarker>,
query: &'a str,
) -> SearchGuildMembers<'a> {
SearchGuildMembers::new(self, guild_id, query)
}
/// Get a member of a guild, by their id.
pub const fn guild_member(
&self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>,
) -> GetMember<'_> {
GetMember::new(self, guild_id, user_id)
}
/// Add a user to a guild.
///
/// An access token for the user with `guilds.join` scope is required. All
/// other fields are optional. See [Discord Docs/Add Guild Member].
///
/// # Errors
///
/// Returns an error of type [`ValidationErrorType::Nickname`] if the
/// nickname is too short or too long.
///
/// [`ValidationErrorType::Nickname`]: twilight_validate::request::ValidationErrorType::Nickname
/// [Discord Docs/Add Guild Member]: https://discord.com/developers/docs/resources/guild#add-guild-member
pub const fn add_guild_member<'a>(
&'a self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>,
access_token: &'a str,
) -> AddGuildMember<'a> {
AddGuildMember::new(self, guild_id, user_id, access_token)
}
/// Kick a member from a guild.
pub const fn remove_guild_member(
&self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>,
) -> RemoveMember<'_> {
RemoveMember::new(self, guild_id, user_id)
}
/// Update a guild member.
///
/// All fields are optional. See [Discord Docs/Modify Guild Member].
///
/// # Examples
///
/// Update a member's nickname to "pinky pie" and server mute them:
///
/// ```no_run
/// use std::env;
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new(env::var("DISCORD_TOKEN")?);
/// let member = client
/// .update_guild_member(Id::new(1), Id::new(2))
/// .mute(true)
/// .nick(Some("pinkie pie"))
/// .await?
/// .model()
/// .await?;
///
/// println!(
/// "user {} now has the nickname '{:?}'",
/// member.user.id, member.nick,
/// );
/// # Ok(()) }
/// ```
///
/// # Errors
///
/// Returns an error of type [`ValidationErrorType::Nickname`] if the
/// nickname length is too short or too long.
///
/// [`ValidationErrorType::Nickname`]: twilight_validate::request::ValidationErrorType::Nickname
/// [Discord Docs/Modify Guild Member]: https://discord.com/developers/docs/resources/guild#modify-guild-member
pub const fn update_guild_member(
&self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>,
) -> UpdateGuildMember<'_> {
UpdateGuildMember::new(self, guild_id, user_id)
}
/// Update the user's member in a guild.
pub const fn update_current_member(
&self,
guild_id: Id<GuildMarker>,
) -> UpdateCurrentMember<'_> {
UpdateCurrentMember::new(self, guild_id)
}
/// Add a role to a member in a guild.
///
/// # Examples
///
/// In guild `1`, add role `2` to user `3`, for the reason `"test"`:
///
/// ```no_run
/// # use twilight_http::{request::AuditLogReason, Client};
/// use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let guild_id = Id::new(1);
/// let role_id = Id::new(2);
/// let user_id = Id::new(3);
///
/// client
/// .add_guild_member_role(guild_id, user_id, role_id)
/// .reason("test")
/// .await?;
/// # Ok(()) }
/// ```
pub const fn add_guild_member_role(
&self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>,
role_id: Id<RoleMarker>,
) -> AddRoleToMember<'_> {
AddRoleToMember::new(self, guild_id, user_id, role_id)
}
/// Remove a role from a member in a guild, by id.
pub const fn remove_guild_member_role(
&self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>,
role_id: Id<RoleMarker>,
) -> RemoveRoleFromMember<'_> {
RemoveRoleFromMember::new(self, guild_id, user_id, role_id)
}
/// Retrieves the onboarding data for a guild.
pub const fn guild_onboarding(&self, guild_id: Id<GuildMarker>) -> GetGuildOnboarding<'_> {
GetGuildOnboarding::new(self, guild_id)
}
/// For public guilds, get the guild preview.
///
/// This works even if the user is not in the guild.
pub const fn guild_preview(&self, guild_id: Id<GuildMarker>) -> GetGuildPreview<'_> {
GetGuildPreview::new(self, guild_id)
}
/// Get the counts of guild members to be pruned.
pub const fn guild_prune_count(&self, guild_id: Id<GuildMarker>) -> GetGuildPruneCount<'_> {
GetGuildPruneCount::new(self, guild_id)
}
/// Begin a guild prune.
///
/// See [Discord Docs/Begin Guild Prune].
///
/// [Discord Docs/Begin Guild Prune]: https://discord.com/developers/docs/resources/guild#begin-guild-prune
pub const fn create_guild_prune(&self, guild_id: Id<GuildMarker>) -> CreateGuildPrune<'_> {
CreateGuildPrune::new(self, guild_id)
}
/// Get a guild's vanity url, if there is one.
pub const fn guild_vanity_url(&self, guild_id: Id<GuildMarker>) -> GetGuildVanityUrl<'_> {
GetGuildVanityUrl::new(self, guild_id)
}
/// Get voice region data for the guild.
///
/// Can return VIP servers if the guild is VIP-enabled.
pub const fn guild_voice_regions(&self, guild_id: Id<GuildMarker>) -> GetGuildVoiceRegions<'_> {
GetGuildVoiceRegions::new(self, guild_id)
}
/// Get the webhooks of a guild.
pub const fn guild_webhooks(&self, guild_id: Id<GuildMarker>) -> GetGuildWebhooks<'_> {
GetGuildWebhooks::new(self, guild_id)
}
/// Get the guild's welcome screen.
///
/// If the welcome screen is not enabled, this requires the [`MANAGE_GUILD`]
/// permission.
///
/// [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
pub const fn guild_welcome_screen(
&self,
guild_id: Id<GuildMarker>,
) -> GetGuildWelcomeScreen<'_> {
GetGuildWelcomeScreen::new(self, guild_id)
}
/// Update the guild's welcome screen.
///
/// Requires the [`MANAGE_GUILD`] permission.
///
/// [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
pub const fn update_guild_welcome_screen(
&self,
guild_id: Id<GuildMarker>,
) -> UpdateGuildWelcomeScreen<'_> {
UpdateGuildWelcomeScreen::new(self, guild_id)
}
/// Get information about an invite by its code.
///
/// If [`with_counts`] is called, the returned invite will contain
/// approximate member counts. If [`with_expiration`] is called, it will
/// contain the expiration date.
///
/// # Examples
///
/// ```no_run
/// # use twilight_http::Client;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let invite = client.invite("code").with_counts().await?;
/// # Ok(()) }
/// ```
///
/// [`with_counts`]: crate::request::channel::invite::GetInvite::with_counts
/// [`with_expiration`]: crate::request::channel::invite::GetInvite::with_expiration
pub const fn invite<'a>(&'a self, code: &'a str) -> GetInvite<'a> {
GetInvite::new(self, code)
}
/// Create an invite, with options.
///
/// Requires the [`CREATE_INVITE`] permission.
///
/// # Examples
///
/// ```no_run
/// # use twilight_http::Client;
/// # use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let channel_id = Id::new(123);
/// let invite = client.create_invite(channel_id).max_uses(3).await?;
/// # Ok(()) }
/// ```
///
/// [`CREATE_INVITE`]: twilight_model::guild::Permissions::CREATE_INVITE
pub const fn create_invite(&self, channel_id: Id<ChannelMarker>) -> CreateInvite<'_> {
CreateInvite::new(self, channel_id)
}
/// Delete an invite by its code.
///
/// Requires the [`MANAGE_CHANNELS`] permission on the channel this invite
/// belongs to, or [`MANAGE_GUILD`] to remove any invite across the guild.
///
/// [`MANAGE_CHANNELS`]: twilight_model::guild::Permissions::MANAGE_CHANNELS
/// [`MANAGE_GUILD`]: twilight_model::guild::Permissions::MANAGE_GUILD
pub const fn delete_invite<'a>(&'a self, code: &'a str) -> DeleteInvite<'a> {
DeleteInvite::new(self, code)
}
/// Get a message by [`Id<ChannelMarker>`] and [`Id<MessageMarker>`].
pub const fn message(
&self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
) -> GetMessage<'_> {
GetMessage::new(self, channel_id, message_id)
}
/// Send a message to a channel.
///
/// The message must include at least one of [`attachments`],
/// [`components`], [`content`], [`embeds`], or [`sticker_ids`].
///
/// # Example
///
/// ```no_run
/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// let client = Client::new("my token".to_owned());
///
/// let channel_id = Id::new(123);
/// let message = client
/// .create_message(channel_id)
/// .content("Twilight is best pony")
/// .tts(true)
/// .await?;
/// # Ok(()) }
/// ```
///
/// [`attachments`]: CreateMessage::attachments
/// [`components`]: CreateMessage::components
/// [`content`]: CreateMessage::content
/// [`embeds`]: CreateMessage::embeds
/// [`sticker_ids`]: CreateMessage::sticker_ids
pub const fn create_message(&self, channel_id: Id<ChannelMarker>) -> CreateMessage<'_> {
CreateMessage::new(self, channel_id)
}
/// Delete a message by [`Id<ChannelMarker>`] and [`Id<MessageMarker>`].
pub const fn delete_message(
&self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
) -> DeleteMessage<'_> {
DeleteMessage::new(self, channel_id, message_id)
}
/// Delete messages by [`Id<ChannelMarker>`] and Vec<[`Id<MessageMarker>`]>.
///
/// The vec count can be between 2 and 100. If the supplied
/// [`Id<MessageMarker>`]s are invalid, they still count towards the lower
/// and upper limits. This method will not delete messages older than two
/// weeks. See [Discord Docs/Bulk Delete Messages].
///
/// # Errors
///
/// Returns an error of type
/// [`ChannelValidationErrorType::BulkDeleteMessagesInvalid`] when the number of
/// messages to delete in bulk is invalid.
///
/// [Discord Docs/Bulk Delete Messages]: https://discord.com/developers/docs/resources/channel#bulk-delete-messages
/// [`ChannelValidationErrorType::BulkDeleteMessagesInvalid`]: twilight_validate::channel::ChannelValidationErrorType::BulkDeleteMessagesInvalid
pub fn delete_messages<'a>(
&'a self,
channel_id: Id<ChannelMarker>,
message_ids: &'a [Id<MessageMarker>],
) -> DeleteMessages<'a> {
DeleteMessages::new(self, channel_id, message_ids)
}
/// Update a message by [`Id<ChannelMarker>`] and [`Id<MessageMarker>`].
///
/// You can pass [`None`] to any of the methods to remove the associated
/// field. Pass [`None`] to [`content`] to remove the content. You must
/// ensure that the message still contains at least one of [`attachments`],
/// [`components`], [`content`], [`embeds`], or stickers.
///
/// # Examples
///
/// Replace the content with `"test update"`:
///
/// ```no_run
/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// let client = Client::new("my token".to_owned());
/// client
/// .update_message(Id::new(1), Id::new(2))
/// .content(Some("test update"))
/// .await?;
/// # Ok(()) }
/// ```
///
/// Remove the message's content:
///
/// ```no_run
/// # use twilight_http::Client;
/// # use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// client
/// .update_message(Id::new(1), Id::new(2))
/// .content(None)
/// .await?;
/// # Ok(()) }
/// ```
///
/// [`attachments`]: UpdateMessage::attachments
/// [`components`]: UpdateMessage::components
/// [`content`]: UpdateMessage::content
/// [`embeds`]: UpdateMessage::embeds
pub const fn update_message(
&self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
) -> UpdateMessage<'_> {
UpdateMessage::new(self, channel_id, message_id)
}
/// Crosspost a message by [`Id<ChannelMarker>`] and [`Id<MessageMarker>`].
pub const fn crosspost_message(
&self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
) -> CrosspostMessage<'_> {
CrosspostMessage::new(self, channel_id, message_id)
}
/// Get the pins of a channel.
pub const fn pins(&self, channel_id: Id<ChannelMarker>) -> GetPins<'_> {
GetPins::new(self, channel_id)
}
/// Create a new pin in a channel, by ID.
pub const fn create_pin(
&self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
) -> CreatePin<'_> {
CreatePin::new(self, channel_id, message_id)
}
/// Delete a pin in a channel, by ID.
pub const fn delete_pin(
&self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
) -> DeletePin<'_> {
DeletePin::new(self, channel_id, message_id)
}
/// Get a list of users that reacted to a message with an `emoji`.
///
/// This endpoint is limited to 100 users maximum, so if a message has more than 100 reactions,
/// requests must be chained until all reactions are retrieved.
pub const fn reactions<'a>(
&'a self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
emoji: &'a RequestReactionType<'a>,
) -> GetReactions<'a> {
GetReactions::new(self, channel_id, message_id, emoji)
}
/// Create a reaction in a [`Id<ChannelMarker>`] on a [`Id<MessageMarker>`].
///
/// The reaction must be a variant of [`RequestReactionType`].
///
/// # Examples
/// ```no_run
/// # use twilight_http::{Client, request::channel::reaction::RequestReactionType};
/// # use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// #
/// let channel_id = Id::new(123);
/// let message_id = Id::new(456);
/// let emoji = RequestReactionType::Unicode { name: "🌃" };
///
/// let reaction = client
/// .create_reaction(channel_id, message_id, &emoji)
/// .await?;
/// # Ok(()) }
/// ```
pub const fn create_reaction<'a>(
&'a self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
emoji: &'a RequestReactionType<'a>,
) -> CreateReaction<'a> {
CreateReaction::new(self, channel_id, message_id, emoji)
}
/// Delete the current user's (`@me`) reaction on a message.
pub const fn delete_current_user_reaction<'a>(
&'a self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
emoji: &'a RequestReactionType<'a>,
) -> DeleteReaction<'a> {
DeleteReaction::new(self, channel_id, message_id, emoji, TargetUser::Current)
}
/// Delete a reaction by a user on a message.
pub const fn delete_reaction<'a>(
&'a self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
emoji: &'a RequestReactionType<'a>,
user_id: Id<UserMarker>,
) -> DeleteReaction<'a> {
DeleteReaction::new(self, channel_id, message_id, emoji, TargetUser::Id(user_id))
}
/// Remove all reactions on a message of an emoji.
pub const fn delete_all_reaction<'a>(
&'a self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
emoji: &'a RequestReactionType<'a>,
) -> DeleteAllReaction<'a> {
DeleteAllReaction::new(self, channel_id, message_id, emoji)
}
/// Delete all reactions by all users on a message.
pub const fn delete_all_reactions(
&self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
) -> DeleteAllReactions<'_> {
DeleteAllReactions::new(self, channel_id, message_id)
}
/// Fire a Typing Start event in the channel.
pub const fn create_typing_trigger(
&self,
channel_id: Id<ChannelMarker>,
) -> CreateTypingTrigger<'_> {
CreateTypingTrigger::new(self, channel_id)
}
/// Create a DM channel with a user.
pub const fn create_private_channel(
&self,
recipient_id: Id<UserMarker>,
) -> CreatePrivateChannel<'_> {
CreatePrivateChannel::new(self, recipient_id)
}
/// Get the roles of a guild.
pub const fn roles(&self, guild_id: Id<GuildMarker>) -> GetGuildRoles<'_> {
GetGuildRoles::new(self, guild_id)
}
/// Create a role in a guild.
///
/// # Examples
///
/// ```no_run
/// # use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// let guild_id = Id::new(234);
///
/// client
/// .create_role(guild_id)
/// .color(0xd90083)
/// .name("Bright Pink")
/// .await?;
/// # Ok(()) }
/// ```
pub const fn create_role(&self, guild_id: Id<GuildMarker>) -> CreateRole<'_> {
CreateRole::new(self, guild_id)
}
/// Delete a role in a guild, by id.
pub const fn delete_role(
&self,
guild_id: Id<GuildMarker>,
role_id: Id<RoleMarker>,
) -> DeleteRole<'_> {
DeleteRole::new(self, guild_id, role_id)
}
/// Update a role by guild id and its id.
pub const fn update_role(
&self,
guild_id: Id<GuildMarker>,
role_id: Id<RoleMarker>,
) -> UpdateRole<'_> {
UpdateRole::new(self, guild_id, role_id)
}
/// Modify the position of the roles.
///
/// The minimum amount of roles to modify, is a swap between two roles.
pub const fn update_role_positions<'a>(
&'a self,
guild_id: Id<GuildMarker>,
roles: &'a [RolePosition],
) -> UpdateRolePositions<'a> {
UpdateRolePositions::new(self, guild_id, roles)
}
/// Create a new stage instance associated with a stage channel.
///
/// Requires the user to be a moderator of the stage channel.
///
/// # Errors
///
/// Returns an error of type [`ValidationError::StageTopic`] when the topic
/// is not between 1 and 120 characters in length.
///
/// [`ValidationError::StageTopic`]: twilight_validate::request::ValidationErrorType::StageTopic
pub fn create_stage_instance<'a>(
&'a self,
channel_id: Id<ChannelMarker>,
topic: &'a str,
) -> CreateStageInstance<'a> {
CreateStageInstance::new(self, channel_id, topic)
}
/// Gets the stage instance associated with a stage channel, if it exists.
pub const fn stage_instance(&self, channel_id: Id<ChannelMarker>) -> GetStageInstance<'_> {
GetStageInstance::new(self, channel_id)
}
/// Update fields of an existing stage instance.
///
/// Requires the user to be a moderator of the stage channel.
pub const fn update_stage_instance(
&self,
channel_id: Id<ChannelMarker>,
) -> UpdateStageInstance<'_> {
UpdateStageInstance::new(self, channel_id)
}
/// Delete the stage instance of a stage channel.
///
/// Requires the user to be a moderator of the stage channel.
pub const fn delete_stage_instance(
&self,
channel_id: Id<ChannelMarker>,
) -> DeleteStageInstance<'_> {
DeleteStageInstance::new(self, channel_id)
}
/// Create a new guild based on a template.
///
/// This endpoint can only be used by bots in less than 10 guilds.
///
/// # Errors
///
/// Returns an error of type [`ValidationErrorType::TemplateName`] if the
/// name is invalid.
///
/// [`ValidationErrorType::TemplateName`]: twilight_validate::request::ValidationErrorType::TemplateName
pub fn create_guild_from_template<'a>(
&'a self,
template_code: &'a str,
name: &'a str,
) -> CreateGuildFromTemplate<'a> {
CreateGuildFromTemplate::new(self, template_code, name)
}
/// Create a template from the current state of the guild.
///
/// Requires the `MANAGE_GUILD` permission. The name must be at least 1 and
/// at most 100 characters in length.
///
/// # Errors
///
/// Returns an error of type [`ValidationErrorType::TemplateName`] if the
/// name is invalid.
///
/// [`ValidationErrorType::TemplateName`]: twilight_validate::request::ValidationErrorType::TemplateName
pub fn create_template<'a>(
&'a self,
guild_id: Id<GuildMarker>,
name: &'a str,
) -> CreateTemplate<'a> {
CreateTemplate::new(self, guild_id, name)
}
/// Delete a template by ID and code.
pub const fn delete_template<'a>(
&'a self,
guild_id: Id<GuildMarker>,
template_code: &'a str,
) -> DeleteTemplate<'a> {
DeleteTemplate::new(self, guild_id, template_code)
}
/// Get a template by its code.
pub const fn get_template<'a>(&'a self, template_code: &'a str) -> GetTemplate<'a> {
GetTemplate::new(self, template_code)
}
/// Get a list of templates in a guild, by ID.
pub const fn get_templates(&self, guild_id: Id<GuildMarker>) -> GetTemplates<'_> {
GetTemplates::new(self, guild_id)
}
/// Sync a template to the current state of the guild, by ID and code.
pub const fn sync_template<'a>(
&'a self,
guild_id: Id<GuildMarker>,
template_code: &'a str,
) -> SyncTemplate<'a> {
SyncTemplate::new(self, guild_id, template_code)
}
/// Update the template's metadata, by ID and code.
pub const fn update_template<'a>(
&'a self,
guild_id: Id<GuildMarker>,
template_code: &'a str,
) -> UpdateTemplate<'a> {
UpdateTemplate::new(self, guild_id, template_code)
}
/// Returns all active threads in the guild.
///
/// Includes public and private threads. Threads are ordered by their ID in
/// descending order.
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// let client = Client::new("my token".to_owned());
/// let guild_id = Id::new(234);
///
/// let threads = client.active_threads(guild_id).await?.model().await?;
/// # Ok(()) }
/// ```
pub const fn active_threads(&self, guild_id: Id<GuildMarker>) -> GetActiveThreads<'_> {
GetActiveThreads::new(self, guild_id)
}
/// Add another member to a thread.
///
/// Requires the ability to send messages in the thread, and that the thread
/// is not archived.
pub const fn add_thread_member(
&self,
channel_id: Id<ChannelMarker>,
user_id: Id<UserMarker>,
) -> AddThreadMember<'_> {
AddThreadMember::new(self, channel_id, user_id)
}
/// Start a thread in a forum channel.
pub const fn create_forum_thread<'a>(
&'a self,
channel_id: Id<ChannelMarker>,
name: &'a str,
) -> CreateForumThread<'a> {
CreateForumThread::new(self, channel_id, name)
}
/// Start a thread that is not connected to a message.
///
/// Automatic archive durations are not locked behind the guild's boost
/// level.
///
/// To make a [`PrivateThread`], the guild must also have the
/// `PRIVATE_THREADS` feature.
///
/// # Errors
///
/// Returns an error of type [`NameInvalid`] if the channel's name's length is
/// incorrect.
///
/// Returns an error of type [`TypeInvalid`] if the channel is not a thread.
///
/// [`NameInvalid`]: twilight_validate::channel::ChannelValidationErrorType::NameInvalid
/// [`PrivateThread`]: twilight_model::channel::ChannelType::PrivateThread
/// [`TypeInvalid`]: twilight_validate::channel::ChannelValidationErrorType::TypeInvalid
pub fn create_thread<'a>(
&'a self,
channel_id: Id<ChannelMarker>,
name: &'a str,
kind: ChannelType,
) -> CreateThread<'a> {
CreateThread::new(self, channel_id, name, kind)
}
/// Create a new thread from an existing message.
///
/// When called on a [`GuildText`] channel, this creates a
/// [`PublicThread`].
///
/// When called on a [`GuildAnnouncement`] channel, this creates a
/// [`AnnouncementThread`].
///
/// Automatic archive durations are not locked behind the guild's boost
/// level.
///
/// The thread's ID will be the same as its parent message. This ensures
/// only one thread can be created per message.
///
/// # Errors
///
/// Returns an error of type [`NameInvalid`] if the channel's name's length is
/// incorrect.
///
/// Returns an error of type [`TypeInvalid`] if the channel is not a thread.
///
/// [`AnnouncementThread`]: twilight_model::channel::ChannelType::AnnouncementThread
/// [`GuildAnnouncement`]: twilight_model::channel::ChannelType::GuildAnnouncement
/// [`GuildText`]: twilight_model::channel::ChannelType::GuildText
/// [`NameInvalid`]: twilight_validate::channel::ChannelValidationErrorType::NameInvalid
/// [`PublicThread`]: twilight_model::channel::ChannelType::PublicThread
/// [`TypeInvalid`]: twilight_validate::channel::ChannelValidationErrorType::TypeInvalid
pub fn create_thread_from_message<'a>(
&'a self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
name: &'a str,
) -> CreateThreadFromMessage<'a> {
CreateThreadFromMessage::new(self, channel_id, message_id, name)
}
/// Add the current user to a thread.
pub const fn join_thread(&self, channel_id: Id<ChannelMarker>) -> JoinThread<'_> {
JoinThread::new(self, channel_id)
}
/// Returns archived private threads in the channel that the current user
/// has joined.
///
/// Threads are ordered by their ID in descending order.
pub const fn joined_private_archived_threads(
&self,
channel_id: Id<ChannelMarker>,
) -> GetJoinedPrivateArchivedThreads<'_> {
GetJoinedPrivateArchivedThreads::new(self, channel_id)
}
/// Remove the current user from a thread.
///
/// Requires that the thread is not archived.
pub const fn leave_thread(&self, channel_id: Id<ChannelMarker>) -> LeaveThread<'_> {
LeaveThread::new(self, channel_id)
}
/// Returns archived private threads in the channel.
///
/// Requires both [`READ_MESSAGE_HISTORY`] and [`MANAGE_THREADS`].
///
/// [`MANAGE_THREADS`]: twilight_model::guild::Permissions::MANAGE_THREADS
/// [`READ_MESSAGE_HISTORY`]: twilight_model::guild::Permissions::READ_MESSAGE_HISTORY
pub const fn private_archived_threads(
&self,
channel_id: Id<ChannelMarker>,
) -> GetPrivateArchivedThreads<'_> {
GetPrivateArchivedThreads::new(self, channel_id)
}
/// Returns archived public threads in the channel.
///
/// Requires the [`READ_MESSAGE_HISTORY`] permission.
///
/// Threads are ordered by [`archive_timestamp`] in descending order.
///
/// When called in a [`GuildText`] channel, returns [`PublicThread`]s.
///
/// When called in a [`GuildAnnouncement`] channel, returns [`AnnouncementThread`]s.
///
/// [`AnnouncementThread`]: twilight_model::channel::ChannelType::AnnouncementThread
/// [`archive_timestamp`]: twilight_model::channel::thread::ThreadMetadata::archive_timestamp
/// [`GuildAnnouncement`]: twilight_model::channel::ChannelType::GuildAnnouncement
/// [`GuildText`]: twilight_model::channel::ChannelType::GuildText
/// [`PublicThread`]: twilight_model::channel::ChannelType::PublicThread
/// [`READ_MESSAGE_HISTORY`]: twilight_model::guild::Permissions::READ_MESSAGE_HISTORY
pub const fn public_archived_threads(
&self,
channel_id: Id<ChannelMarker>,
) -> GetPublicArchivedThreads<'_> {
GetPublicArchivedThreads::new(self, channel_id)
}
/// Remove another member from a thread.
///
/// Requires that the thread is not archived.
///
/// Requires the [`MANAGE_THREADS`] permission, unless both the thread is a
/// [`PrivateThread`], and the current user is the creator of the
/// thread.
///
/// [`MANAGE_THREADS`]: twilight_model::guild::Permissions::MANAGE_THREADS
/// [`PrivateThread`]: twilight_model::channel::ChannelType::PrivateThread
pub const fn remove_thread_member(
&self,
channel_id: Id<ChannelMarker>,
user_id: Id<UserMarker>,
) -> RemoveThreadMember<'_> {
RemoveThreadMember::new(self, channel_id, user_id)
}
/// Returns a [`ThreadMember`] in a thread.
///
/// [`ThreadMember`]: twilight_model::channel::thread::ThreadMember
pub const fn thread_member(
&self,
channel_id: Id<ChannelMarker>,
user_id: Id<UserMarker>,
) -> GetThreadMember<'_> {
GetThreadMember::new(self, channel_id, user_id)
}
/// Returns the [`ThreadMember`]s of the thread.
///
/// [`ThreadMember`]: twilight_model::channel::thread::ThreadMember
pub const fn thread_members(&self, channel_id: Id<ChannelMarker>) -> GetThreadMembers<'_> {
GetThreadMembers::new(self, channel_id)
}
/// Update a thread.
///
/// All fields are optional. The minimum length of the name is 1 UTF-16
/// characters and the maximum is 100 UTF-16 characters.
pub const fn update_thread(&self, channel_id: Id<ChannelMarker>) -> UpdateThread<'_> {
UpdateThread::new(self, channel_id)
}
/// Get a user's information by id.
pub const fn user(&self, user_id: Id<UserMarker>) -> GetUser<'_> {
GetUser::new(self, user_id)
}
/// Update another user's voice state.
///
/// # Caveats
///
/// - `channel_id` must currently point to a stage channel.
/// - User must already have joined `channel_id`.
pub const fn update_user_voice_state(
&self,
guild_id: Id<GuildMarker>,
user_id: Id<UserMarker>,
channel_id: Id<ChannelMarker>,
) -> UpdateUserVoiceState<'_> {
UpdateUserVoiceState::new(self, guild_id, user_id, channel_id)
}
/// Get a list of voice regions that can be used when creating a guild.
pub const fn voice_regions(&self) -> GetVoiceRegions<'_> {
GetVoiceRegions::new(self)
}
/// Get a webhook by ID.
pub const fn webhook(&self, id: Id<WebhookMarker>) -> GetWebhook<'_> {
GetWebhook::new(self, id)
}
/// Create a webhook in a channel.
///
/// # Examples
///
/// ```no_run
/// # use twilight_http::Client;
/// # use twilight_model::id::Id;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("my token".to_owned());
/// let channel_id = Id::new(123);
///
/// let webhook = client.create_webhook(channel_id, "Twily Bot").await?;
/// # Ok(()) }
/// ```
///
/// # Errors
///
/// Returns an error of type [`WebhookUsername`] if the webhook's name is
/// invalid.
///
/// [`WebhookUsername`]: twilight_validate::request::ValidationErrorType::WebhookUsername
pub fn create_webhook<'a>(
&'a self,
channel_id: Id<ChannelMarker>,
name: &'a str,
) -> CreateWebhook<'a> {
CreateWebhook::new(self, channel_id, name)
}
/// Delete a webhook by its ID.
pub const fn delete_webhook(&self, id: Id<WebhookMarker>) -> DeleteWebhook<'_> {
DeleteWebhook::new(self, id)
}
/// Update a webhook by ID.
pub const fn update_webhook(&self, webhook_id: Id<WebhookMarker>) -> UpdateWebhook<'_> {
UpdateWebhook::new(self, webhook_id)
}
/// Update a webhook, with a token, by ID.
pub const fn update_webhook_with_token<'a>(
&'a self,
webhook_id: Id<WebhookMarker>,
token: &'a str,
) -> UpdateWebhookWithToken<'a> {
UpdateWebhookWithToken::new(self, webhook_id, token)
}
/// Execute a webhook, sending a message to its channel.
///
/// The message must include at least one of [`attachments`], [`components`]
/// [`content`], or [`embeds`].
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// let client = Client::new("my token".to_owned());
/// let id = Id::new(432);
///
/// let webhook = client
/// .execute_webhook(id, "webhook token")
/// .content("Pinkie...")
/// .await?;
/// # Ok(()) }
/// ```
///
/// [`attachments`]: ExecuteWebhook::attachments
/// [`components`]: ExecuteWebhook::components
/// [`content`]: ExecuteWebhook::content
/// [`embeds`]: ExecuteWebhook::embeds
pub const fn execute_webhook<'a>(
&'a self,
webhook_id: Id<WebhookMarker>,
token: &'a str,
) -> ExecuteWebhook<'a> {
ExecuteWebhook::new(self, webhook_id, token)
}
/// Get a webhook message by webhook ID, token, and message ID.
pub const fn webhook_message<'a>(
&'a self,
webhook_id: Id<WebhookMarker>,
token: &'a str,
message_id: Id<MessageMarker>,
) -> GetWebhookMessage<'a> {
GetWebhookMessage::new(self, webhook_id, token, message_id)
}
/// Update a message executed by a webhook.
///
/// You can pass [`None`] to any of the methods to remove the associated
/// field. Pass [`None`] to [`content`] to remove the content. You must
/// ensure that the message still contains at least one of [`attachments`],
/// [`components`], [`content`], or [`embeds`].
///
/// # Examples
///
/// ```no_run
/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// let client = Client::new("token".to_owned());
/// client
/// .update_webhook_message(Id::new(1), "token here", Id::new(2))
/// .content(Some("new message content"))
/// .await?;
/// # Ok(()) }
/// ```
///
/// [`attachments`]: UpdateWebhookMessage::attachments
/// [`components`]: UpdateWebhookMessage::components
/// [`content`]: UpdateWebhookMessage::content
/// [`embeds`]: UpdateWebhookMessage::embeds
pub const fn update_webhook_message<'a>(
&'a self,
webhook_id: Id<WebhookMarker>,
token: &'a str,
message_id: Id<MessageMarker>,
) -> UpdateWebhookMessage<'a> {
UpdateWebhookMessage::new(self, webhook_id, token, message_id)
}
/// Delete a message executed by a webhook.
///
/// # Examples
///
/// ```no_run
/// # use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("token".to_owned());
/// client
/// .delete_webhook_message(Id::new(1), "token here", Id::new(2))
/// .await?;
/// # Ok(()) }
/// ```
pub const fn delete_webhook_message<'a>(
&'a self,
webhook_id: Id<WebhookMarker>,
token: &'a str,
message_id: Id<MessageMarker>,
) -> DeleteWebhookMessage<'a> {
DeleteWebhookMessage::new(self, webhook_id, token, message_id)
}
/// Delete a scheduled event in a guild.
///
/// # Examples
///
/// ```no_run
/// # use twilight_http::Client;
/// # use twilight_model::id::Id;
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("token".to_owned());
/// let guild_id = Id::new(1);
/// let scheduled_event_id = Id::new(2);
///
/// client
/// .delete_guild_scheduled_event(guild_id, scheduled_event_id)
/// .await?;
/// # Ok(()) }
/// ```
pub const fn delete_guild_scheduled_event(
&self,
guild_id: Id<GuildMarker>,
scheduled_event_id: Id<ScheduledEventMarker>,
) -> DeleteGuildScheduledEvent<'_> {
DeleteGuildScheduledEvent::new(self, guild_id, scheduled_event_id)
}
/// Create a scheduled event in a guild.
///
/// Once a guild is selected, you must choose one of three event types to
/// create. The request builders will ensure you provide the correct data to
/// Discord. See [Discord Docs/Create Guild Scheduled Event].
///
/// The name must be between 1 and 100 characters in length. For external
/// events, the location must be between 1 and 100 characters in length.
///
/// # Examples
///
/// Create an event in a stage instance:
///
/// ```no_run
/// # use twilight_http::Client;
/// use twilight_model::{guild::scheduled_event::PrivacyLevel, id::Id, util::Timestamp};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("token".to_owned());
/// let guild_id = Id::new(1);
/// let channel_id = Id::new(2);
/// let garfield_start_time = Timestamp::parse("2022-01-01T14:00:00+00:00")?;
///
/// client
/// .create_guild_scheduled_event(guild_id, PrivacyLevel::GuildOnly)
/// .stage_instance(
/// channel_id,
/// "Garfield Appreciation Hour",
/// &garfield_start_time,
/// )
/// .description("Discuss: How important is Garfield to You?")
/// .await?;
/// # Ok(()) }
/// ```
///
/// Create an external event:
///
/// ```no_run
/// # use twilight_http::Client;
/// use twilight_model::{guild::scheduled_event::PrivacyLevel, id::Id, util::Timestamp};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let client = Client::new("token".to_owned());
/// let guild_id = Id::new(1);
/// let garfield_con_start_time = Timestamp::parse("2022-01-04T08:00:00+00:00")?;
/// let garfield_con_end_time = Timestamp::parse("2022-01-06T17:00:00+00:00")?;
///
/// client
/// .create_guild_scheduled_event(guild_id, PrivacyLevel::GuildOnly)
/// .external(
/// "Garfield Con 2022",
/// "Baltimore Convention Center",
/// &garfield_con_start_time,
/// &garfield_con_end_time,
/// )
/// .description(
/// "In a spiritual successor to BronyCon, Garfield fans from \
/// around the globe celebrate all things related to the loveable cat.",
/// )
/// .await?;
/// # Ok(()) }
/// ```
///
/// [Discord Docs/Create Guild Scheduled Event]: https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event
pub const fn create_guild_scheduled_event(
&self,
guild_id: Id<GuildMarker>,
privacy_level: PrivacyLevel,
) -> CreateGuildScheduledEvent<'_> {
CreateGuildScheduledEvent::new(self, guild_id, privacy_level)
}
/// Get a scheduled event in a guild.
pub const fn guild_scheduled_event(
&self,
guild_id: Id<GuildMarker>,
scheduled_event_id: Id<ScheduledEventMarker>,
) -> GetGuildScheduledEvent<'_> {
GetGuildScheduledEvent::new(self, guild_id, scheduled_event_id)
}
/// Get a list of users subscribed to a scheduled event.
///
/// Users are returned in ascending order by `user_id`. [`before`] and
/// [`after`] both take a user id. If both are specified, only [`before`] is
/// respected. The default [`limit`] is 100. See
/// [Discord Docs/Get Guild Scheduled Event Users].
///
/// [`after`]: GetGuildScheduledEventUsers::after
/// [`before`]: GetGuildScheduledEventUsers::before
/// [`limit`]: GetGuildScheduledEventUsers::limit
/// [Discord Docs/Get Guild Scheduled Event Users]: https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event-users
pub const fn guild_scheduled_event_users(
&self,
guild_id: Id<GuildMarker>,
scheduled_event_id: Id<ScheduledEventMarker>,
) -> GetGuildScheduledEventUsers<'_> {
GetGuildScheduledEventUsers::new(self, guild_id, scheduled_event_id)
}
/// Get a list of scheduled events in a guild.
pub const fn guild_scheduled_events(
&self,
guild_id: Id<GuildMarker>,
) -> GetGuildScheduledEvents<'_> {
GetGuildScheduledEvents::new(self, guild_id)
}
/// Update a scheduled event in a guild.
///
/// This endpoint supports changing the type of event. When changing the
/// entity type to either [`EntityType::StageInstance`] or
/// [`EntityType::Voice`], an [`Id<ChannelMarker>`] must be provided if it
/// does not already exist.
///
/// When changing the entity type to [`EntityType::External`], the
/// `channel_id` field is cleared and the [`channel_id`] method has no
/// effect. Additionally, you must set a location with [`location`].
///
/// [`EntityType::External`]: twilight_model::guild::scheduled_event::EntityType::External
/// [`EntityType::StageInstance`]: twilight_model::guild::scheduled_event::EntityType::StageInstance
/// [`EntityType::Voice`]: twilight_model::guild::scheduled_event::EntityType::Voice
/// [`channel_id`]: UpdateGuildScheduledEvent::channel_id
/// [`location`]: UpdateGuildScheduledEvent::location
pub const fn update_guild_scheduled_event(
&self,
guild_id: Id<GuildMarker>,
scheduled_event_id: Id<ScheduledEventMarker>,
) -> UpdateGuildScheduledEvent<'_> {
UpdateGuildScheduledEvent::new(self, guild_id, scheduled_event_id)
}
/// Returns a single sticker by its ID.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let id = Id::new(123);
/// let sticker = client.sticker(id).await?.model().await?;
///
/// println!("{sticker:#?}");
/// # Ok(()) }
/// ```
pub const fn sticker(&self, sticker_id: Id<StickerMarker>) -> GetSticker<'_> {
GetSticker::new(self, sticker_id)
}
/// Returns a list of sticker packs available to Nitro subscribers.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let packs = client.nitro_sticker_packs().await?.model().await?;
///
/// println!("{}", packs.sticker_packs.len());
/// # Ok(()) }
/// ```
pub const fn nitro_sticker_packs(&self) -> GetNitroStickerPacks<'_> {
GetNitroStickerPacks::new(self)
}
/// Returns a list of stickers in a guild.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let guild_id = Id::new(1);
/// let stickers = client.guild_stickers(guild_id).await?.models().await?;
///
/// println!("{}", stickers.len());
/// # Ok(()) }
/// ```
pub const fn guild_stickers(&self, guild_id: Id<GuildMarker>) -> GetGuildStickers<'_> {
GetGuildStickers::new(self, guild_id)
}
/// Returns a guild sticker by the guild's ID and the sticker's ID.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let guild_id = Id::new(1);
/// let sticker_id = Id::new(2);
/// let sticker = client
/// .guild_sticker(guild_id, sticker_id)
/// .await?
/// .model()
/// .await?;
///
/// println!("{sticker:#?}");
/// # Ok(()) }
/// ```
pub const fn guild_sticker(
&self,
guild_id: Id<GuildMarker>,
sticker_id: Id<StickerMarker>,
) -> GetGuildSticker<'_> {
GetGuildSticker::new(self, guild_id, sticker_id)
}
/// Creates a sticker in a guild, and returns the created sticker.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let guild_id = Id::new(1);
/// let sticker = client
/// .create_guild_sticker(
/// guild_id,
/// &"sticker name",
/// &"sticker description",
/// &"sticker,tags",
/// &[23, 23, 23, 23],
/// )
/// .await?
/// .model()
/// .await?;
///
/// println!("{sticker:#?}");
/// # Ok(()) }
/// ```
///
/// # Errors
///
/// Returns an error of type [`DescriptionInvalid`] if the length is invalid.
///
/// Returns an error of type [`NameInvalid`] if the length is invalid.
///
/// Returns an error of type [`TagsInvalid`] if the length is invalid.
///
/// [`DescriptionInvalid`]: twilight_validate::sticker::StickerValidationErrorType::DescriptionInvalid
/// [`NameInvalid`]: twilight_validate::sticker::StickerValidationErrorType::NameInvalid
/// [`TagsInvalid`]: twilight_validate::sticker::StickerValidationErrorType::TagsInvalid
pub fn create_guild_sticker<'a>(
&'a self,
guild_id: Id<GuildMarker>,
name: &'a str,
description: &'a str,
tags: &'a str,
file: &'a [u8],
) -> CreateGuildSticker<'a> {
CreateGuildSticker::new(self, guild_id, name, description, tags, file)
}
/// Updates a sticker in a guild, and returns the updated sticker.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let guild_id = Id::new(1);
/// let sticker_id = Id::new(2);
/// let sticker = client
/// .update_guild_sticker(guild_id, sticker_id)
/// .description("new description")
/// .await?
/// .model()
/// .await?;
///
/// println!("{sticker:#?}");
/// # Ok(()) }
/// ```
pub const fn update_guild_sticker(
&self,
guild_id: Id<GuildMarker>,
sticker_id: Id<StickerMarker>,
) -> UpdateGuildSticker<'_> {
UpdateGuildSticker::new(self, guild_id, sticker_id)
}
/// Deletes a guild sticker by the ID of the guild and its ID.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let guild_id = Id::new(1);
/// let sticker_id = Id::new(2);
///
/// client.delete_guild_sticker(guild_id, sticker_id).await?;
/// # Ok(()) }
/// ```
pub const fn delete_guild_sticker(
&self,
guild_id: Id<GuildMarker>,
sticker_id: Id<StickerMarker>,
) -> DeleteGuildSticker<'_> {
DeleteGuildSticker::new(self, guild_id, sticker_id)
}
/// Creates a test entitlement to a given SKU for a given guild or user. Discord
/// will act as though that user or guild has entitlement to your premium offering.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::{Client, request::application::monetization::CreateTestEntitlementOwner};
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let application_id = Id::new(1);
/// let sku_id = Id::new(2);
/// let owner = CreateTestEntitlementOwner::Guild(Id::new(3));
///
/// client.create_test_entitlement(
/// application_id,
/// sku_id,
/// owner,
/// ).await?;
///
/// # Ok(()) }
pub const fn create_test_entitlement(
&self,
application_id: Id<ApplicationMarker>,
sku_id: Id<SkuMarker>,
owner: CreateTestEntitlementOwner,
) -> CreateTestEntitlement<'_> {
CreateTestEntitlement::new(self, application_id, sku_id, owner)
}
/// Ends a poll in a channel.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let channel_id = Id::new(1);
/// let message_id = Id::new(2);
///
/// client.end_poll(channel_id, message_id).await?;
/// # Ok(()) }
/// ```
pub const fn end_poll(
&self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
) -> EndPoll<'_> {
EndPoll::new(self, channel_id, message_id)
}
/// Deletes a currently-active test entitlement. Discord will act as though that user or
/// guild no longer has entitlement to your premium offering.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let application_id = Id::new(1);
/// let entitlement_id = Id::new(2);
///
/// client.delete_test_entitlement(
/// application_id,
/// entitlement_id,
/// ).await?;
///
/// # Ok(()) }
pub const fn delete_test_entitlement(
&self,
application_id: Id<ApplicationMarker>,
entitlement_id: Id<EntitlementMarker>,
) -> DeleteTestEntitlement<'_> {
DeleteTestEntitlement::new(self, application_id, entitlement_id)
}
/// /// Get the voters for an answer in a poll.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let channel_id = Id::new(1);
/// let message_id = Id::new(2);
/// let answer_id = 1;
///
/// let voters = client.get_answer_voters(channel_id, message_id, answer_id).await?;
///
/// println!("{:?}", voters);
/// # Ok(()) }
pub const fn get_answer_voters(
&self,
channel_id: Id<ChannelMarker>,
message_id: Id<MessageMarker>,
answer_id: u8,
) -> GetAnswerVoters<'_> {
GetAnswerVoters::new(self, channel_id, message_id, answer_id)
}
/// Returns all SKUs for a given application.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let application_id = Id::new(1);
///
/// let skus = client.get_skus(application_id).await?;
///
/// # Ok(()) }
pub const fn get_skus(&self, application_id: Id<ApplicationMarker>) -> GetSKUs<'_> {
GetSKUs::new(self, application_id)
}
/// Gets all emojis associated with an application
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let application_id = Id::new(1);
///
/// let emojis = client.get_application_emojis(application_id).await?;
///
/// # Ok(()) }
/// ```
pub const fn get_application_emojis(
&self,
application_id: Id<ApplicationMarker>,
) -> ListApplicationEmojis<'_> {
ListApplicationEmojis::new(self, application_id)
}
/// Adds an emoji to an application
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let application_id = Id::new(1);
///
/// client
/// .add_application_emoji(application_id, "emoji name", "emoji image")
/// .await?;
///
/// # Ok(()) }
/// ```
pub const fn add_application_emoji<'a>(
&'a self,
application_id: Id<ApplicationMarker>,
name: &'a str,
image: &'a str,
) -> AddApplicationEmoji<'a> {
AddApplicationEmoji::new(self, application_id, name, image)
}
/// Updates an emoji associated with an application.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let application_id = Id::new(1);
/// let emoji_id = Id::new(2);
///
/// client
/// .update_application_emoji(application_id, emoji_id, "new emoji name")
/// .await?;
///
/// # Ok(()) }
/// ```
pub const fn update_application_emoji<'a>(
&'a self,
application_id: Id<ApplicationMarker>,
emoji_id: Id<EmojiMarker>,
name: &'a str,
) -> UpdateApplicationEmoji<'a> {
UpdateApplicationEmoji::new(self, application_id, emoji_id, name)
}
/// Deletes an emoji associated with an application.
///
/// # Examples
///
/// ```no_run
/// use twilight_http::Client;
/// use twilight_model::id::Id;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("my token".to_owned());
///
/// let application_id = Id::new(1);
/// let emoji_id = Id::new(2);
///
/// client
/// .delete_application_emoji(application_id, emoji_id)
/// .await?;
///
/// # Ok(()) }
/// ```
pub const fn delete_application_emoji(
&self,
application_id: Id<ApplicationMarker>,
emoji_id: Id<EmojiMarker>,
) -> DeleteApplicationEmoji<'_> {
DeleteApplicationEmoji::new(self, application_id, emoji_id)
}
/// Execute a request, returning a future resolving to a [`Response`].
///
/// # Errors
///
/// Returns an [`ErrorType::Unauthorized`] error type if the configured
/// token has become invalid due to expiration, revocation, etc.
///
/// [`Response`]: super::response::Response
pub fn request<T>(&self, request: Request) -> ResponseFuture<T> {
match self.try_request::<T>(request) {
Ok(future) => future,
Err(source) => ResponseFuture::error(source),
}
}
fn try_request<T>(&self, request: Request) -> Result<ResponseFuture<T>, Error> {
if let Some(token_invalidated) = self.token_invalidated.as_ref() {
if token_invalidated.load(Ordering::Relaxed) {
return Err(Error {
kind: ErrorType::Unauthorized,
source: None,
});
}
}
let Request {
body,
form,
headers: req_headers,
method,
path,
ratelimit_path,
use_authorization_token,
} = request;
let protocol = if self.use_http { "http" } else { "https" };
let host = self.proxy.as_deref().unwrap_or("discord.com");
let url = format!("{protocol}://{host}/api/v{API_VERSION}/{path}");
tracing::debug!(?url);
let mut builder = hyper::Request::builder().method(method.name()).uri(&url);
if use_authorization_token {
if let Some(token) = self.token.as_deref() {
let value = HeaderValue::from_str(token).map_err(|source| {
let name = AUTHORIZATION.to_string();
Error {
kind: ErrorType::CreatingHeader { name },
source: Some(Box::new(source)),
}
})?;
if let Some(headers) = builder.headers_mut() {
headers.insert(AUTHORIZATION, value);
}
}
}
if let Some(headers) = builder.headers_mut() {
if let Some(form) = &form {
headers.insert(CONTENT_LENGTH, HeaderValue::from(form.len()));
if let Ok(content_type) = HeaderValue::try_from(form.content_type()) {
headers.insert(CONTENT_TYPE, content_type);
}
} else if let Some(bytes) = &body {
headers.insert(CONTENT_LENGTH, HeaderValue::from(bytes.len()));
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
} else if matches!(method, Method::Put | Method::Post | Method::Patch) {
headers.insert(CONTENT_LENGTH, HeaderValue::from(0));
}
#[cfg(feature = "decompression")]
headers.insert(
hyper::header::ACCEPT_ENCODING,
HeaderValue::from_static("br"),
);
headers.insert(USER_AGENT, HeaderValue::from_static(TWILIGHT_USER_AGENT));
if let Some(req_headers) = req_headers {
for (maybe_name, value) in req_headers {
if let Some(name) = maybe_name {
headers.insert(name, value);
}
}
}
if let Some(default_headers) = &self.default_headers {
for (name, value) in default_headers {
headers.insert(name, value.clone());
}
}
}
let try_req = if let Some(form) = form {
builder.body(Full::from(form.build()))
} else if let Some(bytes) = body {
builder.body(Full::from(bytes))
} else {
builder.body(Full::default())
};
let inner = self.http.request(try_req.map_err(|source| Error {
kind: ErrorType::BuildingRequest,
source: Some(Box::new(source)),
})?);
// For requests that don't use an authorization token we don't need to
// remember whether the token is invalid. This may be for requests such
// as webhooks and interactions.
let invalid_token = use_authorization_token
.then(|| self.token_invalidated.clone())
.flatten();
Ok(if let Some(ratelimiter) = &self.ratelimiter {
let tx_future = ratelimiter.wait_for_ticket(ratelimit_path);
ResponseFuture::ratelimit(invalid_token, inner, self.timeout, tx_future)
} else {
ResponseFuture::new(Box::pin(time::timeout(self.timeout, inner)), invalid_token)
})
}
}
#[cfg(test)]
mod tests {
use super::Client;
#[test]
fn client_debug_with_token() {
assert!(
format!("{:?}", Client::new("Bot foo".to_owned())).contains("token: Some(<redacted>)")
);
assert!(format!("{:?}", Client::builder().build()).contains("token: None"));
}
}