Spaces:
Sleeping
Sleeping
File size: 71,377 Bytes
53e1e26 14aed84 ef13acf 7f5c15c 14aed84 53e1e26 a7c61bf b4d2f05 3ff7d5a a7c61bf 7077459 8d92e23 55abc6c d2289a7 e55b6f5 fac4b6b e55b6f5 3cac37d fc8a2ef 3cac37d 14aed84 c83481d 7077459 f0a53ee a678d13 d2289a7 c83481d 53e1e26 f0a53ee e55b6f5 e03e842 f0a53ee d0b8164 3da1194 ef13acf c83481d f0a53ee c83481d 53e1e26 ef13acf 702d428 ef13acf 702d428 ef13acf 702d428 a32c8d9 53e1e26 c83481d f0a53ee 6981ec5 f0a53ee 53e1e26 3da1194 8d92e23 3da1194 8d92e23 ace999e 53e1e26 8d92e23 53e1e26 f0a53ee ca908a9 f0a53ee d86db2c f0a53ee 702d428 a32c8d9 f0a53ee 8d92e23 331f6bf 8d92e23 f0a53ee 8d92e23 c83481d f0a53ee a985014 53e1e26 c83481d f0a53ee 53e1e26 a985014 c83481d a985014 6981ec5 e03e842 6981ec5 e03e842 3bfbd5d 6981ec5 1d2668d e03e842 90597fa e03e842 ca908a9 6981ec5 e03e842 702d428 6981ec5 0d9b3bf 5f2a61d 6981ec5 f0a53ee ace999e 8db37a5 53e1e26 73001f4 53e1e26 702d428 53e1e26 ef13acf 73001f4 702d428 73001f4 e03e842 73001f4 53e1e26 e03e842 702d428 53e1e26 e03e842 f0a53ee ace999e 8db37a5 53e1e26 73001f4 53e1e26 702d428 53e1e26 ef13acf 73001f4 702d428 73001f4 e03e842 73001f4 53e1e26 e03e842 702d428 53e1e26 e03e842 de46e97 e3a866b a32c8d9 a985014 702d428 f0a53ee ace999e f59a505 e03e842 702d428 4981a68 e03e842 702d428 e03e842 702d428 e03e842 702d428 0d9b3bf 702d428 f59a505 90c0c34 0712efd 818b408 702d428 818b408 0712efd 818b408 702d428 818b408 e03e842 0712efd e03e842 0712efd e03e842 818b408 e03e842 0712efd 818b408 e03e842 0712efd 90c0c34 c83481d 0dbbc1a f0a53ee ace999e f0a53ee 7f5c15c f0a53ee 7f5c15c b4f3b88 f0a53ee e03e842 f0a53ee e03e842 f0a53ee e03e842 a32c8d9 0d9b3bf fbfca6e f0a53ee ef13acf ace999e ef13acf 702d428 ef13acf 702d428 fbfca6e 3ec0c8c e03e842 a2298ea e03e842 3ec0c8c e03e842 3ec0c8c 0d9b3bf a32c8d9 ef13acf 6981ec5 a32c8d9 6981ec5 e03e842 6981ec5 d2289a7 e03e842 0d9b3bf fbfca6e d2289a7 b5f3a1a d2289a7 b5f3a1a e03e842 b5f3a1a e03e842 b5f3a1a d2289a7 b5f3a1a 6981ec5 0d9b3bf fbfca6e 6981ec5 9d93df9 e03e842 9d93df9 0d9b3bf fbfca6e 9d93df9 a7c61bf 03c17c6 e55b6f5 702d428 e55b6f5 702d428 03c17c6 e55b6f5 a7c61bf 702d428 e55b6f5 03c17c6 e55b6f5 03c17c6 e03e842 03c17c6 e03e842 03c17c6 a7c61bf 0d9b3bf fbfca6e a7c61bf fc8a2ef a73c447 702d428 a73c447 b975879 a73c447 702d428 c850acf a73c447 a99ad01 c68d52a e03e842 7421af0 a73c447 702d428 fc8a2ef 0d9b3bf fbfca6e fc8a2ef 3ff7d5a 1d2668d 3ff7d5a cce1709 1d2668d cce1709 1d2668d cce1709 3ff7d5a 59ad48c f0a53ee a32c8d9 ef13acf 7f5c15c c83481d 702d428 c83481d e03e842 ef13acf e03e842 ef13acf e03e842 ef13acf e03e842 ef13acf e03e842 a2298ea ef13acf e03e842 c83481d f0a53ee a32c8d9 c83481d 7f5c15c c83481d 702d428 c83481d e03e842 8d92e23 e03e842 a32c8d9 c83481d f0a53ee a32c8d9 c83481d 7f5c15c c83481d 702d428 c83481d e03e842 c83481d e03e842 a32c8d9 c83481d f0a53ee a32c8d9 c83481d 7f5c15c c83481d 702d428 c83481d e03e842 c83481d e03e842 a32c8d9 c83481d f0a53ee a32c8d9 c83481d 7f5c15c c83481d 702d428 c83481d e03e842 c83481d e03e842 c83481d e03e842 a32c8d9 834dc38 f0a53ee a32c8d9 7f5c15c 834dc38 702d428 834dc38 e03e842 834dc38 a32c8d9 e03e842 834dc38 e03e842 834dc38 a32c8d9 e03e842 834dc38 e03e842 a6cebb0 e03e842 a6cebb0 e03e842 a32c8d9 834dc38 a32c8d9 e03e842 834dc38 e03e842 834dc38 e03e842 a32c8d9 3da1194 f0a53ee a32c8d9 a6cebb0 7f5c15c a6cebb0 702d428 a6cebb0 e03e842 7f5c15c ace999e e03e842 a6cebb0 f2a123b 5a90716 a6cebb0 e03e842 ace999e 702d428 c7c1182 e03e842 ace999e 702d428 c7c1182 e03e842 ace999e 702d428 c7c1182 e03e842 ace999e 702d428 c7c1182 702d428 f2a123b a32c8d9 a6cebb0 a32c8d9 14aed84 7f5c15c 14aed84 702d428 14aed84 702d428 e03e842 14aed84 e03e842 14aed84 e03e842 a32c8d9 14aed84 7f5c15c 14aed84 a32c8d9 7f5c15c ccc39b8 702d428 ccc39b8 e03e842 22e1201 e03e842 ccc39b8 22e1201 e03e842 22e1201 e03e842 a32c8d9 ef13acf e03e842 ef13acf e03e842 ef13acf 702d428 ccc39b8 fac4b6b 702d428 fac4b6b e03e842 fac4b6b e03e842 fac4b6b e03e842 fac4b6b e03e842 fac4b6b e03e842 fac4b6b e55b6f5 e03e842 e55b6f5 702d428 e55b6f5 e03e842 fac4b6b 7f5c15c e03e842 7f5c15c e03e842 f6948f9 7f5c15c e03e842 7241c03 7f5c15c e03e842 702d428 7f5c15c 7241c03 e03e842 7f5c15c e03e842 702d428 7f5c15c e03e842 702d428 7f5c15c e03e842 7f5c15c e03e842 f6948f9 7f5c15c e03e842 7241c03 7f5c15c e03e842 702d428 7f5c15c 7241c03 e03e842 7f5c15c e03e842 702d428 7f5c15c e03e842 702d428 7f5c15c 7241c03 7f5c15c e03e842 7f5c15c e03e842 f6948f9 e03e842 f6948f9 e03e842 f6948f9 e03e842 f6948f9 e03e842 f6948f9 7f5c15c f6948f9 e03e842 f6948f9 e03e842 f6948f9 e03e842 7f5c15c e03e842 7f5c15c e03e842 7f5c15c e03e842 f6948f9 e03e842 702d428 7f5c15c e03e842 702d428 7f5c15c 676a005 90597fa 676a005 e03e842 0893492 e03e842 0893492 e03e842 676a005 e03e842 676a005 e03e842 676a005 e03e842 676a005 e03e842 676a005 e03e842 676a005 e03e842 676a005 fac4b6b c83481d d0b8164 f0a53ee f59a505 f0a53ee c83481d f59a505 f0a53ee | 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 | import os
import time
import json
import asyncio
import psutil
import discord
import requests
import socket
import random
from datetime import datetime
from dotenv import load_dotenv
from discord.ext import commands, tasks
from pydvpl.dvpl import compress_dvpl, decompress_dvpl, __LZ4_VERSION__
import pydvpl.version
import pytgpt.phind as phind
import pytgpt.opengpt as opengpt
import pytgpt.blackboxai as blackboxai
import subprocess
import pytgpt
from craiyon import Craiyon, craiyon_utils
from io import BytesIO
import base64
import craiyon
# ENV_LOADER ------------------------------------------------------ START
load_dotenv()
# ENV_LOADER ------------------------------------------------------ END
# DEFINES ------------------------------------------------------ START
BOT_VERSION = '1.4.5'
AUTHORIZED_USER_ID = os.getenv('AUTHORIZED_ID')
TOKEN = os.getenv('DISCORD_TOKEN')
LOG_CHANNEL_ID = os.getenv('CHANNEL_ID')
AUTHORIZED_AI_ACCESS_ID = os.getenv('AUTHORIZED_AI_ID')
MY_SERVER_ID = os.getenv('MY_SERVER_ID')
FEEDBACK_CHANNEL_ID = os.getenv('FEEDBACK_CHANNEL_ID')
UPDATE_INTERVAL = 60
activity_start_time = 0
# Define folder paths
FEEDBACK_FOLDER = "feedback"
ISSUES_FOLDER = os.path.join(FEEDBACK_FOLDER, "issues")
REQUESTS_FOLDER = os.path.join(FEEDBACK_FOLDER, "requests")
COMPRESS_FOLDER= os.path.join("received_to_compress")
DECOMPRESS_FOLDER= os.path.join("received_to_decompress")
# DEFINES ------------------------------------------------------ END
# HELPER ------------------------------------------------------ START
# FUNCTION ------------------------------------------------------ SPLIT
# Ensure the existence of folders
def ensure_folders():
for folder in [FEEDBACK_FOLDER, ISSUES_FOLDER, REQUESTS_FOLDER, COMPRESS_FOLDER, DECOMPRESS_FOLDER]:
if not os.path.exists(folder):
os.makedirs(folder)
# FUNCTION ------------------------------------------------------ SPLIT
async def clean_directory(ctx, directory):
try:
msg = await ctx.reply("Cleaning...")
file_count = 0
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
if os.path.isfile(file_path):
os.remove(file_path)
file_count += 1
await msg.edit(content=f"All files cleaned successfully in {directory}. Total files cleaned: {file_count}.")
except Exception as e:
await msg.edit(content=f"An error occurred while cleaning files: {e}")
# HELPER ------------------------------------------------------ END
# CORE_PREFIX ------------------------------------------------------ START
# Set up bot command prefix
bot_intents = discord.Intents.all()
# Initialize the bot with intents
bot = commands.Bot(command_prefix=">>", intents=bot_intents)
# CORE_PREFIX ------------------------------------------------------ END
# CORE ------------------------------------------------------ START
@bot.event
async def on_ready():
global activity_start_time
activity_start_time = time.time()
# Set initial activity to playing time
await update_playing_time_activity()
# Start the task to update playing time
update_playing_time.start()
await bot.tree.sync()
print(f'{bot.user} has connected to Discord!')
ensure_folders()
# FUNCTION ------------------------------------------------------ SPLIT
@bot.event
async def on_disconnect():
print('Bot disconnected from Discord. Attempting to reconnect...')
await bot.change_presence(status=discord.Status.invisible)
# FUNCTION ------------------------------------------------------ SPLIT
@bot.event
async def on_guild_join(guild):
embed = discord.Embed(
title="Thank You for Adding PyDVPL Bot! 💛",
description="We're excited to be a part of your server. If you have any questions or need assistance, feel free to reach out to us!",
color=discord.Color.yellow()
)
embed.add_field(name="Feedback Commands:", value="`feedback` - Sends feedback to bot developers. (usage: >>feedback issues/requests <message>)", inline=False)
embed.add_field(name="Help Commands:", value="Do `/help` or `>>help` to begin with PyDVPL!", inline=False)
# embed.set_footer(value="Do `/help` or `>>help` to begin with PyDVPL!")
# Check for a suitable channel to send the message
public_updates_channel = guild.public_updates_channel
default_channel = guild.system_channel or guild.text_channels[0] # Default to the first text channel
if public_updates_channel:
await public_updates_channel.send(embed=embed)
else:
if default_channel:
await default_channel.send(embed=embed)
# FUNCTION ------------------------------------------------------ SPLIT
@bot.event
async def on_command(ctx):
# Log command usage
log_channel = bot.get_channel(int(LOG_CHANNEL_ID))
if log_channel:
if ctx.guild:
log_message = f"Command `{ctx.command}` used by `{ctx.author} ({ctx.author.id})` in `{ctx.guild} ({ctx.guild.id})`"
else:
log_message = f"Command `{ctx.command}` used by `{ctx.author} ({ctx.author.id})` in {ctx.me.mention}'s `DM`"
await log_channel.send(log_message)
# FUNCTION ------------------------------------------------------ SPLIT
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.reply("Sorry, I couldn't find that command. Use `/help` or `>>help` to see the list of available commands.")
else:
print(f'An error occurred: {error}')
# FUNCTION ------------------------------------------------------ SPLIT
@bot.event
async def on_error(event, *args):
print(f'An error occurred during event {event}: {args[0]}')
await bot.change_presence(status=discord.Status.dnd)
# CORE ------------------------------------------------------ END
# ACTIVITY ------------------------------------------------------ START
async def update_playing_time_activity():
global activity_start_time
global playing_time_activity
current_time = time.time()
uptime_seconds = int(current_time - activity_start_time)
minutes, seconds = divmod(uptime_seconds, 60)
hours, minutes = divmod(minutes, 60)
playing_time_activity = f"/help or >>help for commands list | online for {hours}h {minutes}m" #seconds {seconds}s
await bot.change_presence(activity=discord.Game(name=playing_time_activity))
# FUNCTION ------------------------------------------------------ SPLIT
@tasks.loop(seconds=UPDATE_INTERVAL)
async def update_playing_time():
await update_playing_time_activity()
# ACTIVITY ------------------------------------------------------ END
# PYDVPL ------------------------------------------------------ START
async def compress_file(file_path):
try:
with open(file_path, "rb") as f:
file_data = f.read()
compressed_data = compress_dvpl(file_data)
compressed_file_path = file_path + ".dvpl" # Example: Add .dvpl extension
with open(compressed_file_path, "wb") as f:
f.write(compressed_data)
return compressed_file_path
except Exception as e:
print(f"Compression failed: {e}")
return None
# FUNCTION ------------------------------------------------------ SPLIT
async def decompress_file(file_path):
try:
with open(file_path, "rb") as f:
file_data = f.read()
decompressed_data = decompress_dvpl(file_data)
decompressed_file_path = os.path.splitext(file_path)[0] # Example: Remove .dvpl extension
with open(decompressed_file_path, "wb") as f:
f.write(decompressed_data)
return decompressed_file_path
except Exception as e:
print(f"Decompression failed: {e}")
return None
# PYDVPL ------------------------------------------------------ END
# UTILITY USER_CMD ------------------------------------------------------ START
bot.remove_command("help")
@bot.hybrid_command(help="Displays the list of available commands.")
async def help(ctx):
# Create an embed to display the list of available commands
embed = discord.Embed(title="Command List", description="Here's a list of available commands:", color=discord.Color.blue())
# Add fields for different categories of commands with their descriptions
embed.add_field(name="PyDVPL Prefix:", value="`/` - Discord's slash command prefix.\n`>>` - PyDVPL default prefix.")
embed.add_field(name="Dvpl Commands:", value="`compress` - Compresses files.\n`decompress` - Decompresses files.", inline=False)
embed.add_field(name="User Utility Commands:", value="`ping` - Checks the bot's latency.\n`invite` - Get the bot's invite link.\n`uptime` - Displays the bot's uptime.\n`clock` - Shows the current date and time.\n`chat` - Chat with AI LLM models like 'phind', 'chatgpt' & 'blackboxai'.\n`coinflip - Plays a coinflip game with the bot`", inline=False)
embed.add_field(name="Premium User Commands:", value="`chat` - Chat with AI LLM models like 'phind', 'chatgpt' & 'blackboxai'.\n`image` - Generate images with 'craiyon' AI.", inline=False)
embed.add_field(name="Moderator Commands:", value="`kick` - Kick a member from the server.\n`ban` - Ban a member from the server.\n`timeout` - Timeout a member for a specified duration.\n`purge` - Bulk deletes set amount of messages in guilds.", inline=False)
embed.add_field(name="Admin Utility Commands:", value="`stats` - Displays bot statistics.\n`list` - Lists server members.\n`say` - Make the bot say something.\n`announce` - Announces a message to a channel.\n`activity` - Sets bot activity status.\n`online` - Sets bot status to online.\n`dnd` - Sets bot status to Do Not Disturb.\n`offline` - Sets bot status to offline.\n`clean` - Cleans up bot's messages.\n`update` - Update a Python package using pip.\n`ip` - Shows the IP address of the current server.", inline=False)
embed.add_field(name="Feedback Commands:", value="`feedback` - Sends feedback to bot developers. (usage: >>feedback issues/requests <message>)", inline=False)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
# Send the embed as an ephemeral message, visible only to the command invoker
await ctx.reply(embed=embed, ephemeral=True)
#await ctx.reply(f"The command `help` was executed by - {ctx.author.mention}")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Compresses attached files.")
async def compress(ctx , attachments: discord.Attachment):
attachments = ctx.message.attachments
if not attachments:
await ctx.reply("No file attached.")
return
for attachment in attachments:
file_path = os.path.join(COMPRESS_FOLDER, attachment.filename)
msg = await ctx.reply("Compressing...")
# Check if the file is already in .dvpl format, if so, skip it
if file_path.endswith(".dvpl"):
embed = discord.Embed(
title="Compression Skipped",
description=f"File {attachment.filename} is already in .dvpl format.",
color=discord.Color.gold()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
continue
await attachment.save(file_path)
compressed_file_path = await compress_file(file_path)
if compressed_file_path:
embed = discord.Embed(
title="Compression Successful",
description=f"File {attachment.filename} has been successfully compressed.",
color=discord.Color.green()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
await ctx.reply(file=discord.File(compressed_file_path))
os.remove(file_path) # Delete the original file
os.remove(compressed_file_path) # Delete the compressed file
else:
embed = discord.Embed(
title="Compression Failed",
description="Failed to compress the file.",
color=discord.Color.red()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
@bot.hybrid_command(help="Decompresses attached files.")
async def decompress(ctx, attachments: discord.Attachment):
attachments = ctx.message.attachments
if not attachments:
await ctx.reply("No file attached.")
return
for attachment in attachments:
file_path = os.path.join(DECOMPRESS_FOLDER, attachment.filename)
msg = await ctx.reply("Decompressing...")
# Check if the file is not in .dvpl format, if so, skip it
if not file_path.endswith(".dvpl"):
embed = discord.Embed(
title="Decompression Skipped",
description=f"File {attachment.filename} is not in .dvpl format.",
color=discord.Color.gold()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
continue
await attachment.save(file_path)
decompressed_file_path = await decompress_file(file_path)
if decompressed_file_path:
embed = discord.Embed(
title="Decompression Successful",
description=f"File {attachment.filename} has been successfully decompressed.",
color=discord.Color.green()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
await ctx.reply(file=discord.File(decompressed_file_path))
os.remove(file_path) # Delete the original file
os.remove(decompressed_file_path) # Delete the decompressed file
else:
embed = discord.Embed(
title="Decompression Failed",
description="Failed to decompress the file.",
color=discord.Color.red()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
#await ctx.reply(f"The command `decompress` was executed by - {ctx.author.mention}")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Pings to check bot's latency")
async def ping(ctx):
start_time = time.monotonic()
msg = await ctx.reply("Pinging...")
# Measure WebSocket latency
ws_latency = bot.latency * 1000
# Calculate elapsed time since sending the message
end_time = time.monotonic()
elapsed_time = (end_time - start_time) * 1000
# Create an embedded message
embed = discord.Embed(
title="Pong! 🏓",
description=f"WebSocket latency: `{ws_latency:.2f}ms`\nResponse time: `{elapsed_time:.2f}ms`",
color=discord.Color.blurple()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
#await ctx.reply(f"The command `ping` was executed by - {ctx.author.mention}")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Pings domain names and ip addresses.")
async def pinger(ctx, target):
try:
# Attempt to resolve the target to an IP address
ip_address = socket.gethostbyname(target)
msg = await ctx.reply("Pinging...")
# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set a timeout for the connection attempt
s.settimeout(5)
# Record the start time
start_time = time.time()
# Connect to the target IP address on port 80 (HTTP)
s.connect((ip_address, 80))
# Calculate the round trip time (RTT)
rtt = (time.time() - start_time) * 1000 # Convert to milliseconds
# Close the socket
s.close()
# Create an embedded message
embed = discord.Embed(
title="Ping Result",
color=discord.Color.green()
)
embed.add_field(name="Target", value=target, inline=False)
embed.add_field(name="IP Address", value=ip_address, inline=False) # Add IP address field
embed.add_field(name="Status", value="Successful 🟢", inline=False)
embed.add_field(name="Latency", value=f"{rtt:.2f}ms", inline=False)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
# Send the embedded message
await msg.edit(content=None, embed=embed)
except socket.gaierror:
# Create an embedded message for resolution error
embed = discord.Embed(
title="Ping Result",
description=f"Error: Unable to resolve {target} to an IP address. 🔴",
color=discord.Color.red()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
except socket.error:
# Create an embedded message for unreachable error
embed = discord.Embed(
title="Ping Result",
description=f"Error: {target} is unreachable. 🔴",
color=discord.Color.red()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Generates an invite link for the bot and sends it to your DM.")
async def invite(ctx):
permissions = discord.Permissions(
read_messages=True,
send_messages=True,
embed_links=True,
attach_files=True,
read_message_history=True,
mention_everyone=True,
add_reactions=True,
manage_guild=True,
ban_members=True,
kick_members=True,
moderate_members=True,
use_application_commands=True,
manage_roles=True,
administrator=True
)
client_id = bot.user.id
invite_link = discord.utils.oauth_url(client_id, permissions=permissions, scopes=['bot'])
# Create an embedded message for the invite link
invite_embed = discord.Embed(
title="Invite Link",
description=f"Click the button below to invite PyDVPL to your server",
color=discord.Color.blue()
)
invite_embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
invite_embed.timestamp = ctx.message.created_at
# Create a button for the invite link
invite_button = discord.ui.Button(
style=discord.ButtonStyle.link,
label="Invite PyDVPL",
url=invite_link
)
# Create a View to hold the button
view = discord.ui.View()
view.add_item(invite_button)
# Send the embed with the button to the user's DM
try:
await ctx.author.send(
embed=invite_embed,
view=view
)
invite_confirmation_embed = discord.Embed(
title="Invite Link Sent",
description=f"The invite link has been sent to your DM, {ctx.author.mention}.",
color=discord.Color.green()
)
invite_confirmation_embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
invite_confirmation_embed.timestamp = ctx.message.created_at
await ctx.reply(embed=invite_confirmation_embed)
except discord.Forbidden:
invite_error_embed = discord.Embed(
title="Invite Link Sending Failed",
description=f"Failed to send the invite link to your DM, {ctx.author.mention}. Please make sure your DMs are open.",
color=discord.Color.red()
)
invite_error_embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
invite_error_embed.timestamp = ctx.message.created_at
await ctx.reply(embed=invite_error_embed)
#await ctx.reply(f"The command `invite` was executed by - {ctx.author.mention}")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Send feedback or report issues", usage="<requests/issues> <message>")
async def feedback(ctx, category: str, *, message: str):
if category.lower() not in ["requests", "issues"]:
await ctx.reply("Invalid category. Please choose 'requests' or 'issues'.")
return
feedback_data = {
"author_id": ctx.author.id,
"author_name": ctx.author.name,
"timestamp": str(ctx.message.created_at),
"message": message
}
folder_path = REQUESTS_FOLDER if category.lower() == "requests" else ISSUES_FOLDER
file_path = os.path.join(folder_path, f"{category.lower()}.json")
try:
with open(file_path, "r") as f:
data = json.load(f)
except FileNotFoundError:
data = []
data.append(feedback_data)
with open(file_path, "w") as f:
json.dump(data, f, indent=4)
await ctx.reply(f"Thank you for your {category.lower()}. It has been recorded.")
# Create an Embed object for the feedback data
embed = discord.Embed(
title=f"New {category.lower()} feedback",
description=f"**Author Name:** {feedback_data['author_name']}\n**Timestamp:** {feedback_data['timestamp']}\n**Message:** {feedback_data['message']}",
color=discord.Color.yellow()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
# Send the embed to the specified server's feedback channel
feedback_channel_id = bot.get_channel(int(FEEDBACK_CHANNEL_ID))
if feedback_channel_id:
if feedback_channel_id:
await feedback_channel_id.send(embed=embed)
else:
print("Feedback channel not found in the server.")
else:
print("Server not found.")
#await ctx.reply(f"The command `feedback` was executed by - {ctx.author.mention}")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Show how long the bot has been playing the current game.")
async def uptime(ctx):
global activity_start_time
if activity_start_time == 0:
bot_mention = ctx.me.mention
await ctx.reply(f"{bot_mention}'s activity hasn't been set yet.")
return
current_time = time.time()
uptime_seconds = int(current_time - activity_start_time)
minutes, seconds = divmod(uptime_seconds, 60)
hours, minutes = divmod(minutes, 60)
bot_mention = ctx.me.mention
# Create an embedded message for the uptime
embed = discord.Embed(
title="Bot Uptime",
description=f"{bot_mention} has been playing for:",
color=discord.Color.blue()
)
embed.add_field(name="Hours", value=hours)
embed.add_field(name="Minutes", value=minutes)
embed.add_field(name="Seconds", value=seconds)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await ctx.reply(embed=embed)
#await ctx.reply(f"The command `uptime` was executed by - {ctx.author.mention}")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Shows the bot's version number.")
async def version(ctx):
# Create an embed message to display the bot version
embed = discord.Embed(
title="Bot Version",
description="The current version of the bot and its dependencies.",
color=discord.Color.gold() # Changed color to gold for a more visually appealing look
)
bot_ver = {
f"PyDVPL Bot Version": f"{BOT_VERSION}",
}
bot_ver_formatted = "\n".join([f"```{name}: {value}```" for name, value in bot_ver.items()])
# Bot version
embed.add_field(name="**CORE**", value=bot_ver_formatted, inline=False) # Changed to bold and capitalized "CORE"
# Add dependencies as child fields
dependencies = {
f"PyDVPL Lib Version": f"{pydvpl.version.__version__}",
f"LZ4 PY Lib Version": f"{__LZ4_VERSION__}",
f"Discord PY Version": f"{discord.__version__}",
f"PyTGPT Lib Version": f"{pytgpt.__version__}",
f"Craiyon Lib Version": f"{craiyon.__version__}"
}
# Format and layout dependencies
dependencies_formatted = "\n".join([f"```{name}: {value}```" for name, value in dependencies.items()])
embed.add_field(name="**DEPENDENCIES**", value=dependencies_formatted, inline=False) # Changed to bold and capitalized "DEPENDENCIES"
embed.set_footer(
text=f"Requested by {ctx.author.display_name}",
icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty
)
embed.timestamp = ctx.message.created_at
# Send the embed message
await ctx.reply(embed=embed)
#await ctx.reply(f"The command `version` was executed by - {ctx.author.mention}")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Shows the current date and time.")
async def clock(ctx):
# Get the current date and time
now = datetime.now()
# Format the date and time
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
# Create an embed message to display the current date and time
embed = discord.Embed(
title="Current Date and Time",
description=f"```\n{formatted_now}\n```",
color=discord.Color.blue()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
# Send the embed message
await ctx.reply(embed=embed)
#await ctx.reply(f"The command `clock` was executed by - {ctx.author.mention}")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Chat with AI LLM models like 'phind', 'chatgpt', & 'blackboxai'.")
async def chat(ctx, model, *, message):
if str(ctx.author.id) not in AUTHORIZED_AI_ACCESS_ID:
await ctx.reply("You are not authorized to use this command. Only `@rifsxd`'s server boosters & special permitted users can enjoy free `ChatGPT` access.")
return
msg = await ctx.reply("Responding...")
if model.lower() == "phind":
bot = phind.PHIND()
elif model.lower() == "chatgpt":
bot = opengpt.OPENGPT()
elif model.lower() == "blackboxai":
bot = blackboxai.BLACKBOXAI()
else:
await ctx.reply("Invalid model. Please choose 'phind' or 'chatgpt' or 'blackboxai'.")
return
response = bot.chat(message)
if len(response) > 2000:
half_length = len(response) // 2
first_half = response[:half_length]
second_half = response[half_length:]
embed = discord.Embed(
title="Response",
color=discord.Color.green()
)
embed.add_field(name="First Half", value=f"{first_half}-")
embed.add_field(name="Second Half", value=f"-{second_half}")
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
else:
embed = discord.Embed(
title="Response",
description=response,
color=discord.Color.green()
)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
#await ctx.reply(f"The command `chat` was executed by - {ctx.author.mention}")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Generate images with 'craiyon' ai.")
async def image(ctx, *, prompt: str):
# Check if the user is authorized to use the command
if str(ctx.author.id) not in AUTHORIZED_AI_ACCESS_ID:
await ctx.reply("You are not authorized to use this command.")
return
# Inform the user that the generation process has started
msg = await ctx.reply(f"Generating images for prompt: `{prompt}`. Please be patient...")
try:
generator = Craiyon()
generated_images = await generator.async_generate(prompt)
# Encode images to base64
b64_list = await craiyon_utils.async_encode_base64(generated_images.images)
# Prepare images for sending
images = []
for index, image_b64 in enumerate(b64_list):
img_bytes = BytesIO(base64.b64decode(image_b64))
image_file = discord.File(img_bytes, filename=f"result{index}.webp")
images.append(image_file)
embed = discord.Embed(
title="Generated Images",
description=f"Sucessfully generated images for prompt: `{prompt}`.",
color=discord.Color.green()
)
# Add a field for each generated image
for index, image in enumerate(images):
embed.add_field(name=f"Image {index+1}", value=f"[Click here to view]({image.url})")
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content=None, embed=embed)
except Exception as e:
# Print the specific exception message for debugging
print(f"An error occurred while generating images: {e}")
await ctx.reply("An error occurred while generating images. Please try again later.")
#await ctx.reply(f"The command `image` was executed by - {ctx.author.mention}")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.command(help="Plays a coinflip game with the bot")
async def coinflip(ctx):
emojis = ["🐈", "😸"] # Add more emojis if needed
# Create an embedded message
embed = discord.Embed(title="Coin Flip", description="React with 🐈 for tails or 😸 for heads!", color=discord.Colour.yellow())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
flip_msg = await ctx.send(embed=embed)
# Add reactions for heads and tails
for emoji in emojis:
await flip_msg.add_reaction(emoji)
# Wait for reactions
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in emojis
try:
reaction, _ = await bot.wait_for('reaction_add', timeout=30.0, check=check)
user_choice = reaction.emoji
except asyncio.TimeoutError:
await ctx.send("You didn't react in time. Aborting...")
return
await asyncio.sleep(1)
for i in range(3, 0, -1):
embed.description = f"Flipping the coin in {i}..."
await flip_msg.edit(embed=embed)
await asyncio.sleep(1)
# Randomly choose the result
result = random.choice(emojis)
embed.description = f"The result is **{result}**!"
if result == user_choice:
winner = ctx.author.display_name
else:
winner = "The bot"
embed.set_footer(text=f"Winner: {winner}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
await flip_msg.edit(embed=embed)
# UTILITY USER_CMD ------------------------------------------------------ END
# UTILITY ADMIN_CMD ------------------------------------------------------ START
@bot.hybrid_command(help="Cleans files in specific directories")
async def clean(ctx, clean_mode):
# Check if the author is authorized to use this command
if str(ctx.author.id) != AUTHORIZED_USER_ID:
await ctx.reply("You are not authorized to use this command.")
return
embed = discord.Embed(title="File Cleaning Command", color=0x00ff00) # Green color for the embed
if clean_mode.lower() == 'compress':
await clean_directory(ctx, COMPRESS_FOLDER)
embed.add_field(name="Action", value="Compress Folder Cleaning", inline=False)
elif clean_mode.lower() == 'decompress':
await clean_directory(ctx, DECOMPRESS_FOLDER)
embed.add_field(name="Action", value="Decompress Folder Cleaning", inline=False)
elif clean_mode.lower() == 'issues':
await clean_directory(ctx, ISSUES_FOLDER)
embed.add_field(name="Action", value="Issues Folder Cleaning", inline=False)
elif clean_mode.lower() == 'requests':
await clean_directory(ctx, REQUESTS_FOLDER)
embed.add_field(name="Action", value="Requests Folder Cleaning", inline=False)
elif clean_mode.lower() == 'feedback':
await clean_directory(ctx, REQUESTS_FOLDER)
await clean_directory(ctx, ISSUES_FOLDER)
embed.add_field(name="Action", value="Feedback Folders Cleaning", inline=False)
elif clean_mode.lower() == 'dvpl':
await clean_directory(ctx, DECOMPRESS_FOLDER)
await clean_directory(ctx, COMPRESS_FOLDER)
embed.add_field(name="Action", value="DVPL Folders Cleaning", inline=False)
else:
embed.add_field(name="Error", value="Invalid clean mode. Please choose 'compress', 'decompress', 'issues', or 'requests'.", inline=False)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await ctx.reply(embed=embed)
return
embed.add_field(name="Status", value="Cleaning completed successfully.", inline=False)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await ctx.reply(embed=embed)
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Set bot's presence to online")
async def online(ctx):
# Check if the author is authorized to use this command
if str(ctx.author.id) != AUTHORIZED_USER_ID:
await ctx.reply("You are not authorized to use this command.")
return
# Your playing_time_activity variable should be defined somewhere
playing_time_activity = "Your default activity here"
# Change the bot's presence
await bot.change_presence(activity=discord.Game(name=playing_time_activity))
# Prepare an embed for response
embed = discord.Embed(title="Bot Presence Update", color=0x00ff00) # Green color for the embed
embed.add_field(name="Status", value="Bot's presence set to online with activity: " + playing_time_activity, inline=False)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
# Send the embed as a reply
await ctx.reply(embed=embed)
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Set bot's presence to Do Not Disturb")
async def dnd(ctx):
# Check if the author is authorized to use this command
if str(ctx.author.id) != AUTHORIZED_USER_ID:
await ctx.reply("You are not authorized to use this command.")
return
# Change the bot's presence to Do Not Disturb
await bot.change_presence(status=discord.Status.dnd)
# Prepare an embed for response
embed = discord.Embed(title="Bot Presence Update", color=0xff0000) # Red color for the embed
embed.add_field(name="Status", value="Bot's presence set to Do Not Disturb", inline=False)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
# Send the embed as a reply
await ctx.reply(embed=embed)
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Set bot's presence to offline")
async def offline(ctx):
# Check if the author is authorized to use this command
if str(ctx.author.id) != AUTHORIZED_USER_ID:
await ctx.reply("You are not authorized to use this command.")
return
# Change the bot's presence to offline
await bot.change_presence(status=discord.Status.offline)
# Prepare an embed for response
embed = discord.Embed(title="Bot Presence Update", color=0x000000) # Black color for the embed
embed.add_field(name="Status", value="Bot's presence set to offline", inline=False)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
# Send the embed as a reply
await ctx.reply(embed=embed)
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Set bot's activity")
async def activity(ctx, activity_type, *, activity_text=None):
# Check if the author is authorized to use this command
if str(ctx.author.id) != AUTHORIZED_USER_ID:
await ctx.reply("You are not authorized to use this command.")
return
# Check if a valid activity type is provided
valid_activity_types = ['listening', 'watching', 'playing']
if activity_type.lower() not in valid_activity_types:
embed = discord.Embed(title="Invalid Activity Type", color=0xff0000) # Red color for the embed
embed.add_field(name="Error", value='Invalid activity type. Please choose either "listening", "playing" or "watching".', inline=False)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await ctx.reply(embed=embed)
return
# Check if activity text is provided
if not activity_text:
embed = discord.Embed(title="Activity Text Missing", color=0xff0000) # Red color for the embed
embed.add_field(name="Error", value='Please provide an activity text.', inline=False)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await ctx.reply(embed=embed)
return
# Determine the activity based on the provided type
if activity_type.lower() == 'listening':
activity = discord.Activity(type=discord.ActivityType.listening, name=activity_text)
elif activity_type.lower() == 'watching':
activity = discord.Activity(type=discord.ActivityType.watching, name=activity_text)
elif activity_type.lower() == 'playing':
activity = discord.Activity(type=discord.ActivityType.playing, name=activity_text)
# Change the bot's presence
await bot.change_presence(activity=activity)
# Prepare an embed for response
embed = discord.Embed(title="Bot Activity Update", color=0x00ff00) # Green color for the embed
embed.add_field(name="Status", value=f'Activity set to {activity_type.capitalize()} {activity_text}', inline=False)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
# Send the embed as a reply
await ctx.reply(embed=embed)
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Send messages to specific channels or users")
async def say(ctx, destination_type, *, id, message):
# Check if the author is authorized to use this command
if str(ctx.author.id) != AUTHORIZED_USER_ID:
await ctx.reply("You are not authorized to use this command.")
return
# Define function to send reply and return
async def send_reply(reply):
embed = discord.Embed(title="Message Sent", color=0x00ff00) # Green color for the embed
embed.add_field(name="Status", value=reply, inline=False)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await ctx.reply(embed=embed)
# Check destination type and send message accordingly
if destination_type.lower() == 'channel':
try:
channel_id = int(id)
channel = bot.get_channel(channel_id)
if channel:
await channel.send(message)
await send_reply(f"Message `{message}` sent to channel `{channel.name}`.")
else:
await send_reply("Channel not found.")
except ValueError:
await send_reply("Channel ID must be a valid integer.")
elif destination_type.lower() == 'server':
try:
server_id = int(id)
server = bot.get_guild(server_id)
if server:
announcement_channel = discord.utils.get(server.channels, name="important-announcements")
if announcement_channel:
await announcement_channel.send(message)
await send_reply(f"Message `{message}` sent to server `{server.name}` in `important-announcements` channel.")
else:
announcements_channel = discord.utils.get(server.channels, name="announcements")
if announcements_channel:
await announcements_channel.send(message)
await send_reply(f"Message `{message}` sent to server `{server.name}` in `announcements` channel.")
else:
public_updates_channel = server.public_updates_channel
if public_updates_channel:
await public_updates_channel.send(message)
await send_reply(f"Message `{message}` sent to server `{server.name}` in `public updates` channel.")
else:
default_channel = server.system_channel or server.text_channels[0] # Default to the first text channel
if default_channel:
await default_channel.send(message)
await send_reply(f"Message `{message}` sent to server `{server.name}` in the default channel.")
else:
await send_reply("No announcement channels found in the server. Also, no default `public updates` neither `default` channels found.")
else:
await send_reply("Server not found.")
except ValueError:
await send_reply("Server ID must be a valid integer.")
elif destination_type.lower() == 'user':
try:
user_id = int(id)
user = bot.get_user(user_id)
if user:
try:
await user.send(message)
await send_reply(f"Message `{message}` sent to user '{user.display_name}'.")
except discord.Forbidden:
await send_reply(f"Couldn't send message to `{user.display_name}`. Their DMs are closed.")
else:
await send_reply("User not found.")
except ValueError:
await send_reply("User ID must be a valid integer.")
else:
await send_reply("Invalid destination type. Use either 'channel', 'server', or 'user'.")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Send announcements to all servers")
async def announce(ctx, *, message):
# Check if the author is authorized to use this command
if str(ctx.author.id) != AUTHORIZED_USER_ID:
await ctx.reply("You are not authorized to use this command.")
return
# Prepare an embed for the announcement message
embed = discord.Embed(title="Announcement!", description=message, color=discord.Color.yellow())
# Iterate through all servers the bot is in and send the announcement
for server in bot.guilds:
# First, check for an "important-announcements" channel
announcement_channel = discord.utils.get(server.channels, name="important-announcements")
if announcement_channel:
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await announcement_channel.send(embed=embed)
await ctx.reply(f"Message `{message}` sent to server `{server.name}` in `important-announcements` channel.")
else:
# If no "important-announcements" channel, check for "announcements" channel
announcements_channel = discord.utils.get(server.channels, name="announcements")
if announcements_channel:
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await announcements_channel.send(embed=embed)
await ctx.reply(f"Message `{message}` sent to server `{server.name}` in `announcements` channel.")
else:
# If neither channel exists, send to the default channel or public updates channel
public_updates_channel = server.public_updates_channel
if public_updates_channel:
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await public_updates_channel.send(embed=embed)
await ctx.reply(f"Message `{message}` sent to server `{server.name}` in `public updates` channel.")
else:
default_channel = server.system_channel or server.text_channels[0]
if default_channel:
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await default_channel.send(embed=embed)
await ctx.reply(f"Message `{message}` sent to server `{server.name}` in `defaults` channel.")
else:
await ctx.reply(f"No suitable announcement channel found in server `{server.name}`.")
# Delete the original command message
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Show statistics about bot's health and connection.")
async def stats(ctx):
# Check if the author is authorized to use this command
if str(ctx.author.id) != AUTHORIZED_USER_ID:
await ctx.reply("You are not authorized to use this command.")
return
# Send a message to indicate that statistics are being fetched
msg = await ctx.reply("Fetching statistics...")
# Get bot's statistics
guild_count = len(bot.guilds)
member_count = len(set(bot.get_all_members()))
uptime_seconds = int(time.time() - activity_start_time)
uptime_minutes, uptime_seconds = divmod(uptime_seconds, 60)
uptime_hours, uptime_minutes = divmod(uptime_minutes, 60)
uptime_days, uptime_hours = divmod(uptime_hours, 24)
latency = round(bot.latency * 1000) # latency in milliseconds
# Get CPU usage
cpu_usage = psutil.cpu_percent(interval=None)
# Get memory usage
memory_usage = psutil.virtual_memory().percent
# Prepare an embed for the statistics
embed = discord.Embed(title="Bot Statistics & Vitals", color=discord.Color.blue())
embed.add_field(name="Servers", value=f"`{guild_count}`", inline=True)
embed.add_field(name="Members", value=f"`{member_count}`", inline=True)
embed.add_field(name="Uptime", value=f"`{uptime_days} days`, `{uptime_hours} hours`, `{uptime_minutes} minutes`, `{uptime_seconds} seconds`", inline=False)
embed.add_field(name="Latency", value=f"`{latency}ms`", inline=True)
embed.add_field(name="CPU Usage", value=f"`{cpu_usage}%`", inline=True)
embed.add_field(name="Memory Usage", value=f"`{memory_usage}%`", inline=True)
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
# Edit the initial message with the statistics embed
await msg.edit(content=None, embed=embed)
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="List issues, requests, or servers")
async def list(ctx, list_type):
# Check if the author is authorized to use this command
if str(ctx.author.id) != AUTHORIZED_USER_ID:
await ctx.reply("You are not authorized to use this command.")
return
async def list_feedback(ctx, folder_path, title):
files = os.listdir(folder_path)
feedback_embed = discord.Embed(title=title, color=discord.Color.yellow())
for file in files:
file_path = os.path.join(folder_path, file)
with open(file_path, "r") as f:
feedback_data = json.load(f)
for feedback in feedback_data:
author_name = feedback['author_name']
author_id = feedback['author_id']
timestamp = feedback['timestamp']
message = feedback['message']
feedback_embed.add_field(
name=f"Author: {author_name} (ID: {author_id})",
value=f"Timestamp: {timestamp}\nMessage: {message}",
inline=False
)
if feedback_embed.fields:
feedback_embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
feedback_embed.timestamp = ctx.message.created_at
await ctx.reply(embed=feedback_embed)
else:
await ctx.reply("No feedback found.")
if list_type.lower() == 'servers':
# Create a list of embed fields for each server
fields = []
for server in bot.guilds:
joined_date = server.me.joined_at.strftime("%Y-%m-%d")
field_name = server.name
field_value = f"Joined ({joined_date})\nID: {server.id}"
fields.append((field_name, field_value))
# Create an embed with the servers list
embed = discord.Embed(title="Servers List", color=discord.Color.green())
# Add embed fields for each server
for name, value in fields:
embed.add_field(name=name, value=value, inline=False)
# Set footer with requester's display name and timestamp
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.avatar.url if ctx.author.avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
# Send the embed as a reply
await ctx.reply(embed=embed)
elif list_type.lower() == 'issues':
await list_feedback(ctx, ISSUES_FOLDER, "List of issues:")
elif list_type.lower() == 'requests':
await list_feedback(ctx, REQUESTS_FOLDER, "List of requests:")
else:
await ctx.reply("Invalid list type. Please choose 'servers', 'issues', or 'requests'.")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Update a Python package using pip.")
async def update(ctx, pkg_name):
# Check if the author is authorized to use this command
if str(ctx.author.id) != AUTHORIZED_USER_ID:
await ctx.reply("You are not authorized to use this command.")
return
try:
# Send a message to indicate that the package update process has started
msg = await ctx.reply(f"Updating package `{pkg_name}`...")
# Run pip install command to upgrade the package
process = subprocess.Popen(['pip', 'install', pkg_name, '--upgrade'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
# Check if any errors occurred during the update process
if error:
# If there was an error, update the message with the error information
embed = discord.Embed(title="Package Update Failed", description=f"Failed to update package `{pkg_name}`.\nError: {error.decode('utf-8')}", color=discord.Color.red())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(embed=embed)
else:
# If the update was successful, update the message to indicate success
embed = discord.Embed(title="Package Update Successful", description=f"Package `{pkg_name}` successfully updated.", color=discord.Color.green())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(embed=embed)
except Exception as e:
# If an exception occurs during the update process, update the message with the exception information
embed = discord.Embed(title="An Error Occurred", description=f"An error occurred while updating package `{pkg_name}`: {e}", color=discord.Color.red())
await msg.edit(embed=embed)
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Shows the IP address of the current server.")
async def ip(ctx):
# Check if the author is authorized to use this command
if str(ctx.author.id) != AUTHORIZED_USER_ID:
await ctx.reply("You are not authorized to use this command.")
return
try:
# Send a message to indicate that the IP address is being fetched
msg = await ctx.reply("Fetching IP address...")
# Fetch the IP address using the ipify API
response = requests.get('https://api.ipify.org')
if response.status_code == 200:
# If the request was successful, send the IP address as a reply
embed = discord.Embed(title="IP Address", description=f"Your IP address is: `{response.text}`", color=discord.Color.green())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(embed=embed)
else:
# If the request failed, update the message to indicate failure
embed = discord.Embed(title="Failed to Fetch IP Address", description="Failed to fetch IP address.", color=discord.Color.red())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(embed=embed)
except Exception as e:
# If an exception occurs during the process, update the message with the exception information
embed = discord.Embed(title="An Error Occurred", description=f"An error occurred while fetching IP address: {e}", color=discord.Color.red())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(embed=embed)
# UTILITY ADMIN_CMD ------------------------------------------------------ END
# UTILITY MODERATOR_CMD ------------------------------------------------------ START
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Kick a member from the server.")
async def kick(ctx, member: discord.Member, *, reason=None):
# Check if the command invoker has the necessary permissions to kick members
if ctx.author.guild_permissions.kick_members or ctx.author == ctx.guild.owner:
# Check if the invoker has a higher role than the member to be kicked
if ctx.author.top_role.position > member.top_role.position:
try:
# Attempt to send a direct message to the kicked member
dm_message = f"You have been kicked from the server `{ctx.guild.name}`"
if reason:
dm_message += f" for the following reason: `{reason}`"
await member.send(dm_message)
except discord.Forbidden:
# If unable to send a DM to the kicked member, inform the invoker
await ctx.reply(f"Failed to send a direct message to {member}.")
# Kick the member from the server
await member.kick(reason=reason)
# Send an embedded message confirming the member has been kicked
embed = discord.Embed(title="Member Kicked", description=f"{member} has been kicked from the server.", color=discord.Color.green())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await ctx.reply(embed=embed)
else:
# If the invoker does not have a higher role than the member, inform them
await ctx.reply("You do not have permission to kick this member.")
else:
# If the invoker does not have the necessary permissions, inform them
await ctx.reply("You do not have permission to use this command.")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Ban a member from the server.")
async def ban(ctx, member: discord.Member, *, reason=None):
# Check if the command invoker has the necessary permissions to ban members
if ctx.author.guild_permissions.ban_members or ctx.author == ctx.guild.owner:
# Check if the invoker has a higher role than the member to be banned
if ctx.author.top_role.position > member.top_role.position:
try:
# Attempt to send a direct message to the banned member
dm_message = f"You have been banned from the server `{ctx.guild.name}`"
if reason:
dm_message += f" for the following reason: `{reason}`"
await member.send(dm_message)
except discord.Forbidden:
# If unable to send a DM to the banned member, inform the invoker
await ctx.reply(f"Failed to send a direct message to {member}.")
# Ban the member from the server
await member.ban(reason=reason)
# Send an embedded message confirming the member has been banned
embed = discord.Embed(title="Member Banned", description=f"{member} has been banned from the server.", color=discord.Color.green())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await ctx.reply(embed=embed)
else:
# If the invoker does not have a higher role than the member, inform them
await ctx.reply("You do not have permission to ban this member.")
else:
# If the invoker does not have the necessary permissions, inform them
await ctx.reply("You do not have permission to use this command.")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Timeout a member for a specified duration.")
async def timeout(ctx, member: discord.Member, duration: int, *, reason=None):
# Check if the author is authorized to use this command
if ctx.author.guild_permissions.manage_roles or ctx.author == ctx.guild.owner:
# Check if the invoker has a higher role than the member to be timed out
if ctx.author.top_role.position > member.top_role.position:
try:
# Timeout duration in seconds
timeout_duration = duration
# Timeout the member by removing all roles
await member.edit(roles=[], reason=reason)
# Inform about the timeout
embed = discord.Embed(title="Member Timed Out", description=f"`{member}` has been timed out for `{duration} seconds`.\nReason: `{reason}`", color=discord.Color.green())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await ctx.reply(embed=embed)
# Send a DM to the timed-out member
dm_message = f"You have been timed out in the server `{ctx.guild.name}` for `{duration} seconds`"
if reason:
dm_message += f" for the following reason: `{reason}`"
await member.send(dm_message)
except Exception as e:
# If an error occurs during the timeout process, inform the invoker
embed = discord.Embed(title="Error", description=f"An error occurred while timing out `{member}`: {e}", color=discord.Color.red())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await ctx.reply(embed=embed)
return
# Wait for the duration of the timeout
await asyncio.sleep(timeout_duration)
# Restore the member's roles after the timeout
try:
await member.edit(roles=member.roles, reason=reason)
except Exception as e:
# If an error occurs while restoring roles, inform the invoker
print(f"An error occurred while restoring roles to `{member}`: {e}")
return
# Inform the member that their timeout has expired
dm_message = f"Your timeout in the server `{ctx.guild.name}` for `{duration} seconds`"
if reason:
dm_message += f" for the following reason: `{reason}` has expired."
try:
await member.send(dm_message)
except discord.Forbidden:
# If unable to send a DM, inform the invoker
embed = discord.Embed(title="Error", description=f"Failed to send DM to `{member}` to notify timeout expiration.", color=discord.Color.red())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await ctx.reply(embed=embed)
else:
# If the invoker does not have a higher role than the member, inform them
await ctx.reply("You do not have permission to timeout this member.")
else:
# If the invoker does not have the necessary permissions, inform them
await ctx.reply("You do not have permission to use this command.")
# FUNCTION ------------------------------------------------------ SPLIT
@bot.hybrid_command(help="Bulk deletes set amount of messages in guilds.")
async def purge(ctx, amount: int):
# Check if the command is invoked in a direct message channel
if isinstance(ctx.channel, discord.DMChannel):
# Inform that purging is not supported in direct messages
embed = discord.Embed(title="Purge Error", description="Purging is not supported in direct messages.", color=discord.Color.red())
await ctx.reply(embed=embed)
return
# Check if the invoker has the necessary permissions to manage roles or is the guild owner
if ctx.author.guild_permissions.manage_roles or ctx.author == ctx.guild.owner:
try:
# Send a message to indicate that purging is in progress
msg = await ctx.reply(f"Purging `{amount}` messages...")
try:
# Use the before parameter to only purge messages before the command is invoked
await ctx.channel.purge(limit=amount, before=ctx.message)
# Update the message to indicate successful purging
embed = discord.Embed(title="Purge Successful", description=f"`{amount}` messages purged successfully.", color=discord.Color.green())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content="", embed=embed) # Edit the message to remove content and set the new embed
except discord.Forbidden:
# If the bot doesn't have permission to delete messages, inform the invoker
embed = discord.Embed(title="Purge Error", description="I don't have permission to delete messages in this channel.", color=discord.Color.red())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content="", embed=embed) # Edit the message to remove content and set the new embed
except discord.HTTPException:
# If an error occurs during purging, inform the invoker
embed = discord.Embed(title="Purge Error", description="Failed to purge messages due to an error.", color=discord.Color.red())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content="", embed=embed) # Edit the message to remove content and set the new embed
except Exception as e:
# If an error occurs during the process, inform the invoker
embed = discord.Embed(title="Error", description=f"An error occurred: {e}", color=discord.Color.red())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content="", embed=embed)
return
else:
# If the invoker doesn't have the necessary permissions, inform them
embed = discord.Embed(title="Permission Denied", description="You do not have permission to use this command.", color=discord.Color.red())
embed.set_footer(text=f"Requested by {ctx.author.display_name}", icon_url=ctx.author.display_avatar.url if ctx.author.display_avatar else discord.Embed.Empty)
embed.timestamp = ctx.message.created_at
await msg.edit(content="", embed=embed)
# UTILITY MODERATOR_CMD ------------------------------------------------------ END
# RUN PYDVPL ------------------------------------------------------ START
bot.run(TOKEN)
# RUN PYDVPL ------------------------------------------------------ END |