コード例 #1
0
 async def shell(self, ctx, *, cmd: str):
     """A system shell, does not support command persistance."""
     p = await asyncio.create_subprocess_shell(
         cmd,
         stdout=asyncio.subprocess.PIPE,
         stderr=asyncio.subprocess.PIPE)
     msg = await ctx.send("Executing...")
     try:
         stdout, stderr = (None, None)
         tbefore = time.perf_counter()
         stdout, stderr = await asyncio.wait_for(p.communicate(), 360)
         tafter = time.perf_counter()
     except asyncio.TimeoutError:
         log(content=f'Command "shell" timed out.')
         await msg.edit(content="Process timed out.")
     except asyncio.CancelledError:
         log(content="Process cancelled.")
         await msg.edit(content="Process cancelled.")
         await p.terminate()
     if p.stderr == None:
         await msg.edit(
             content=
             f"```py\nExit code: {p.returncode}\n{decode(stdout)}\nTook {round((tafter-tbefore)*1000, 2)}ms```"
         )
     else:
         await msg.edit(
             content=
             f"```py\nExit code: {p.returncode}\nStdout:\n{decode(stdout)}\nStderr:\n{decode(stderr)}\nTook {round((tafter-tbefore)*1000, 2)}ms```"
         )
コード例 #2
0
    async def on_command_error(self, ctx, e):
        #Check if command has custom error handler
        if self.extra_events.get('on_command_error', None):
            return
        if hasattr(ctx.command, 'on_error'):
            return
        cog = ctx.cog
        if cog:
            attr = '_{0.__class__.__name__}__error'.format(cog)
            if hasattr(cog, attr):
                return

        if await decheck(ctx, e):  #Check for default error
            return
        log(content="No custom error handler found, using default handler.")
        await sendError(ctx, e)
コード例 #3
0
 async def on_command_completion(self, ctx):
     log(ctx, 'general')
コード例 #4
0
import time
import subprocess

import core.helper as core

PRODUCTION_CHAIN = 'production.pkl'
CONSUMPTION_CHAIN = 'consumption.pkl'


