Spaces:
Runtime error
Runtime error
File size: 185,414 Bytes
ece74a6 15e1434 ece74a6 15e1434 ece74a6 29814ab ece74a6 15e1434 ece74a6 1a8fb24 ece74a6 1a8fb24 ece74a6 1a8fb24 a5fd7b9 ece74a6 b685b8b ece74a6 aebc424 2a732a9 ece74a6 1a8fb24 ece74a6 1a8fb24 ece74a6 1a8fb24 ece74a6 1a8fb24 ece74a6 1a8fb24 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 1a8fb24 ece74a6 1a8fb24 ece74a6 e807fd6 15e1434 ece74a6 6c9a078 50670e8 6c9a078 ece74a6 d0ee5fb ece74a6 15e1434 ece74a6 26c0ee0 896356c 26c0ee0 ece74a6 26c0ee0 ece74a6 26c0ee0 ece74a6 26c0ee0 ece74a6 26c0ee0 5f967d3 26c0ee0 5f967d3 26c0ee0 5f967d3 26c0ee0 5f967d3 26c0ee0 d0ee5fb ece74a6 26c0ee0 ece74a6 15dd4e3 1a8fb24 15e1434 ece74a6 15e1434 ece74a6 93acd56 1362033 ece74a6 1a8fb24 ece74a6 15e1434 ece74a6 15e1434 ece74a6 15e1434 ece74a6 d0ee5fb 15e1434 ece74a6 15e1434 ece74a6 e807fd6 ece74a6 e807fd6 ece74a6 15e1434 ece74a6 15e1434 ece74a6 d0ee5fb 15e1434 ece74a6 15e1434 ece74a6 d0ee5fb ece74a6 667d520 ece74a6 be13bae ece74a6 be13bae ece74a6 ae28340 667d520 ece74a6 667d520 ece74a6 15e1434 d0ee5fb 15e1434 ece74a6 15e1434 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 1362033 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb 23be771 ece74a6 6c9a078 50670e8 6c9a078 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 1a8fb24 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 1a8fb24 d0ee5fb ece74a6 1a8fb24 d0ee5fb ece74a6 1a8fb24 d0ee5fb ece74a6 d0ee5fb ece74a6 1a8fb24 1362033 15e1434 ece74a6 d0ee5fb ece74a6 1a8fb24 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 1a8fb24 c8f5ec1 ece74a6 1a8fb24 325c568 79148ac 53bf9de 325c568 53bf9de 325c568 53bf9de 325c568 5d1220a 325c568 5d1220a 325c568 5d1220a 325c568 5d1220a 325c568 5d1220a 325c568 5d1220a 325c568 ece74a6 1a8fb24 ece74a6 1a8fb24 ece74a6 1a8fb24 ece74a6 1362033 b8c29c9 ece74a6 15e1434 ece74a6 1a8fb24 15e1434 ece74a6 15e1434 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 c8f5ec1 ece74a6 c8f5ec1 ece74a6 c8f5ec1 ece74a6 c8f5ec1 d10e08b c8f5ec1 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 9e7d490 ece74a6 d0ee5fb ece74a6 1362033 15e1434 ece74a6 15e1434 ece74a6 15e1434 ece74a6 cbc99c6 9e7d490 cbc99c6 9e7d490 cbc99c6 895f81c cbc99c6 ece74a6 d0ee5fb ece74a6 1a8fb24 ece74a6 1a8fb24 ece74a6 1a8fb24 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb 667d520 d0ee5fb 667d520 d0ee5fb 667d520 d0ee5fb 667d520 d0ee5fb 667d520 d0ee5fb 667d520 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 c8f5ec1 d0ee5fb ece74a6 d0ee5fb 50797f4 d0ee5fb 50670e8 50797f4 ece74a6 50797f4 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 79148ac 9e7d490 53bf9de d0ee5fb ece74a6 53bf9de d0ee5fb 53bf9de d0ee5fb 5d1220a d0ee5fb 5d1220a d0ee5fb 5d1220a ece74a6 d0ee5fb 5d1220a d0ee5fb 5d1220a d0ee5fb 5d1220a d0ee5fb ece74a6 d0ee5fb ece74a6 1a8fb24 ece74a6 1a8fb24 ece74a6 d0ee5fb ece74a6 1a8fb24 15e1434 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 15e1434 ece74a6 9e7d490 d0ee5fb ece74a6 1a8fb24 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb 1a8fb24 ece74a6 9e7d490 ece74a6 d0ee5fb ece74a6 1a8fb24 ece74a6 9e7d490 ece74a6 9e7d490 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 9e7d490 ece74a6 9e7d490 ece74a6 5d1220a ece74a6 5d1220a 9e7d490 ece74a6 5d1220a 9e7d490 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 1a8fb24 15e1434 ece74a6 15e1434 ece74a6 1362033 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 15e1434 ece74a6 bd7e714 ece74a6 e87f6b4 bd7e714 ece74a6 e87f6b4 ece74a6 e87f6b4 895f81c e87f6b4 ece74a6 e87f6b4 ece74a6 e87f6b4 ece74a6 bd7e714 ece74a6 bd7e714 a5fd7b9 29814ab a5fd7b9 bd7e714 a5fd7b9 1916bfe a5fd7b9 1916bfe a5fd7b9 ece74a6 bd7e714 ece74a6 c42152c ece74a6 9e7d490 ece74a6 9e7d490 ece74a6 9e7d490 c42152c ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 b685b8b ece74a6 d0ee5fb ece74a6 1a8fb24 ece74a6 1362033 ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb ece74a6 d0ee5fb c7bba94 d0ee5fb ece74a6 d0ee5fb ece74a6 15e1434 ece74a6 15e1434 ece74a6 bd7e714 ece74a6 bd7e714 ece74a6 bd7e714 ece74a6 bd7e714 ece74a6 55b7f0e ece74a6 c8f5ec1 ece74a6 bd7e714 ece74a6 bd7e714 ece74a6 bd7e714 ece74a6 bd7e714 ece74a6 1362033 ece74a6 9e7d490 | 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 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 | "use strict";
// -------------------------------------------------------------
// DEBUG LOGGING - FIRST LINES
// -------------------------------------------------------------
console.log(">>> [BOOT] Application process group starting...");
process.stdout.write(">>> [BOOT] Purity check: Stdout is writeable.\n");
console.error(">>> [BOOT] Purity check: Stderr is writeable.");
process.on('unhandledRejection', (reason, promise) => {
console.error('>>> [BOOT] UNHANDLED REJECTION:', reason);
});
process.on('uncaughtException', (err) => {
console.error('>>> [BOOT] UNCAUGHT EXCEPTION:', err);
console.error(err.stack);
});
console.log(">>> [BOOT] Loading dependencies...");
require('dotenv').config();
const ultimateFix = require('./ultimate_fix'); // High priority fix
const networkFix = require('./network_fix');
const { Client, GatewayIntentBits, Partials, Collection, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, UserSelectMenuBuilder, ChannelSelectMenuBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ComponentType, MessageFlags, ChannelType } = require('discord.js');
function sendServerTransaction(type, guild) {
if (!guild || !guild.id) return;
console.log('SEND_SERVER_TRANSACTION', type, guild.id, guild.name || '');
}
function sendJoinTransaction(guild) {
sendServerTransaction('join', guild);
}
function sendLeaveTransaction(guild) {
sendServerTransaction('leave', guild);
}
console.log(">>> [BOOT] Discord.js loaded.");
console.log(">>> [BOOT] Loading Storage...");
const storage = require('./storage');
console.log(">>> [BOOT] Storage loaded.");
console.log(">>> [BOOT] Loading RoleStorage...");
const roleStorage = require('./roleStorage');
console.log(">>> [BOOT] RoleStorage loaded.");
console.log(">>> [BOOT] Loading Web Server module...");
const server = require('./server');
console.log(">>> [BOOT] Web Server module loaded.");
const { guildLineups, guildLineupsB, guildScrimMode, guildSelectedFormationA, guildSelectedFormationB, guildSelectedFormation, lineupOwners, activeLineupMessages, managerBoards, guildCustomFormations, guildCustomFormationNames, guildPingType, guildFriendlyPingType, save: saveLineup } = require('./lineup_persistence');
const guildActiveCategory = new Map(); // Stores the currently selected category in the UI for each guild
try {
const { createLineupAttachment, renderLineupImage } = require('./lineupRenderer');
const { createProfileAttachment } = require('./profileRenderer');
const { TACTICS, createTacticAttachment } = require('./tacticRenderer');
global.createLineupAttachment = createLineupAttachment;
global.createProfileAttachment = createProfileAttachment;
global.createTacticAttachment = createTacticAttachment;
global.TACTICS = TACTICS;
global.saveLineup = saveLineup;
console.log(">>> [BOOT] Graphics Renderers & Persistence loaded.");
} catch (err) {
console.error(">>> [BOOT] ERROR LOADING GRAPHICS:", err.message);
}
const { UI } = require('./NewBotStyle');
const broadcastSystem = require('./broadcast_system');
const grantSystem = require('./grant_system');
console.log(`[SYSTEM] Starting FriendlyBot v4.0 (Watchdog Relaxed: ${new Date().toISOString()})`);
process.on('unhandledRejection', (reason, promise) => {
console.error('[!] Unhandled Rejection:', reason);
});
process.on('uncaughtException', (err) => {
console.error('[!] Uncaught Exception:', err);
});
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildEmojisAndStickers
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
rest: {
timeout: 60000,
retries: 3
}
});
const DISCORD_ENDPOINTS = [
'https://discord.com/api',
'https://canary.discord.com/api',
'https://ptb.discord.com/api'
];
let currentEndpointIndex = 0;
// Increased to 240s (4 minutes) for extremely slow HF cold-starts + multiple endpoint retries
let connectionTimeout = setTimeout(() => {
if (!client.isReady()) {
console.error(">>> [CONNECTION WATCHDOG] Still offline after 240s or blocked. Attempting final emergency refresh...");
process.exit(1);
}
}, 240000);
console.log(`[*] Discord Client Initialized with Canary Failover + 90s Watchdog.`);
// Load Emergency Response Handler (Fix for bot not replying)
require('./emergency_handler')(client);
client.on('error', (err) => console.error('[Discord client]', err?.message || err));
client.on('shardError', (err, id) => console.error(`[Discord shard ${id}]`, err?.message || err));
client.on('shardDisconnect', (ev, id) => console.warn(`[Discord] Shard ${id} disconnected (code ${ev?.code}). Will auto-reconnect.`));
client.on('shardReconnecting', (id) => console.log(`[Discord] Shard ${id} reconnecting...`));
client.on('invalidated', () => {
console.error('[Discord] Session invalidated! Restarting process...');
process.exit(1);
});
client.commands = new Collection();
// --- 1. CONFIG ---
let RAW_TOKEN = process.env.BOT_TOKEN || process.env.TOKEN || process.env.DISCORD_TOKEN;
const TOKEN = RAW_TOKEN ? RAW_TOKEN.trim().replace(/['"]+/g, '').replace(/[\u200b-\u200d\ufeff]/g, '').replace(/^Bot\s+/i, '') : null;
if (!TOKEN) {
console.error("[!] CRITICAL: No Discord token found in environment variables.");
} else {
console.log(`[*] Token Found (Length: ${TOKEN.length}, Pattern: ${TOKEN.substring(0, 4)}...${TOKEN.substring(TOKEN.length - 4)})`);
}
// --- 2. COMMAND REGISTRATION ---
const commandsData = [
{ name: 'ping', description: 'Check bot latency' },
{
name: 'friendly', description: 'Start a friendly match poll', options: [
{ name: 'needed', type: 4, description: 'Players needed', required: false },
{ name: 'mention', type: 3, description: 'Mention type (everyone or here)', required: false }
]
},
{
name: 'leaguematch', description: 'Schedule a league match', options: [
{ name: 'home', type: 3, description: 'Home team', required: true },
{ name: 'away', type: 3, description: 'Away team', required: true },
{ name: 'link', type: 3, description: 'Match link', required: true },
{ name: 'time', type: 3, description: 'Time (e.g. 5pm)', required: false }
]
},
{
name: 'lineup', description: 'Show current lineup board', options: [
{ name: 'mention', type: 3, description: 'Mention type (everyone or here)', required: false }
]
},
{ name: 'clear', description: 'Clear messages', options: [{ name: 'amount', type: 4, description: 'Number of messages', required: true }] },
{ name: 'lock', description: 'Lock the current channel' },
{ name: 'unlock', description: 'Unlock the current channel' },
{
name: 'win', description: 'Record a win', options: [
{ name: 'result', type: 3, description: 'The score (e.g. 3-0)', required: true },
{ name: 'scorers', type: 3, description: 'Mentions and goals', required: false }
]
},
{
name: 'loss', description: 'Record a loss', options: [
{ name: 'result', type: 3, description: 'The score', required: true },
{ name: 'scorers', type: 3, description: 'Mentions and goals', required: false }
]
},
{
name: 'draw', description: 'Record a draw', options: [
{ name: 'result', type: 3, description: 'The score', required: true },
{ name: 'scorers', type: 3, description: 'Mentions and goals', required: false }
]
},
{ name: 'top', description: 'View leaderboard' },
{ name: 'record', description: 'View server record' },
{ name: 'addrole', description: 'Whitelist a role', options: [{ name: 'role', type: 8, description: 'The role', required: true }] },
{ name: 'removerole', description: 'Remove role from whitelist', options: [{ name: 'role', type: 8, description: 'The role', required: true }] },
{ name: 'setup', description: 'Configure bot features (Admin)' },
{ name: 'friendlybotsettings', description: 'View bot status and whitelist' },
{ name: 'managerlineup', description: 'Open the GUI editor to draft players interactively' },
{ name: 'lineupimage', description: 'Generate a high-quality visual representation of the lineup' },
{ name: 'sendlink', description: 'Send a match link publicly', options: [{ name: 'link', type: 3, description: 'The link to send', required: true }] },
{ name: 'profile', description: 'Generate a custom profile card', options: [{ name: 'user', type: 6, description: 'The user to check', required: false }] },
{ name: 'profileimage', description: 'Generate a high-quality visual profile card', options: [{ name: 'user', type: 6, description: 'The user to check', required: false }] },
{
name: 'tactic',
description: 'View tactical information for 7v7 formations with current lineup',
options: [
{
name: 'formation',
type: 3,
description: 'Choose a 7v7 formation',
required: true,
choices: [
{ name: 'default (4-2-1)', value: 'default' },
{ name: '3-1-2', value: '3-1-2' },
{ name: '3-0-3', value: '3-0-3' },
{ name: '3-2-1', value: '3-2-1' },
{ name: '2-3-1', value: '2-3-1' },
{ name: '2-2-2', value: '2-2-2' },
{ name: '4-1-1', value: '4-1-1' },
{ name: '3-3-0', value: '3-3-0' },
{ name: '2-1-3', value: '2-1-3' },
{ name: '1-4-1', value: '1-4-1' },
{ name: '4-2-0', value: '4-2-0' },
{ name: '3-1-3', value: '3-1-3' },
{ name: '5-0-1', value: '5-0-1' },
{ name: '3-1-1-1', value: '3-1-1-1' },
{ name: '2-2-1-1', value: '2-2-1-1' },
{ name: '4-1-2', value: '4-1-2' },
{ name: '2-3-2', value: '2-3-2' }
]
}
]
},
{ name: 'giverole', description: 'Give a role to members (Admin)', options: [{ name: 'role', type: 8, description: 'The role', required: true }] },
{ name: 'uptime', description: 'Show how long the bot has been online' },
{ name: 'motm', description: 'Award Man of the Match to a player', options: [{ name: 'player', type: 6, description: 'The player to award', required: true }] },
{
name: 'scrimlineup',
description: 'Start a scrimmage lineup with two teams facing each other',
options: [
{ name: 'mention', type: 3, description: 'Mention type (everyone or here)', required: false }
]
},
{
name: 'swap',
description: 'Swap two players positions in the lineup',
options: [
{ name: 'player1', type: 6, description: 'First player', required: true },
{ name: 'player2', type: 6, description: 'Second player', required: true }
]
},
{ name: 'on', description: 'Turn the bot on' },
{ name: 'off', description: 'Turn the bot off' },
{
name: 'scheduledfriendly',
description: 'Schedule a friendly match and send a lineup board',
options: [
{ name: 'time', type: 3, description: 'Time/Date (e.g. 9 PM or 2026/5/4 9 PM)', required: true },
{
name: 'type',
type: 3,
description: 'Lineup type',
required: false,
choices: [
{ name: 'Voting (Poll)', value: 'voting' },
{ name: 'Manager (Manual)', value: 'manager' }
]
}
]
}
];
client.once('ready', async () => {
console.log(`[SYSTEM] ##########################################`);
console.log(`[SYSTEM] FriendlyBot is ONLINE as ${client.user.tag}`);
console.log(`[SYSTEM] Connected to ${client.guilds.cache.size} servers`);
console.log(`[SYSTEM] ##########################################`);
try {
const guildCount = client.guilds.cache.size;
if (guildCount === 0) {
console.log('[*] Bot is in no servers yet — registering global slash commands...');
await client.application.commands.set(commandsData);
} else {
// Per-guild registration so / commands show up immediately (global can take up to ~1 hour).
console.log(`[*] Syncing slash commands to ${guildCount} server(s)...`);
await client.application.commands.set([]).catch(() => { });
for (const guild of client.guilds.cache.values()) {
await guild.commands.set(commandsData).catch((err) => {
console.error(`[!] Slash sync failed for "${guild.name}" (${guild.id}):`, err.message);
});
}
}
console.log('[*] Slash commands synchronized.');
} catch (e) {
console.error(`[!] Command Sync Error: ${e.message}`);
}
// Auto-Scan Pending Polls & Cleanup
for (const guild of client.guilds.cache.values()) {
const backupChannel = guild.channels.cache.find(c => c.name === 'friendlybot-storage');
if (backupChannel) {
backupChannel.delete().catch(() => { });
}
}
// Auto-Friendly Background Loop
setInterval(async () => {
const now = Date.now();
for (const guild of client.guilds.cache.values()) {
const config = storage.data.config[guild.id];
if (config?.autoFriendlyEnabled && config?.autoFriendlyChannel) {
const intervalMs = (config.autoFriendlyInterval || 40) * 60000;
const lastRun = config.lastAutoFriendly || 0;
if (now - lastRun >= intervalMs) {
try {
const channel = await guild.channels.fetch(config.autoFriendlyChannel).catch(() => null);
if (channel && channel.isTextBased()) {
const needed = 7;
const content = getFriendlyText(guild.id, needed);
const msg = await channel.send({ content, allowedMentions: { parse: ['everyone', 'roles', 'users'] } });
await msg.react('🟩');
await msg.react('🟥');
storage.data.active_polls[guild.id] = msg.id;
config.lastAutoFriendly = now;
storage.save('config');
storage.save('active_polls');
}
} catch (err) {
console.error(`Auto-friendly error in ${guild.name}:`, err);
}
}
}
}
// Leaderboard Auto-Post
for (const guild of client.guilds.cache.values()) {
const config = storage.data.config[guild.id];
if (config?.leaderboardChannel && config?.statsFrequency && config.statsFrequency !== 'never') {
const freqMs = config.statsFrequency === 'daily' ? 86400000 : config.statsFrequency === 'weekly' ? 604800000 : config.statsFrequency === 'monthly' ? 2592000000 : 0;
const lastRun = config.lastLeaderboard || 0;
if (freqMs > 0 && now - lastRun >= freqMs) {
try {
const channel = await guild.channels.fetch(config.leaderboardChannel).catch(() => null);
if (channel && channel.isTextBased()) {
// "best to worst the best coming from the bottom until the best to the top" -> means 100 at top, 1 at bottom.
const sorted = Object.entries(storage.data.stats || {})
.sort((a, b) => (b[1].matches || 0) - (a[1].matches || 0))
.slice(0, 30);
// Map to strings with normal 1-based ranks
const ranked = sorted.map(([id, data], i) => `**#${i + 1}** <@${id}> — \`${data.matches || 0}\` matches | ⭐ \`${data.mvps || 0}\` MVPs`);
let text = ranked.join('\n');
if (!text) text = "No data yet.";
// Split into chunks if > 4096 chars (Discord embed limit)
const chunks = [];
let currentChunk = "";
const lines = text.split('\n');
for (const line of lines) {
if (currentChunk.length + line.length > 4000) {
chunks.push(currentChunk);
currentChunk = line + "\n";
} else {
currentChunk += line + "\n";
}
}
if (currentChunk) chunks.push(currentChunk);
// Delete old message if we have one (to keep it fresh and clean)
if (config.leaderboardMessageId) {
try {
const oldMsg = await channel.messages.fetch(config.leaderboardMessageId).catch(() => null);
if (oldMsg) await oldMsg.delete().catch(() => {});
} catch (e) {}
}
let lastMsgId = null;
for (let i = 0; i < chunks.length; i++) {
const embed = UI.createEmbed("🏆 Most Active Players", chunks[i]);
if (i === 0) embed.setDescription(chunks[i]); // ensuring it's set
const msg = await channel.send({ embeds: [embed] });
lastMsgId = msg.id; // Store the last one or the only one
}
config.leaderboardMessageId = lastMsgId;
config.lastLeaderboard = now;
storage.save('config');
}
} catch (err) {
console.error(`Leaderboard auto-post error in ${guild.name}:`, err);
}
}
}
}
// --- NEW MAINTENANCE SYSTEM ---
// 1. Handle Auto-Cleanup Queue
const newCleanupQueue = [];
for (const item of (storage.data.cleanup_queue || [])) {
if (now >= item.expiry) {
try {
const channel = await client.channels.fetch(item.channelId).catch(() => null);
if (channel) {
const msg = await channel.messages.fetch(item.messageId).catch(() => null);
if (msg) await msg.delete().catch(() => { });
}
} catch (e) { }
} else {
newCleanupQueue.push(item);
}
}
if (newCleanupQueue.length !== (storage.data.cleanup_queue || []).length) {
storage.data.cleanup_queue = newCleanupQueue;
storage.save('active_polls');
}
// 2. Handle Match Reminders
const newScheduledMatches = [];
let changed = false;
for (const match of (storage.data.scheduled_matches || [])) {
const config = storage.data.config[match.guildId] || {};
if (config.remindersEnabled && !match.reminded) {
const leadMs = (config.remindersLead || 30) * 60000;
const timeToKickoff = match.timestamp - now;
// Remind if we are within the window (with 30s buffer)
if (now >= match.timestamp - leadMs - 30000 && now < match.timestamp) {
console.log(`[REMINDER] Firing for guild ${match.guildId} (Match TS: ${match.timestamp}, Now: ${now})`);
match.reminded = true;
changed = true;
const players = new Set();
// 1. Get people on the lineup board
const lineup = getGuildLineup(match.guildId);
for (const uids of lineup.values()) {
if (Array.isArray(uids)) {
uids.forEach(uid => players.add(uid));
}
}
// 2. Get people who reacted (voters)
if (match.messageId && match.channelId) {
try {
const channel = await client.channels.fetch(match.channelId).catch(() => null);
if (channel) {
const msg = await channel.messages.fetch(match.messageId).catch(() => null);
if (msg) {
// Fetch ALL reactions live to ensure we don't miss anyone after restart
const reaction = msg.reactions.cache.get('🟩');
if (reaction) {
const voters = await reaction.users.fetch({ limit: 100 }).catch(() => new Map());
voters.forEach(v => { if (!v.bot) players.add(v.id); });
}
}
}
} catch (e) { console.error("[REMINDER] Voter fetch error:", e.message); }
}
if (players.size === 0) {
console.log(`[REMINDER] Skipping - No players or voters found for match ${match.timestamp}`);
continue;
}
console.log(`[REMINDER] Sending DMs to ${players.size} unique users.`);
const embed = UI.createEmbed("🕒 MATCH REMINDER",
match.type === 'friendly'
? `Your scheduled friendly match starts in **${config.remindersLead || 30} minutes**!\n\n⚽ **Friendly Match**\n⏰ **Kickoff**: ${match.timeInput || 'Soon'}`
: `Your league match against **${match.away}** starts in **${config.remindersLead || 30} minutes**!\n\n🏟️ **Field**: ${match.home}\n🔗 **Link**: ${match.link}`,
UI.colors.primary);
for (const uid of players) {
try {
const user = await client.users.fetch(uid).catch(() => null);
if (user) {
await user.send({ embeds: [embed] }).catch(err => {
console.warn(`[REMINDER] Could not DM user ${uid}: ${err.message}`);
});
}
} catch (e) { }
}
}
}
// Keep matches until 1 hour after kickoff
if (now < match.timestamp + 3600000) {
newScheduledMatches.push(match);
} else {
changed = true;
}
}
if (changed || newScheduledMatches.length !== (storage.data.scheduled_matches || []).length) {
storage.data.scheduled_matches = newScheduledMatches;
storage.save('active_polls');
}
}, 30000); // Check every 30 seconds for better precision
});
function addToCleanupQueue(guildId, channelId, messageId, type = 'poll') {
const config = storage.data.config[guildId] || {};
const hours = type === 'lineup' ? (config.lineupCleanupHours || 2) : (config.cleanupHours || 2);
const expiry = Date.now() + (hours * 3600000);
if (!storage.data.cleanup_queue) storage.data.cleanup_queue = [];
storage.data.cleanup_queue.push({ guildId, channelId, messageId, expiry });
storage.save('active_polls');
}
const inviteCache = new Map();
let cachedApp = null;
let cachedLogChannel = null;
async function logTransaction(client, commandName, user, guild, member) {
try {
const logChannelId = '1495044946107961364';
if (!cachedLogChannel) {
cachedLogChannel = await client.channels.fetch(logChannelId).catch(() => null);
}
const channel = cachedLogChannel;
if (channel) {
let inviteUrl = null;
if (guild) {
if (inviteCache.has(guild.id)) {
inviteUrl = inviteCache.get(guild.id);
} else {
try {
let sysChannel = guild.systemChannel || guild.channels.cache.find(c => c.isTextBased() && c.permissionsFor(guild.members.me).has('CreateInstantInvite'));
if (sysChannel) {
const invites = await sysChannel.fetchInvites().catch(() => new Map());
if (invites.size > 0) {
inviteUrl = invites.first().url;
} else {
const inv = await sysChannel.createInvite({ maxAge: 0, maxUses: 0 }).catch(() => null);
if (inv) inviteUrl = inv.url;
}
if (inviteUrl) inviteCache.set(guild.id, inviteUrl);
}
} catch (e) { }
}
}
let worked = true;
let isWhiteListed = guild && member ? roleStorage.isWhitelisted(guild.id, member) : false;
let isAdmin = member && member.permissions ? member.permissions.has('Administrator') : false;
if (!cachedApp) {
cachedApp = await client.application.fetch().catch(() => null);
}
const app = cachedApp;
let isOwner = app && app.owner ? (user.id === app.owner.ownerId || user.id === app.owner.id) : false;
const whitelistCmds = ['friendly', 'lineup', 'win', 'loss', 'draw', 'leaguematch', 'clear', 'lock', 'unlock', 'sendlink', 'lineupimage', 'managerlineup'];
const adminCmds = ['setup', 'addrole', 'removerole', 'sync', 'sync_cmds'];
const ownerCmds = ['reboot', 'grantservers'];
if (whitelistCmds.includes(commandName) && !isWhiteListed && !isAdmin && !isOwner) worked = false;
if (adminCmds.includes(commandName) && !isAdmin && !isOwner) worked = false;
if (ownerCmds.includes(commandName) && !isOwner) worked = false;
if (commandName === 'servers' && !isOwner && user.id !== (storage.data.settings?.serverViewer || "")) worked = false;
const statusStr = worked ? "✅ Success" : "❌ Failed (No Permission)";
const serverField = guild ? (inviteUrl ? `[${guild.name}](${inviteUrl})` : guild.name) : 'DM';
const embed = new EmbedBuilder()
.setTitle(`Command Executed: ${commandName}`)
.addFields(
{ name: 'User', value: `${user.tag} (${user.id})`, inline: true },
{ name: 'Server', value: serverField, inline: true },
{ name: 'Status', value: statusStr, inline: false }
)
.setColor(worked ? 0x5865F2 : 0xED4245)
.setTimestamp();
await channel.send({ embeds: [embed] }).catch(() => { });
}
} catch (e) {
console.error("Log Transaction Error:", e);
}
}
// --- 3. EVENT HANDLERS ---
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
const prefix = storage.getPrefix(message.guildId);
if (!prefix || !message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const rawCommandName = args.shift().toLowerCase();
// Alias support
const config = storage.data.config[message.guildId] || {};
const aliasMap = config.aliases || {};
const commandName = aliasMap[rawCommandName] || rawCommandName;
if (message.channel.type === 1) { // DM channel
return;
}
const botEnabled = config.botEnabled !== false; // Default to true if not set
if (!botEnabled && commandName !== 'on') {
return message.reply("⚠️ The bot is currently **OFF**. Please use `/on` if you want to use the bot.");
}
// Removed locks for better responsiveness as requested by user
const userId = String(message.author?.id || 'unknown');
if (commandName === 'friendly') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null;
let needed = 6;
let pingType = 'everyone';
if (mentionArg === 'here' || mentionArg === 'everyone') {
pingType = mentionArg;
needed = parseInt(args[1]) || 6;
} else if (parseInt(mentionArg)) {
needed = parseInt(mentionArg);
if (args[1] === 'here' || args[1] === 'everyone') {
pingType = args[1];
}
}
guildFriendlyPingType.set(message.guildId, pingType);
saveLineup();
pollNeededCount.set(message.guildId, needed);
let content = pingType === 'here' ? getFriendlyText(message.guildId, needed).replace(/@everyone/gi, '@here') : getFriendlyText(message.guildId, needed);
const msg = await message.channel.send({ content, allowedMentions: { parse: ['everyone', 'roles', 'users'] } });
await msg.react('🟩').catch(() => { });
await msg.react('🟥').catch(() => { });
storage.data.active_polls[message.guildId] = msg.id;
storage.save('active_polls');
const joined = new Set();
const filter = (reaction, user) => (reaction.emoji.name === '🟩' || reaction.emoji.name === "I'm In") && !user.bot;
const collector = msg.createReactionCollector({ filter, time: 600000 });
collector.on('collect', (reaction, user) => {
if (!joined.has(user.id)) {
joined.add(user.id);
msg.edit({
content: content + `\n\n${joined.size}/${needed} players joined. Waiting for more...`,
allowedMentions: { parse: ['everyone', 'roles', 'users'] }
}).catch(() => {});
}
if (joined.size >= needed) collector.stop('ready');
});
collector.on('end', async (col, reason) => {
if (reason === 'ready') {
const lineup = getGuildLineup(message.guildId);
lineup.clear();
saveLineup();
// Produce final lineup as a single message, reusing existing lineup message if present
const view = createLineupView(message.guildId);
let lineupMsg = null;
const existingInfo = activeLineupMessages.get(message.guildId);
if (existingInfo) {
try {
const ch = await client.channels.fetch(existingInfo.channelId).catch(() => null);
if (ch) {
const existing = await ch.messages.fetch(existingInfo.messageId).catch(() => null);
if (existing) {
await existing.edit(view).catch(() => {});
lineupMsg = existing;
}
}
} catch {}
}
if (!lineupMsg) {
lineupMsg = await message.channel.send(view);
}
activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: lineupMsg.id });
addToCleanupQueue(message.guildId, message.channelId, lineupMsg.id, 'lineup');
// Update poll to show it's ready
try {
await msg.edit({
content: content + `\n\n✅ **Match is Ready!** Check the board below.`,
allowedMentions: { parse: ['everyone', 'roles', 'users'] }
}).catch(() => { });
} catch { /* ignore */ }
} else {
// If not ready, inform via the poll message only
try {
await msg.edit({
content: content + `\n\n❌ Canceled: not enough players joined.`,
allowedMentions: { parse: ['everyone', 'roles', 'users'] }
}).catch(() => { });
} catch { /* ignore */ }
}
delete storage.data.active_polls[message.guildId];
pollNeededCount.delete(message.guildId);
storage.save('active_polls');
});
addToCleanupQueue(message.guildId, message.channelId, msg.id, 'poll');
return;
}
if (commandName === 'lineup') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null;
const pingType = mentionArg === 'here' ? 'here' : 'everyone';
guildPingType.set(message.guildId, pingType);
lineupOwners.set(message.guildId, message.author.id);
guildScrimMode.set(message.guildId, false); // Ensure normal mode
saveLineup();
// Clear lineup before showing to ensure no names in it
const lineup = getGuildLineup(message.guildId);
lineup.clear();
saveLineup();
// Show lineup immediately as a fresh message for maximum speed
console.log(`[DEBUG] LINEUP-MSG: guild=${message.guildId} pingType=${pingType} owner=${message.author?.id || 'unknown'}`);
const view = createLineupView(message.guildId);
const lineupMsg = await message.channel.send(view);
activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: lineupMsg.id });
addToCleanupQueue(message.guildId, message.channelId, lineupMsg.id, 'lineup');
return;
}
if (commandName === 'scrimlineup') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null;
const pingType = mentionArg === 'here' ? 'here' : 'everyone';
guildPingType.set(message.guildId, pingType);
lineupOwners.set(message.guildId, message.author.id);
guildScrimMode.set(message.guildId, true); // Set scrim mode
saveLineup();
const lineup = getGuildLineup(message.guildId);
lineup.clear();
const lineupB = getGuildLineupB(message.guildId);
lineupB.clear();
saveLineup();
try {
const view = createScrimLineupView(message.guildId);
const lineupMsg = await message.channel.send(view);
activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: lineupMsg.id });
addToCleanupQueue(message.guildId, message.channelId, lineupMsg.id, 'lineup');
} catch (err) {
console.error(`[DEBUG] Error in !scrimlineup command:`, err);
}
return;
}
if (commandName === 'top') {
const sorted = Object.entries(storage.data.stats || {})
.sort((a, b) => (b[1].matches || 0) - (a[1].matches || 0))
.slice(0, 30);
const ranked = sorted.map(([id, data], i) => `**#${i + 1}** <@${id}> — \`${data.matches || 0}\` matches | ⭐ \`${data.mvps || 0}\` MVPs`);
let text = ranked.join('\n');
if (!text) text = "No data yet.";
const chunks = [];
let currentChunk = "";
const lines = text.split('\n');
for (const line of lines) {
if (currentChunk.length + line.length > 4000) {
chunks.push(currentChunk);
currentChunk = line + "\n";
} else {
currentChunk += line + "\n";
}
}
if (currentChunk) chunks.push(currentChunk);
for (let i = 0; i < chunks.length; i++) {
const embed = UI.createEmbed("🏆 Most Active Players", chunks[i]);
if (i === 0) await message.reply({ embeds: [embed] });
else await message.channel.send({ embeds: [embed] });
}
return;
}
if (commandName === 'motm') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
const target = message.mentions.users.first();
if (!target) return message.reply("❌ Please mention the player! (e.g. `!motm @User`)");
storage.addStat(target.id, 'mvps');
const embed = UI.createEmbed("🌟 MAN OF THE MATCH", `The MVP award has been granted to <@${target.id}>!`, UI.colors.success);
await message.channel.send({ embeds: [embed] });
return;
}
if (commandName === 'record') {
const r = storage.getRecord(message.guildId);
await message.reply({ embeds: [UI.createEmbed("📊 Server Match Record", `✅ Wins: \`${r.wins}\`\n🟥 Losses: \`${r.losses}\`\n🤝 Draws: \`${r.draws}\``)] });
return;
}
if (commandName === 'friendlybotsettings') {
const roles = roleStorage.roles[message.guildId] || [];
const rInfo = roles.length > 0 ? roles.map(r => `<@&${r}>`).join(', ') : "Only administrator.";
await message.reply(`🟢 **Online**\nWhitelist: ${rInfo}`);
return;
}
if (commandName === 'tactic') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
const formationArg = args[0] || 'default';
const formation = FORMATIONS[formationArg];
if (!formation || formation.length !== 7) {
return message.reply("❌ Please specify a valid 7v7 formation. Usage: `!tactic [formation_name]`\nExample: `!tactic 3-1-2`");
}
try {
// Get current lineup
const lineup = getGuildLineup(message.guildId);
// Get tactic data
const tacticData = global.TACTICS[formationArg] || global.TACTICS["default"];
// Generate tactic image
const attachment = await global.createTacticAttachment(formationArg, formation, lineup, tacticData, client);
// Build numbered position list with player names
let positionList = "";
formation.forEach(([posKey, posLabel], index) => {
const number = index + 1;
const players = lineup.get(posKey) || [];
const playerDisplay = players.length > 0 ? `<@${players[0]}>` : '*Empty*';
positionList += `**${number}.** ${posLabel} - ${playerDisplay}\n`;
});
// Create embed
const embed = UI.createEmbed(
`📋 TACTIC — ${tacticData.name}`,
`${tacticData.summary}\n\n${positionList}`
);
embed.setImage('attachment://tactic.png');
embed.addFields(
{ name: '⚽ Attack', value: tacticData.attack, inline: false },
{ name: '🛡️ Defense', value: tacticData.defense, inline: false },
{ name: '🎯 Key Points', value: tacticData.keyPoints.join('\n'), inline: false }
);
embed.setFooter({ text: 'FriendlyBot Tactics | 7v7 Only' });
embed.setTimestamp();
await message.channel.send({ embeds: [embed], files: [attachment] });
} catch (e) {
console.error('[Tactic] Error:', e);
await message.reply('❌ Failed to generate tactic.');
}
return;
}
if (commandName === 'teamrandom') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
const count = parseInt(args[0]) || 2;
const lineup = getGuildLineup(message.guildId);
let allPlayers = [];
for (const [pos, players] of lineup) {
allPlayers.push(...players);
}
if (allPlayers.length === 0) {
return message.reply("❌ No players in the lineup! Use `!lineup` first and add players.");
}
const shuffled = allPlayers.sort(() => Math.random() - 0.5);
const teamSize = Math.ceil(shuffled.length / count);
let teams = [];
for (let i = 0; i < count; i++) {
teams.push(shuffled.slice(i * teamSize, (i + 1) * teamSize));
}
let description = "";
teams.forEach((team, index) => {
if (team.length > 0) {
description += `**Team ${index + 1}:**\n`;
team.forEach(playerId => {
description += `• <@${playerId}>\n`;
});
description += "\n";
}
});
const embed = UI.createEmbed("🎲 Random Teams", description || "No players found.", UI.colors.success);
await message.channel.send({ embeds: [embed] });
return;
}
if (commandName === 'playerstats') {
const target = message.mentions.users.first() || message.author;
const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 };
const record = storage.getRecord(message.guildId);
const embed = UI.createEmbed(`🎴 Player Stats — ${target.username}`,
`**Matches:** ${stats.matches || 0}\n**Goals:** ${stats.goals || 0}\n**MVPs:** ${stats.mvps || 0}`,
UI.colors.primary);
embed.setThumbnail(target.displayAvatarURL({ dynamic: true }));
await message.channel.send({ embeds: [embed] });
return;
}
if (commandName === 'matchpredict') {
const lineup = getGuildLineup(message.guildId);
let playerCount = 0;
for (const [pos, players] of lineup) {
playerCount += players.length;
}
if (playerCount === 0) {
return message.reply("❌ No players in the lineup! Add some players first.");
}
const outcomes = ["🏆 Victory", "🤝 Draw", "🟥 Defeat"];
const prediction = outcomes[Math.floor(Math.random() * outcomes.length)];
const confidence = Math.floor(Math.random() * 30) + 70;
const embed = UI.createEmbed("🎯 Match Prediction",
`Based on current lineup of **${playerCount}** players:\n\n**Predicted Result:** ${prediction}\n**Confidence:** ${confidence}%`,
UI.colors.warning);
await message.channel.send({ embeds: [embed] });
return;
}
if (commandName === 'win' || commandName === 'loss' || commandName === 'draw') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
const type = commandName;
const res = args[0] || "?-?";
const scorers = args.slice(1).join(" ");
const record = storage.getRecord(message.guildId);
if (type === 'win') record.wins++;
else if (type === 'loss') record.losses++;
else record.draws++;
// Auto-increment matches for everyone on the lineup board
const lineup = getGuildLineup(message.guildId);
const playersOnBoard = new Set();
for (const players of lineup.values()) {
players.forEach(p => playersOnBoard.add(p));
}
playersOnBoard.forEach(uid => storage.addStat(uid, 'matches'));
const mentions = scorers.match(/<@!?(\d+)>/g) || [];
mentions.forEach(m => storage.addStat(m.replace(/[<@!>]/g, ''), 'goals'));
storage.save('records');
const embed = UI.createEmbed(`⭐ ${type.toUpperCase()} RECORDED`, `🏟️ **Result**: ${res}\n\n⚽ **Scorers**:\n${scorers || "None"}\n\n📊 *Matches have been recorded for everyone on the current lineup board.*`, type === 'win' ? UI.colors.success : UI.colors.danger);
await message.channel.send({ embeds: [embed] });
return;
}
if (commandName === 'scheduledfriendly') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
// !scheduledfriendly 9 PM / 2026/5/4 9 PM voting
const fullArg = args.join(' ');
const typeMatch = fullArg.match(/(voting|manager)$/i);
const type = typeMatch ? typeMatch[1].toLowerCase() : 'voting';
const timeInput = fullArg.replace(/(voting|manager)$/i, '').trim();
if (!timeInput) return message.reply("❌ Usage: `!scheduledfriendly [time] [voting|manager]`\nExample: `!scheduledfriendly 9 PM manager` or `!scheduledfriendly 9 PM / 2026/5/4 9 PM voting`")
// Parse date - check for ' / ' separator first
let dateStr = timeInput;
if (timeInput.includes(' / ')) {
const parts = timeInput.split(' / ');
dateStr = parts[parts.length - 1].trim();
}
// Normalize "9 PM" to "9:00 PM" for better Node.js parsing
dateStr = dateStr.replace(/(\d+)\s*(AM|PM)/i, "$1:00 $2");
let timestamp = Date.parse(dateStr);
// If it's just a time or failed, try assuming today with a clear format
if (isNaN(timestamp) || timestamp < Date.now() - 86400000) {
const today = new Date();
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const datePrefix = `${monthNames[today.getMonth()]} ${today.getDate()}, ${today.getFullYear()}`;
timestamp = Date.parse(`${datePrefix} ${dateStr}`);
}
if (isNaN(timestamp)) {
return message.reply("❌ Invalid date format. Use `9 PM` or `2026/5/4 9 PM`.");
}
const matchId = `friendly_${Date.now()}`;
pendingMatches.set(matchId, {
guildId: message.guildId,
channelId: message.channelId,
type: 'friendly',
friendlyType: type,
timeInput: timeInput,
userId: message.author.id
});
if (type === 'voting') {
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId(`tz_select_${matchId}`)
.setPlaceholder('Select YOUR current timezone...')
.addOptions(TIMEZONE_OPTIONS)
);
await message.reply({ content: "🌍 **Select your timezone** to finalize the friendly schedule:", components: [row] });
} else {
lineupOwners.set(message.guildId, message.author.id);
saveLineup();
const row1 = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId(`manager_formation_select_${matchId}`)
.setPlaceholder('⚽ Select 7v7 Formation...')
.addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k })))
);
await message.channel.send({ content: "📋 **Step 1: Choose Formation for Scheduled Friendly**", components: [row1] });
}
return;
}
if (commandName === 'leaguematch') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
const home = args[0] || "Home";
const away = args[1] || "Away";
const link = args[2] || "TBA";
const timeInput = args.slice(3).join(" ");
if (!timeInput) return message.reply("❌ Please provide a time (e.g. `!leaguematch Home Away Link 9 PM`)!");
const matchId = `match_${Date.now()}`;
pendingMatches.set(matchId, { home, away, link, timeInput, channelId: message.channelId });
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId(`tz_select_${matchId}`)
.setPlaceholder('Select YOUR current timezone...')
.addOptions(TIMEZONE_OPTIONS)
);
await message.reply({ content: "🌍 **One last step!** Please select your timezone below so I can set the exact time for everyone:", components: [row] });
return;
}
if (commandName === 'setup') {
if (!message.member.permissions.has('Administrator')) return message.reply("❌ Admin Only");
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('settings_select')
.setPlaceholder('Configure bot features...')
.addOptions([
{ label: 'Cloud Backup', description: 'Enable/Disable Discord Cloud Backup', value: 'toggle_backup' },
{ label: 'Auto Friendly', description: 'Configure automated friendly polls', value: 'auto_friendly_settings' }
])
);
await message.channel.send({ content: "⚙️ **Settings**", components: [row] });
return;
}
if (commandName === 'on') {
if (!message.member.permissions.has('Administrator') && !roleStorage.isWhitelisted(message.guildId, message.member)) {
return sendNoPermission(message);
}
if (!storage.data.config[message.guildId]) storage.data.config[message.guildId] = {};
storage.data.config[message.guildId].botEnabled = true;
storage.save('config');
return message.reply("✅ The bot has been turned **ON**.");
}
if (commandName === 'off') {
if (!message.member.permissions.has('Administrator') && !roleStorage.isWhitelisted(message.guildId, message.member)) {
return sendNoPermission(message);
}
if (!storage.data.config[message.guildId]) storage.data.config[message.guildId] = {};
storage.data.config[message.guildId].botEnabled = false;
storage.save('config');
return message.reply("❌ The bot has been turned **OFF**. Use `/on` to re-enable it.");
}
if (commandName === 'clear') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
const amount = parseInt(args[0]);
if (amount) {
await message.channel.bulkDelete(amount, true);
const msg = await message.channel.send(`✅ Cleared ${amount} messages.`);
setTimeout(() => msg.delete(), 3000);
}
return;
}
if (commandName === 'lock') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, { SendMessages: false });
await message.reply("🔒 Channel Locked.");
return;
}
if (commandName === 'unlock') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, { SendMessages: true });
await message.reply("🔓 Channel Unlocked.");
return;
}
if (commandName === 'swap') {
const ownerId = lineupOwners.get(message.guildId);
if (ownerId && message.author.id !== ownerId) return message.reply(`❌ Only <@${ownerId}> can swap players!`);
const p1 = message.mentions.users.first();
const p2 = message.mentions.users.at(1);
if (!p1 || !p2) return message.reply("❌ Please mention two players to swap.");
const lineup = getGuildLineup(message.guildId);
let pos1 = null, idx1 = -1;
let pos2 = null, idx2 = -1;
for (const [pos, players] of lineup) {
const i1 = players.indexOf(p1.id);
if (i1 !== -1) { pos1 = pos; idx1 = i1; }
const i2 = players.indexOf(p2.id);
if (i2 !== -1) { pos2 = pos; idx2 = i2; }
}
if (!pos1 || !pos2) return message.reply("❌ Both players must be in the lineup to swap.");
// Perform swap
const arr1 = lineup.get(pos1);
const arr2 = lineup.get(pos2);
arr1[idx1] = p2.id;
arr2[idx2] = p1.id;
saveLineup();
await message.reply(`✅ Swapped <@${p1.id}> with <@${p2.id}>!`);
// Update the board
const boardInfo = activeLineupMessages.get(message.guildId);
if (boardInfo) {
try {
const channel = await client.channels.fetch(boardInfo.channelId);
const msg = await channel.messages.fetch(boardInfo.messageId);
if (msg) await msg.edit(createLineupView(message.guildId));
} catch (e) { }
}
return;
}
if (commandName === 'sync' || commandName === 'sync_cmds') {
if (!message.member.permissions.has('Administrator')) return;
const count = client.guilds.cache.size;
const notifyMsg = await message.reply(`🔄 **Purging duplicates & Syncing** to all **${count}** proxy servers...`);
// Nuke global commands to clear duplicates
await client.application.commands.set([]);
// Sync locally
for (const guild of client.guilds.cache.values()) {
await guild.commands.set(commandsData).catch(() => { });
}
await notifyMsg.edit(`✅ Done! Purged duplicate global commands and force-synchronized ALL missing commands to ALL **${count}** servers! (Please press Ctrl+R to refresh your Discord App.)`);
return;
}
if (commandName === 'reboot') {
const app = await client.application.fetch();
const ownerId = app.owner?.ownerId || app.owner?.id;
if (message.author.id !== ownerId) return message.reply("❌ Owner Only");
await message.reply("🔄 Rebooting process... Hugging Face will restart me automatically.");
setTimeout(() => process.exit(1), 1000);
return;
}
if (commandName === 'sendlink') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
await message.channel.send(`Link : ${args[0] || 'None'}`);
return;
}
if (commandName === 'grantservers' || commandName === 'revokeservers') {
const targetUser = message.mentions.users.first();
if (!targetUser) return message.reply("❌ Please mention the user! (e.g. `!grantservers @User`) ");
if (commandName === 'grantservers') {
const result = await grantSystem.grantAccess(client, targetUser.id, message.author.id);
await message.reply(result.success ? `✅ ${result.message}` : `❌ ${result.message}`);
} else {
const result = await grantSystem.revokeAccess(client, targetUser.id, message.author.id);
await message.reply(result.success ? `✅ ${result.message}` : `❌ ${result.message}`);
}
return;
}
if (commandName === 'servers') {
const app = await client.application.fetch();
const ownerId = app.owner?.ownerId || app.owner?.id;
if (!grantSystem.hasAccess(message.author.id, ownerId)) {
return message.reply("❌ This is a highly restricted command. Only the Official Bot Owner or authorized viewers can use this!");
}
const statusMsg = await message.reply("🔍 Scanning all servers and generating invite links... This may take a moment.");
const guildsInfoRaw = await Promise.all(client.guilds.cache.map(async g => {
let invite = null;
try {
let channel = g.systemChannel || g.channels.cache.find(c => c.isTextBased() && c.permissionsFor(g.members.me).has('CreateInstantInvite'));
if (channel) {
const inv = await channel.createInvite({ maxAge: 0, maxUses: 0 });
invite = inv.url;
}
} catch (e) { }
return { name: g.name, count: g.memberCount, link: invite };
}));
guildsInfoRaw.sort((a, b) => b.count - a.count);
let desc = "";
guildsInfoRaw.forEach((g, i) => {
const serverName = g.link ? `[${g.name}](${g.link})` : g.name;
let line = `**${i + 1}.** ${serverName} — \`${g.count}\` members\n`;
if (desc.length + line.length < 4000) desc += line; // Embed safety cap
});
desc += `\nTotal servers: ${client.guilds.cache.size}`;
const embed = new EmbedBuilder()
.setTitle(`🌐 Serving ${client.guilds.cache.size} Servers`)
.setDescription(desc)
.setColor('#5865F2');
await statusMsg.edit({ content: null, embeds: [embed] });
return;
}
if (commandName === 'uptime') {
const up = process.uptime();
const d = Math.floor(up / 86400);
const h = Math.floor(up / 3600) % 24;
const m = Math.floor(up / 60) % 60;
await message.reply(`⏱️ **Uptime**: ${d}d ${h}h ${m}m ${Math.floor(up % 60)}s`);
return;
}
// --- OWNER ONLY BROADCAST COMMANDS ---
if (commandName === 'broadcast' || commandName === 'removebroadcast' || commandName === 'checkbroadcast') {
const app = await client.application.fetch();
const ownerId = app.owner?.ownerId || app.owner?.id;
if (message.author.id !== ownerId) return; // Silent ignore for non-owners
if (commandName === 'broadcast') {
const content = args.join(' ');
if (!content) return message.reply("❌ Usage: `!broadcast [message]`");
const waitMsg = await message.reply("📡 **Broadcasting...** This may take a moment.");
const result = await broadcastSystem.broadcast(client, content, message.author);
await waitMsg.edit(`✅ **Broadcast Sent!**\nServers reached: \`${result.count}\`\nBroadcast ID: \`${result.id}\``);
}
if (commandName === 'removebroadcast') {
const target = args.join(' ');
if (!target) return message.reply("❌ Usage: `!removebroadcast [ID or Text snippet]`");
const waitMsg = await message.reply("🗑️ **Removing broadcast messages...**");
const result = await broadcastSystem.removeBroadcast(client, target);
if (result.success) {
await waitMsg.edit(`✅ **Removed!** Deleted from \`${result.count}\` servers and history.`);
} else {
await waitMsg.edit(`❌ ${result.message}`);
}
}
if (commandName === 'checkbroadcast') {
const history = broadcastSystem.getBroadcastHistory();
const sevenDaysAgo = Date.now() - (7 * 24 * 60 * 60 * 1000);
// Filter history for messages sent in the last 7 days
const recentHistory = history.filter(b => new Date(b.timestamp).getTime() > sevenDaysAgo);
if (recentHistory.length === 0) return message.reply("📜 No broadcast history found from the last 7 days.");
let report = "📜 **BROADCAST HISTORY (Last 7 Days)**\n\n";
recentHistory.slice(-15).forEach(b => {
const date = new Date(b.timestamp);
report += `🆔 **${b.id}** | 👤 **${b.senderTag}**\n📝 *${b.content.substring(0, 50)}${b.content.length > 50 ? '...' : ''}*\n📅 ${date.toLocaleString()} | 🌍 \`${b.messages.length}\` servers\n\n`;
});
const embed = new EmbedBuilder()
.setTitle("Broadcast Audit Log")
.setDescription(report)
.setColor('#5865F2')
.setFooter({ text: `Showing last ${Math.min(recentHistory.length, 15)} broadcasts` });
await message.reply({ embeds: [embed] });
}
return;
}
if (commandName === 'addrole' || commandName === 'removerole') {
if (!message.member.permissions.has('Administrator')) return message.reply("❌ Admin Only");
const role = message.mentions.roles.first();
if (!role) return message.reply("❌ Please mention a role! (e.g. `!addrole @Staff`)");
const gid = message.guildId;
if (commandName === 'addrole') {
roleStorage.addRole(gid, role.id);
const count = await triggerOnboardingForRole(message.guild, role);
await message.reply(`✅ Added **${role.name}** to whitelist. Sent onboarding DM to **${count}** members.`);
} else {
roleStorage.removeRole(gid, role.id);
await message.reply(`✅ Removed **${role.name}** from whitelist.`);
}
return;
}
if (commandName === 'help' || commandName === 'cmds' || commandName === 'commands') {
const h = `⭐ FRIENDLYBOT OFFICIAL COMMANDS ⭐
--- ⚽ MATCH & LINEUP MANAGEMENT ---
!friendly /friendly - Start a standard lineup vote for players to join.
!lineup /lineup - Generate the standard interactive lineup board.
!lineupimage /lineupimage - Generate a high-quality visual representation of the starting lineup.
!leaguematchimage /leaguematchimage - Generate a visual representation for a league match.
!leaguematch /leaguematch - Schedule a professional league match with an opponent, link, and time.
--- 📈 COMPETITION & STATS ---
!top /top - 🏆 Show the Top 10 most active players in the server.
!profile /profile - 🎴 Generate a custom profile card showing your stats.
!profileimage /profileimage - 🎨 Generate a high-quality visual profile image card.
!motm /motm - 🌟 (Admin/Staff) Grant the "Man of the Match" award to a player.
!record /record - 📊 View the server's global Win/Loss/Draw record.
!win /win - (Admin/Staff) Record a victory.
!loss /loss - (Admin/Staff) Record a defeat.
!draw /draw - (Admin/Staff) Record a draw.
--- ⚙️ SYSTEM & STAFF SETUP ---
!setup /setup - (Admin Only) Opens the interactive settings panel.
!addrole /addrole - (Admin Only) Add a role to the bot staff whitelist.
!removerole /removerole - (Admin Only) Remove a role from the bot staff whitelist.
!giverole /giverole - (Admin Only) Sync roles for members.
!friendlybotsettings /friendlybotsettings - View bot status and permitted roles.
!sync /sync - (Admin Only) Synchronize slash commands.
!reboot /reboot - (Owner Only) Restart the bot.
!ping /ping - Check bot latency.
!uptime /uptime - Show bot uptime.
!clear /clear - (Admin/Staff) Clear messages.
!lock /lock - (Admin/Staff) Lock the current channel.
!unlock /unlock - (Admin/Staff) Unlock the current channel.
⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐
Tip: All commands support Discord Slash Commands (/) for a better experience!`;
await message.reply(`\`\`\`\n${h}\n\`\`\``);
return;
}
if (commandName === 'lineupimage') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
const waitMsg = await message.reply('⏳ **Generating lineup image...**');
try {
const lineup = getGuildLineup(message.guildId);
// Robust formKey resolution for text-based lineup as fallback if the map isn't available
let formKey;
if (typeof guildSelectedFormation !== 'undefined' && guildSelectedFormation && typeof guildSelectedFormation.get === 'function') {
formKey = guildSelectedFormation.get(message.guildId) || 'default';
} else {
formKey = (guildSelectedFormationA && guildSelectedFormationA.get(message.guildId)) || (guildSelectedFormationB && guildSelectedFormationB.get(message.guildId)) || 'default';
}
const formation = formKey === `custom_${message.guildId}` ? guildCustomFormations.get(message.guildId) : FORMATIONS[formKey];
const formDisplayName = formKey === `custom_${message.guildId}` ? (guildCustomFormationNames.get(message.guildId) || "Custom") : formKey;
const attachment = await createLineupAttachment(lineup, formDisplayName, formation || FORMATIONS["default"], client);
const embed = UI.createEmbed(`⚽ Lineup — ${formDisplayName}`, 'Current starting lineup positions');
embed.setImage('attachment://lineup.png');
await waitMsg.edit({ content: null, embeds: [embed], files: [attachment] });
} catch (e) {
console.error('Lineup image error:', e);
await waitMsg.edit('❌ Failed to generate lineup image. Make sure a lineup has been set up first!');
}
return;
}
if (commandName === 'profile') {
const target = message.mentions.users.first() || message.author;
const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 };
const embed = new EmbedBuilder()
.setTitle(`🎴 PLAYER PROFILE — ${target.username.toUpperCase()}`)
.setThumbnail(target.displayAvatarURL({ dynamic: true }))
.addFields(
{ name: '🏟️ Matches', value: `\`${stats.matches || 0}\``, inline: true },
{ name: '⚽ Goals', value: `\`${stats.goals || 0}\``, inline: true },
{ name: '🌟 MOTM Awards', value: `\`${stats.mvps || 0}\``, inline: true }
)
.setColor(UI.colors.primary)
.setFooter({ text: 'FriendlyBot Pro Stats' });
await message.reply({ embeds: [embed] });
return;
}
if (commandName === 'profileimage') {
const target = message.mentions.users.first() || message.author;
const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 };
const waitMsg = await message.reply('⏳ **Generating profile card...**');
try {
const attachment = await createProfileAttachment(target, stats);
await waitMsg.edit({ content: null, files: [attachment] });
} catch (e) {
console.error('Profile image error:', e);
await waitMsg.edit('❌ Failed to generate profile image.');
}
return;
}
if (commandName === 'giverole') {
await message.reply(`🖌️ **Feature Migration in Progress!**\nThe \`${commandName}\` feature is currently being updated to Next-Gen graphics. Check back shortly!`);
return;
}
if (commandName === 'managerlineup') {
if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
lineupOwners.set(message.guildId, message.author.id);
saveLineup();
const row1 = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('manager_formation_select_7v7')
.setPlaceholder('⚽ Select 7v7 Formation...')
.addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k })))
);
const row2 = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('manager_formation_select_11v11')
.setPlaceholder('🏆 Select 11v11 Formation...')
.addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 11).slice(0, 25).map(k => ({ label: k, value: k })))
);
const row3 = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('manager_formation_select_other')
.setPlaceholder('🎮 Select Other Sizes...')
.addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length !== 7 && FORMATIONS[k].length !== 11).slice(0, 25).map(k => ({ label: k, value: k })))
);
await message.channel.send({ content: "📋 **Step 1: Choose Formation for GUI Editor**", components: [row1, row2, row3] });
return;
}
});
async function safeReply(interaction, options) {
try {
if (interaction.deferred || interaction.replied) {
return await interaction.editReply(options);
} else {
return await interaction.reply(options);
}
} catch (e) {
console.error(`[!] Reply Failed: ${e.message}`);
}
}
async function sendNoPermission(ctx) {
const msg = "❌ No Permission\n*(Note: Use Slash Commands `/` for private error messages)*";
try {
if (ctx.isChatInputCommand || ctx.isButton || ctx.isStringSelectMenu || ctx.isUserSelectMenu) {
return await safeReply(ctx, { content: msg, flags: [MessageFlags.Ephemeral] });
} else {
const reply = await ctx.reply(msg);
setTimeout(() => {
reply.delete().catch(() => { });
if (ctx.deletable) ctx.delete().catch(() => { });
}, 3000);
}
} catch (e) { }
}
// Simple per-user cooldown: 2 seconds between text commands (hard lock to ensure one reply)
// Interaction Handler
client.on('interactionCreate', async (interaction) => {
// 1. Handle Timezone Selection IMMEDIATELY (Priority)
if (interaction.isStringSelectMenu() && interaction.customId && interaction.customId.startsWith('tz_select_')) {
try {
await interaction.deferUpdate().catch(() => {});
const matchId = interaction.customId.replace('tz_select_', '');
const matchData = pendingMatches.get(matchId);
if (!matchData) {
return interaction.followUp({ content: "❌ Match session expired or bot restarted. Please try the command again.", flags: [MessageFlags.Ephemeral] });
}
const offset = parseFloat(interaction.values[0]);
let timeStr = matchData.timeInput;
if (timeStr.includes(' / ')) {
timeStr = timeStr.split(' / ').pop().trim();
}
let normalized = timeStr;
// Robustly normalize "9 PM" to "9:00 PM" without breaking "8:30 PM"
if (!normalized.includes(':')) {
normalized = normalized.replace(/\b(\d+)\s*(AM|PM)\b/i, "$1:00 $2");
}
const targetDate = new Date();
// Use word boundaries to ensure we match the start of the time, not just the minutes
const hoursMatch = normalized.match(/\b(\d+):(\d+)\s*(am|pm)\b/i) || normalized.match(/\b(\d+)\s*(am|pm)\b/i);
if (!hoursMatch) {
return interaction.followUp({ content: "❌ Could not parse your time input. Please use a format like `9 PM`.", flags: [MessageFlags.Ephemeral] });
}
let hours = parseInt(hoursMatch[1]);
const minutes = parseInt(hoursMatch[2] || "0");
const ampm = (hoursMatch[3] || "").toLowerCase();
if (ampm === 'pm' && hours !== 12) hours += 12;
if (ampm === 'am' && hours === 12) hours = 0;
const dateMatch = normalized.match(/(\d+)[/-](\d+)[/-](\d+)/) || normalized.match(/(\w+)\s+(\d+),?\s+(\d+)/);
if (dateMatch) {
const d = new Date(normalized);
if (!isNaN(d.getTime())) {
targetDate.setUTCFullYear(d.getFullYear());
targetDate.setUTCMonth(d.getMonth());
targetDate.setUTCDate(d.getDate());
}
}
targetDate.setUTCHours(hours, minutes, 0, 0);
const finalTs = Math.floor(targetDate.getTime() / 1000) - (offset * 3600);
if (matchData.type === 'friendly') {
if (!storage.data.scheduled_matches) storage.data.scheduled_matches = [];
storage.data.scheduled_matches.push({
guildId: interaction.guildId,
type: 'friendly',
timeInput: matchData.timeInput,
timestamp: finalTs * 1000,
reminded: false
});
storage.save('active_polls');
await interaction.editReply({ content: `✅ Friendly scheduled for <t:${finalTs}:F>!`, components: [] });
if (matchData.friendlyType === 'voting') {
const lineup = getGuildLineup(interaction.guildId);
lineup.clear();
saveLineup();
const view = createLineupView(interaction.guildId);
const lineupMsg = await interaction.channel.send(view);
await lineupMsg.react('🟩').catch(() => { });
await lineupMsg.react('🟥').catch(() => { });
activeLineupMessages.set(interaction.guildId, { channelId: interaction.channelId, messageId: lineupMsg.id });
addToCleanupQueue(interaction.guildId, interaction.channelId, lineupMsg.id, 'lineup');
if (storage.data.scheduled_matches.length > 0) {
storage.data.scheduled_matches[storage.data.scheduled_matches.length - 1].messageId = lineupMsg.id;
storage.data.scheduled_matches[storage.data.scheduled_matches.length - 1].channelId = interaction.channelId;
storage.save('active_polls');
}
} else {
const guildId = interaction.guildId;
guildSelectedFormationA.set(guildId, matchData.selectedFormation);
const map = new Map();
guildLineups.set(guildId, map);
saveLineup();
const editor = createManagerEditor(guildId, client);
const editorMsg = await interaction.channel.send(editor);
managerBoards.set(guildId, { channelId: interaction.channelId, messageId: editorMsg.id });
}
} else {
const content = `⭐▬▬ 🏆 **LEAGUE MATCH** 🏆 ▬▬⭐\n🏟️ **${matchData.home}** vs **${matchData.away}**\n🔗 ${matchData.link}\n🕒 **Time**: <t:${finalTs}:F> (<t:${finalTs}:R>)\n🤝 Session\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n@everyone`;
const channel = await client.channels.fetch(matchData.channelId).catch(() => null);
if (!channel) return interaction.followUp({ content: "❌ Original channel not found.", flags: [MessageFlags.Ephemeral] });
const msg = await channel.send({ content, allowedMentions: { parse: ['everyone', 'roles', 'users'] } });
await msg.react('🟩').catch(() => { });
await msg.react('🟥').catch(() => { });
// Removed from active_polls to prevent reaction listeners from overwriting it with friendly text
// storage.data.active_polls[interaction.guildId] = msg.id;
if (!storage.data.scheduled_matches) storage.data.scheduled_matches = [];
storage.data.scheduled_matches.push({
guildId: interaction.guildId,
home: matchData.home,
away: matchData.away,
link: matchData.link,
timestamp: finalTs * 1000,
reminded: false,
messageId: msg.id,
channelId: interaction.channelId
});
storage.save('active_polls');
addToCleanupQueue(interaction.guildId, interaction.channelId, msg.id, 'poll');
await interaction.editReply({ content: "✅ Match scheduled! I have posted it in the channel.", components: [] });
}
pendingMatches.delete(matchId);
} catch (err) {
console.error("[TZ] Priority Error:", err);
}
return;
}
// Handle slash commands in DMs
if (!interaction.guildId) {
if (interaction.isChatInputCommand()) {
await interaction.reply({ content: "This command is not available in DMs.", flags: [MessageFlags.Ephemeral] });
return;
}
return;
}
// Only defer ChatInputCommands to prevent conflict with Button/Menu deferUpdate()
if (interaction.isChatInputCommand()) {
const noDeferCmds = ['ping', 'friendly', 'lineup', 'scrimlineup'];
if (!noDeferCmds.includes(interaction.commandName)) {
await interaction.deferReply().catch(() => { });
}
}
if (interaction.isChatInputCommand()) {
const config = storage.data.config[interaction.guildId] || {};
const botEnabled = config.botEnabled !== false;
if (!botEnabled && interaction.commandName !== 'on') {
return safeReply(interaction, { content: "⚠️ The bot is currently **OFF**. Please use `/on` if you want to use the bot.", flags: [MessageFlags.Ephemeral] });
}
try {
logTransaction(client, interaction.commandName, interaction.user, interaction.guild, interaction.member);
if (interaction.commandName === 'ping') {
await safeReply(interaction, `Latency: ${client.ws.ping}ms`);
}
if (interaction.commandName === 'friendly') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
const needed = interaction.options.getInteger('needed') || 7;
const mentionArg = interaction.options.getString('mention');
let pingType = 'everyone';
if (mentionArg) {
pingType = mentionArg.toLowerCase() === 'here' ? 'here' : 'everyone';
}
guildFriendlyPingType.set(interaction.guildId, pingType);
saveLineup();
let content;
if (pingType === 'here') {
content = getFriendlyText(interaction.guildId, needed).replace(/@everyone/gi, '@here');
} else {
content = getFriendlyText(interaction.guildId, needed);
}
// Reply ephemerally to the interaction to prevent timeout and keep interaction response private
await safeReply(interaction, { content: "✅ Friendly poll started!", flags: [MessageFlags.Ephemeral] });
const mentionParse = ['everyone', 'roles', 'users'];
console.log(`[DEBUG] FRIENDLY-INTERACT: guild=${interaction.guildId} pingType=${pingType} needed=${needed} contentPreview="${(content || '').slice(0, 60)}"`);
// Send the actual poll as a normal channel message
const msg = await interaction.channel.send({ content, allowedMentions: { parse: mentionParse } }).catch(() => null);
if (msg) {
await msg.react('🟩').catch(() => { });
await msg.react('🟥').catch(() => { });
storage.data.active_polls[interaction.guildId] = msg.id;
pollNeededCount.set(interaction.guildId, needed);
storage.save('active_polls');
// Wait for players to react
const joined = new Set();
const filter = (reaction, user) => (reaction.emoji.name === '🟩' || reaction.emoji.name === "I'm In") && !user.bot;
const collector = msg.createReactionCollector({ filter, time: 600000 });
collector.on('collect', (reaction, user) => {
if (!joined.has(user.id)) {
joined.add(user.id);
msg.edit({
content: content + `\n\n${joined.size}/${needed} players joined. Waiting for more...`,
allowedMentions: { parse: mentionParse }
}).catch(() => {});
}
if (joined.size >= needed) {
collector.stop('ready');
}
});
collector.on('end', async (col, reason) => {
if (reason === 'ready') {
const lineup = getGuildLineup(interaction.guildId);
lineup.clear();
saveLineup();
const view = createLineupView(interaction.guildId);
const lineupMsg = await interaction.channel.send(view);
activeLineupMessages.set(interaction.guildId, { channelId: interaction.channelId, messageId: lineupMsg.id });
addToCleanupQueue(interaction.guildId, interaction.channelId, lineupMsg.id, 'lineup');
// Update poll to show it's done
await msg.edit({
content: content + `\n\n✅ **Match is Ready!** Check the board below.`,
allowedMentions: { parse: mentionParse }
}).catch(() => {});
} else {
// Canceled
await msg.edit({
content: content + `\n\n❌ Canceled: not enough players joined.`,
allowedMentions: { parse: mentionParse }
}).catch(() => {});
}
pollNeededCount.delete(interaction.guildId);
delete storage.data.active_polls[interaction.guildId];
storage.save('active_polls');
});
addToCleanupQueue(interaction.guildId, interaction.channelId, msg.id, 'poll');
}
}
if (interaction.commandName === 'leaguematch') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
const home = interaction.options.getString('home');
const away = interaction.options.getString('away');
const link = interaction.options.getString('link');
const timeInput = interaction.options.getString('time');
const matchId = `match_${Date.now()}`;
pendingMatches.set(matchId, { home, away, link, timeInput, channelId: interaction.channelId });
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId(`tz_select_${matchId}`)
.setPlaceholder('Select YOUR current timezone...')
.addOptions(TIMEZONE_OPTIONS)
);
await safeReply(interaction, { content: "🌍 **Select your timezone** to finalize the match schedule:", components: [row], flags: [MessageFlags.Ephemeral] });
}
if (interaction.commandName === 'win' || interaction.commandName === 'loss' || interaction.commandName === 'draw') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
const type = interaction.commandName;
const res = interaction.options.getString('result');
const scorers = interaction.options.getString('scorers') || "";
const record = storage.getRecord(interaction.guildId);
if (type === 'win') record.wins++;
else if (type === 'loss') record.losses++;
else record.draws++;
// Auto-increment matches for everyone on the lineup board
const lineup = getGuildLineup(interaction.guildId);
const playersOnBoard = new Set();
for (const players of lineup.values()) {
players.forEach(p => playersOnBoard.add(p));
}
playersOnBoard.forEach(uid => storage.addStat(uid, 'matches'));
// Process scorers
const mentions = scorers.match(/<@!?(\d+)>/g) || [];
mentions.forEach(m => {
const uid = m.replace(/[<@!>]/g, '');
storage.addStat(uid, 'goals');
});
storage.save('records');
const embed = UI.createEmbed(`⭐ ${type.toUpperCase()} RECORDED`, `🏟️ **Result**: ${res}\n\n⚽ **Scorers**:\n${scorers || "None"}\n\n📊 *Matches have been recorded for everyone on the current lineup board.*`, type === 'win' ? UI.colors.success : UI.colors.danger);
await safeReply(interaction, { embeds: [embed] });
}
if (interaction.commandName === 'top') {
const sorted = Object.entries(storage.data.stats || {})
.sort((a, b) => (b[1].matches || 0) - (a[1].matches || 0))
.slice(0, 30);
const ranked = sorted.map(([id, data], i) => `**#${i + 1}** <@${id}> — \`${data.matches || 0}\` matches | ⭐ \`${data.mvps || 0}\` MVPs`);
let text = ranked.join('\n');
if (!text) text = "No data yet.";
const chunks = [];
let currentChunk = "";
const lines = text.split('\n');
for (const line of lines) {
if (currentChunk.length + line.length > 4000) {
chunks.push(currentChunk);
currentChunk = line + "\n";
} else {
currentChunk += line + "\n";
}
}
if (currentChunk) chunks.push(currentChunk);
for (let i = 0; i < chunks.length; i++) {
const embed = UI.createEmbed("🏆 Most Active Players", chunks[i]);
if (i === 0) await safeReply(interaction, { embeds: [embed] });
else await interaction.channel.send({ embeds: [embed] });
}
}
if (interaction.commandName === 'motm') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
const target = interaction.options.getUser('player');
storage.addStat(target.id, 'mvps');
const embed = UI.createEmbed("🌟 MAN OF THE MATCH", `The MVP award has been granted to <@${target.id}>!`, UI.colors.success);
await safeReply(interaction, { embeds: [embed] });
}
if (interaction.commandName === 'record') {
const r = storage.getRecord(interaction.guildId);
const embed = UI.createEmbed("📊 Server Match Record", `✅ Wins: \`${r.wins}\`\n🟥 Losses: \`${r.losses}\`\n🤝 Draws: \`${r.draws}\``);
await safeReply(interaction, { embeds: [embed] });
}
if (interaction.commandName === 'setup') {
if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('settings_select')
.setPlaceholder('Configure bot features...')
.addOptions([
{ label: 'Cloud Backup', description: 'Enable/Disable Discord Cloud Backup', value: 'toggle_backup' },
{ label: 'Auto Friendly', description: 'Configure automated friendly polls', value: 'auto_friendly_settings' }
])
);
await safeReply(interaction, { content: "⚙️ **Settings**", components: [row] });
}
if (interaction.commandName === 'friendlybotsettings') {
const roles = roleStorage.roles[interaction.guildId] || [];
const rInfo = roles.length > 0 ? roles.map(r => `<@&${r}>`).join(', ') : "Only administrator.";
const config = storage.data.config[interaction.guildId] || {};
const status = config.botEnabled !== false ? "🟢 **Online**" : "🔴 **Offline**";
await safeReply(interaction, { content: `${status}\nWhitelist: ${rInfo}` });
}
if (interaction.commandName === 'on') {
if (!interaction.member.permissions.has('Administrator') && !roleStorage.isWhitelisted(interaction.guildId, interaction.member)) {
return sendNoPermission(interaction);
}
if (!storage.data.config[interaction.guildId]) storage.data.config[interaction.guildId] = {};
storage.data.config[interaction.guildId].botEnabled = true;
storage.save('config');
await safeReply(interaction, "✅ The bot has been turned **ON**.");
}
if (interaction.commandName === 'off') {
if (!interaction.member.permissions.has('Administrator') && !roleStorage.isWhitelisted(interaction.guildId, interaction.member)) {
return sendNoPermission(interaction);
}
if (!storage.data.config[interaction.guildId]) storage.data.config[interaction.guildId] = {};
storage.data.config[interaction.guildId].botEnabled = false;
storage.save('config');
await safeReply(interaction, "❌ The bot has been turned **OFF**. Use `/on` to re-enable it.");
}
if (interaction.commandName === 'lineup') {
console.log(`[DEBUG] LINEUP-INTERACT: guild=${interaction.guildId} user=${interaction.user?.id} ` +
`args=${JSON.stringify(interaction.options?.getString?.('mention'))}`);
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
const mention = interaction.options.getString('mention') || 'everyone';
const pingType = mention.toLowerCase() === 'here' ? 'here' : 'everyone';
guildPingType.set(interaction.guildId, pingType);
lineupOwners.set(interaction.guildId, interaction.user.id);
saveLineup();
const row1 = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('formation_select_initial_7v7')
.setPlaceholder('⚽ Select 7v7 Formation...')
.addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k })))
);
const row2 = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('formation_select_initial_11v11')
.setPlaceholder('🏆 Select 11v11 Formation...')
.addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 11).slice(0, 25).map(k => ({ label: k, value: k })))
);
const row3 = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('formation_select_initial_other')
.setPlaceholder('🎮 Select Other Sizes (6v6, 8v8, 9v9, 10v10)...')
.addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length !== 7 && FORMATIONS[k].length !== 11).slice(0, 25).map(k => ({ label: k, value: k })))
);
const row4 = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('open_custom_lineup_modal')
.setLabel('Custom Positions / Numbers')
.setStyle(ButtonStyle.Primary)
.setEmoji("🛠️")
);
const embed = UI.createEmbed("📋 Initialize Lineup", "Select a formation from the dropdowns below, or create your own custom layout.", UI.colors.primary);
const pingMention = pingType === 'here' ? '@here' : '@everyone';
// Use a robust allowedMentions parse value
const mentionParse = ['everyone', 'roles', 'users'];
await safeReply(interaction, { content: `${pingMention}\n**Lineup Session Active!**`, embeds: [embed], components: [row1, row2, row3, row4], allowedMentions: { parse: mentionParse } });
}
if (interaction.commandName === 'scrimlineup') {
console.log(`[DEBUG] SCRIMLINEUP-INTERACT: guild=${interaction.guildId} user=${interaction.user?.id} ` +
`args=${JSON.stringify(interaction.options?.getString?.('mention'))}`);
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
const mention = interaction.options.getString('mention') || 'everyone';
const pingType = mention.toLowerCase() === 'here' ? 'here' : 'everyone';
guildPingType.set(interaction.guildId, pingType);
lineupOwners.set(interaction.guildId, interaction.user.id);
guildScrimMode.set(interaction.guildId, true); // Set scrim mode
saveLineup();
const lineup = getGuildLineup(interaction.guildId);
lineup.clear();
const lineupB = getGuildLineupB(interaction.guildId);
lineupB.clear();
saveLineup();
const embed = UI.createEmbed("📋 Initialize Scrimmage Lineup", "Select a formation from the dropdowns below to start! Two teams will face each other.", UI.colors.primary);
const pingMention = pingType === 'here' ? '@here' : '@everyone';
const mentionParse = ['everyone', 'roles', 'users'];
// Re-use the view generator for components
const view = createScrimLineupView(interaction.guildId);
await safeReply(interaction, { content: `${pingMention}\n**🔥 SCRIMMAGE LINEUP SESSION ACTIVE!**\n*Two teams facing each other!*`, embeds: [embed], components: view.components, allowedMentions: { parse: mentionParse } });
}
if (interaction.commandName === 'clear') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
const amount = interaction.options.getInteger('amount');
await interaction.channel.bulkDelete(amount, true);
await safeReply(interaction, { content: `✅ Cleared ${amount} messages.`, ephemeral: true });
}
if (interaction.commandName === 'lock') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
await interaction.channel.permissionOverwrites.edit(interaction.guild.roles.everyone, { SendMessages: false });
await safeReply(interaction, { content: "🔒 Channel Locked." });
}
if (interaction.commandName === 'unlock') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
await interaction.channel.permissionOverwrites.edit(interaction.guild.roles.everyone, { SendMessages: true });
await safeReply(interaction, { content: "🔓 Channel Unlocked." });
}
if (interaction.commandName === 'swap') {
const ownerId = lineupOwners.get(interaction.guildId);
if (ownerId && interaction.user.id !== ownerId) return safeReply(interaction, { content: `❌ Only <@${ownerId}> can swap players!`, flags: [MessageFlags.Ephemeral] });
const p1 = interaction.options.getUser('player1');
const p2 = interaction.options.getUser('player2');
const lineup = getGuildLineup(interaction.guildId);
let pos1 = null, idx1 = -1;
let pos2 = null, idx2 = -1;
for (const [pos, players] of lineup) {
const i1 = players.indexOf(p1.id);
if (i1 !== -1) { pos1 = pos; idx1 = i1; }
const i2 = players.indexOf(p2.id);
if (i2 !== -1) { pos2 = pos; idx2 = i2; }
}
if (!pos1 || !pos2) return safeReply(interaction, { content: "❌ Both players must be in the lineup to swap.", flags: [MessageFlags.Ephemeral] });
// Perform swap
const arr1 = lineup.get(pos1);
const arr2 = lineup.get(pos2);
arr1[idx1] = p2.id;
arr2[idx2] = p1.id;
saveLineup();
await safeReply(interaction, { content: `✅ Swapped <@${p1.id}> with <@${p2.id}>!`, flags: [MessageFlags.Ephemeral] });
// Update the board
const boardInfo = activeLineupMessages.get(interaction.guildId);
if (boardInfo) {
try {
const channel = await client.channels.fetch(boardInfo.channelId);
const msg = await channel.messages.fetch(boardInfo.messageId);
if (msg) await msg.edit(createLineupView(interaction.guildId));
} catch (e) { }
}
}
if (interaction.commandName === 'sendlink') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
const link = interaction.options.getString('link');
await safeReply(interaction, `Link : ${link}`);
}
if (interaction.commandName === 'uptime') {
const up = process.uptime();
const d = Math.floor(up / 86400);
const h = Math.floor(up / 3600) % 24;
const m = Math.floor(up / 60) % 60;
await safeReply(interaction, `⏱️ **Uptime**: ${d}d ${h}h ${m}m ${Math.floor(up % 60)}s`);
}
if (interaction.commandName === 'addrole' || interaction.commandName === 'removerole') {
if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
const role = interaction.options.getRole('role');
if (!role) return safeReply(interaction, { content: "❌ Please select a role!", ephemeral: true });
const gid = interaction.guildId;
if (interaction.commandName === 'addrole') {
roleStorage.addRole(gid, role.id);
const count = await triggerOnboardingForRole(interaction.guild, role);
await safeReply(interaction, `✅ Added <@&${role.id}> to whitelist. Sent onboarding DM to **${count}** members.`);
} else {
roleStorage.removeRole(gid, role.id);
await safeReply(interaction, `✅ Removed <@&${role.id}> from whitelist.`);
}
}
if (interaction.commandName === 'managerlineup') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return interaction.reply({ content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
lineupOwners.set(interaction.guildId, interaction.user.id);
saveLineup();
const row1 = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('manager_formation_select_7v7')
.setPlaceholder('⚽ Select 7v7 Formation...')
.addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k })))
);
const row2 = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('manager_formation_select_11v11')
.setPlaceholder('🏆 Select 11v11 Formation...')
.addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 11).slice(0, 25).map(k => ({ label: k, value: k })))
);
const row3 = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('manager_formation_select_other')
.setPlaceholder('🎮 Select Other Sizes...')
.addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length !== 7 && FORMATIONS[k].length !== 11).slice(0, 25).map(k => ({ label: k, value: k })))
);
await safeReply(interaction, { content: "📋 **Step 1: Choose Formation for GUI Editor**", components: [row1, row2, row3] });
}
if (interaction.commandName === 'lineupimage') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
try {
const lineup = getGuildLineup(interaction.guildId);
const formKey = guildSelectedFormation.get(interaction.guildId) || 'default';
const formation = formKey === `custom_${interaction.guildId}` ? guildCustomFormations.get(interaction.guildId) : FORMATIONS[formKey];
const formDisplayName = formKey === `custom_${interaction.guildId}` ? (guildCustomFormationNames.get(interaction.guildId) || "Custom") : formKey;
const attachment = await createLineupAttachment(lineup, formDisplayName, formation || FORMATIONS["default"], client);
const embed = UI.createEmbed(`⚽ Lineup — ${formDisplayName}`, 'Current starting lineup positions');
embed.setImage('attachment://lineup.png');
await safeReply(interaction, { embeds: [embed], files: [attachment] });
} catch (e) {
console.error('Lineup image error:', e);
await safeReply(interaction, '❌ Failed to generate lineup image.');
}
}
if (interaction.commandName === 'profile') {
const target = interaction.options.getUser('user') || interaction.user;
const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 };
const embed = new EmbedBuilder()
.setTitle(`🎴 PLAYER PROFILE — ${target.username.toUpperCase()}`)
.setThumbnail(target.displayAvatarURL({ dynamic: true }))
.addFields(
{ name: '🏟️ Matches', value: `\`${stats.matches || 0}\``, inline: true },
{ name: '⚽ Goals', value: `\`${stats.goals || 0}\``, inline: true },
{ name: '🌟 MOTM Awards', value: `\`${stats.mvps || 0}\``, inline: true }
)
.setColor(UI.colors.primary)
.setFooter({ text: 'FriendlyBot Pro Stats' });
await safeReply(interaction, { embeds: [embed] });
}
if (interaction.commandName === 'profileimage') {
const target = interaction.options.getUser('user') || interaction.user;
const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 };
try {
const attachment = await createProfileAttachment(target, stats);
await safeReply(interaction, { files: [attachment] });
} catch (e) {
console.error('Profile image error:', e);
await safeReply(interaction, '❌ Failed to generate profile image.');
}
}
if (interaction.commandName === 'tactic') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member))
return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
try {
const formationName = interaction.options.getString('formation');
const formation = FORMATIONS[formationName];
if (!formation || formation.length !== 7) {
return safeReply(interaction, { content: "❌ Please select a valid 7v7 formation.", flags: [MessageFlags.Ephemeral] });
}
// Get current lineup
const lineup = getGuildLineup(interaction.guildId);
// Get tactic data
const tacticData = global.TACTICS[formationName] || global.TACTICS["default"];
// Generate tactic image with numbered positions and player names
const attachment = await global.createTacticAttachment(formationName, formation, lineup, tacticData, client);
// Build numbered position list with player names
let positionList = "";
formation.forEach(([posKey, posLabel], index) => {
const number = index + 1;
const players = lineup.get(posKey) || [];
const playerDisplay = players.length > 0 ? `<@${players[0]}>` : '*Empty*';
positionList += `**${number}.** ${posLabel} - ${playerDisplay}\n`;
});
// Create embed
const embed = UI.createEmbed(
`📋 TACTIC — ${tacticData.name}`,
`${tacticData.summary}\n\n${positionList}`
);
embed.setImage('attachment://tactic.png');
embed.addFields(
{ name: '⚽ Attack', value: tacticData.attack, inline: false },
{ name: '🛡️ Defense', value: tacticData.defense, inline: false },
{ name: '🎯 Key Points', value: tacticData.keyPoints.join('\n'), inline: false }
);
embed.setFooter({ text: 'FriendlyBot Tactics | 7v7 Only' });
embed.setTimestamp();
await safeReply(interaction, { embeds: [embed], files: [attachment] });
} catch (e) {
console.error('[Tactic] Error:', e);
await safeReply(interaction, '❌ Failed to generate tactic.');
}
}
if (interaction.commandName === 'scheduledfriendly') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
const timeInput = interaction.options.getString('time');
const type = interaction.options.getString('type') || 'voting';
// Parse date - check for ' / ' separator first
let dateStr = timeInput;
if (timeInput.includes(' / ')) {
const parts = timeInput.split(' / ');
dateStr = parts[parts.length - 1].trim();
}
// Normalize "9 PM" to "9:00 PM" safely
if (!dateStr.includes(':')) {
dateStr = dateStr.replace(/\b(\d+)\s*(AM|PM)\b/i, "$1:00 $2");
}
let timestamp = Date.parse(dateStr);
// If it's just a time or failed, try assuming today with a clear format
if (isNaN(timestamp) || timestamp < Date.now() - 86400000) {
const today = new Date();
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const datePrefix = `${monthNames[today.getMonth()]} ${today.getDate()}, ${today.getFullYear()}`;
timestamp = Date.parse(`${datePrefix} ${dateStr}`);
}
if (isNaN(timestamp)) {
return safeReply(interaction, { content: "❌ Invalid date format. Use `9 PM` or `2026/5/4 9 PM`.", flags: [MessageFlags.Ephemeral] });
}
const matchId = `friendly_${Date.now()}`;
pendingMatches.set(matchId, {
guildId: interaction.guildId,
channelId: interaction.channelId,
type: 'friendly',
friendlyType: type,
timeInput: timeInput,
userId: interaction.user.id
});
if (type === 'voting') {
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId(`tz_select_${matchId}`)
.setPlaceholder('Select YOUR current timezone...')
.addOptions(TIMEZONE_OPTIONS)
);
await safeReply(interaction, { content: "🌍 **Select your timezone** to finalize the friendly schedule:", components: [row], flags: [MessageFlags.Ephemeral] });
} else {
lineupOwners.set(interaction.guildId, interaction.user.id);
saveLineup();
const row1 = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId(`manager_formation_select_${matchId}`)
.setPlaceholder('⚽ Select 7v7 Formation...')
.addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k })))
);
await safeReply(interaction, { content: "📋 **Step 1: Choose Formation for Scheduled Friendly**", components: [row1] });
}
}
if (interaction.commandName === 'giverole') {
await safeReply(interaction, { content: `🖌️ **Feature Migration in Progress!**\nThe \`${interaction.commandName}\` feature is currently being updated to Next-Gen graphics. Check back shortly!`, ephemeral: true });
}
} catch (err) {
console.error(`[INTERACTION ERROR] ${interaction.commandName}:`, err);
await safeReply(interaction, { content: "❌ A system error occurred while processing this command.", ephemeral: true }).catch(() => { });
}
}
if (interaction.isStringSelectMenu()) {
if (interaction.customId === 'settings_select') {
await interaction.deferUpdate().catch(() => { });
const value = interaction.values[0];
if (value === 'auto_friendly_settings') {
await showAutoFriendlyPanel(interaction);
} else {
await safeReply(interaction, { content: "✅ Settings interaction acknowledged.", ephemeral: true });
}
}
}
if (interaction.isChannelSelectMenu()) {
if (interaction.customId === 'auto_friendly_channel_select') {
if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
const channelId = interaction.values[0];
const config = storage.data.config[interaction.guildId] || {};
config.autoFriendlyChannel = channelId;
storage.data.config[interaction.guildId] = config;
storage.save('config');
await interaction.deferUpdate();
await showAutoFriendlyPanel(interaction);
}
}
if (interaction.isButton()) {
if (interaction.customId === 'open_custom_lineup_modal') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
const modal = new ModalBuilder()
.setCustomId('custom_lineup_modal')
.setTitle('Custom Lineup / Other Sizes');
const customInput = new TextInputBuilder()
.setCustomId('custom_input')
.setLabel("Enter Custom Positions (Comma separated)")
.setPlaceholder("Example: GK, LB, CB, CB, RB, CDM, CM, LW, ST, RW")
.setStyle(TextInputStyle.Paragraph)
.setRequired(true);
modal.addComponents(
new ActionRowBuilder().addComponents(customInput)
);
await interaction.showModal(modal);
}
if (interaction.customId === 'toggle_auto_friendly') {
if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
const config = storage.data.config[interaction.guildId] || {};
config.autoFriendlyEnabled = !config.autoFriendlyEnabled;
storage.data.config[interaction.guildId] = config;
storage.save('config');
await interaction.deferUpdate();
await showAutoFriendlyPanel(interaction);
}
if (interaction.customId === 'open_interval_modal') {
if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
const modal = new ModalBuilder()
.setCustomId('auto_friendly_interval_modal')
.setTitle('Auto Friendly Interval');
const intervalInput = new TextInputBuilder()
.setCustomId('interval_input')
.setLabel("Interval in minutes (e.g. 40)")
.setStyle(TextInputStyle.Short)
.setRequired(true)
.setPlaceholder('40');
modal.addComponents(new ActionRowBuilder().addComponents(intervalInput));
await interaction.showModal(modal);
}
}
if (interaction.isModalSubmit()) {
if (interaction.customId === 'custom_lineup_modal') {
const custom = interaction.fields.getTextInputValue('custom_input').trim();
let formation = null;
let formName = "Custom";
if (custom) {
formation = autoDetectFormation(custom);
formName = `Custom (${formation.length}v${formation.length})`;
}
if (!formation) {
return safeReply(interaction, { content: "❌ Could not find that preset or parse your custom positions. Example: `GK, CB, CM, ST`", ephemeral: true });
}
const guildId = interaction.guildId;
// Store this custom formation and its name persistently
guildCustomFormations.set(guildId, formation);
guildCustomFormationNames.set(guildId, formName);
const tempKey = `custom_${guildId}`;
guildSelectedFormation.set(guildId, tempKey);
// Clear current lineup as formation changed
const map = new Map();
guildLineups.set(guildId, map);
saveLineup();
const view = createLineupView(guildId);
// If the modal was triggered from a message (like the initial setup message), update it!
if (interaction.message) {
await interaction.update(view);
activeLineupMessages.set(guildId, { channelId: interaction.channelId, messageId: interaction.message.id });
addToCleanupQueue(guildId, interaction.channelId, interaction.message.id, 'lineup');
} else {
// Otherwise reply ephemerally and send a new message
await interaction.reply({ content: `✅ Formation set to **${formName}**!`, ephemeral: true });
const msg = await interaction.channel.send(view);
activeLineupMessages.set(guildId, { channelId: interaction.channelId, messageId: msg.id });
addToCleanupQueue(guildId, interaction.channelId, msg.id, 'lineup');
}
return;
}
if (interaction.customId === 'auto_friendly_interval_modal') {
const interval = parseInt(interaction.fields.getTextInputValue('interval_input'));
if (isNaN(interval) || interval < 1) {
return safeReply(interaction, { content: "❌ Please enter a valid number of minutes.", ephemeral: true });
}
const config = storage.data.config[interaction.guildId] || {};
config.autoFriendlyInterval = interval;
storage.data.config[interaction.guildId] = config;
storage.save('config');
await safeReply(interaction, { content: `✅ Auto Friendly interval set to **${interval}** minutes.`, ephemeral: true });
}
}
if (interaction.isStringSelectMenu() && interaction.customId.startsWith('formation_select_initial_')) {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
const ownerId = lineupOwners.get(interaction.guildId);
if (ownerId && interaction.user.id !== ownerId) {
return interaction.reply({ content: `❌ Only <@${ownerId}> can initialize this lineup!`, ephemeral: true });
}
const guildId = interaction.guildId;
const formKey = interaction.values[0];
guildSelectedFormation.set(guildId, formKey);
guildSelectedFormationA.set(guildId, formKey); // Keep in sync for image renderer
// Clear current lineup as formation changed
const map = new Map();
guildLineups.set(guildId, map);
saveLineup();
const view = createLineupView(guildId);
await interaction.update(view);
activeLineupMessages.set(guildId, { channelId: interaction.channelId, messageId: interaction.message.id });
addToCleanupQueue(guildId, interaction.channelId, interaction.message.id, 'lineup');
saveLineup();
return;
}
if (interaction.isStringSelectMenu()) {
if (interaction.customId === 'scrim_join_team_a' || interaction.customId === 'scrim_join_team_b') {
await interaction.deferUpdate().catch(() => { });
const isTeamA = interaction.customId === 'scrim_join_team_a';
const selectedValue = interaction.values[0];
const pos = isTeamA ? selectedValue.replace('a_', '') : selectedValue.replace('b_', '');
const lineupGuildId = interaction.guildId;
const targetLineup = isTeamA ? getGuildLineup(lineupGuildId) : getGuildLineupB(lineupGuildId);
const userId = String(interaction.user.id);
let wasInCurrentPos = false;
const currentQ = targetLineup.get(pos) || [];
if (currentQ.includes(userId)) wasInCurrentPos = true;
for (const [p, players] of targetLineup) {
targetLineup.set(p, players.filter(id => id !== userId));
}
const oppositeLineup = isTeamA ? getGuildLineupB(lineupGuildId) : getGuildLineup(lineupGuildId);
for (const [p, players] of oppositeLineup) {
oppositeLineup.set(p, players.filter(id => id !== userId));
}
if (!wasInCurrentPos) {
if (!targetLineup.get(pos)) targetLineup.set(pos, []);
targetLineup.get(pos).push(userId);
}
saveLineup();
const view = createScrimLineupView(lineupGuildId);
await interaction.editReply({ embeds: view.embeds, components: view.components });
return;
}
if (interaction.customId === 'formation_category_select') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
const ownerId = lineupOwners.get(interaction.guildId);
if (ownerId && interaction.user.id !== ownerId) {
return interaction.reply({ content: `❌ Only <@${ownerId}> can manage this lineup!`, ephemeral: true });
}
const cat = interaction.values[0];
const guildId = interaction.guildId;
let filteredKeys = [];
let catLabel = "";
if (cat === 'cat_7v7') {
filteredKeys = Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7);
catLabel = "7v7";
} else if (cat === 'cat_11v11') {
filteredKeys = Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 11);
catLabel = "11v11";
} else {
filteredKeys = Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length !== 7 && FORMATIONS[k].length !== 11);
catLabel = "Other Sizes";
}
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId(`formation_select_ephemeral_${interaction.message.id}`)
.setPlaceholder(`⚽ Pick a ${catLabel} Formation...`)
.addOptions(filteredKeys.slice(0, 25).map(k => ({ label: k, value: k })))
);
await interaction.reply({
content: `📂 **Browsing ${catLabel} Formations**\nSelect an option below to update the public board.`,
components: [row],
flags: [MessageFlags.Ephemeral]
});
return;
}
}
if (interaction.isStringSelectMenu() && interaction.customId.startsWith('formation_select_ephemeral_')) {
const publicMessageId = interaction.customId.replace('formation_select_ephemeral_', '');
const formKey = interaction.values[0];
const guildId = interaction.guildId;
guildSelectedFormation.set(guildId, formKey);
guildSelectedFormationA.set(guildId, formKey); // Keep in sync for image renderer
const map = new Map();
guildLineups.set(guildId, map);
saveLineup();
await interaction.update({ content: `✅ Updated public board to **${formKey}**!`, components: [] });
try {
const channel = interaction.channel;
const publicMsg = await channel.messages.fetch(publicMessageId);
await publicMsg.edit(createLineupView(guildId));
} catch (e) {
console.error("[!] Failed to update public board from ephemeral menu:", e.message);
}
return;
}
if (interaction.isStringSelectMenu() && interaction.customId === 'formation_select_active') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
const ownerId = lineupOwners.get(interaction.guildId);
if (ownerId && interaction.user.id !== ownerId) {
return interaction.reply({ content: `❌ Only <@${ownerId}> can change the formation!`, ephemeral: true });
}
const guildId = interaction.guildId;
if (guildScrimMode.get(guildId)) {
guildSelectedFormationA.set(guildId, interaction.values[0]);
guildSelectedFormationB.set(guildId, interaction.values[0]);
guildSelectedFormation.set(guildId, interaction.values[0]);
} else {
guildSelectedFormationA.set(guildId, interaction.values[0]);
guildSelectedFormation.set(guildId, interaction.values[0]);
}
const map = new Map();
guildLineups.set(guildId, map);
await interaction.update(createLineupView(guildId));
saveLineup();
return;
}
if (interaction.isStringSelectMenu() && interaction.customId.startsWith('formation_select_')) {
if (interaction.customId.includes('_initial_') || interaction.customId.includes('_active')) return;
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
const ownerId = lineupOwners.get(interaction.guildId);
if (ownerId && interaction.user.id !== ownerId) {
return interaction.reply({ content: `❌ Only <@${ownerId}> can change the formation!`, ephemeral: true });
}
const guildId = interaction.guildId;
if (guildScrimMode.get(guildId)) {
guildSelectedFormationA.set(guildId, interaction.values[0]);
guildSelectedFormationB.set(guildId, interaction.values[0]);
guildSelectedFormation.set(guildId, interaction.values[0]);
} else {
guildSelectedFormationA.set(guildId, interaction.values[0]);
guildSelectedFormation.set(guildId, interaction.values[0]);
}
const map = new Map();
guildLineups.set(guildId, map);
await interaction.update(createLineupView(guildId));
saveLineup();
return;
}
if (interaction.isStringSelectMenu() && interaction.customId.startsWith('manager_formation_select_')) {
const guildId = interaction.guildId;
const formationKey = interaction.values[0];
// Check if this is part of a scheduled friendly flow
const matchId = interaction.customId.replace('manager_formation_select_', '');
if (matchId.startsWith('friendly_')) {
const matchData = pendingMatches.get(matchId);
if (matchData) {
matchData.selectedFormation = formationKey;
const row = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId(`tz_select_${matchId}`)
.setPlaceholder('Select YOUR current timezone...')
.addOptions(TIMEZONE_OPTIONS)
);
await interaction.update({ content: "🌍 **Step 2: Select your timezone** to finalize the kickoff time:", components: [row] });
return;
}
}
if (guildScrimMode.get(guildId)) {
guildSelectedFormationA.set(guildId, formationKey);
guildSelectedFormationB.set(guildId, formationKey);
guildSelectedFormation.set(guildId, formationKey);
} else {
guildSelectedFormationA.set(guildId, formationKey);
guildSelectedFormation.set(guildId, formationKey);
}
const map = new Map();
guildLineups.set(guildId, map);
const editor = createManagerEditor(guildId, client);
await interaction.update(editor);
managerBoards.set(guildId, { channelId: interaction.channelId, messageId: interaction.message.id });
saveLineup();
return;
}
if (interaction.isUserSelectMenu() && interaction.customId.startsWith('man_pick_')) {
const posKey = interaction.customId.replace('man_pick_', '');
const targetUser = interaction.values[0];
const guildId = interaction.guildId;
const lineup = getGuildLineup(guildId);
lineup.set(posKey, [targetUser]);
saveLineup();
await interaction.update({ content: `✅ Assigned <@${targetUser}> to **${posKey}**`, components: [] });
const boardInfo = managerBoards.get(guildId);
if (boardInfo) {
try {
const channel = await client.channels.fetch(boardInfo.channelId);
const msg = await channel.messages.fetch(boardInfo.messageId);
if (msg) await msg.edit(createManagerEditor(guildId, client));
} catch (e) { console.error("Could not update manager board live", e); }
}
return;
}
const lineupGuildId = interaction.guildId;
const lineupBoard = getGuildLineup(lineupGuildId);
if (interaction.isButton()) {
if (interaction.customId.startsWith('man_edit_')) {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
const posKey = interaction.customId.replace('man_edit_', '');
const row = new ActionRowBuilder().addComponents(
new UserSelectMenuBuilder()
.setCustomId(`man_pick_${posKey}`)
.setPlaceholder(`Select player for ${posKey}...`)
);
await interaction.reply({ content: `👤 Pick a player for **${posKey}**`, components: [row], flags: [MessageFlags.Ephemeral] });
return;
}
if (interaction.customId.startsWith('join_')) {
await interaction.deferUpdate().catch(() => { });
const isScrim = guildScrimMode.get(lineupGuildId) === true;
let targetLineup = lineupBoard;
let pos = interaction.customId.replace('join_', '');
if (isScrim && pos.startsWith('scrim_join_a_')) {
pos = pos.replace('scrim_join_a_', '');
targetLineup = lineupBoard;
} else if (isScrim && pos.startsWith('scrim_join_b_')) {
pos = pos.replace('scrim_join_b_', '');
targetLineup = getGuildLineupB(lineupGuildId);
}
const userId = interaction.user.id;
let wasInCurrentPos = false;
const currentQ = targetLineup.get(pos) || [];
if (currentQ.includes(userId)) wasInCurrentPos = true;
for (const [p, players] of targetLineup) {
targetLineup.set(p, players.filter(id => id !== userId));
}
if (isScrim) {
const oppositeLineup = (targetLineup === lineupBoard) ? getGuildLineupB(lineupGuildId) : lineupBoard;
for (const [p, players] of oppositeLineup) {
oppositeLineup.set(p, players.filter(id => id !== userId));
}
}
if (!wasInCurrentPos) {
if (!targetLineup.get(pos)) targetLineup.set(pos, []);
targetLineup.get(pos).push(userId);
}
saveLineup();
// Re-fetch the lineup to ensure memory view is up to date before rendering
const refreshedLineup = getGuildLineup(lineupGuildId);
const view = isScrim ? createScrimLineupView(lineupGuildId) : createLineupView(lineupGuildId);
await interaction.editReply({ embeds: view.embeds, components: view.components });
return;
}
if (interaction.customId === 'lineup_clear') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
const ownerId = lineupOwners.get(interaction.guildId);
if (ownerId && interaction.user.id !== ownerId) {
return interaction.reply({ content: `❌ Only <@${ownerId}> can clear the board!`, ephemeral: true });
}
lineupBoard.clear();
const isScrim = guildScrimMode.get(lineupGuildId) === true;
if (isScrim) {
const lineupB = getGuildLineupB(lineupGuildId);
lineupB.clear();
}
saveLineup();
const view = isScrim ? createScrimLineupView(lineupGuildId) : createLineupView(lineupGuildId);
await interaction.update({ embeds: view.embeds, components: view.components });
return;
}
if (interaction.customId === 'lineup_done') {
if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) {
return sendNoPermission(interaction);
}
const ownerId = lineupOwners.get(interaction.guildId);
if (ownerId && interaction.user.id !== ownerId) {
return interaction.reply({ content: `❌ Only <@${ownerId}> can generate the final image!`, flags: [MessageFlags.Ephemeral] });
}
await interaction.deferReply().catch(() => { });
try {
const isScrim = guildScrimMode.get(lineupGuildId) === true;
if (isScrim) {
const formKeyA = guildSelectedFormationA.get(lineupGuildId) || 'default';
const formationA = formKeyA === `custom_${lineupGuildId}` ? guildCustomFormations.get(lineupGuildId) : FORMATIONS[formKeyA];
const formDisplayNameA = formKeyA === `custom_${lineupGuildId}` ? (guildCustomFormationNames.get(lineupGuildId) || "Custom") : formKeyA;
const effFormationA = formationA || FORMATIONS["default"];
const formKeyB = guildSelectedFormationB.get(lineupGuildId) || 'default';
const formationB = formKeyB === `custom_${lineupGuildId}` ? guildCustomFormations.get(lineupGuildId) : FORMATIONS[formKeyB];
const formDisplayNameB = formKeyB === `custom_${lineupGuildId}` ? (guildCustomFormationNames.get(lineupGuildId) || "Custom") : formKeyB;
const effFormationB = formationB || FORMATIONS["default"];
const teamABuffer = await renderLineupImage(lineupBoard, `TEAM A - ${formDisplayNameA}`, effFormationA, client);
const lineupB = getGuildLineupB(lineupGuildId);
const teamBBuffer = await renderLineupImage(lineupB, `TEAM B - ${formDisplayNameB}`, effFormationB, client, true);
const attA = new AttachmentBuilder(teamABuffer, { name: 'team_a.png' });
const attB = new AttachmentBuilder(teamBBuffer, { name: 'team_b.png' });
const embedA = new EmbedBuilder()
.setColor('#5865F2')
.setTitle(`TEAM A — ${formDisplayNameA}`)
.setDescription('Team A lineup (attacking upward)')
.setImage('attachment://team_a.png');
const embedB = new EmbedBuilder()
.setColor('#ff4444')
.setTitle(`TEAM B — ${formDisplayNameB}`)
.setDescription('Team B lineup (attacking downward, facing Team A)')
.setImage('attachment://team_b.png');
await interaction.editReply({ embeds: [embedA, embedB], files: [attA, attB] });
} else {
const formKey = guildSelectedFormationA.get(lineupGuildId) || 'default';
const formation = formKey === `custom_${lineupGuildId}` ? guildCustomFormations.get(lineupGuildId) : FORMATIONS[formKey];
const formDisplayName = formKey === `custom_${lineupGuildId}` ? (guildCustomFormationNames.get(lineupGuildId) || "Custom") : formKey;
const effFormation = formation || FORMATIONS["default"];
const attachment = await createLineupAttachment(lineupBoard, formDisplayName, effFormation, client);
const embed = UI.createEmbed(`⚽ Final Lineup — ${formDisplayName}`, "Here is the visual representation of the starting lineup.");
embed.setImage('attachment://lineup.png');
await interaction.editReply({ embeds: [embed], files: [attachment] });
}
} catch (err) {
console.error("Failed to generate lineup image:", err);
await interaction.editReply({ content: "❌ Failed to generate lineup image. Please try again." }).catch(() => { });
}
return;
}
}
});
// Store needed count for each active poll
const pollNeededCount = new Map();
async function fetchWithRetry(fetchFn, retries = 3, delay = 1000) {
for (let i = 0; i < retries; i++) {
try {
return await fetchFn();
} catch (err) {
if (i === retries - 1) throw err;
await new Promise(res => setTimeout(res, delay));
}
}
}
// Handle reaction removal to decrease count
client.on('messageReactionRemove', async (reaction, user) => {
if (user.bot) return;
try {
// Handle partials for both reaction and message to ensure content is available
if (reaction.partial) await fetchWithRetry(() => reaction.fetch());
if (reaction.message.partial) await fetchWithRetry(() => reaction.message.fetch());
if (reaction.emoji.name === '🟩') {
const guildId = reaction.message.guildId;
const activePollId = storage.data.active_polls[guildId];
if (reaction.message.id === activePollId) {
const content = reaction.message.content || "";
// Safety check: Don't edit if it's a league match or NOT a friendly poll
if (content.includes('LEAGUE MATCH')) return;
if (!content.includes('FRIENDLY')) return;
const count = reaction.count - (reaction.me ? 1 : 0);
const needed = pollNeededCount.get(guildId) || 6;
// Update the message with current count
const baseText = getFriendlyText(guildId, needed);
await reaction.message.edit({ content: baseText + `\n\n${count}/${needed} players joined. Waiting for more...` });
}
}
} catch (err) {
console.error("[REACTION-REMOVE] Error handling removal:", err);
}
});
// Staff Onboarding System
client.on('guildMemberUpdate', async (oldMember, newMember) => {
try {
const guildId = newMember.guild.id;
const oldRoles = oldMember.roles.cache;
const newRoles = newMember.roles.cache;
// Find added roles
const addedRoles = newRoles.filter(role => !oldRoles.has(role.id));
if (addedRoles.size === 0) return;
// Check if any of the added roles are in the whitelist
const whitelist = roleStorage.roles[guildId] || [];
const hasNewWhitelistRole = addedRoles.some(role => whitelist.includes(role.id));
if (hasNewWhitelistRole) {
// Check if already onboarded
if (!storage.data.onboarded[guildId]) storage.data.onboarded[guildId] = [];
if (storage.data.onboarded[guildId].includes(newMember.id)) return;
// Send onboarding DM
const dashboardUrl = getSpacePublicUrl() || 'https://brozy123-lineup-bot.hf.space';
const embed = UI.createEmbed("🎉 Welcome to the Staff Team!", `You have been granted a **Staff Role** in **${newMember.guild.name}**!\n\nYou now have access to manage lineups, record match stats, and use admin commands.`, UI.colors.primary);
embed.addFields(
{ name: "🌐 Management Dashboard", value: `Access settings and logs here:\n[**Open Dashboard**](${dashboardUrl})` },
{ name: "⚽ Key Commands", value: "`!friendly` - Start a friendly poll\n`!lineup` - Start a lineup board\n`!lineupimage` - Generate lineup image\n`!leaguematchimage` - Generate match image" },
{ name: "📖 Help", value: "If you need any help, check the dashboard or contact the server owner." }
);
await newMember.send({ embeds: [embed] }).catch(() => {
console.log(`[Onboarding] Could not send DM to ${newMember.user.tag}`);
});
// Mark as onboarded
storage.data.onboarded[guildId].push(newMember.id);
storage.save('active_polls');
}
} catch (err) {
console.error("[Onboarding] Error:", err);
}
});
// Log server join to designated log channel
client.on('guildCreate', async (guild) => {
sendJoinTransaction(guild);
try {
console.log(`[SYSTEM] Bot joined a new guild: "${guild.name}" (${guild.id})`);
const logChannelId = '1508759327731875977';
const channel = await client.channels.fetch(logChannelId).catch(() => null);
if (!channel) {
console.warn(`[SYSTEM] Could not find the guild-join log channel: ${logChannelId}`);
return;
}
// Fetch owner details
let ownerTag = 'Unknown';
let ownerMention = 'Unknown';
try {
const owner = await guild.fetchOwner().catch(() => null);
if (owner) {
ownerTag = owner.user.tag;
ownerMention = `<@${owner.id}>`;
} else {
const ownerUser = await client.users.fetch(guild.ownerId).catch(() => null);
if (ownerUser) {
ownerTag = ownerUser.tag;
ownerMention = `<@${ownerUser.id}>`;
} else if (guild.ownerId) {
ownerMention = `<@${guild.ownerId}>`;
}
}
} catch (e) {
console.error(`[SYSTEM] Error fetching owner for guild ${guild.id}:`, e);
}
// Try to generate an invite link for logs/audits
let inviteUrl = 'N/A';
try {
const sysChannel = guild.systemChannel || guild.channels.cache.find(c => c.isTextBased() && c.permissionsFor(guild.members.me).has('CreateInstantInvite'));
if (sysChannel) {
const invites = await sysChannel.fetchInvites().catch(() => new Map());
if (invites.size > 0) {
inviteUrl = invites.first().url;
} else {
const inv = await sysChannel.createInvite({ maxAge: 0, maxUses: 0 }).catch(() => null);
if (inv) inviteUrl = inv.url;
}
}
} catch (e) {
console.error(`[SYSTEM] Error creating invite link for guild ${guild.id}:`, e);
}
const memberCount = guild.memberCount || 0;
const iconUrl = guild.iconURL({ dynamic: true }) || null;
const currentGuildsCount = client.guilds.cache.size;
const embed = new EmbedBuilder()
.setTitle(`📥 Bot Joined a New Guild!`)
.setThumbnail(iconUrl)
.addFields(
{ name: '🌐 Server Name', value: `**${guild.name}**`, inline: true },
{ name: '🆔 Server ID', value: `\`${guild.id}\``, inline: true },
{ name: '👑 Owner', value: `${ownerTag} (${ownerMention})`, inline: true },
{ name: '👥 Member Count', value: `\`${memberCount}\` members`, inline: true },
{ name: '🔗 Server Invite', value: inviteUrl !== 'N/A' ? `[Join Server](${inviteUrl})` : '`No Permission`', inline: true },
{ name: '📊 Total Servers Now', value: `\`${currentGuildsCount}\` guilds`, inline: true }
)
.setColor(0x57F287) // Green / Success
.setTimestamp();
await channel.send({ embeds: [embed] }).catch((err) => {
console.error(`[SYSTEM] Failed to send guild join embed log to channel:`, err);
});
} catch (err) {
console.error("[SYSTEM] Error inside guildCreate event handler:", err);
}
});
// Log server leave to designated log channel
client.on('guildDelete', async (guild) => {
sendLeaveTransaction(guild);
try {
console.log(`[SYSTEM] Bot left a guild: "${guild.name}" (${guild.id})`);
const logChannelId = '1508759327731875977';
const channel = await client.channels.fetch(logChannelId).catch(() => null);
if (!channel) {
console.warn(`[SYSTEM] Could not find the guild-leave log channel: ${logChannelId}`);
return;
}
// Try to find who kicked the bot from audit logs
let kickedBy = 'Unknown';
try {
const auditLogs = await guild.fetchAuditLogs({ limit: 10 }).catch(() => null);
if (auditLogs) {
const kickEntry = auditLogs.entries.find(entry =>
entry.targetId === client.user.id &&
(entry.action === 'MemberKick' || entry.action === 'MemberBanAdd')
);
if (kickEntry && kickEntry.executor) {
kickedBy = kickEntry.executor.username;
}
}
} catch (e) {
console.warn(`[SYSTEM] Could not fetch audit logs for guild ${guild.id}`);
}
const embed = new EmbedBuilder()
.setTitle(`📤 Bot Left a Guild`)
.addFields(
{ name: '🌐 Server Name', value: `**${guild.name}**`, inline: true },
{ name: '🆔 Server ID', value: `\`${guild.id}\``, inline: true },
{ name: '👤 Kicked By', value: `**${kickedBy}**`, inline: true },
{ name: '👥 Member Count', value: `\`${guild.memberCount || 0}\` members`, inline: true },
{ name: '📊 Total Servers Now', value: `\`${client.guilds.cache.size}\` guilds`, inline: true }
)
.setColor(0xED4245) // Red / Failure
.setTimestamp();
await channel.send({ embeds: [embed] }).catch((err) => {
console.error(`[SYSTEM] Failed to send guild leave embed log to channel:`, err);
});
} catch (err) {
console.error("[SYSTEM] Error inside guildDelete event handler:", err);
}
});
async function triggerOnboardingForRole(guild, role) {
const guildId = guild.id;
const dashboardUrl = getSpacePublicUrl() || 'https://brozy123-lineup-bot.hf.space';
try {
// Ensure members are cached to find role holders
await guild.members.fetch().catch(() => { });
const membersWithRole = guild.members.cache.filter(m => m.roles.cache.has(role.id) && !m.user.bot);
if (!storage.data.onboarded[guildId]) storage.data.onboarded[guildId] = [];
const onboardingEmbed = UI.createEmbed("🎉 Welcome to the Staff Team!", `Your role **${role.name}** has been whitelisted as a **Staff Role** in **${guild.name}**!\n\nYou now have access to manage lineups, record match stats, and use admin commands.`, UI.colors.primary);
onboardingEmbed.addFields(
{ name: "🌐 Management Dashboard", value: `Access settings and logs here:\n[**Open Dashboard**](${dashboardUrl})` },
{ name: "⚽ Key Commands", value: "`!friendly` - Start a friendly poll\n`!lineup` - Start a lineup board\n`!lineupimage` - Generate lineup image\n`!leaguematchimage` - Generate match image" },
{ name: "📖 Help", value: "If you need any help, check the dashboard or contact the server owner." }
);
let sentCount = 0;
for (const [id, member] of membersWithRole) {
if (!storage.data.onboarded[guildId].includes(id)) {
const success = await member.send({ embeds: [onboardingEmbed] }).then(() => true).catch(() => false);
if (success) {
storage.data.onboarded[guildId].push(id);
sentCount++;
}
}
}
if (sentCount > 0) storage.save('active_polls');
return sentCount;
} catch (err) {
console.error("[Onboarding] Retroactive Error:", err);
return 0;
}
}
const TIMEZONE_MAP = {
'EST': -5, 'EDT': -4, 'CST': -6, 'CDT': -5, 'MST': -7, 'MDT': -6,
'PST': -8, 'PDT': -7, 'GMT': 0, 'UTC': 0, 'BST': 1, 'CET': 1,
'CEST': 2, 'EET': 2, 'EEST': 3, 'MSK': 3, 'IST': 5.5, 'KST': 9, 'JST': 9
};
const pendingMatches = new Map();
const TIMEZONE_OPTIONS = [
{ label: 'UTC -11 (Midway)', value: '-11' },
{ label: 'UTC -10 (Hawaii)', value: '-10' },
{ label: 'UTC -9 (Alaska)', value: '-9' },
{ label: 'UTC -8 (Pacific Time)', value: '-8' },
{ label: 'UTC -7 (Mountain Time)', value: '-7' },
{ label: 'UTC -6 (Central Time)', value: '-6' },
{ label: 'UTC -5 (Eastern Time)', value: '-5' },
{ label: 'UTC -4 (Atlantic Time)', value: '-4' },
{ label: 'UTC -3 (Brazil/Argentina)', value: '-3' },
{ label: 'UTC -2 (Mid-Atlantic)', value: '-2' },
{ label: 'UTC -1 (Azores)', value: '-1' },
{ label: 'UTC +0 (GMT / London)', value: '0' },
{ label: 'UTC +1 (Central Europe)', value: '1' },
{ label: 'UTC +2 (Eastern Europe / Egypt)', value: '2' },
{ label: 'UTC +3 (Moscow / Saudi / Iraq / EEST)', value: '3' },
{ label: 'UTC +4 (Dubai / Baku)', value: '4' },
{ label: 'UTC +5 (Pakistan / Uzbekistan)', value: '5' },
{ label: 'UTC +5:30 (India / IST)', value: '5.5' },
{ label: 'UTC +6 (Bangladesh)', value: '6' },
{ label: 'UTC +7 (Thailand / Vietnam)', value: '7' },
{ label: 'UTC +8 (China / Singapore / Perth)', value: '8' },
{ label: 'UTC +9 (Japan / Korea)', value: '9' },
{ label: 'UTC +10 (Sydney / Guam)', value: '10' },
{ label: 'UTC +11 (Solomon Islands)', value: '11' },
{ label: 'UTC +12 (New Zealand / Fiji)', value: '12' }
];
function parseMatchTime(timeInput, offsetHours = 0) {
if (!timeInput) return null;
const now = new Date();
let targetDate = new Date();
// Support formats like "9 PM", "4/23 9 PM", "4-23 9PM"
// Use word boundaries for the time part to avoid matching minutes/seconds as hours
const regex = /(?:(\d+)[/-](\d+)\s+)?\b(\d+)(?::(\d+))?\s*(am|pm)\b/i;
const match = timeInput.match(regex);
if (match) {
const month = match[1];
const day = match[2];
let hours = parseInt(match[3]);
const minutes = parseInt(match[4] || "0");
const ampm = match[5].toLowerCase();
if (month && day) {
targetDate.setMonth(parseInt(month) - 1);
targetDate.setDate(parseInt(day));
}
if (ampm === 'pm' && hours !== 12) hours += 12;
if (ampm === 'am' && hours === 12) hours = 0;
targetDate.setHours(hours, minutes, 0, 0);
// Convert local time (targetDate) to UTC by applying offsetHours
const utcSeconds = Math.floor(targetDate.getTime() / 1000) - (offsetHours * 3600);
return utcSeconds;
}
return null;
}
// --- 4. LINEUP LOGIC ---
const FORMATIONS = {
// 6v6 Formations
"2-2-1 (6v6)": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CM1", "CM"], ["CM2", "CM"], ["ST", "ST"]],
"3-1-1 (6v6)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["CM", "CM"], ["ST", "ST"]],
"2-1-2 (6v6)": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CM", "CM"], ["ST1", "ST"], ["ST2", "ST"]],
"3-2-0 (6v6)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["LCM", "CM"], ["RCM", "CM"]],
// 7v7 Formations (Visible in primary dropdown)
"default": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CM", "CM"], ["RW", "RW"], ["LW", "LW"]],
"3-1-2": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CM", "CM"], ["ST1", "ST"], ["ST2", "ST"]],
"3-0-3": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"]],
"3-2-1": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CM1", "CM"], ["CM2", "CM"], ["ST", "ST"]],
"2-3-1": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST", "ST"]],
"2-2-2": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CM1", "CM"], ["CM2", "CM"], ["ST1", "ST"], ["ST2", "ST"]],
"4-1-1": [["GK", "GK"], ["LCB", "LCB"], ["RCB", "RCB"], ["LB", "LB"], ["RB", "RB"], ["CDM", "CDM"], ["ST", "ST"]],
"3-3-0": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"]],
"2-1-3": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CM", "CM"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"]],
"1-4-1": [["GK", "GK"], ["CB", "CB"], ["LM", "LM"], ["LCM", "LCM"], ["RCM", "RCM"], ["RM", "RM"], ["ST", "ST"]],
"4-2-0": [["GK", "GK"], ["LCB", "LCB"], ["RCB", "RCB"], ["LB", "LB"], ["RB", "RB"], ["LCM", "LCM"], ["RCM", "RCM"]],
"3-1-3": [["GK", "GK"], ["CB", "CB"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"], ["ST1", "ST"], ["ST2", "ST"]],
"5-0-1": [["GK", "GK"], ["LCB", "LCB"], ["CB", "CB"], ["RCB", "RCB"], ["LB", "LB"], ["RB", "RB"], ["ST", "ST"]],
"3-1-1-1": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CDM", "CDM"], ["CAM", "CAM"], ["ST", "ST"]],
"2-2-1-1": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["LCM", "LCM"], ["RCM", "RCM"], ["CAM", "CAM"], ["ST", "ST"]],
"4-1-2": [["GK", "GK"], ["LCB", "LCB"], ["RCB", "RCB"], ["CDM", "CDM"], ["LB", "LB"], ["RB", "RB"], ["ST", "ST"]],
"1-3-2": [["GK", "GK"], ["CB", "CB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST1", "ST"], ["ST2", "ST"]],
"2-1-1-2": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CDM", "CDM"], ["CAM", "CAM"], ["ST1", "ST"], ["ST2", "ST"]],
// 8v8 Formations
"3-3-1 (8v8)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST", "ST"]],
"3-2-2 (8v8)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["CM1", "CM"], ["CM2", "CM"], ["ST1", "ST"], ["ST2", "ST"]],
"2-3-2 (8v8)": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST1", "ST"], ["ST2", "ST"]],
"4-2-1 (8v8)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LCM", "CM"], ["RCM", "CM"], ["ST", "ST"]],
"2-4-1 (8v8)": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST", "ST"]],
// 9v9 Formations
"3-3-2 (9v9)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST1", "ST"], ["ST2", "ST"]],
"4-3-1 (9v9)": [["GK", "GK"], ["LB", "LB"], ["LCB", "LCB"], ["RCB", "RCB"], ["RB", "RB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST", "ST"]],
"3-4-1 (9v9)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST", "ST"]],
"4-2-2 (9v9)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LCM", "CM"], ["RCM", "CM"], ["ST1", "ST"], ["ST2", "ST"]],
// 10v10 Formations
"4-4-1 (10v10)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST", "ST"]],
"4-3-2 (10v10)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LCM", "CM"], ["CM", "CM"], ["RCM", "CM"], ["ST1", "ST"], ["ST2", "ST"]],
"3-4-2 (10v10)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST1", "ST"], ["ST2", "ST"]],
// 11v11 Formations
"4-3-3 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "LCB"], ["RCB", "RCB"], ["RB", "RB"], ["CDM", "CDM"], ["LCM", "LCM"], ["RCM", "RCM"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"]],
"4-4-2 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "LCB"], ["RCB", "RCB"], ["RB", "RB"], ["LM", "LM"], ["CM1", "CM"], ["CM2", "CM"], ["RM", "RM"], ["ST1", "ST"], ["ST2", "ST"]],
"3-5-2 (11v11)": [["GK", "GK"], ["CB", "CB"], ["LCB", "LCB"], ["RCB", "RCB"], ["LWB", "LWB"], ["RWB", "RWB"], ["CDM", "CDM"], ["LCM", "LCM"], ["RCM", "RCM"], ["ST1", "ST"], ["ST2", "ST"]],
"4-2-3-1 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "LCB"], ["RCB", "RCB"], ["RB", "RB"], ["CDM1", "CDM"], ["CDM2", "CDM"], ["CAM", "CAM"], ["LM", "LM"], ["RM", "RM"], ["ST", "ST"]],
"4-1-4-1 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["CDM", "CDM"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST", "ST"]],
"4-5-1 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LM", "LM"], ["LCM", "CM"], ["CM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST", "ST"]],
"5-3-2 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["CB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LCM", "CM"], ["CM", "CM"], ["RCM", "CM"], ["ST1", "ST"], ["ST2", "ST"]],
"3-4-3 (11v11)": [["GK", "GK"], ["LCB", "CB"], ["CB", "CB"], ["RCB", "CB"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"]]
};
/**
* Auto-detects positions from a formation string (like "4-3-3") or a comma-separated list.
*/
function autoDetectFormation(input) {
if (!input) return FORMATIONS["default"];
// 1. Check for numeric formation pattern (e.g. 4-3-3 or 4-2-3-1)
const numRegex = /^(\d)-(\d)-(\d)(?:-(\d))?$/;
const numMatch = input.trim().match(numRegex);
if (numMatch) {
const result = [['GK', 'GK']];
const dfCount = parseInt(numMatch[1]);
const mid1Count = parseInt(numMatch[2]);
const mid2Count = parseInt(numMatch[3]);
const fwCount = numMatch[4] ? parseInt(numMatch[4]) : 0;
// --- Assign Defenders ---
if (dfCount === 1) result.push(['CB', 'CB']);
else if (dfCount === 2) result.push(['LCB', 'CB'], ['RCB', 'CB']);
else if (dfCount === 3) result.push(['LB', 'LB'], ['CB', 'CB'], ['RB', 'RB']);
else if (dfCount === 4) result.push(['LB', 'LB'], ['LCB', 'CB'], ['RCB', 'CB'], ['RB', 'RB']);
else if (dfCount === 5) result.push(['LB', 'LB'], ['LCB', 'CB'], ['CB', 'CB'], ['RCB', 'CB'], ['RB', 'RB']);
if (!numMatch[4]) {
// 3-PART FORMATION (DF-MF-FW)
// Midfielders
if (mid1Count === 1) result.push(['CM', 'CM']);
else if (mid1Count === 2) result.push(['LCM', 'CM'], ['RCM', 'CM']);
else if (mid1Count === 3) result.push(['LCM', 'CM'], ['CM', 'CM'], ['RCM', 'CM']);
else if (mid1Count === 4) result.push(['LM', 'LM'], ['LCM', 'CM'], ['RCM', 'CM'], ['RM', 'RM']);
else if (mid1Count === 5) result.push(['LM', 'LM'], ['LCM', 'CM'], ['CM', 'CM'], ['RCM', 'CM'], ['RM', 'RM']);
// Forwards
if (mid2Count === 1) result.push(['ST', 'ST']);
else if (mid2Count === 2) result.push(['ST1', 'ST'], ['ST2', 'ST']);
else if (mid2Count === 3) result.push(['LW', 'LW'], ['ST', 'ST'], ['RW', 'RW']);
else if (mid2Count === 4) result.push(['LW', 'LW'], ['ST1', 'ST'], ['ST2', 'ST'], ['RW', 'RW']);
} else {
// 4-PART FORMATION (DF-DM-AM-FW)
// CDMs
if (mid1Count === 1) result.push(['CDM', 'CDM']);
else if (mid1Count === 2) result.push(['CDM1', 'CDM'], ['CDM2', 'CDM']);
// AMs
if (mid2Count === 1) result.push(['CAM', 'CAM']);
else if (mid2Count === 2) result.push(['CAM1', 'CAM'], ['CAM2', 'CAM']);
else if (mid2Count === 3) result.push(['LM', 'LM'], ['CAM', 'CAM'], ['RM', 'RM']);
// Forwards
if (fwCount === 1) result.push(['ST', 'ST']);
else if (fwCount === 2) result.push(['ST1', 'ST'], ['ST2', 'ST']);
}
return result;
}
// 2. Fallback to comma/space separated list of positions
const parts = input.split(/[,|\s]+/).map(s => s.trim().toUpperCase()).filter(s => s.length > 0);
const counts = {};
const result = [];
parts.forEach(pos => {
counts[pos] = (counts[pos] || 0) + 1;
let key = pos;
const totalCount = parts.filter(p => p === pos).length;
if (totalCount > 1) {
key = `${pos}${counts[pos]}`;
if (totalCount === 2) {
if (pos === 'CB') key = counts[pos] === 1 ? 'LCB' : 'RCB';
if (pos === 'CM') key = counts[pos] === 1 ? 'LCM' : 'RCM';
if (pos === 'ST') key = counts[pos] === 1 ? 'ST1' : 'ST2';
if (pos === 'CDM') key = counts[pos] === 1 ? 'CDM1' : 'CDM2';
if (pos === 'CAM') key = counts[pos] === 1 ? 'CAM1' : 'CAM2';
}
} else {
key = pos;
}
result.push([key, pos]);
});
if (!result.some(r => r[1] === 'GK')) {
result.unshift(['GK', 'GK']);
}
return result;
}
// Persistence is now handled by lineup_persistence.js
function getGuildLineup(guildId) {
if (!guildLineups.get(guildId)) {
guildLineups.set(guildId, new Map());
saveLineup();
}
return guildLineups.get(guildId);
}
function getGuildLineupB(guildId) {
if (!guildLineupsB.get(guildId)) {
guildLineupsB.set(guildId, new Map());
saveLineup();
}
return guildLineupsB.get(guildId);
}
function resolveEmojis(text, guildId) {
if (!text || typeof text !== 'string') return text;
const guild = client.guilds.cache.get(guildId);
return text.replace(/:([a-zA-Z0-9_]+):/g, (match, name) => {
// 1. Try finding in current guild (case-insensitive)
let emoji = guild?.emojis.cache.find(e => e.name.toLowerCase() === name.toLowerCase());
// 2. Try finding globally if not found in guild
if (!emoji && client) {
emoji = client.emojis.cache.find(e => e.name.toLowerCase() === name.toLowerCase());
}
return emoji ? emoji.toString() : match;
});
}
function getFriendlyText(guildId, needed) {
const config = storage.data.config[guildId] || {};
let text = config.friendlyText || "⭐▬▬▬▬▬ **FRIENDLY** ▬▬▬▬▬⭐\n🤝 Session\n🟩 I'm In\n🟥 Busy\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n🗳️ Needed: {needed}\n@everyone";
// Replace {needed} placeholder
text = text.replace('{needed}', needed);
// Resolve custom emojis
return resolveEmojis(text, guildId);
}
function createLineupView(guildId) {
const lineup = getGuildLineup(guildId);
// Prefer explicit map if present; otherwise fall back to A/B maps or default
let formKey;
if (typeof guildSelectedFormation !== 'undefined' && guildSelectedFormation && typeof guildSelectedFormation.get === 'function') {
formKey = guildSelectedFormation.get(guildId) || 'default';
} else {
const kb = (guildSelectedFormationA && guildSelectedFormationA.get(guildId)) || null;
const kb2 = (guildSelectedFormationB && guildSelectedFormationB.get(guildId)) || null;
formKey = kb || kb2 || 'default';
}
const formation = formKey === `custom_${guildId}` ? guildCustomFormations.get(guildId) : FORMATIONS[formKey];
const formDisplayName = formKey === `custom_${guildId}` ? (guildCustomFormationNames.get(guildId) || "Custom") : formKey;
if (!formation) return { content: "❌ Error: Formation not found." };
let text = "";
for (const [posKey, posLabel] of formation) {
const players = lineup.get(posKey) || [];
const resolvedLabel = resolveEmojis(posLabel, guildId);
if (players.length > 0) {
const starter = players[0];
const subs = players.slice(1);
let line = `🟩 **${resolvedLabel}** ➔ <@${starter}>`;
if (subs.length > 0) {
line += ` (Substitute: ` + subs.map(p => `<@${p}>`).join(', ') + `)`;
}
text += line + "\n\n";
} else {
text += `⬛ **${resolvedLabel}** ➔ *Open*\n\n`;
}
}
const embed = UI.createEmbed(`⚽ MATCH LINEUP — ${resolveEmojis(formDisplayName, guildId)}`, text, UI.colors.primary);
embed.setFooter({ text: "Click a position below to join/leave! Use the dropdown to change formation." });
const rows = [];
const categoryRow = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('formation_category_select')
.setPlaceholder('📂 Change Formation Size (7v7, 11v11, others...)')
.addOptions([
{ label: '⚽ 7v7 Formations', value: 'cat_7v7', emoji: '⚽' },
{ label: '🏆 11v11 Formations', value: 'cat_11v11', emoji: '🏆' },
{ label: '🎮 Other Sizes (6v6, 8v8, 9v9, 10v10)', value: 'cat_other', emoji: '🎮' }
])
);
rows.push(categoryRow);
let currentRow = new ActionRowBuilder();
let currentPosCount = 0;
formation.forEach(([posKey, posLabel]) => {
if (currentPosCount === 5) {
rows.push(currentRow);
currentRow = new ActionRowBuilder();
currentPosCount = 0;
}
const players = lineup.get(posKey) || [];
const btnLabel = posLabel;
const btn = new ButtonBuilder()
.setCustomId(`join_${posKey}`)
.setLabel(players.length > 0 ? `${btnLabel}: ✅` : btnLabel)
.setStyle(players.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Primary);
if (players.length > 0) btn.setEmoji("✅");
currentRow.addComponents(btn);
currentPosCount++;
});
if (currentPosCount > 0) rows.push(currentRow);
rows.push(new ActionRowBuilder().addComponents(
new ButtonBuilder().setCustomId('lineup_done').setLabel('Show Final Image').setStyle(ButtonStyle.Success).setEmoji("🖼️"),
new ButtonBuilder().setCustomId('open_custom_lineup_modal').setLabel('Custom / Other Sizes').setStyle(ButtonStyle.Primary).setEmoji("🛠️"),
new ButtonBuilder().setCustomId('lineup_clear').setLabel('Clear Board').setStyle(ButtonStyle.Danger)
));
const pingType = guildPingType.get(guildId) || 'everyone';
const pingMention = pingType === 'here' ? '@here' : '@everyone';
const mentionParse = ['everyone', 'roles', 'users'];
const content = `${pingMention}\n**Lineup Session Active!**`;
return { content, embeds: [embed], components: rows, allowedMentions: { parse: mentionParse } };
}
function createScrimLineupView(guildId) {
const lineupA = getGuildLineup(guildId);
const lineupB = getGuildLineupB(guildId);
const formKeyA = guildSelectedFormationA.get(guildId) || 'default';
const formationA = formKeyA === `custom_${guildId}` ? guildCustomFormations.get(guildId) : FORMATIONS[formKeyA];
const formDisplayNameA = formKeyA === `custom_${guildId}` ? (guildCustomFormationNames.get(guildId) || "Custom") : formKeyA;
const formKeyB = guildSelectedFormationB.get(guildId) || 'default';
const formationB = formKeyB === `custom_${guildId}` ? guildCustomFormations.get(guildId) : FORMATIONS[formKeyB];
const formDisplayNameB = formKeyB === `custom_${guildId}` ? (guildCustomFormationNames.get(guildId) || "Custom") : formKeyB;
if (!formationA || !formationB) return { content: "❌ Error: Formation not found." };
let textA = "";
let textB = "";
for (const [posKey, posLabel] of formationA) {
const resolvedLabel = resolveEmojis(posLabel, guildId);
const playersA = lineupA.get(posKey) || [];
if (playersA.length > 0) {
const starter = playersA[0];
const subs = playersA.slice(1);
let line = `🟩 **${resolvedLabel}** ➔ <@${starter}>`;
if (subs.length > 0) line += ` (Sub: ` + subs.map(p => `<@${p}>`).join(', ') + `)`;
textA += line + "\n\n";
} else { textA += `⬛ **${resolvedLabel}** ➔ *Open*\n\n`; }
}
for (const [posKey, posLabel] of formationB) {
const resolvedLabel = resolveEmojis(posLabel, guildId);
const playersB = lineupB.get(posKey) || [];
if (playersB.length > 0) {
const starter = playersB[0];
const subs = playersB.slice(1);
let line = `🟩 **${resolvedLabel}** ➔ <@${starter}>`;
if (subs.length > 0) line += ` (Sub: ` + subs.map(p => `<@${p}>`).join(', ') + `)`;
textB += line + "\n\n";
} else { textB += `⬛ **${resolvedLabel}** ➔ *Open*\n\n`; }
}
const embedA = UI.createEmbed(`🔵 TEAM A — ${resolveEmojis(formDisplayNameA, guildId)}`, textA, UI.colors.primary);
embedA.setFooter({ text: "Click buttons below to join Team A" });
const embedB = UI.createEmbed(`🔴 TEAM B — ${resolveEmojis(formDisplayNameB, guildId)}`, textB, 0xff4444);
embedB.setFooter({ text: "Click buttons below to join Team B" });
const allButtons = [];
formationA.forEach(([pk, pl]) => {
const pA = lineupA.get(pk) || [];
allButtons.push(new ButtonBuilder().setCustomId(`scrim_join_a_${pk}`).setLabel(pA.length > 0 ? `${pl}: ✅` : pl).setStyle(pA.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Primary).setEmoji(pA.length > 0 ? "✅" : null));
});
formationB.forEach(([pk, pl]) => {
const pB = lineupB.get(pk) || [];
allButtons.push(new ButtonBuilder().setCustomId(`scrim_join_b_${pk}`).setLabel(pB.length > 0 ? `${pl}: ✅` : pl).setStyle(pB.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Primary).setEmoji(pB.length > 0 ? "✅" : null));
});
allButtons.push(new ButtonBuilder().setCustomId('lineup_done').setLabel('Show Image').setStyle(ButtonStyle.Success).setEmoji("🖼️"));
allButtons.push(new ButtonBuilder().setCustomId('open_custom_lineup_modal').setLabel('Custom').setStyle(ButtonStyle.Primary).setEmoji("🛠️"));
allButtons.push(new ButtonBuilder().setCustomId('lineup_clear').setLabel('Clear').setStyle(ButtonStyle.Danger));
let rows = [];
for (let i = 0; i < allButtons.length; i += 5) {
rows.push(new ActionRowBuilder().addComponents(allButtons.slice(i, i + 5)));
}
// Limit to 5 rows to prevent Discord API error
if (rows.length > 5) rows = rows.slice(0, 5);
const pingType = guildPingType.get(guildId) || 'everyone';
const pingMention = pingType === 'here' ? '@here' : '@everyone';
const mentionParse = ['everyone', 'roles', 'users'];
const content = `${pingMention}\n**🔥 SCRIMMAGE LINEUP SESSION ACTIVE!**\n*Two teams facing each other!*`;
return { content, embeds: [embedA, embedB], components: rows, allowedMentions: { parse: mentionParse } };
}
function createManagerEditor(guildId, client) {
const lineup = getGuildLineup(guildId);
const formKey = guildSelectedFormation.get(guildId) || 'default';
const formation = formKey === `custom_${guildId}` ? guildCustomFormations.get(guildId) : FORMATIONS[formKey];
const formDisplayName = formKey === `custom_${guildId}` ? (guildCustomFormationNames.get(guildId) || "Custom") : formKey;
if (!formation) return { content: "❌ Error: Formation not found." };
let text = `🛠️ **LINEUP GUI EDITOR** — ${resolveEmojis(formDisplayName, guildId)}\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n`;
for (const [posKey, posLabel] of formation) {
const players = lineup.get(posKey) || [];
const userStr = players.length > 0 ? `<@${players[0]}>` : "---";
text += `📦 **${resolveEmojis(posLabel, guildId)}**: ${userStr}\n`;
}
text += "▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n*Click a box below to edit a position!*";
const rows = [];
let currentRow = new ActionRowBuilder();
let currentPosCount = 0;
formation.forEach(([posKey, posLabel]) => {
if (currentPosCount === 4) {
rows.push(currentRow);
currentRow = new ActionRowBuilder();
currentPosCount = 0;
}
const players = lineup.get(posKey) || [];
let valTitle = "---";
if (players.length > 0 && client) {
const tempUser = client.users.cache.get(players[0]);
valTitle = tempUser ? tempUser.username : "Player";
} else if (players.length > 0) { valTitle = "Player"; }
currentRow.addComponents(
new ButtonBuilder()
.setCustomId(`man_edit_${posKey}`)
.setLabel(`${posLabel}: ${valTitle}`)
.setStyle(ButtonStyle.Secondary)
.setEmoji("🛠️")
);
currentPosCount++;
});
if (currentPosCount > 0) rows.push(currentRow);
// Add a Done/Submit button at the bottom
rows.push(new ActionRowBuilder().addComponents(
new ButtonBuilder().setCustomId('lineup_done').setLabel('Generate Final Image').setStyle(ButtonStyle.Success).setEmoji("🖼️")
));
return { content: text, components: rows };
}
// --- 5. 24/7 HEARTBEAT & RECOVERY ---
const fetch = require('node-fetch');
/** Public Space URL for keep-alive pings (HF injects these at runtime). */
function getSpacePublicUrl() {
const host = (process.env.SPACE_HOST || '').trim();
if (host) return host.startsWith('http') ? host : `https://${host}`;
const spaceId = (process.env.SPACE_ID || '').trim();
if (spaceId) return `https://${spaceId.replace('/', '-').toLowerCase()}.hf.space`;
const author = (process.env.SPACE_AUTHOR_NAME || '').trim();
const repo = (process.env.SPACE_REPO_NAME || '').trim();
if (author && repo) return `https://${author}-${repo}`.toLowerCase().replace(/\s+/g, '') + '.hf.space';
return '';
}
let recoveryDisconnectedSince = null;
let recoveryAttempts = 0;
setInterval(async () => {
const url = getSpacePublicUrl();
if (url) {
fetch(url, { method: 'GET' }).catch(() => { });
}
// Recovery Check: Handle BOTH online-but-degraded AND fully offline states
const isReady = client.isReady();
const wsStatus = client.ws?.status ?? -1;
if (isReady && wsStatus === 0) {
// Everything is healthy — reset recovery state
recoveryDisconnectedSince = null;
recoveryAttempts = 0;
return;
}
// Something is wrong — either not ready, or gateway is degraded
if (!recoveryDisconnectedSince) recoveryDisconnectedSince = Date.now();
const downMs = Date.now() - recoveryDisconnectedSince;
if (isReady && wsStatus !== 0) {
// Client thinks it's ready but gateway is degraded
console.log(`[!] Gateway degraded. WS status: ${wsStatus}. Down for ${Math.round(downMs / 1000)}s.`);
} else {
// Client is fully offline
console.log(`[!] Bot is OFFLINE. WS status: ${wsStatus}. Down for ${Math.round(downMs / 1000)}s.`);
}
// After 2 minutes of issues, rotate DNS and attempt reconnect
if (downMs > 2 * 60 * 1000 && recoveryAttempts < 3) {
recoveryAttempts++;
console.log(`[RECOVERY] Attempt ${recoveryAttempts}/3: Rotating DNS and attempting re-login...`);
networkFix.rotateEndpoint();
try {
client.destroy();
await new Promise(r => setTimeout(r, 2000));
await client.login(TOKEN);
console.log('[RECOVERY] Re-login successful!');
recoveryDisconnectedSince = null;
recoveryAttempts = 0;
} catch (err) {
console.error(`[RECOVERY] Re-login failed: ${err?.message || err}`);
}
}
// After 3 failed recovery attempts (~6+ minutes), force restart the container
if (recoveryAttempts >= 3 && downMs > 6 * 60 * 1000) {
console.error('[RECOVERY] All recovery attempts exhausted. Forcing process exit for container restart...');
process.exit(1);
}
}, 2 * 60 * 1000); // Every 2 minutes
async function showAutoFriendlyPanel(interaction) {
const guildId = interaction.guildId;
const config = storage.data.config[guildId] || {};
const enabled = config.autoFriendlyEnabled || false;
const interval = config.autoFriendlyInterval || 40;
const channelId = config.autoFriendlyChannel;
const embed = UI.createEmbed("🤖 Auto Friendly Settings",
`Configure the bot to automatically start friendly polls.\n\n` +
`**Status**: ${enabled ? '✅ Enabled' : '❌ Disabled'}\n` +
`**Interval**: \`${interval}\` minutes\n` +
`**Target Channel**: ${channelId ? `<#${channelId}>` : '`Not Set`'}`,
enabled ? UI.colors.success : UI.colors.primary
);
const row1 = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('toggle_auto_friendly')
.setLabel(enabled ? 'Disable Auto Friendly' : 'Enable Auto Friendly')
.setStyle(enabled ? ButtonStyle.Danger : ButtonStyle.Success),
new ButtonBuilder()
.setCustomId('open_interval_modal')
.setLabel('Set Interval')
.setStyle(ButtonStyle.Primary)
);
const row2 = new ActionRowBuilder().addComponents(
new ChannelSelectMenuBuilder()
.setCustomId('auto_friendly_channel_select')
.setPlaceholder('Select target channel...')
.addChannelTypes(ChannelType.GuildText)
);
if (interaction.replied || interaction.deferred) {
await interaction.editReply({ embeds: [embed], components: [row1, row2] });
} else {
await interaction.reply({ embeds: [embed], components: [row1, row2], ephemeral: true });
}
}
/**
* Application Entry Point
*/
async function initialize() {
let retryCount = 0;
const maxRetryDelay = 60000; // Cap at 1 minute between retries
// STEP 1: Start the web server FIRST.
// HF will kill the container if port 7860 doesn't respond quickly.
console.log("[*] Starting Web Dashboard...");
server.startServer(client, commandsData);
// STEP 2: Give the container's network stack a moment to settle.
// On HF cold-starts, the outbound network may not be ready immediately.
console.log("[*] Waiting 3s for network stack to stabilize...");
await new Promise(r => setTimeout(r, 3000));
// STEP 3: Start the Discord login loop.
login();
async function login() {
if (!TOKEN || TOKEN.length < 10) {
console.error("[CRITICAL] Discord Token is missing or malformed.");
process.exit(1);
}
retryCount++;
try {
const currentApi = DISCORD_ENDPOINTS[currentEndpointIndex];
console.log(`[*] 📡 VERIFYING: ${currentApi}...`);
// Manual Force-Fetch to bypass Discord.js token-not-present error
const { request } = require('undici');
let testRes = null;
let testError = null;
try {
const response = await request(`${currentApi}/v10/users/@me`, {
method: 'GET',
headers: {
'Authorization': `Bot ${TOKEN}`,
'User-Agent': 'DiscordBot (FriendlyBot, 4.0)'
}
});
if (response.statusCode === 200) testRes = { ok: true };
else if (response.statusCode === 401) testRes = { status: 401 };
else testError = { status: response.statusCode, message: "Blocked or Rate Limited" };
} catch (e) {
testError = e;
}
if (testRes && testRes.status === 401) {
console.error("[CRITICAL] ❌ TOKEN INVALID (401). Check Discord Dev Portal!");
return;
} else if (testRes) {
console.log(`[SUCCESS] ✅ Connected via ${currentApi}`);
client.token = TOKEN;
} else {
const errDetail = testError ? `${testError.status || 'TIMEOUT'} - ${testError.message}` : "Unknown Error";
console.warn(`[BLOCKED] ⚠️ ${currentApi} failed: ${errDetail}`);
currentEndpointIndex = (currentEndpointIndex + 1) % DISCORD_ENDPOINTS.length;
throw new Error("Cycle endpoints");
}
console.log(`[*] Attempting connection to Discord (Attempt ${retryCount}) using ${currentApi}...`);
// Destroy any stale connection before retrying
if (retryCount > 1) {
try { client.destroy(); } catch (_) { }
await new Promise(r => setTimeout(r, 1000));
}
await client.login(TOKEN);
console.log('[*] Discord login() resolved successfully.');
if (connectionTimeout) clearTimeout(connectionTimeout);
retryCount = 0; // Reset on success
} catch (err) {
const msg = err && err.message ? err.message : String(err);
console.error(`[ERROR] Discord login failed: ${msg}`);
if (/intent|disallowed|4014|privileg/i.test(msg)) {
console.error('[HINT] https://discord.com/developers/applications → your app → Bot → Privileged Gateway Intents: turn ON "Server Members Intent" and "Message Content Intent", then restart this Space.');
}
// Token errors are fatal — don't retry forever
if (/token|unauthorized|authentication|403|401/i.test(msg) && retryCount >= 3) {
console.error('[CRITICAL] Token appears invalid after 3 attempts. Stopping retries.');
return;
}
// Rotate endpoint for next attempt if this was an actual connection/login failure
if (msg !== 'Cycle endpoints') {
currentEndpointIndex = (currentEndpointIndex + 1) % DISCORD_ENDPOINTS.length;
}
const delay = Math.min(1000 * Math.pow(2, retryCount), maxRetryDelay);
console.log(`[*] Retrying in ${delay / 1000}s... (attempt ${retryCount})`);
setTimeout(login, delay);
}
}
// --- 24/7 Heartbeat + Self-Healing ---
// Runs every 5 minutes (not hourly!) for faster detection of problems.
let disconnectedSince = null;
setInterval(async () => {
const up = process.uptime();
const h = Math.floor(up / 3600);
const m = Math.floor(up / 60) % 60;
const connected = client.isReady();
const wsStatus = client.ws?.status ?? -1;
console.log(`[24/7 HEARTBEAT] Uptime: ${h}h ${m}m | Discord: ${connected ? 'CONNECTED ✓' : 'DISCONNECTED ✗'} | WS: ${wsStatus}`);
// Track how long we've been disconnected
if (!connected) {
if (!disconnectedSince) disconnectedSince = Date.now();
const disconnectedMs = Date.now() - disconnectedSince;
// After 5 minutes disconnected, try to reconnect with fresh DNS
if (disconnectedMs > 5 * 60 * 1000 && disconnectedMs <= 6 * 60 * 1000) {
console.warn(`[HEARTBEAT] Bot disconnected for ${Math.round(disconnectedMs / 60000)} minutes. Attempting DNS rotation + re-login...`);
networkFix.rotateEndpoint();
try {
client.destroy();
await new Promise(r => setTimeout(r, 2000));
await client.login(TOKEN);
console.log('[HEARTBEAT] Re-login successful!');
disconnectedSince = null;
} catch (err) {
console.error(`[HEARTBEAT] Re-login failed: ${err?.message || err}`);
}
}
// If disconnected for over 15 minutes even after reconnect attempts, force restart
if (disconnectedMs > 15 * 60 * 1000) {
console.error(`[!] Bot disconnected for ${Math.round(disconnectedMs / 60000)} minutes. Forcing process exit for container restart...`);
process.exit(1);
}
} else {
disconnectedSince = null;
}
// Ping own public URL to prevent HF from sleeping the Space
const spaceHost = process.env.SPACE_HOST;
if (spaceHost) {
fetch(`https://${spaceHost}/healthz`).catch(() => { });
}
// Also ping localhost as fallback
fetch(`http://0.0.0.0:${process.env.PORT || 7860}/healthz`).catch(() => { });
}, 5 * 60 * 1000); // Every 5 minutes
}
initialize().catch(err => {
console.error(">>> [BOOT] CRITICAL INITIALIZATION ERROR:", err);
process.exit(1);
});
|