-
Notifications
You must be signed in to change notification settings - Fork 34
/
mongoBot.pyw
1077 lines (949 loc) · 32.9 KB
/
mongoBot.pyw
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
"""This is the discord bot for the mongoDB server list
"""
# pyright: basic, reportGeneralTypeIssues=false, reportOptionalSubscript=false, reportOptionalMemberAccess=false
import asyncio
import datetime
import json
import random
import sys
import time
import traceback
import interactions
import pymongo
import requests
from bson.errors import InvalidId
from bson.objectid import ObjectId
from interactions.ext.files import (
command_edit,
command_send,
component_edit,
component_send,
)
import utils
autoRestart = False
allowJoin = False
DEBUG = False
try:
from privVars import *
except ImportError:
MONGO_URL = "mongodb+srv://..."
TOKEN = "..."
if MONGO_URL == "mongodb+srv://...":
print("Please add your mongo url to privVars.py")
input()
sys.exit()
if TOKEN == "...":
print("Please add your bot token to privVars.py")
input()
sys.exit()
# Setup
# ---------------------------------------------
bot = interactions.Client(
token=TOKEN, intents=interactions.Intents.GUILD_MESSAGE_CONTENT
)
client = pymongo.MongoClient(MONGO_URL, server_api=pymongo.server_api.ServerApi("1")) # type: ignore
db = client["mc"]
col = db["servers"]
utils = utils.utils(col, debug=DEBUG, allowJoin=allowJoin)
logger = utils.logger
databaseLib = utils.database
finderLib = utils.finder
playerLib = utils.players
serverLib = utils.server
def print(*args, **kwargs):
logger.print(" ".join(map(str, args)), **kwargs)
def timeNow():
# return local time
return datetime.datetime.now(
datetime.timezone(
datetime.timedelta(hours=0) # no clue why this is needed but it works now?
)
).strftime("%Y-%m-%d %H:%M:%S")
# Commands
# ---------------------------------------------
@bot.command(
name="find",
description="Find a server",
options=[
interactions.Option(
name="_id",
type=interactions.OptionType.STRING,
description="The ID of the server",
required=False,
),
interactions.Option(
name="host",
description="The host of the server",
type=interactions.OptionType.STRING,
required=False,
),
interactions.Option(
name="port",
description="The port of the server",
type=interactions.OptionType.INTEGER,
required=False,
value=25565,
),
interactions.Option(
name="player",
description="The player to search for (uuid or player name) **WIP**",
type=interactions.OptionType.STRING,
required=False,
),
interactions.Option(
name="version",
description="The version of the server",
type=interactions.OptionType.STRING,
required=False,
),
interactions.Option(
name="motd",
description="The motd of the server",
type=interactions.OptionType.STRING,
required=False,
),
interactions.Option(
name="maxplayers",
description="The max players of the server",
type=interactions.OptionType.INTEGER,
required=False,
min_value=0,
),
interactions.Option(
name="cracked",
description="If the server blocks the EULA",
type=interactions.OptionType.BOOLEAN,
required=False,
value=False,
),
interactions.Option(
name="hasfavicon",
description="If the server has a favicon",
type=interactions.OptionType.BOOLEAN,
required=False,
value=False,
),
],
)
async def find(
ctx: interactions.CommandContext,
_id: str = "",
host: str = "",
port: int = 25565,
player: str = "",
version: str = "",
motd: str = "",
maxplayers: int = -1,
cracked: bool = False,
hasfavicon: bool = False,
):
"""Find a server
Args:
_id (str, optional): The ID of the server. Defaults to None.
host (str, optional): The host of the server. Defaults to None.
Player (str, optional): The player to search for. Defaults to None.
version (str, optional): The version of the server. Defaults to None.
motd (str, optional): The motd of the server. Defaults to None.
port (int, optional): The port of the server. Defaults to 25565.
maxplayers (int, optional): The max players of the server. Defaults to -1.
cracked (bool, optional): If the server blocks the EULA. Defaults to False.
hasfavicon (bool, optional): If the server has a favicon. Defaults to False.
"""
print(
"find",
"id:" + _id,
"host:" + host,
"port:" + str(port),
'player:"' + player + '"',
'version:"' + version + '"',
'motd:"' + motd + '"',
"maxplayers:" + str(maxplayers),
"cracked:" + str(cracked),
"hasfavicon:" + str(hasfavicon),
)
# send as embed
await ctx.defer()
serverList = []
# pipline that matches version name case insensitive, motd case insensitive, max players, cracked and has favicon
pipeline = [{"$match": {"$and": []}}]
pipeline[0]["$match"]["$and"].append({"lastOnlinePlayersMax": {"$gt": 0}})
pipeline[0]["$match"]["$and"].append({"lastOnlinePlayers": {"$lte": 100000}})
info = {}
flag = False
numServers = 0
# if parameters are given, add them to the search
# special matching
if host:
validServ = True
# check if the given host is a valid server
serverList = [None]
if host.replace(".", "").isdigit():
serverList = [col.find_one({"host": host})]
if serverList[0] is None:
serverList = [col.find_one({"hostname": host})]
else:
serverList = [col.find_one({"hostname": host})]
if serverList[0] is None:
serverList = [col.find_one({"host": host})]
if serverList[0] is None:
logger.print("Server not in database")
# try to get the server info from check
info = finderLib.check(host, port)
if info is None:
logger.print("Server not online")
validServ = False
else:
serverList = col.find_one({"host": info["host"]})
if validServ:
flag = True
numServers = 1
pipeline[0]["$match"]["$and"].append(
{"_id": ObjectId(serverList[0]["_id"])}
)
else:
# search the database for serbers with similar hostnames
# search with regex applyed to 'hostname' and 'host' of .*host.*
pipeline[0]["$match"]["$and"].append(
{
"$or": [
{"hostname": {"$regex": ".*" + host + ".*"}},
{"host": {"$regex": ".*" + host + ".*"}},
]
}
)
if _id:
# check that _id is vaild
if len(_id) != 12 and len(_id) != 24:
logger.print("Invalid ID: " + str(len(_id)))
await command_send(
ctx,
embeds=[
interactions.Embed(
title="Error",
description="Invalid ID Length",
timestamp=timeNow(),
color=finderLib.RED,
)
],
ephemeral=True,
)
return
else:
logger.print("Valid ID: " + _id)
try:
res = col.find({"_id": ObjectId(_id)})
except InvalidId:
logger.print("Invalid ID for ObjectID: " + _id)
await command_send(
ctx,
embeds=[
interactions.Embed(
title="Error",
description="Invalid ID",
timestamp=timeNow(),
color=finderLib.RED,
)
],
ephemeral=True,
)
return
logger.print(res)
flag = True
if res is None:
logger.print("Server not found")
await command_send(
ctx,
embeds=[
interactions.Embed(
title="Error",
description="Server not found",
timestamp=timeNow(),
color=finderLib.RED,
)
],
ephemeral=True,
)
return
else:
logger.print("Server found")
serverList = res
numServers = 1
if player:
flag = True
name = ""
uuid = ""
isID = len(player) > 16
if isID:
url = (
"https://sessionserver.mojang.com/session/minecraft/profile/"
+ player.replace("-", "")
)
else:
url = "https://api.mojang.com/users/profiles/minecraft/" + player
resp = requests.get(url)
jresp = resp.json()
if "error" in resp.text or resp.text == "": # if the player is not found
logger.print("Player not found in minecraft api")
await command_send(
ctx,
embeds=[
interactions.Embed(
title="Error",
description=f"{player} not found in minecraft api",
timestamp=timeNow(),
color=finderLib.RED,
)
],
ephemeral=True,
)
return
else:
uuid = jresp["id"]
name = jresp["name"]
pipeline[0]["$match"]["$and"].append(
{"lastOnlinePlayersList.uuid": uuid.replace("-", "")}
)
logger.print(pipeline)
serverList = col.aggregate(pipeline)
numServers = col.count_documents(pipeline[0]["$match"])
logger.print("Finding player", player)
face = utils.players.playerHead(name)
if numServers == 0:
logger.print("Player not found in database")
embeds = [
interactions.Embed(
title="Error",
description=f"{player} not found in database",
color=finderLib.RED,
timestamp=timeNow(),
)
]
embeds[0].set_thumbnail(url="attachment://playerhead.png")
await command_send(ctx, embeds=embeds, files=[face], ephemeral=True)
return
embed = interactions.Embed(
title=f"{name} found",
description=f"Found {name} in {numServers} servers",
color=finderLib.GREEN,
timestamp=timeNow(),
)
embed.set_thumbnail(url="attachment://playerhead.png")
await command_send(ctx, embeds=[embed], files=[face])
if version:
pipeline[0]["$match"]["$and"].append(
{"lastOnlineVersion": {"$regex": ".*" + version + ".*", "$options": "i"}}
)
if motd:
pipeline[0]["$match"]["$and"].append(
{"lastOnlineDescription": {"$regex": ".*" + motd + ".*", "$options": "i"}}
)
if maxplayers > 0:
pipeline[0]["$match"]["$and"].append({"lastOnlinePlayersMax": maxplayers})
if cracked:
pipeline[0]["$match"]["$and"].append({"cracked": cracked})
if hasfavicon:
pipeline[0]["$match"]["$and"].append(
{
"$expr": {
"$and": [
{"$ne": ["$favicon", None]},
{"$gt": [{"$strLenCP": "$favicon"}, 10]},
]
}
}
)
if (
pipeline
== [
{
"$match": {
"$and": [
{"lastOnlinePlayersMax": {"$gt": 0}},
{"lastOnlinePlayers": {"$lte": 100000}},
]
}
}
]
and not flag
):
await command_send(
ctx,
embeds=[
interactions.Embed(
title="Error",
description="No search parameters given",
color=finderLib.YELLOW,
timestamp=timeNow(),
)
],
ephemeral=True,
)
else:
try:
# get server info
if not flag:
serverList = []
logger.print("Flag is down, getting server info from database")
numServers = col.count_documents(pipeline[0]["$match"])
logger.print(f"Number of servers: {numServers}")
serverList = col.aggregate(pipeline)
else:
pipeline = (
{}
if pipeline
== [
{
"$match": {
"$and": [
{"lastOnlinePlayersMax": {"$gt": 0}},
{"lastOnlinePlayers": {"$lte": 100000}},
]
}
}
]
else pipeline
)
logger.print("Flag is up, setting server info")
logger.print(f"Servers:{numServers}|Search:{pipeline}|Flag:{flag}")
if numServers == 0:
logger.print("No servers found in database")
await command_send(
ctx,
embeds=[
interactions.Embed(
title="Error",
description="No servers found",
color=finderLib.YELLOW,
timestamp=timeNow(),
)
],
ephemeral=True,
)
return
await command_send(
ctx,
embeds=[
interactions.Embed(
title="Searching...",
description="Getting info about a server out of "
+ str(numServers)
+ " servers...",
timestamp=timeNow(),
color=finderLib.BLUE,
)
],
)
# setup the embed
embed = finderLib.genEmbed(
index=0, numServ=numServers, search=pipeline, allowJoin=allowJoin
)
_file = embed[1]
comps = embed[2]
embed = embed[0]
logger.print("Embed generated", embed, comps, _file)
# send the embed sometimes with the favicon
if _file:
await command_edit(ctx, embeds=[embed], files=[_file], components=comps)
else:
await command_edit(ctx, embeds=[embed], components=comps)
except Exception:
logger.print(traceback.format_exc())
await command_send(
ctx,
embeds=[
interactions.Embed(
title="Error",
description="An error occured while searching. Please try again later and check the logs for more details.",
color=finderLib.RED,
timestamp=timeNow(),
)
],
ephemeral=True,
)
print(
f"----\n{traceback.format_exc()}\n====\n{type(info)}\n====\n{info}\n----"
)
@bot.component("show_players")
async def show_players(ctx: interactions.ComponentContext):
try:
msg = ctx.message
await ctx.defer(ephemeral=True)
host = msg.embeds[0].title[2:] # exclude the online symbol
players = utils.players.playerList(host)
random.shuffle(players) # for servers with more than 25 logged players
embed = interactions.Embed(
title="Players",
description="{} players logged".format(len(players)),
timestamp=timeNow(),
color=finderLib.GREEN,
)
for player in players:
try:
# check if online is in the dict
if "online" not in player:
player["online"] = False
embed.add_field(
name=("🟢 " if player["online"] else "🔴 ") + player["name"],
value="`{}`".format(player["uuid"]),
inline=True,
)
except Exception:
print(traceback.format_exc())
print(player)
break
logger.print(embed, "\n---\n", players)
await component_send(ctx, embeds=[embed], ephemeral=True)
except Exception:
print(traceback.format_exc(), ctx.message)
await component_send(
ctx,
embeds=[
interactions.Embed(
title="Error",
description="An error occured while searching. Please try again later and check the logs for more details.",
color=finderLib.RED,
timestamp=timeNow(),
)
],
ephemeral=True,
)
@bot.component("rand_select")
async def rand_select(ctx: interactions.ComponentContext):
try:
logger.print("Fetching message")
msg = ctx.message.embeds[0]
logger.print(str(msg))
if "---n/a---" in msg.footer.text:
return
await ctx.defer(edit_origin=True)
buttons = [
interactions.Button(
label="Show Players",
custom_id="show_players",
style=interactions.ButtonStyle.PRIMARY,
disabled=True,
),
interactions.Button(
label="Next Server",
custom_id="rand_select",
style=interactions.ButtonStyle.PRIMARY,
disabled=True,
),
interactions.Button(
label="Join",
custom_id="join",
style=interactions.ButtonStyle.PRIMARY,
disabled=True,
),
]
row = interactions.ActionRow(
components=buttons # pyright: ignore [reportGeneralTypeIssues]
)
await component_edit(
ctx,
embeds=[
interactions.Embed(
title="Loading...",
description="Loading the next server...",
color=finderLib.BLUE,
timestamp=timeNow(),
footer=interactions.EmbedFooter(
text="Key:---n/a---/|\\0"
), # key and index
)
],
components=[row],
)
text = msg.footer.text
text = text.split("\n")[2]
text = text.split("Key:")[1]
text = text.split("/|\\")
key = text[0]
index = int(text[1])
logger.print("Index: " + str(index))
logger.print("Key: " + key)
key = json.loads(key) if key != "---n/a---" else {}
if key == {}: # if the key is empty, return
return
logger.print("ReGenerating list")
numServers = col.count_documents(key[0]["$match"])
logger.print("List generated: " + str(numServers) + " servers")
index = (index + 1) if (index + 1 < numServers) else 0
info = finderLib.get_doc_at_index(col, key, index)
if info == None:
logger.print(
"Error: No server found at index "
+ str(index)
+ " out of "
+ str(numServers)
+ " servers"
)
return
await component_edit(
ctx,
embeds=[
interactions.Embed(
title="Loading...",
description="Loading {}...".format(info["host"]),
color=finderLib.BLUE,
timestamp=timeNow(),
footer=interactions.EmbedFooter(
text="Key:---n/a---/|\\{}".format(index)
),
),
],
components=[row],
)
embed = finderLib.genEmbed(
search=key, index=index, numServ=numServers, allowJoin=allowJoin
)
_file = embed[1]
button = embed[2]
embed = embed[0]
logger.print("Embed generated", embed, button, _file)
if _file:
await component_edit(ctx, embeds=[embed], files=[_file], components=button)
else:
await component_edit(ctx, embeds=[embed], components=button)
except Exception:
await component_send(
ctx,
embeds=[
interactions.Embed(
title="Error",
description="An error occured while searching. Please try again later and check the logs for more details.",
color=finderLib.RED,
timestamp=timeNow(),
)
],
ephemeral=True,
)
async def emailModal(ctx: interactions.Modal, host: str):
textInp = interactions.TextInput(
label="Email",
custom_id="email",
placeholder="[email protected]",
min_length=1,
max_length=100,
style=interactions.TextStyleType.SHORT,
)
modal = interactions.Modal(
title="Email for " + host,
custom_id="email_modal",
description="Please enter the email you want to join with.",
components=[textInp],
)
await ctx.popup(modal)
@bot.component("join")
async def joinServer(ctx: interactions.ComponentContext):
"""Join a servver"""
# get the original message
msg = ctx.message.embeds[0]
host = msg.title[2:] # exclude the online symbol
# clear nmp cache
serverLib.clearNMPCache()
# spawn a text box to ask for an email
await emailModal(ctx, host)
@bot.modal("email_modal")
async def emailModalResponse(
ctx: interactions.CommandContext, email: interactions.TextInput
):
modal = ctx.message.embeds[0].title
host = modal[2:]
await ctx.defer(ephemeral=True)
serverLib.start(
ip=host,
port=25565,
username=email,
)
while serverLib.getState() == "NOT_CONNECTED":
await asyncio.sleep(0.1)
if "AUTHENTICATING:" in serverLib.getState():
code = serverLib.getState().split("AUTHENTICATING:")[1]
logger.print("Code: " + code)
await command_send(
ctx,
embeds=[
interactions.Embed(
label="Authentication required",
description="Please enter the code `{}` at https://www.microsoft.com/link in order to authenticate.\nYou will have three minutes before the code expires.".format(
code
),
color=finderLib.BLUE,
)
],
ephemeral=True,
)
tStart = time.time()
while "AUTHENTICATING:" in serverLib.getState() and time.time() - tStart < 180:
await asyncio.sleep(1)
if "AUTHENTICATING:" in serverLib.getState():
await command_send(
ctx,
embeds=[
interactions.Embed(
label="Authentication required",
description="The code has expired. Please try again.",
color=finderLib.RED,
)
],
ephemeral=True,
)
return
else:
await command_send(
ctx,
embeds=[
interactions.Embed(
label="Join server",
description="Connecting to {}...".format(host),
color=finderLib.ORANGE,
)
],
ephemeral=True,
) if DEBUG else None
logger.print("state: " + serverLib.getState())
while serverLib.getState() == "CONNECTING":
await asyncio.sleep(0.1)
if serverLib.getState() == "CONNECTED":
print("Connected")
serverInfo = serverLib.getInfo()
players = serverInfo["names"]
position = serverInfo["position"]
heldItem = serverInfo["heldItem"]
# update player list
dbVal = col.find_one({"host": host})
players2 = []
for player in players:
url = "https://api.mojang.com/users/profiles/minecraft/{}".format(player)
uuid = (
requests.get(url).json()["id"]
if "id" in requests.get(url).json()
else ""
)
if uuid == "":
continue
player = {
"name": player,
"uuid": uuid,
}
players2.append(player)
if player not in dbVal["lastOnlinePlayersList"]:
dbVal["lastOnlinePlayersList"].append(player)
players = players2
plyOnline = len(players)
col.update_one(
{"host": host},
{"$set": {"players": dbVal["lastOnlinePlayersList"]}},
upsert=True,
)
players2 = []
for player in dbVal["lastOnlinePlayersList"]:
player["online"] = player in players
players2.append(player)
players = players2
embed = interactions.Embed(
title="Join Server",
description="Done! You spawned at {} with {} players holding a(n) {}.".format(
position, plyOnline, heldItem
),
color=finderLib.GREEN,
timestamp=timeNow(),
).set_footer("Powered by MineFlayer")
for player in players:
embed.add_field(
name=(
player["name"] + (" (Online)" if player["online"] else " (Offline)")
),
value="`" + player["uuid"] + "`",
inline=True,
)
await command_send(ctx, embeds=[embed], ephemeral=True)
serverLib.clearNMPCache()
return
if serverLib.getState().startswith("DISCONNECTED"):
reason = serverLib.getState().split("DISCONNECTED:")[1]
if reason == "WHITELISTED":
# update the server to be whitelisted
col.update_one(
{"host": host},
{"$set": {"whitelisted": True}},
upsert=True,
)
await command_send(
ctx,
embeds=[
interactions.Embed(
title="Join Server",
description="Error: This server is whitelisted or you are banned. Please contact the server owner to be allowed back in.",
color=finderLib.YELLOW,
timestamp=timeNow(),
)
],
ephemeral=True,
)
else:
print("Error")
serverLib.clearNMPCache()
return
await command_send( # failed to join
ctx,
embeds=[
interactions.Embed(
title="Join Server",
description="Error: {}".format(serverLib.getState()),
color=finderLib.RED,
timestamp=timeNow(),
)
],
ephemeral=True,
)
serverLib.clearNMPCache()
@bot.command(
name="stats",
description="Get stats about the database",
)
async def stats(ctx: interactions.CommandContext):
await ctx.defer()
try:
"""Get stats about the database"""
await ctx.send(
embeds=[
interactions.Embed(
title="Stats",
description="Getting stats...",
timestamp=timeNow(),
color=finderLib.BLUE,
)
]
)
logger.print("Getting stats...")
serverCount = col.count_documents({})
# add commas to server count
serverCount = "{:,}".format(serverCount)
text = f"Total servers: `{serverCount}`\nPlayer Count: `...`\nPlayers logged: `...`\nMost common version:\n`...`"
await ctx.edit(
embeds=[
interactions.Embed(
title="Stats",
description=text,
timestamp=timeNow(),
color=finderLib.BLUE,
)
]
)
logger.print("Getting versions...")
versions = await databaseLib.get_sorted_versions(col)
topTen = [x["version"] for x in versions[:10]]
text = "Total servers: `{}`\nRough Player Count: `...`\nMost common version:```css\n{}\n```".format(
serverCount, ("\n".join(topTen[:5]))
)
await ctx.edit(
embeds=[
interactions.Embed(
title="Stats",
description=text,
timestamp=timeNow(),
color=finderLib.BLUE,
)
]
)
logger.print("Getting player count...")
players = await databaseLib.get_total_players_online(col)
# add commas to player count
players = "{:,}".format(players)
logger.print("Getting players logged...")
pLogged = await databaseLib.getPlayersLogged(col)
pLogged = "{:,}".format(pLogged)
text = "Total servers: `{}`\nRough Player Count: `{}`\nPlayers logged: `{}`\nMost common version:```css\n{}\n```".format(
serverCount, players, pLogged, ("\n".join(topTen[:5]))
)
print(
f"Total servers: {serverCount}\nRough Player Count: {pLogged}/{players}\nMost common versions: {topTen}"
)
await ctx.edit(
embeds=[
interactions.Embed(
title="Stats",
description=text,
timestamp=timeNow(),
color=finderLib.BLUE,
)
]
)
except Exception:
print(f"====\nError: {traceback.format_exc()}\n====")
logger.print(traceback.format_exc())
await ctx.send(
embeds=[
interactions.Embed(
title="Error",
description="Error getting stats, check the console and log for more info.",
timestamp=timeNow(), # local time
)
],
ephemeral=True,
)