def start_ewf_client():
    subprocess.Popen(["assets/ewf-client-arm", "--jsonrpc-apis", "all", "--reserved-peers", "assets/tobalaba-peers"],
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    print('waiting for ewf-client...\n\n')
    time.sleep(60)


if __name__ == '__main__':
    infinite = True
    while infinite:
        configuration = core.print_config()
        config = {
            "prod_chain_file": PRODUCTION_CHAIN,
            "cons_chain_file": CONSUMPTION_CHAIN,
            "configuration": configuration
        }
        core.log(**config)
        core.schedule(config)
コード例 #5
0
    async def prunemembers(self,
                           ctx,
                           days: int,
                           include_no_message: bool = False):
        """Prune inactive member (i.e. no message sent) given an inactive interval(days, minimum 1).
		Note that join/pin system message will also be considered as user's message.
		"""
        if days == 0 and include_no_message:
            await ctx.send("Pruning members with no message...")
        elif days < 1:
            await ctx.send(
                "Interval too short, minimum accepted interval is 1.")
            return
        elif days >= 1100:
            await ctx.send("Interval too long, please consider lowering it.")
            return
        no_activity_members = []
        inactive_members = []
        last_msgs = []
        status_msg_content = "Searching and collecting data, this could take some time..."
        status_msg = await ctx.send(status_msg_content)
        guild_members = ctx.guild.members
        for pos, member in enumerate(guild_members):
            if member.bot: continue
            for channel in ctx.guild.text_channels:
                try:
                    history = await channel.history().get(author__id=member.id)
                    if history is not None: last_msgs.append(history)
                except discord.errors.Forbidden:
                    pass
            while len(last_msgs) > 1:
                if last_msgs[0].created_at > last_msgs[
                        1].created_at:  # message is older
                    last_msgs.append(last_msgs[0])  # append to the last
                del last_msgs[0]
            last_msg = last_msgs[0] if last_msgs else None
            # for those didn't send a message
            if last_msg == None and include_no_message:
                no_activity_members.append(member)
            elif last_msg == None:
                continue
            elif (datetime.datetime.now() - last_msg.created_at).days > days:
                inactive_members.append(member)
            last_msgs.clear()
            # Progress
            if pos % 2 == 0:
                await status_msg.edit(
                    content=status_msg_content +
                    "\n{percentage}% ({current}/{total} processed)".format(
                        percentage=round((pos + 1) / len(guild_members) * 100),
                        current=pos + 1,
                        total=len(guild_members)))
        # status report
        await status_msg.edit(content=status_msg_content + "done")
        if no_activity_members:
            await ctx.send(
                "User that have no message in the server:\n{ulist}".format(
                    ulist='\n'.join(
                        ['- ' + str(m) for m in no_activity_members])))
        if inactive_members:
            await ctx.send(
                "User who haven’t sent any messages in the past {count} day{s}:\n{ulist}"
                .format(count=days,
                        s='s' if days > 1 else '',
                        ulist='\n'.join(
                            ['- ' + str(m) for m in inactive_members])))
        # Kicking
        rand = randint(1000, 9999)
        count = len(no_activity_members) + len(inactive_members)
        if count != 0:
            await ctx.send(
                "<@!{uid}> Are you sure you want to kick these {count} members?\nType `yes {rand}` or `(n)o` to cancel."
                .format(uid=ctx.author.id,
                        count=len(no_activity_members) + len(inactive_members),
                        rand=rand))
        else:
            await ctx.send(
                "{mention} There're currently no inactive user, good job!".
                format(mention=ctx.author.mention))
            return
        try:
            response = await self.bot.wait_for(
                'message',
                check=lambda msg: msg.author == ctx.author and msg.channel ==
                ctx.channel,
                timeout=120.0)
        except TimeoutError:
            await ctx.send("Timeout reached, task cancelled.")
        response.content = response.content.lower()
        if response.content == f"yes {rand}":
            kick_status = await ctx.send("Kicking users...")
            for m in no_activity_members:
                log(content=f"Kicking {m} (no activity)")
                await ctx.guild.kick(
                    m,
                    reason=
                    "Haven't send a single message in the server, requested by {member}."
                    .format(member=ctx.author))
            for m in inactive_members:
                log(content=f'Kicking {m} (inactive)')
                await ctx.guild.kick(
                    m,
                    reason=
                    "Haven't send a message in {days} days, requested by {member}."
                    .format(days=days, member=ctx.author))
            await kick_status.edit(content="Kicked out {count} users.".format(
                count=len(no_activity_members) + len(inactive_members)))
        elif response.content in ('n', 'no'):
            await ctx.send("Task aborted.")
        elif response.content in ('c', 'cancel'):
            await ctx.send("Task cancelled.")
        else:
            await ctx.send("Invalid response, task cancelled.")
コード例 #6
0
import subprocess
import time

import core.helper as core

JSON = 'configFun/local/producer.json'
RESIN_DEVICE_UUID = '734e348be116e254fcc7a6f46708e96a'
TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MzQwNTAsInVzZXJuYW1lIjoiZ2hfY2VyZWFsa2lsbCIsImVtYWlsIjoiZGVwcmF6ekBnbWFpbC5jb20iLCJjcmVhdGVkX2F0IjoiMjAxOC0wMi0xNVQxMDozMjozOC4wMTlaIiwiZmlyc3RfbmFtZSI6IlBhdWwiLCJsYXN0X25hbWUiOiJEZXBy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
        "--reserved-peers", "/Users/r2d2/software/ewf/tobalaba-reserved-peers"
    ],
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
    print('waiting for ewf-client...\n\n')
    time.sleep(60)


if __name__ == '__main__':
    configuration = core.print_config(JSON)
    core.log(configuration)
    # core.schedule(config)