class Proc(object): def __init__(self, pid): self.pid = pid self.proc = Process(pid) with self.proc.oneshot(): self.name = self.proc.name() self.owner = self.proc.username() self.created = self.proc.create_time() def poll(self, delay=1): if not self.proc.is_running(): return ( self.pid, '**DEAD**' + self.name, self.owner, 0, 0 ) with self.proc.oneshot(): self.poll1 = self.proc.cpu_times() self.virtual1 = self.proc.memory_info().vms self.system1 = cpu_times() time.sleep(delay) with self.proc.oneshot(): self.poll2 = self.proc.cpu_times() self.virtual2 = self.proc.memory_info().vms self.system2 = cpu_times() self.proc_time = sum(self.poll2) - sum(self.poll1) self.cpu_time = sum(self.system2) - sum(self.system1) self.virtual = MB(( self.virtual1 + self.virtual2 ) / 2) self.cpu_percent = 100 * ( self.proc_time / self.cpu_time ) return ( self.pid, self.name, self.owner, self.cpu_percent, self.virtual ) def is_running(self): return self.proc.is_running() def __repr__(self): return "**process** %s (%d)" % ( self.proc.name(), self.pid ) def __str__(self): return template.format(self.pid, self.name, self.owner, self.cpu_percent, self.virtual)
async def botstats(self, ctx): embed = discord.Embed(title="Statistics", colour=discord.Colour.red(), thumbnail=self.bot.user.avatar_url, timestamp=datetime.utcnow()) proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) embed.add_field(name="Python version", value=python_version(), inline=True), embed.add_field(name="discord.py version", value=discord_version, inline=True), embed.add_field(name="Uptime", value=uptime, inline=True), embed.add_field(name="CPU time", value=cpu_time, inline=True), embed.add_field( name="Memory usage", value= f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", inline=True), #embed.add_field(name = "Users", value = f"{ctx.guild.member_count:,}", inline =True) await ctx.send(embed=embed)
async def botinfo(self, ctx): handles = self.db.get_count('handles') matches = self.db.get_count('finished') rounds = self.db.get_count('finished_rounds') guilds = len(self.client.guilds) uptime_ = int(time.time()) - self.uptime proc = Process() with proc.oneshot(): mem_total = virtual_memory().total / (1024 ** 3) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) embed = discord.Embed(description="A discord bot to compete with others on codeforces in a Lockout format", color=discord.Color.magenta()) embed.set_author(name="Bot Stats", icon_url=self.client.user.avatar_url) embed.set_thumbnail(url=self.client.user.avatar_url) embed.add_field(name="Handles Set", value=f"**{handles}**", inline=True) embed.add_field(name="Matches played", value=f"**{matches}**", inline=True) embed.add_field(name="Rounds played", value=f"**{rounds}**", inline=True) embed.add_field(name="Servers", value=f"**{guilds}**", inline=True) embed.add_field(name="Uptime", value=f"**{timeez(uptime_)}**", inline=True) embed.add_field(name="Memory usage", value=f"{int(mem_usage * 1024)} MB / {mem_total:,.0f} GB ({mem_of_total:.0f}%)", inline=True) embed.add_field(name="GitHub repository", value=f"[GitHub]({GITHUB_LINK})", inline=True) embed.add_field(name="Bot Invite link", value=f"[Invite]({BOT_INVITE})", inline=True) embed.add_field(name="Support Server", value=f"[Server]({SERVER_INVITE})", inline=True) await ctx.send(embed=embed)
async def advinfo(self, ctx): proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) bot = await self.client.application_info() e = discord.Embed(title=f"{bot.name}", description=f"{bot.description}", colour=COLOURS['purple']) e.add_field(name="Bot Version", value=f'{BOT_VERSION}', inline=False) e.add_field(name="Uptime", value=f'{str(uptime).split(".")[0]}', inline=True) e.add_field(name="", value="") e.add_field(name="CPU time", value=f'{str(cpu_time).split(".")[0]}', inline=True) # name and value of below field are Zero Width Space not empty # Check this : https://emojipedia.org/zero-width-joiner/ e.add_field(name="Ping", value=f'{round(self.client.latency*1000)}ms', inline=True) e.add_field(name="", value="") e.add_field(name="Response Time", value=f'-', inline=False) e.add_field(name="Memory Usage", value=f'{mem_usage:,.0f}/{mem_total:,.0f} MB', inline=True) e.add_field(name="Memory Usage %", value=f'{mem_of_total:,.2f}%', inline=True) e.set_thumbnail(url=str(bot.icon_url)) e.set_footer( text=f'Python Version - {version_info.major}.{version_info.minor}.{version_info.micro} | Discord.py Version - {discord.version_info.major}.{discord.version_info.minor}.{discord.version_info.micro}') start = time() msg = await ctx.send(embed=e) end = time() e.set_field_at(index=6, name="Response Time", value=f'{round((end-start)*1000)}ms', inline=True) await msg.edit(embed=e)
async def show_bot_stats(self, ctx): embed = Embed(title="Bot stats", colour=ctx.author.colour, thumbnail=self.bot.user.avatar_url, timestamp=datetime.utcnow()) proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) fields = [ ("Bot version", self.bot.VERSION, True), ("Python version", python_version(), True), ("discord.py version", discord_version, True), ("Uptime", uptime, True), ("CPU time", cpu_time, True), ("Memory usage", f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True), ("Users", f"{self.bot.guild.member_count:,}", True) ] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) await ctx.send(embed=embed)
async def show_bot_stats(self, ctx): '''Displays Statistical Information''' embed = Embed(title="Bot stats", colour=ctx.author.colour, thumbnail=self.bot.user.avatar_url, timestamp=datetime.utcnow()) proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) #cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) mo = self.bot.guilds sum1 = 0 for s in mo: sum1 += len(s.members) fields = [ ("Python version", python_version(), True), ("discord.py version", discord_version, True), ("Uptime", uptime, True), ("CPU time", f"{cpu_time}%", True), ("Memory usage", f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True), ("Users", f"{sum1:,}", True), ("Servers", f"{len(self.bot.guilds)}", True), ("Region", f"`Europe`", True), ("Latency", "`{0}`".format(round(self.bot.latency, 4) * 1000), True) ] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) await ctx.send(embed=embed)
async def info(self, ctx): """Shows you information about the bot owner, bot uptime, latency, memory and cpu usage.""" embed = Embed(color=0x000000) embed.set_thumbnail(url=ctx.bot.user.avatar_url) app = await ctx.bot.application_info() owner = app.owner embed.set_author(name=str(owner), icon_url=owner.avatar_url) proc = Process() with proc.oneshot(): uptime = datetime.utcnow() - ctx.bot.launched_at mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) cpu_usage = proc.cpu_percent() / cpu_count() embed.add_field(name='Uptime', value=str(uptime), inline=False) embed.add_field(name='Latency', value=f'{round(ctx.bot.latency * 1000, 2)} ms', inline=False) embed.add_field( name='Memory usage', value= f'{int(mem_usage)} / {int(mem_total)} MiB ({round(mem_of_total)}%)', inline=False) embed.add_field(name='CPU usage', value=f'{round(cpu_usage)}%', inline=False) await ctx.send(embed=embed)
def check_resources(process: psutil.Process): with process.oneshot(): user_time_used = process.cpu_times().user system_time_used = process.cpu_times().system cpu_time_used = (user_time_used + system_time_used) * 1000 memory_used = process.memory_info().rss // 1024 return memory_used, cpu_time_used
def track_process(p: psutil.Process): pid = p.pid with p.oneshot(): try: res = p.memory_info() tracker.add({ f'process.{p.pid}.{p.name()}.rss': res.rss, f'process.{p.pid}.{p.name()}.vms': res.vms }) except psutil.AccessDenied: pass try: res = p.memory_percent() tracker.add({ f'process.{p.pid}.{p.name()}.mem': res, }) except psutil.AccessDenied: pass try: res = p.cpu_percent() tracker.add({ f'process.{p.pid}.{p.name()}.cpu': res, }) except psutil.AccessDenied: pass try: res = p.num_threads() tracker.add({ f'process.{p.pid}.{p.name()}.threads': res, }) except psutil.AccessDenied: pass
def get_resource_usage(self) -> ResourceUsage: """ Return various resource usage statistics about the running process. """ assert not self.returncode, "Can't collect data on stopped process" proc = Process(self.ps.pid) if 'bitcoind' in self.cmd: def find_process(proc_): """ Process graph looks like this: sh(327)───time(334)───bitcoind(335) """ name = proc_.name() # Recurse into child processes if need be. if name in ['sh', 'time']: assert len(proc_.children()) == 1 return find_process(proc_.children()[0]) assert (name.startswith('bitcoin') or name.startswith('b-')) return proc_ proc = find_process(proc) with proc.oneshot(): return ResourceUsage( cpu_percent=proc.cpu_percent(), memory_info=proc.memory_info(), num_fds=proc.num_fds(), )
async def uptime(self, ctx): proc = Process() with proc.oneshot(): up_time = timedelta(seconds=time() - proc.create_time()) e = discord.Embed(colour=COLOURS['black']) e.add_field(name="Uptime", value=f"{timetotext(up_time)}", inline=False) e.add_field( name="Started On", value= f'{(date.today() - up_time).strftime("%d %B, %Y")} at {datetime.fromtimestamp(proc.create_time()).strftime("%H:%M:%S")}' ) await ctx.send(embed=e)
def get_proc_data(proc: psutil.Process) -> Dict[str, Union[int, float]]: data: Dict[str, Union[int, float]] = {} try: with proc.oneshot(): data.update(proc.memory_full_info()._asdict()) data["cpu_percent"] = proc.cpu_percent() data["rss_percent"] = data["rss"] / TOTAL_MEMORY * 100 data["pss_percent"] = data["pss"] / TOTAL_MEMORY * 100 data["uss_percent"] = data["uss"] / TOTAL_MEMORY * 100 data["vms_percent"] = data["vms"] / TOTAL_MEMORY * 100 except psutil.NoSuchProcess: raise ValueError(f"The process no longer exists: {proc.pid}") else: return data
async def stats(self, ctx): embed = Embed(title="Bot Stats", color=ctx.author.color, thumbnail=self.client.user.avatar_url, timestamp=datetime.utcnow()) proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) fields = [("Python Version", python_version(), True), ("Discord Version", discord_version, True), ("Uptime", uptime, True), ("Users", f"{self.client.guild.member_count:,}", True)] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) await ctx.send(embed=embed)
async def ping(self, ctx): user = ctx.author proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) embed = discord.Embed(description="ADMN observer is always alive", color=discord.Color.dark_purple()) embed.add_field(name="BOT latency", value="%s ms" % round(self.bot.latency * 1000)) embed.add_field(name="Bot Uptime", value=uptime) embed.set_footer(text="Requested by:- " + ctx.author.name + " | " + datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S"), icon_url=user.avatar_url) await ctx.send(embed=embed)
def _rkill(process: psutil.Process, *, dry=True) -> List[KillVictim]: victims = [] if process.is_running(): with process.oneshot(): ppid = process.ppid() pid = process.pid name = process.name() for child_process in process.children(recursive=True): victims.extend(_rkill(child_process, dry=dry)) victims.append(KillVictim(ppid, pid, name, ("SKIPPED" if dry else _kill(process)))) return victims
def __init__(self, proc: psutil.Process, proctable): """ Class constructor """ _dead = False self._children = list() self._parent = 0 parent = None self._proc, self._pt = proc, proctable try: self._pgid = os.getpgid(proc.pid) except: self._pgid = 0 _dead = True if not _dead: parent = proc.parent() if parent: self._parent = parent.pid if not _dead: self._children = [ p.pid for p in proc.children() ] with proc.oneshot(): if proc.is_running(): self.rss = proc.memory_info().rss self.vms = proc.memory_info().vms self.ctx_vol = proc.num_ctx_switches().voluntary self.ctx_invol = proc.num_ctx_switches().involuntary self._cmdline = proc.cmdline() self.pcpu = None #self.pcpu += proc.cpu_percent(interval=DEFAULT_INTERVAL) else: self.rss = 0 self.vms = 0 self.ctx_vol = 0 self.ctx_invol = 0 self.cmdline = [ ] self.pcpu = 0.0
async def show_bot_info(self, ctx): t = datetime.utcnow() proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) e = Embed(title=f"Information about `ICE X`", colour=ctx.author.colour) fields = [ ("Bot version", self.bot.VERSION, True), ("Bot Owner", f"<@!537634097137188875>", True), ("Python version", python_version(), True), ("discord.py version", discord_version, True), ("Uptime", uptime, True), ("CPU time", cpu_time, True), ("Memory usage", f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True), ("Invite Bot", '**[Invite](https://discord.com/api/oauth2/authorize?client_id=723380957343907911&permissions=8&scope=bot "Invite the bot to your server")**', False) ] for name, value, inline in fields: e.add_field(name=name, value=value, inline=inline) e.set_thumbnail(url=self.bot.user.avatar_url) e.set_author( name=f"{ctx.author.display_name}#{ctx.author.discriminator}", icon_url=ctx.author.avatar_url) e.set_footer( text= f"Requested by {ctx.author.display_name} | {t.strftime('%b %d, %Y | %I:%M %p UTC')}" ) await ctx.send(embed=e)
async def cmd_stats(self, ctx): async with ctx.typing(): start = time() msg = await ctx.send("-") end = time() dwsp_latency = round(self.bot.latency*1000) response_latency = round((end-start)*1000) proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time()-proc.create_time()) cpu_time = timedelta(seconds=(cpu:=proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = round(mem_total * (mem_of_total / 100),2) mem_of_total = round(mem_of_total, 2) mem_total = round(mem_total/1024) embed=Embed( title=self.bot.user.name, color=ctx.guild.me.color if ctx.guild else ctx.author.color, timestamp=datetime.utcnow() ) embed.set_author(name=self.bot.user, icon_url=self.bot.user.avatar_url) embed.set_thumbnail(url=self.bot.user.avatar_url) fields=[ ("Default Prefix", self.bot.prefix, True), ("DWSP Latency", f"{dwsp_latency}ms", True), ("Response Latency", f"{response_latency}ms", True), ("Bot Version", self.bot.VERSION, True), ("Python Version", python_version(), True), ("Discord.py Version", discord_version, True), ("Uptime", uptime, True), ("CPU Time", cpu_time, True), ("Loaded Cogs", len(self.bot.extensions), True), ("Memory Usage", f"{mem_usage}MB/{mem_total}GB {mem_of_total}%", False), ("Servers", len(self.bot.guilds), True), ("Users", len(self.bot.users), True), ("Banned Users", len(self.bot.banlist), True)] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) await msg.delete() await ctx.send(embed=embed)
def stats(): proc = Process() with proc.oneshot(): uptime = naturaldelta(time()-proc.create_time()) uptime = uptime[:-6] cpu_usage = int(cpu_percent()) mem_total = virtual_memory().total >> 20 pid = getpid() py = Process(pid) memoryUse = py.memory_info()[0] * 10**6 fields = [ ('Uso della CPU', str(cpu_usage) + '%', True), ('Utilizzo della memoria', str(memoryUse)[:2] + ' MB', True), ('Totale memoria', str(mem_total) + ' MB', True), ('Discord.py', discord_version, True), ('Python', python_version(), True), ('Uptime', uptime, True) ] return fields
async def gbotinfo(self, ctx): embed = discord.Embed(title='About gBot', colour=discord.Colour.blurple()) proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) fields = [ ("Developed by:", "Galax028#9474", True), ("Hosted using:", "https://mydiscordbothosting.com", True), ("Version:", f"`{version}`", True), ("Total Commands:", f"{len(self.bot.commands)}", True), ("Invite the bot:", "[Click Here](https://rb.gy/wzzuvm)", True), ("Support Server:", "[Click Here](https://discord.gg/2hVmdnb)", True), ("⠀", "----------------------------------------------------------------------", False), ("Python Version:", f"`{python_version()}`", True), ("discord.py Version:", f"`{discord_version}`", True), ("⠀", "⠀", True), ("Uptime:", f"`{uptime}`", True), ("CPU Time:", f"`{cpu_time}`", True), ("RAM Usage:", f"`{mem_usage:,.3f}/250 MiB`", True), ("⠀", "----------------------------------------------------------------------", False), ("Special Thanks:", "PixelEdition#2116, Marxist Gamer#3000, Sir.Nick#4646", False), ("⠀", "⠀", False) ] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) embed.set_footer(text="Thank you for using gBot!") await ctx.send(embed=embed)
async def botstats(self, ctx): """ Displays the bots statistics """ embed = discord.Embed(colour=ctx.author.colour, title="Bot Stats", thumbnail=self.bot.user.avatar_url) proc = Process() with proc.oneshot(): now = int(time.time()) nt = now - proc.create_time() uptime = timedelta(seconds=nt) memory_total = virtual_memory().total / (1024**3) memory_of_total = proc.memory_percent() memory_usage = memory_total * (memory_of_total / 100) ft = "gif" if ctx.author.is_avatar_animated() else "png" embed.add_field(name="Python Version", value=python_version(), inline=True) embed.add_field(name="Discord.py Version", value=discord.__version__, inline=True) embed.add_field(name="Uptime", value=uptime, inline=False) embed.add_field( name="Memory Usage", value= f"{memory_usage:,.2} / {memory_total:,.0f} GB ({memory_of_total:,.0f}%)", inline=False) embed.set_footer(text=f"Requested by {ctx.author.name}") embed.set_thumbnail(url=self.bot.user.avatar_url_as(format=ft)) await ctx.send(embed=embed)
def track_process(self, p: psutil.Process): with p.oneshot(): key = None if p.pid in self.pids: key = self.pids[p.pid] if self.processes[key].name != p.name(): key = None if key is None: key = len(self.processes) self.processes.append(ProcessInfo(key, p.pid, p.name())) self.pids[p.pid] = key self.data.update({ f'process.{key}.name': p.name(), f'process.{key}.pid': p.pid, f'process.{key}.ppid': p.ppid(), f'process.{key}.create_time': p.create_time(), }) try: self.data.update({ f'process.{key}.exe': p.exe(), }) except (psutil.AccessDenied, psutil.ZombieProcess): pass try: self.data.update({ f'process.{key}.cmdline': '\n'.join(p.cmdline()), }) except (psutil.AccessDenied, psutil.ZombieProcess): pass self.processes[key].active = True try: res = p.memory_info() self.data.update({ f'process.{key}.rss': res.rss, f'process.{key}.vms': res.vms, }) except (psutil.AccessDenied, psutil.ZombieProcess): pass try: res = p.cpu_times() self.data.update({ f'process.{key}.user': res.user, f'process.{key}.system': res.system, }) if hasattr(res, 'iowait'): self.data.update({ f'process.{key}.iowait': res.iowait, }) except (psutil.AccessDenied, psutil.ZombieProcess): pass try: res = p.cpu_percent() self.data.update({ f'process.{key}.cpu': res, }) except (psutil.AccessDenied, psutil.ZombieProcess): pass try: res = p.num_threads() self.data.update({ f'process.{key}.threads': res, }) except (psutil.AccessDenied, psutil.ZombieProcess): pass
def _get_data(p: psutil.Process): with p.oneshot(): t = p.cpu_times().user + p.cpu_times().system m = p.memory_info().rss return t, m
def run_subprocess(command, shell=False, doexec=True, monitor=False, tile_id=None): """Subprocess runner If subrocess returns non-zero exit code, STDERR is sent to the logger. Parameters ---------- command : list of str Command to pass to subprocess.run(). Eg ['wget', '-q', '-r', dl_url] shell : bool Passed to subprocess.run() doexec : bool Execute the subprocess or just print out the concatenated command Returns ------- nothing nothing """ if doexec: cmd = " ".join(command) if shell: command = cmd logger.debug(command) popen = Popen(command, shell=shell, stderr=PIPE, stdout=PIPE) pid = popen.pid if monitor: proc = Process(pid) with proc.oneshot(): try: logger_perf.debug( "%s;%s;%s" % (tile_id, virtual_memory().used, swap_memory().used)) except NoSuchProcess or ZombieProcess: logger.debug("%s is Zombie or NoSuchProcess" % tile_id) except AccessDenied as e: logger_perf.exception(e) # if monitor: # running = True # proc = Process(pid) # with proc.oneshot(): # while running: # try: # logger_perf.debug("%s - %s - %s - %s - %s" % ( # tile_id, proc.cpu_percent(), proc.cpu_times(), proc.memory_full_info(), swap_memory())) # except NoSuchProcess or ZombieProcess: # logger.debug("%s is Zombie or NoSuchProcess" % tile_id) # break # except AccessDenied as e: # logger_perf.exception(e) # break # running = proc.is_running() # logger.debug("%s is running: %s" % (tile_id, running)) # sleep(1) stdout, stderr = popen.communicate() err = stderr.decode(locale.getpreferredencoding(do_setlocale=True)) popen.wait() if popen.returncode != 0: logger.debug("Process returned with non-zero exit code: %s", popen.returncode) logger.error(err) return False else: return True else: logger.debug("Not executing %s", command) return True
class HentaiBot(commands.Cog): def __init__(self, client): self.client = client self.process = Process() self.reader_id = None #region events @commands.Cog.listener() async def on_ready(self): await self.client.change_presence( status=discord.Status.idle, activity=discord.Game("Now taking requests!💕")) print( f"[{dt.now().strftime('%d.%m.%Y %H:%M:%S')}] Initializing HentaiBot" ) #endregion #region commands @commands.command(aliases=['lid']) async def lookup_id(self, ctx, id: int): if not Hentai.exists(id): await ctx.send("Error: Invalid ID.") else: doujin = Hentai(id) embed = discord.Embed( title=doujin.title(Format.Pretty), description=f"🌍 {', '.join(Tag.get_names(doujin.language))}", url=doujin.url, color=discord.Color.red()) embed.add_field(name="Author", value=Tag.get_names(doujin.artist)) embed.add_field(name="Favorites", value=f"❤ {doujin.num_favorites}") embed.add_field(name="Pages", value=f"📕 {doujin.num_pages}") embed.set_thumbnail(url=doujin.thumbnail) embed.set_footer( text=f"Tags: {', '.join(Tag.get_names(doujin.tag))}") await self.client.change_presence( status=discord.Status.online, activity=discord.Game( f"Now reading {doujin.title(Format.Pretty)}🥰")) await ctx.send(embed=embed) @commands.command(aliases=['read']) async def read_id(self, ctx, id: int): if not Hentai.exists(id): await ctx.send("Error: Invalid ID.") else: doujin = Hentai(id) reactions = { 'prev': Emoji[':arrow_left:'], 'next': Emoji[':arrow_right:'] } embed = discord.Embed(title=doujin.title(Format.Pretty), description=f"Page 1 of {doujin.num_pages}", color=discord.Color.red()) embed.set_image(url=doujin.cover) # TODO: implement emoji reaction event handler for pagination message = await ctx.send(embed=embed) self.reader_id = message.id print(type(message)) print(self.reader_id) for emoji in reactions.values(): await message.add_reaction(emoji) @lookup_id.error async def on_argument_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send("Error: Missing argument.") @commands.command(aliases=['rid']) async def random_id(self, ctx): await self.lookup_id(ctx, id=Utils.get_random_id(make_request=True)) @commands.command(aliases=['ut'], pass_context=True) @has_permissions(manage_roles=True) async def uptime(self, ctx): with self.process.oneshot(): uptime = timedelta(seconds=time() - self.process.create_time()) await ctx.send( f"Uptime: {uptime.days}d:{uptime.days // 3600}h:{(uptime.seconds // 60) % 60}m:{uptime.seconds}s." ) @commands.command(pass_context=True) async def help(self, ctx): embed = discord.Embed(title="Usage", color=discord.Color.gold()) embed.add_field(name="`/lookup_id id:int || /lid id:int`", value="Lookup an user-specified ID.", inline=False) embed.add_field(name="`/read_id id:int || /read id:int`", value="Read an user-specified ID in chat.", inline=False) embed.add_field(name="`/random_id || /rid`", value="Roll a random ID.", inline=False) embed.add_field(name="`/uptime || /ut`", value="Shows bot uptime.") await ctx.send(embed=embed)
async def show_bot_info(self, ctx, patreon_status): embed = Embed(title="Krinio Info", colour=ctx.author.colour, timestamp=datetime.utcnow()) bot_version = self.bot.VERSION proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user) mem_total = virtual_memory().total / (1025**2) mem_of_total = proc.memory_percent() mem_usg = mem_total * (mem_of_total / 100) fields = [ ("Name", "Krinio", False), ("Developers", "<@308000668181069824>", False), ("Krinio's Server Count", f"{str(len(self.bot.guilds))}", True), ("Krinio's Member Count", f"{str(len(self.bot.users))}", True), ( "The ping for Krinio is...", f" :ping_pong: {round(self.bot.latency * 1000)} ms", False, ), ("Python Version", python_version(), True), ("Uptime", uptime, True), ("CPU Time", cpu_time, True), ( "Memory Usage", f"{mem_usg:,.3f} MiB / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True, ), ("Library", f"discord.py {discord_version}", True), ( "Bot Version", f"{self.bot.VERSION} - [Changelog](https://github.com/doobdev/Krinio/blob/master/CHANGELOG.md#v{bot_version.replace('.', '')})", True, ), ("Top.gg Link", "https://top.gg/bot/744377689095536750", False), ( "Invite Link", "[Invite Link Here](https://discord.com/oauth2/authorize?client_id=744377689095536750&scope=bot&permissions=271674430)", True, ), ( "GitHub Repository", "[Click Here](https://github.com/doobdev/Krinio)", True, ), ] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) embed.set_thumbnail(url=ctx.guild.me.avatar_url) embed.set_footer( text=f"{ctx.author.name} requested Krinio's information", icon_url=ctx.author.avatar_url, ) if patreon_status == True: embed.add_field( name="Patreon", value= f"Thanks for [Donating](https://patreon.com/doobdev) {ctx.author.display_name}! :white_check_mark:", inline=False, ) await ctx.send(embed=embed) if patreon_status == False: embed.add_field( name="Patreon", value="[Click Here for Patreon](https://patreon.com/doobdev)", inline=False, ) await ctx.send(embed=embed)
async def command_bot_info(self, ctx: commands.Context) -> None: proc = Process() with proc.oneshot(): uptime = chron.short_delta( timedelta(seconds=time() - proc.create_time())) cpu_time = chron.short_delta( timedelta(seconds=(cpu := proc.cpu_times()).system + cpu.user), milliseconds=True) mem_total = virtual_memory().total / (1024**2) mem_of_total = proc.memory_percent() mem_usage = mem_total * (mem_of_total / 100) await ctx.send(embed=discord.Embed.from_dict({ "title": "Carberretta Information", "color": DEFAULT_EMBED_COLOUR, "thumbnail": { "url": f"{self.bot.user.avatar_url}" }, "author": { "name": "Carberretta" }, "footer": { "text": f"Requested by {ctx.author.display_name}", "icon_url": f"{ctx.author.avatar_url}", }, "fields": [ { "name": "Bot Version", "value": self.bot.version, "inline": True }, { "name": "Python Version", "value": python_version(), "inline": True }, { "name": "discord.py Version", "value": discord.__version__, "inline": True }, { "name": "Uptime", "value": uptime, "inline": True }, { "name": "CPU Time", "value": cpu_time, "inline": True }, { "name": "Memory Usage", "value": f"{mem_usage:,.3f} / {mem_total:,.0f} MiB ({mem_of_total:,.0f}%)", "inline": True, }, { "name": "Code Lines", "value": f"{int(self.bot.loc.code):,}", "inline": True }, { "name": "Docs Lines", "value": f"{int(self.bot.loc.docs):,}", "inline": True }, { "name": "Blank Lines", "value": f"{int(self.bot.loc.empty):,}", "inline": True }, { "name": "Database Calls", "value": f"{self.bot.db._calls:,}", "inline": True }, ], }))
async def show_bot_info(self, ctx, patreon_status): embed = Embed( title="Doob Info <:doob:754762131085459498>", colour=ctx.author.colour, timestamp=datetime.utcnow(), ) bot_version = self.bot.VERSION proc = Process() with proc.oneshot(): uptime = timedelta(seconds=time() - proc.create_time()) cpu_time = timedelta( seconds=(cpu := proc.cpu_times()).system + cpu.user ) # pylint: disable=used-before-assignment mem_total = virtual_memory().total / (1025 ** 2) mem_of_total = proc.memory_percent() mem_usg = mem_total * (mem_of_total / 100) fields = [ ("Name", "Doob <:doob:754762131085459498>", False), ( "Description", "The multipurpose Discord Bot with global leveling and powerful logging tools for your server.", False, ), ("Developers", "<@308000668181069824>", False), ("Doob's Server Count", f"{str(len(self.bot.guilds))}", True), ("Doob's Member Count", f"{str(len(self.bot.users))}", True), ( "The ping for Doob is...", f" :ping_pong: {round(self.bot.latency * 1000)} ms", False, ), ("Python Version", python_version(), True), ("Uptime", uptime, True), ("CPU Time", cpu_time, True), ( "Memory Usage", f"{mem_usg:,.3f} MiB / {mem_total:,.0f} MiB ({mem_of_total:.0f}%)", True, ), ("Library", f"discord.py {discord_version}", True), ( "Bot Version", f"{self.bot.VERSION} - [Changelog](https://github.com/doobdev/doob/blob/master/CHANGELOG.md#v{bot_version.replace('.', '')})", True, ), ("Top.gg Link", "https://top.gg/bot/680606346952966177", False), ( "Invite Link", "[Invite Link Here](https://doob.link/invite)", True, ), ( "GitHub Repository", "[Click Here](https://github.com/doobdev/doob)", True, ), ] for name, value, inline in fields: embed.add_field(name=name, value=value, inline=inline) embed.set_thumbnail(url=ctx.guild.me.avatar_url) embed.set_footer( text=f"{ctx.author.name} requested Doob's information", icon_url=ctx.author.avatar_url, ) if patreon_status == True: embed.add_field( name="Patreon", value=f"Thanks for [Donating](https://patreon.com/doobdev) {ctx.author.display_name}! :white_check_mark:", inline=False, ) await ctx.reply(embed=embed) if patreon_status == False: embed.add_field( name="Patreon", value="[Click Here for Patreon](https://patreon.com/doobdev)", inline=False, ) await ctx.reply(embed=embed)
class _ProcessMonitor: WARNING_THRESHOLD = 100 * 1024 * 1024 busy = False def __init__(self): self.process = Process() self.peak_mem_res = 0 self.low_mem_warning = False def monitor_task(self): if sys.stdout.isatty(): while self.busy: try: # only print the data out every 10 seconds if datetime.now().second / 10 == 0: info = self._get_info() output.debug(info) else: # call get_mem so that we record peak more accurately self._get_mem() time.sleep(1) except Exception: output.debug_exception() self.busy = False pass else: # if this isn't a TTY, no point in doing any of this self.busy = False def _get_info(self) -> str: from yawast.external.memory_size import Size # prime the call to cpu_percent, as the first call doesn't return useful data self.process.cpu_percent(interval=1) # use oneshot() to cache the data, so we minimize hits with self.process.oneshot(): pct = self.process.cpu_percent() times = self.process.cpu_times() mem = self._get_mem() mem_res = "{0:cM}".format(Size(mem.rss)) mem_virt = "{0:cM}".format(Size(mem.vms)) thr = self.process.num_threads() vm = psutil.virtual_memory() mem_total = "{0:cM}".format(Size(vm.total)) mem_avail_bytes = vm.available mem_avail = "{0:cM}".format(Size(vm.available)) if mem_avail_bytes < self.WARNING_THRESHOLD and not self.low_mem_warning: self.low_mem_warning = True output.error(f"Low RAM Available: {mem_avail}") cons = -1 try: cons = len(self.process.connections(kind="inet")) except Exception: # we don't care if this fails output.debug_exception() cpu_freq = psutil.cpu_freq() info = (f"Process Stats: CPU: {pct}% - Sys: {times.system} - " f"User: {times.user} - Res: {mem_res} - Virt: {mem_virt} - " f"Available: {mem_avail}/{mem_total} - Threads: {thr} - " f"Connections: {cons} - CPU Freq: " f"{int(cpu_freq.current)}MHz/{int(cpu_freq.max)}MHz") return info def _get_mem(self): mem = self.process.memory_info() if mem.rss > self.peak_mem_res: self.peak_mem_res = mem.rss output.debug(f"New high-memory threshold: {self.peak_mem_res}") return mem def __enter__(self): self.busy = True threading.Thread(target=self.monitor_task).start() return self def __exit__(self, exception, value, tb): self.busy = False if exception is not None: return False