Example #1
0
    async def checking_bot_stats(self, ctx):
        """Bot Statistics! (CPU/Mem Usage etc)"""

        stats = Embed(title=f"<:github:741000905364603010> Ensō~Chan {self.bot.version} Statistics",
                      url="https://github.com/sgoudham/Enso-Bot",
                      colour=self.bot.admin_colour,
                      timestamp=datetime.datetime.utcnow())
        stats.set_thumbnail(url=self.bot.user.avatar_url)
        stats.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar_url)

        # Grabbing technical statistics of the bot
        proc = Process()
        with proc.oneshot():
            uptime = datetime.timedelta(seconds=time() - proc.create_time())
            mem_total = virtual_memory().total / (1024 ** 2)
            mem_of_total = proc.memory_percent()
            mem_usage = mem_total * (mem_of_total / 100)

        uptime_hours, uptime_remainder = divmod(uptime.seconds, 3600)
        uptime_minutes, uptime_seconds = divmod(uptime_remainder, 60)
        frmt_uptime = f'{int(uptime_hours):01} Hour(s), {int(uptime_minutes):01} Minute(s), {int(uptime_seconds):01} Second(s)'

        # Grabbing total number of channels across all guilds in which the bot is present in
        channels = map(lambda m: len(m.channels), self.bot.guilds)

        # Setting up fields
        fields = [
            ("Developer", f"{self.bot.hammyMention} | Hamothy#5619", False),

            ("Language | Library",
             f"<:python:747224674319990895> Python {python_version()} | <:discord:747224665553895544> Discord.py {discord_version}",
             False),

            ("<:discord:747224665553895544> Support Server",
             "[Here!](https://discord.com/invite/SZ5nexg)", True),

            ("<:invite:740998357643952139> Invite Link",
             "[Here!](https://discord.bots.gg/bots/716701699145728094)", True),

            ("❗ Current Prefix", ctx.prefix, True),

            ("Discord Stats",
             f"Guilds: {len(self.bot.guilds)}"
             f"\nChannels: {sum(list(channels))}"
             f"\nEmojis: {len(self.bot.emojis)}"
             f"\nCommands: {len(self.bot.commands)}"
             f"\nUsers: {len(self.bot.users):,}", True),

            ("Line Count", await line_count(), True),
            ("Uptime", frmt_uptime, False),
            ("Memory Usage", f"{mem_usage:,.2f} / {mem_total:,.2f} MiB ({mem_of_total:.2f}%)", False)]

        # Add fields to the embed
        for name, value, inline in fields:
            stats.add_field(name=name, value=value, inline=inline)

        await ctx.send(embed=stats)
Example #2
0
 def run_subprocess():
     transport, protocol = yield from loop.subprocess_shell(
             protocol_factory,
             cmd, stdin=stdin, stdout=stdout,
             stderr=stderr, **kwds)
     process = Process(transport, protocol, loop)
     protocol.configure_handler(process, callback)
     yield from process.wait()
     return process
Example #3
0
    async def _stop_process(self, process: Process):
        """Stop a process

        Args:
            process (Process): the process to stop
        """
        if process.returncode is None:
            process.terminate()
            try:
                await asyncio.wait_for(process.wait(), 5)
            except asyncio.TimeoutError:
                process.kill()
Example #4
0
 def run_subprocess():
     transport, protocol = yield from loop.subprocess_shell(
         protocol_factory,
         cmd,
         stdin=stdin,
         stdout=stdout,
         stderr=stderr,
         **kwds)
     process = Process(transport, protocol, loop)
     protocol.configure_handler(process, callback)
     yield from process.wait()
     return process
Example #5
0
async def poll_client(reader: StreamReader, process: Process, stdin: StreamWriter):
    """
    Continuously waits to receive a stdin message from the client.
    """
    while True:
        (message_type, body) = await read_client(reader)
        if message_type == MESSAGE_STDIN:
            if len(body) == 0:
                stdin.write_eof()
            else:
                stdin.write(body)
        elif message_type == MESSAGE_SIGNAL:
            signal = int.from_bytes(body, "big", signed=False)
            print("Got signal", signal)
            process.send_signal(signal)
Example #6
0
    def _consume_in_subprocess(self, job, kwargs):
        params = dict(self.json_params())
        loop = job._loop

        transport, protocol = yield from loop.subprocess_exec(
            lambda: StreamProtocol(job),
            sys.executable,
            PROCESS_FILE,
            json.dumps(sys.path),
            json.dumps(params),
            job.task.serialise())
        process = Process(transport, protocol, loop)
        yield from process.communicate()
        if job.task.stacktrace:
            raise RemoteStackTrace
        return job.task.result
