This repository was archived by the owner on Sep 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbot.py
2633 lines (2065 loc) · 86.6 KB
/
bot.py
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
import re
import os
import json
import time
import copy
import urllib
import typing
import random
import string
import base64
import shutil
import asyncio
import logging
import inspect
import pathlib
import platform
import datetime
import textwrap
from io import BytesIO, StringIO
from collections import namedtuple
import psutil
import discord
import asyncpg
import jishaku
import aiohttp
import mystbin
import cpuinfo
import humanize
import aioredis
import tabulate
import speedtest
import aiospotify
import async_timeout
from discord import app_commands
from discord.ext import commands
from humanize import naturalsize as get_size
from openrobot import discord_activities as discord_activity
import config
from cogs.utils import (
MenuPages,
CodePaginator,
executor,
Bot as BaseBot,
ChristmasEvent,
Command,
ApplyPrefix,
case_insensitive_prefix,
no_prefix_for_owner,
checks,
rdanny,
naturalnumber,
)
from cogs.utils.spotify import spotify as spotify_img
description = """
I am OpenRobot. I provide help and utilities for OpenRobot stuff such as our API (Hosted at <https://api.openrobot.xyz>).
GitHub: <https://github.com/OpenRobot>
Website: <https://openrobot.xyz/>
"""
LineCount = namedtuple("LineCount", ["files", "lines", "classes", "functions", "coroutines", "comments"],
defaults=(0,) * 6)
class Bot(BaseBot):
CDN_BUCKET = "openrobot-cdn"
CDN_BUCKET_URL = "cdn.openrobot.xyz"
ICDN_URL = "icdn.openrobot.xyz"
BOT_FLAGS = {}
EXTS = [
# 'jishaku',
"cogs.api",
"cogs.error",
# "cogs.music",
"cogs.help",
"cogs.jsk",
"cogs.fun",
"cogs.speech",
"cogs.ai",
"cogs.repi",
"cogs.ipc",
"cogs.events",
"cogs.maps"
]
@staticmethod
def line_count(directory: str = "./") -> LineCount:
p = pathlib.Path(directory)
cm = cr = fn = cl = ls = fc = 0
for f in p.rglob("*.py"):
if str(f).startswith("venv"):
continue
fc += 1
with f.open() as of:
for l in of.readlines():
l = l.strip()
if l.startswith("class"):
cl += 1
if l.startswith("def"):
fn += 1
if l.startswith("async def"):
cr += 1
if "#" in l:
cm += 1
ls += 1
return LineCount(
files=fc, lines=ls, classes=cl, functions=fn, coroutines=cr, comments=cm
)
@staticmethod
def set_flags(flags):
Bot.BOT_FLAGS = flags
async def _perform_flags(self):
self.pool = None
self.redis = None
self.spotify_redis = None
self.rethinkdb = None
flags = Bot.BOT_FLAGS
if flags.get('db'):
self.pool = await asyncpg.create_pool(config.DATABASE)
# bot.spotify_pool = await asyncpg.create_pool(config.SPOTIFY_DATABASE)
self.redis = aioredis.Redis(**config.REDIS_DATABASE_CRIDENTIALS)
self.spotify_redis = aioredis.Redis(
**config.REDIS_DATABASE_CRIDENTIALS, db=1
)
# bot.tb_pool = await asyncpg.create_pool(config.TRACEBACK_DATABASE)
# bot.cache = aioredis.Redis(**config.REDIS_DATABASE_CRIDENTIALS, db=2)
try:
bot.rethinkdb.connect(**config.RETHINKDB_CRIDENTIALS).repl()
except:
pass
if flags.get("cogs") is False:
Bot.EXTS.clear()
elif flags.get("cogs") is not None and "cogs" not in flags:
l = list(
filter(lambda i: i[0].startswith("without-") and i[1], flags.items())
)
for i in l:
try:
Bot.EXTS.remove(i)
except KeyError:
try:
Bot.EXTS.remove("cogs." + i)
except:
pass
if flags.get("colour") and self.color is None:
try:
self.color = await commands.ColourConverter().convert(
None, flags.get("colour")
) # ctx argument isn't used, so we'll just pass in None.
except:
pass
if flags.get("color") and self.color is None:
try:
bot.color = await commands.ColourConverter().convert(
None, flags.get("color")
) # ctx argument isn't used, so we'll just pass in None.
except:
pass
self.color = self.color or discord.Colour(0x38B6FF)
async def _load_music(self):
await self.wait_until_ready()
# self.owner = bot.get_user(699839134709317642)
try:
await bot.cogs["Music"].initiate_node()
except KeyError: # Cog isn't loaded
pass
async def _do_restart_message(self):
await self.wait_until_ready()
utcnow = discord.utils.utcnow()
with open("restart.json", "r") as f:
js: dict = json.load(f)
with open("restart.json", "w") as f:
json.dump({}, f, indent=4)
if ("channel_id" in js) and ("message_id" in js) and ("restarted_at" in js):
restarted_at = datetime.datetime.fromtimestamp(
js["restarted_at"], tz=datetime.timezone.utc
)
restart_duration = utcnow - restarted_at
chan = bot.get_channel(js["channel_id"])
if chan:
msg = chan.get_partial_message(js["message_id"])
try:
await msg.edit(
embed=discord.Embed(
description=f"Back in `{restart_duration.seconds} seconds`.",
color=bot.color,
)
)
except:
pass
async def _send_online_msg(self):
await self.wait_until_ready()
utcnow = discord.utils.utcnow()
webhook = discord.Webhook.from_url(config.UPTIME_WEBHOOK, session=bot.session)
await webhook.send(
embed=discord.Embed(
description=f'<:status_online:596576749790429200> OpenRobot is going online and up!\n\nAt: {discord.utils.format_dt(utcnow, "F")}',
color=bot.color,
timestamp=utcnow,
)
)
def _start_tasks(self):
self.create_task(self._load_music())
self.create_task(self._do_restart_message())
self.create_task(self._send_online_msg())
try:
self.create_task(self.cogs["Music"].renew())
except KeyError: # Cog isnt loaded
pass
try:
self.create_task(self.cogs["Error"].initiate_tb_pool())
except KeyError: # Cog isnt loaded
pass
# self.christmas = ChristmasEvent(bot)
# self.christmas.start()
#self.ipc.start()
def shutdown(self):
utcnow = discord.utils.utcnow()
webhook = discord.SyncWebhook.from_url(config.UPTIME_WEBHOOK)
webhook.send(
embed=discord.Embed(
description=f'<:status_offline:596576752013279242> OpenRobot is going offline and shutting down!\n\nAt: {discord.utils.format_dt(utcnow, "F")}',
color=bot.color,
timestamp=utcnow,
)
)
async def setup_hook(self):
await super().setup_hook()
await self._perform_flags()
for ext in Bot.EXTS:
try:
await bot.load_extension(ext)
except Exception as e:
raise e
pass
self._start_tasks()
@executor()
def screenshot(self, url: str, *, delay: int = None, ad_block: bool = False, use_proxy: bool = False):
if delay is not None:
if delay <= 0:
delay = None
with self.driver(ad_block=ad_block or False, use_proxy=use_proxy or False) as driver:
driver.get(url)
driver.set_window_size(1920, 1080)
if delay:
time.sleep(delay)
buffer = BytesIO(driver.get_screenshot_as_png())
return buffer
# async def publishCdn(
# self, fp: BytesIO, filename: str = "uwu.png", from_aiohttp=True, file_type=None
# ):
# fileType = file_type or f"{filename.split('.')[-1:]}"
#
# if from_aiohttp:
# original = fp.close
# fp.close = lambda: None
#
# data = aiohttp.FormData()
# data.add_field("file", fp)
#
# url = f"https://cdn.ayomerdeka.com/upload?Authorization={config.CDN_TOKEN}&File-Type={fileType}"
#
# try:
# async with self.session.post(url, data=data) as resps:
# if resps.status == 200:
# d = await resps.json()
# return d["url"]
# else:
# return None
# finally:
# if from_aiohttp:
# fp.close = original
@executor() # CDN may be blocking, so lets just use an executor just in case
def publish_s3_cdn(
self, fp: BytesIO | bytes, filename: str, *, raw: bool = False
) -> str | dict | typing.Any:
hash = "".join(
random.choices(
string.ascii_letters + string.digits, k=random.randint(10, 32)
)
)
file_type = filename.split(".")
file_type = file_type[-1]
with open(f"./cdn-images/{hash}.{file_type}", "wb") as f:
f.write(getattr(fp, "getvalue", lambda: fp)())
response = self.cdn.upload_file(
f"./cdn-images/{hash}.{file_type}", self.CDN_BUCKET, filename
)
try:
os.remove(f"./cdn-images/{hash}.{file_type}")
except:
pass
if not raw:
return "https://" + self.CDN_BUCKET_URL + "/" + filename
else:
return response
async def publish_icdn(
self, fp: BytesIO | bytes, content_type: str = None, *, raw: bool = False
) -> str | dict | typing.Any:
data = aiohttp.FormData()
data.add_field("file", BytesIO(fp), content_type=content_type)
async with self.session.post(f"https://{self.ICDN_URL}/upload", headers={'Authorization': config.ICDN_TOKEN},
data=data) as resp:
js = await resp.json()
if raw:
return js
else:
return f"https://{self.ICDN_URL}/{js['file_id']}"
async def publish_cdn(self, *args, imoog: bool = False, try_both=False, **kwargs):
if try_both:
if imoog:
try:
return await self.publish_icdn(*args, **kwargs)
except:
return await self.publish_s3_cdn(*args, **kwargs)
else:
try:
return await self.publish_s3_cdn(*args, **kwargs)
except:
return await self.publish_icdn(*args, **kwargs)
if imoog:
return await self.publish_icdn(*args, **kwargs)
else:
return await self.publish_s3_cdn(*args, **kwargs)
async def close(self):
if self.redis:
await self.redis.close()
if self.pool:
await self.pool.close()
if self.spotify_pool:
await self.spotify_pool.close()
if self.spotify_redis:
await self.spotify_redis.close()
if self.tb_pool:
await self.tb_pool.close()
# await self.spotify.close() Broken: AttributeError: 'HTTPClient' object has no attribute 'close'
await self.session.close()
return await super().close()
bot = Bot(
command_prefix=ApplyPrefix(
config.PREFIXES,
case_insensitive_prefix(),
commands.when_mentioned,
# no_prefix_for_owner(),
),
owner_ids=config.OWNER_IDS,
help_command=commands.MinimalHelpCommand(
no_category="Miscellaneous"
), # For old help command purposes only. This is used whenever the help cog fails.
intents=discord.Intents.all(),
activity=discord.Activity(type=discord.ActivityType.listening, name="or.help"),
case_insensitive=True,
description=description,
slash_commands=True,
)
api = None
def override(func): # Plainly just for `source` command.
func.__is_overridden__ = True
return func
# logger = logging.getLogger('discord')
# logger.setLevel(logging.DEBUG)
# handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
# handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
# logger.addHandler(handler)
@bot.event
@override
async def on_ready():
print(f"{bot.user} is ready!")
global api
api = bot.api
@bot.event
@override
async def on_message(message: discord.Message):
if re.match(rf"^<@!?{bot.user.id}>$", message.content):
return await message.reply(
"My prefix is `or.`! You can also mention me!", mention_author=False
)
await bot.process_commands(message)
@bot.event
@override
async def on_message_edit(before: discord.Message, after: discord.Message):
if after.content == before.content:
return # Do not process commands if the msg content is the same, e.g. URL Embed, etc.
await bot.process_commands(after)
@bot.command(hidden=True)
@commands.is_owner()
async def sync(ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: typing.Optional[typing.Literal["~", "*"]] = None):
if not guilds:
if spec == "~":
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
else:
fmt = await ctx.bot.tree.sync()
return await ctx.send(
f"Synced {len(fmt)} commands {'globally' if spec is None else 'to the current guild.'}"
)
fmt = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
fmt += 1
return await ctx.send(f"Synced the tree to {fmt}/{len(guilds)} guilds.")
@bot.command(name="beta", cls=Command, example="beta spotify", hidden=True)
async def execute_beta(ctx: commands.Context, *, command):
if not command:
return await ctx.send("A command name is a required argument to provide!")
msg = copy.copy(ctx.message)
msg.content = f"{ctx.prefix}" + command
ctx = await bot.get_context(msg)
ctx.beta = True
return await bot.invoke(ctx)
@bot.command(aliases=["latency"], cls=Command, example="ping")
@commands.cooldown(1, 10, commands.BucketType.channel)
@commands.max_concurrency(1, commands.BucketType.channel)
async def ping(ctx: commands.Context):
"""
Gets the latency of the bot, databases and more.
"""
if ctx.interaction is not None:
await ctx.interaction.response.defer()
def do_ping_string(ping: int) -> str:
s = "```diff\n"
if ping <= 250:
s += f"+ {ping} ms"
else:
s += f"- {ping} ms"
s += "```"
return s
TASK_STATS = [False] * 9
TASK_LATENCY = [None] * 7
async def ping_task(m, embed, index, index_latency, func):
try:
_latency = await discord.utils.maybe_coroutine(func)
except Exception as e:
raise e
_latency = None
if not _latency:
embed._fields[index]['value'] = "Unavailable"
else:
_latency *= 1000
latency = round(_latency, 2)
TASK_LATENCY[index_latency] = _latency
embed._fields[index]['value'] = do_ping_string(latency)
await m.edit(embed=embed, allowed_mentions=discord.AllowedMentions.none())
TASK_STATS[index] = True
async def calculate_average_discord_latency(m, embed, index):
while not all([False if x is None else True for x in TASK_LATENCY[:3]]):
await asyncio.sleep(.3)
_latency = sum(TASK_LATENCY[:3]) / 3
latency = round(_latency, 2)
embed._fields[index]['value'] = do_ping_string(latency)
await m.edit(embed=embed, allowed_mentions=discord.AllowedMentions.none())
TASK_STATS[index] = True
async def remove_content_on_finish(m):
while not all(TASK_STATS):
await asyncio.sleep(.3)
await m.edit(content=None, allowed_mentions=discord.AllowedMentions.none())
async def calculate_average_database_latency(m, embed, index):
while not all([False if x is None else True for x in TASK_LATENCY[3:5]]):
await asyncio.sleep(.3)
_latency = sum(TASK_LATENCY[3:5]) / 3
latency = round(_latency, 2)
embed._fields[index]['value'] = do_ping_string(latency)
await m.edit(embed=embed, allowed_mentions=discord.AllowedMentions.none())
TASK_STATS[index] = True
embed = (
discord.Embed(color=bot.color, timestamp=ctx.message.created_at)
.set_author(name="Latency/Ping Info:", icon_url=ctx.author.display_avatar.url)
.set_footer(icon_url=ctx.author.display_avatar.url, text=f"Requested by: {ctx.author}")
.add_field(name=f'{bot.ping.EMOJIS["bot"]} Bot Latency:', value="```fix\nCalculating...```") # 0
.add_field(name=f'{bot.ping.EMOJIS["typing"]} Typing Latency:', value="```fix\nCalculating...```") # 1
.add_field(name=f'{bot.ping.EMOJIS["discord"]} Discord Web Latency:', value="```fix\nCalculating...```") # 2
.add_field(name=f'Average Discord Latency:', value="```fix\nCalculating...```", inline=False) # 3
.add_field(name=f'{bot.ping.EMOJIS["postgresql"]} PostgreSQL Latency:', value="```fix\nCalculating...```") # 4
.add_field(name=f'{bot.ping.EMOJIS["redis"]} Redis Latency:', value="```fix\nCalculating...```") # 5
.add_field(name=f'Average Database Latency:', value="```fix\nCalculating...```") # 6
.add_field(name=f'{bot.ping.EMOJIS["openrobot-api"]} OpenRobot API Latency:', value="```fix\nCalculating...```") # 7
.add_field(name=f'{bot.ping.EMOJIS["r2"]} CDN/Storage (Cloudflare R2) Latency:', value="```fix\nCalculating...```") # 8
)
msg = await ctx.send("Calculating Latency...", embed=embed)
# Reason why we don't use enumerate here is because enumerate doesn't continue with the Embed's index.
task_params = [
(0, bot.ping.bot_latency),
(1, bot.ping.typing_latency),
(2, bot.ping.discord_web_ping),
(4, bot.ping.database.postgresql),
(5, bot.ping.database.redis),
(7, bot.ping.api.openrobot),
(8, bot.ping.r2_ping),
]
tasks = [
*[ping_task(msg, embed, index, index_latency, func) for index_latency, (index, func) in enumerate(task_params)],
remove_content_on_finish(msg),
calculate_average_discord_latency(msg, embed, 3),
calculate_average_database_latency(msg, embed, 6),
remove_content_on_finish(msg),
]
await asyncio.gather(*tasks)
@bot.command("uptime", aliases=["up"])
async def uptime(ctx: commands.Context):
"""
Gets the Uptime info of the bot.
"""
if ctx.interaction is not None:
await ctx.interaction.response.defer()
embed = (
discord.Embed(color=bot.color, timestamp=ctx.message.created_at)
.set_author(name="Uptime Info:", icon_url=ctx.author.display_avatar.url)
.set_footer(icon_url=ctx.author.display_avatar.url, text=f"Requested by: {ctx.author}")
)
time_elapsed = discord.utils.utcnow() - bot.start_time
embed.description = f"""
**Uptime:** `{humanize.naturaldelta(time_elapsed)}`
**Launch/Start Time:** {discord.utils.format_dt(bot.start_time, 'F')} | {discord.utils.format_dt(bot.start_time, 'R')}
**Messages sent since last restart:** `{bot.sent_messages}`
**Messages edited since last restart:** `{bot.edited_messages}`
**Messages deleted since last restart:** `{bot.deleted_messages}`
**Commands invoked since last restart:** `{bot.commands_invoked}`
"""
await ctx.send(embed=embed)
@bot.command("system", aliases=["sys", "info"], cls=Command, example="system")
async def system(ctx: commands.Context):
"""
Gets system information e.g CPU, Memory, Disk, etc.
"""
if ctx.interaction is not None:
await ctx.interaction.response.defer()
async with ctx.typing():
embed = discord.Embed(color=bot.color)
msg = await ctx.send(
"Retrieving Basic Information...",
allowed_mentions=discord.AllowedMentions.none(),
)
start = time.perf_counter()
embed.description = f"""```yml
Python Version: Python {platform.python_version()}
Discord.py Version: {discord.__version__}
Guilds: {len(bot.guilds)}
Members: {len(list(bot.get_all_members()))}```
"""
await msg.edit(
content="Retrieving System Information...",
allowed_mentions=discord.AllowedMentions.none(),
)
uname = platform.uname()
system_name = uname.system
node_name = uname.node
machine = uname.machine
processor = uname.processor
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time(), datetime.timezone.utc)
embed.add_field(
name="System:",
value=f"""Boot Time: {discord.utils.format_dt(boot_time, 'F')} | {discord.utils.format_dt(boot_time, 'R')}
```yml
OS: {system_name}
Name: {node_name}
Machine: {machine}
Processor: {processor}```
""",
inline=False,
)
await msg.edit(
content="Retrieving CPU Information...",
allowed_mentions=discord.AllowedMentions.none(),
)
physical_cores = psutil.cpu_count(logical=False)
total_cores = psutil.cpu_count(logical=True)
cpufreq = psutil.cpu_freq()
current_cpu_freq = f"{cpufreq.current:.2f}Mhz"
cpu_usage = []
total_cpu_usage = psutil.cpu_percent()
for i, usage in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
cpu_usage.append(f"Core {i}: {usage}%")
cpu_usage = '\n'.join(cpu_usage)
embed.add_field(
name="CPU:",
value=f"""```yml
Name: {cpuinfo.get_cpu_info()['brand_raw']}
Physical cores: {physical_cores}
Total cores: {total_cores}
Frequency: {current_cpu_freq}
```
""",
)
embed.add_field(
name="CPU Usage:",
value=f"""```yml
Total CPU Usage: {total_cpu_usage}%
{cpu_usage}
```
""",
)
await msg.edit(
content="Retrieving Code Information...",
allowed_mentions=discord.AllowedMentions.none(),
)
line_count = bot.line_count()
embed.add_field(
name="Code Stats:",
value=f"""```yml
Files: {line_count.files}
Lines: {line_count.lines}
Classes: {line_count.classes}
Functions: {line_count.functions}
Coroutines: {line_count.coroutines}
Comments: {line_count.comments}```
""",
inline=False,
)
await msg.edit(
content="Retrieving Memory Information...",
allowed_mentions=discord.AllowedMentions.none(),
)
svmem = psutil.virtual_memory()
total_mem = f"{get_size(svmem.total)}"
available_mem = f"{get_size(svmem.available)}"
free_mem = f"{get_size(svmem.free)}"
used_mem = f"{get_size(svmem.used)}"
mem_perc = f"{svmem.percent}%"
embed.add_field(
name="Memory:",
value=f"""```yml
Total: {total_mem}
Available: {available_mem}
Free: {free_mem}
Used: {used_mem}
Percentage: {mem_perc}```
""",
)
await msg.edit(
content="Retrieving Disk Information...",
allowed_mentions=discord.AllowedMentions.none(),
)
disk_io = psutil.disk_io_counters()
disk_io_bytes_read = f"{get_size(disk_io.read_bytes)}"
disk_io_bytes_send = f"{get_size(disk_io.write_bytes)}"
total, used, free = shutil.disk_usage("/")
total_gib = total // (2 ** 30)
used_gib = used // (2 ** 30)
free_gib = free // (2 ** 30)
percentage_used = used_gib / total_gib * 100
percentage_free = free_gib / total_gib * 100
embed.add_field(
name="Disk:",
value=f"""```yml
Total: {total_gib} GiB
Used: {used_gib} GiB
Free: {free_gib} GiB
Percentage Used: {round(percentage_used, 1)}%
Read: {disk_io_bytes_read}
Send: {disk_io_bytes_send}```
""",
)
await msg.edit(
content="Retrieving Network and Speedtest Information...",
allowed_mentions=discord.AllowedMentions.none(),
)
net_io = psutil.net_io_counters()
net_io_bytes_sent = f"{get_size(net_io.bytes_sent)}"
net_io_bytes_recv = f"{get_size(net_io.bytes_recv)}"
packets_sent = f"{naturalnumber(net_io.packets_sent)} ({net_io.packets_sent:,})"
packets_recv = f"{naturalnumber(net_io.packets_recv)} ({net_io.packets_recv:,})"
embed.add_field(
name="Network:",
value=f"""```yml
Bytes Sent: {net_io_bytes_sent}
Bytes Received: {net_io_bytes_recv}
Packets Sent: {packets_sent}
Packets Received: {packets_recv}```
""",
inline=False,
)
proc = await asyncio.create_subprocess_shell(
"speedtest -f json",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await proc.communicate()
if ctx.debug:
await ctx.send("Stdout: " + (stdout.decode() or "Empty."))
await ctx.send("Stderr: " + (stderr.decode() or "Empty."))
await ctx.send("Return Code: " + str(proc.returncode))
if not stdout or proc.returncode != 0 or stderr:
s = speedtest.Speedtest()
s.get_best_server()
s.download()
s.upload(pre_allocate=False)
data = s.results.dict()
try:
s.get_servers([23373, 37568])
s.download()
s.upload(pre_allocate=False)
data2 = s.results.dict()
if (
data["download"] < data2["download"]
and data["upload"] < data2["upload"]
):
data = data2
except Exception as e:
if ctx.debug:
raise e
pass
embed.add_field(
name="Speedtest:",
value=f"""`{data['client']['isp']}, {data['client']['country']}` --> `{data['server']['sponsor']} - {data['server']['name']}, {data['server']['cc']}`:
```yml
Download: {round(data['download'] / 1000000, 2)} Mbps ({round(data['download'] / 1000000 / 1000, 2)} Gbps)
Upload: {round(data['upload'] / 1000000, 2)} Mbps ({round(data['upload'] / 1000000 / 1000, 2)} Gbps)
Ping: {round(data['ping'], 2)} ms
Bytes Sent: {round(data['bytes_sent'], 5)}
Bytes Received: {round(data['bytes_received'], 5)}
```Result URL: {'https://' + '.'.join(s.results.share().replace('http://', '').split('.')[:-1])}
""",
inline=False,
)
else:
data = json.loads(stdout.decode())
embed.add_field(
name="Speedtest:",
value=f"""`{data['isp']}` --> `{data['server']['name']} - {data['server']['location']}, {data['server']['country']}`:
```yml
Download:
- Result: {round(data['download']['bandwidth'] / 125000, 2)} Mbps ({round(data['download']['bandwidth'] / 125000 / 1000, 2)} Gbps)
- Data Used: {get_size(data['download']['bytes'])}
Upload:
- Result: {round(data['upload']['bandwidth'] / 125000, 2)} Mbps ({round(data['upload']['bandwidth'] / 125000 / 1000, 2)} Gbps)
- Data Used: {get_size(data['upload']['bytes'])}
Ping:
- Jitter: {round(data['ping']['jitter'], 2)} ms
- Latency: {round(data['ping']['latency'], 2)} ms
Packet Loss: {str(round(data['packetLoss'], 2)) + '%' if 'packetLoss' in data else 'Not available.'}
```Result URL: {data['result']['url']}
""",
inline=False,
)
embed.set_footer(text=f"PID: {os.getpid()}")
end = time.perf_counter()
await msg.delete()
await ctx.send(content=f'Time took: {round(end - start, 1)}s', embed=embed)
# @bot.command(
# aliases=["act"], cls=Command, example="activity My-VC-Channel Watch Together"
# )
# async def activity(
# ctx: commands.Context,
# channel: typing.Optional[discord.VoiceChannel] = commands.Option(
# None, description="The voice channel to start the activity. Defaults to the channel you are in."
# ),
# *,
# activity: typing.Literal[
# "Watch Together",
# "Poker Night",
# "Chess",
# "Sketch Heads",
# "Word Snacks",
# "Letter Leauge",
# "Spellcast",
# "Checkers",
# "Fishington",
# "Betrayal",
# "Ocho"
# ] = commands.Option(None, description="The activity to start."),
# ):
# channel = channel or (ctx.author.voice.channel if ctx.author.voice else None)
#
# if channel is None:
# return await ctx.send("A channel is required to start the activity!")
#
# if channel.permissions_for(ctx.me).create_instant_invite is False:
# return await ctx.send(
# f"I need the `Create Invite` permissions for {channel.mention} to start the activity!"
# )
#
# if activity is None:
# activities = discord_activity.ActivityType._member_names_
#
# class Select(discord.ui.Select):
# def __init__(self):
# super().__init__(
# placeholder="Select an activity",
# options=[
# discord.SelectOption(
# label=x.replace("_", " ").title(),
# description=f"Start a {x.replace('_', ' ').title()} activity.",
# )
# for x in activities
# ],
# )
#
# async def callback(self, interaction: discord.Interaction):
# nonlocal activity
# activity = self.values[0]
#
# await interaction.message.delete()
#
# self.view.stop()
#
# class View(discord.ui.View):