Example #7
0
async def wait_for_child_process(child: Process,
                                 timeout: int) -> Tuple[bytes, int, bool]:
    try:
        output, _ = await asyncio.wait_for(child.communicate(),
                                           timeout=timeout)
        timed_out = False
        returncode = child.returncode if child.returncode else 0
    except asyncio.TimeoutError:
        timed_out = True
        returncode = -9
        try:
            child.terminate()  # Give mpiexec a chance to shutdown
        except ProcessLookupError:
            pass
        output, _ = await child.communicate()

    return output, returncode, timed_out
Example #8
0
    async def _consume_in_subprocess(self, job, kwargs):
        params = dict(self.json_params())
        loop = job._loop

        transport, protocol = await loop.subprocess_exec(
            lambda: StreamProtocol(job), sys.executable, PROCESS_FILE,
            json.dumps(sys.path), json.dumps(params),
            json.dumps(job.task.tojson()))
        process = Process(transport, protocol, loop)
        await process.communicate()
        if job.task.stacktrace:
            raise RemoteStackTrace
        return job.task.result
Example #9
0
    async def binfo(self, ctx):

        #Defining the embed
        #And adding our github, bot's avatar, etc.
        stats = discord.Embed(
            title="<:github:741045521577279559> Spark ++'s Source Code",
            url="https://github.com/AndrewNunnes/Spark-Bot",
            timestamp=datetime.datetime.utcnow())
        stats.set_thumbnail(url=self.bot.user.avatar_url)
        stats.set_footer(text=f"Requested by {ctx.author}",
                         icon_url='{}'.format(ctx.author.avatar_url))

        # Grabbing technical statistics of the bot
        proc = Process()
        with proc.oneshot():
            uptime = datetime.timedelta(seconds=time() - proc.create_time())
            mem_total = virtual_memory().total / (1024**2)
            mem_of_total = proc.memory_percent()
            mem_usage = mem_total * (mem_of_total / 100)

        uptime_hours, uptime_remainder = divmod(uptime.seconds, 3600)
        uptime_minutes, uptime_seconds = divmod(uptime_remainder, 60)
        frmt_uptime = '{:01} Hour(s), {:01} Minute(s), {:01} Second(s)'.format(
            int(uptime_hours), int(uptime_minutes), int(uptime_seconds))

        # Grabbing total number of channels across all guilds in which the bot is present in
        channels = map(lambda m: len(m.channels), self.bot.guilds)

        # Setting up fields
        fields = [
            ("__*Developer*__", "Andrew Nunnes#1148", False),
            ("__*Language | Library*__",
             f"<:Python_Logo:741046229441708152> Python {python_version()} | <:discord:741045246435262482> Discord.py {discord_version}",
             False),
            ("__*<:discord:741045246435262482> Support Server*__",
             "[Here!](https://discord.com/invite/fkdW9hB)", True),
            ("__*<:invite:741045282929901678> Invite Link*__",
             "[Here!](https://discord.com/oauth2/authorize?client_id=721397896704163965&scope=bot&permissions=470117623)",
             True), ("__*❗ Current Prefix*__", f'`{ctx.prefix}`', True),
            ("__*Discord Stats*__", "All Guilds: {}"
             "\nAll Channels: {}"
             "\nAll Emojis: {}"
             "\nAll Commands: {}"
             "\nAll Users: {:,}".format(len(self.bot.guilds),
                                        sum(list(channels)),
                                        len(self.bot.emojis),
                                        len(self.bot.commands),
                                        len(self.bot.users)), True),
            ("__*Line Count*__", lineCount(), True),
            ("__*Uptime*__", frmt_uptime, False),
            ("__*Latency*__", f'{round(self.bot.latency * 1000)}ms', False),
            ("__*Memory Usage*__",
             f"{mem_usage:,.2f} / {mem_total:,.2f} MiB ({mem_of_total:.2f}%)",
             False)
        ]

        # Add fields to the embed
        for name, value, inline in fields:
            stats.add_field(name=name, value=value, inline=inline)

        await ctx.send(embed=stats)
Example #10
0
async def stop_tunnel(p: Process):
    if p:
        p.send_signal(signal.SIGTERM)
        await p.wait()
        logger.info('Tunnel stopped')