コード例 #1
0
ファイル: base.py プロジェクト: matts1/PCsocDiscordBot-Python
 def tag_markup(cls):
     func_args = inspect.getargspec(
         cls.eval).args[1:] + [inspect.getargspec(cls.eval).varargs]
     if func_args[-1] is None: func_args.pop()
     prefix = cls.tag_prefix_list
     prefix[0] = PREFIX + prefix[0]
     return ' '.join(bold(code(item)) for item in prefix) + ' ' + \
            ' '.join(underline(code(cls.pprint.get(item, item))) for item in func_args)
コード例 #2
0
ファイル: tags.py プロジェクト: 1lann/PCSocBot
 def eval(self, name):
     user = self.from_name(name)
     if user is None:
         raise CommandFailure("User not found")
     tags = Tag.select_or_err(lambda x: x.user == int(user.id),
                              "User has no tags")
     return EmbedTable(fields=['Platform', 'Tag'],
                       table=[(x.platform.title(), x.tag) for x in tags],
                       colour=self.EMBED_COLOR,
                       user=user,
                       title="Tags for " + bold(user.name))
コード例 #3
0
ファイル: base.py プロジェクト: matts1/PCsocDiscordBot-Python
 def help(cls):
     if cls.subcommands:
         lines = [
             cls.desc, '',
             bold('Commands' if cls.__base__ == object else 'Subcommands')
         ]
         if cls.__base__ != object:
             lines = [cls.tag_markup] + lines
         for command in cls.subcommands.values():
             lines.append(command.tag_markup)
             lines.append(command.desc)
     else:
         lines = [cls.tag_markup, cls.desc]
     return '\n'.join(lines)
コード例 #4
0
ファイル: tags.py プロジェクト: 1lann/PCSocBot
 def eval(self, platform, tag):
     warning = ''
     if not select(count(t)
                   for t in Tag if t.platform == platform.lower())[:][0]:
         platforms = ', '.join(sorted(select(t.platform for t in Tag)[:]))
         warning = bold(
             'WARNING: creating a new platform. Please check that the platform doesn\'t already '
             'exist by another name.\n'
         ) + 'Current platforms are ' + platforms + '\n'
     Tag.create_or_update(user=self.user,
                          platform=platform.lower(),
                          tag=tag)
     return "%s%s added as %s tag for %s" % (warning, tag, platform.title(),
                                             self.name)
コード例 #5
0
ファイル: tags.py プロジェクト: 1lann/PCSocBot
 def eval(self, name, platform, tag):
     user = self.from_name(name)
     if user is None:
         raise CommandFailure("User not found")
     warning = ''
     if not select(count(t)
                   for t in Tag if t.platform == platform.lower())[:][0]:
         platforms = ', '.join(sorted(select(t.platform for t in Tag)[:]))
         warning = bold(
             'WARNING: creating a new platform. Please check that the platform doesn\'t already '
             'exist by another name.\n'
         ) + 'Current platforms are ' + platforms + '\n'
     Tag.create_or_update(user=int(user.id),
                          platform=platform.lower(),
                          tag=tag)
     return "%s%s added as %s tag for %s" % (warning, tag, platform.title(),
                                             user.name)
コード例 #6
0
ファイル: handler.py プロジェクト: TheMegaTB/TwixT
def main():
    parallel_games = 2
    rounds = 30
    if len(sys.argv) >= 2 and sys.argv[1]:
        rounds = int(sys.argv[1])

    boards, links, scores = reset(parallel_games)

    times = []
    finished_games = np.zeros(parallel_games, dtype=bool)
    for gid in range(parallel_games):
        for i in range(rounds):
            if not finished_games[gid]:
                start = timer()
                boards[gid], links[gid], scores[gid], finished_games[gid] \
                    = next_round(boards[gid], links[gid], scores[gid])
                times.append(timer() - start)
        if config.PRINT_BOARDS and parallel_games < config.PRINT_THRESHOLD:
            h.print_board(boards[gid])

    times = times[1:]  # Exclude the first round to prevent the time the JIT compilation takes to falsify the stats
    total_time = 0
    for i in range(len(times)):
        total_time += times[i]

    # ------------------------------------------------- STATS PRINTING -------------------------------------------------
    if config.PRINT_STATS:
        stats_header = "Simulated " + h.bold(str(parallel_games)) + " games with a total of " + h.bold(
            str(parallel_games * rounds)) + " rounds."

        spaces = " " * int((103 - len(stats_header)) / 1.5)
        stats_header = spaces + stats_header + spaces

        print('\n' * 2)

        print(stats_header)

        print("-------------------------------------------------------------------------------------------------------")

        print("Total time: " + '\033[1m' + str(total_time * 1000) + " milliseconds" + '\033[0m')
        print("Average time per round: " + '\033[1m' + str(np.mean(times) * 1000 * 1000) + " microseconds" + '\033[0m')
        print("-------------------------------------------------------------------------------------------------------")
        print("              (All times exclude the first round to compensate for the JIT compiler)")

        print('\n' * 2)
コード例 #7
0
ファイル: base.py プロジェクト: matts1/PCsocDiscordBot-Python
class Command(metaclass=Tree):
    roles_required = None
    db_required = False
    desc = bold(
        'PCSocBot'
    ) + ' - PC Enthusiasts society Discord bot made with discord.py by Matt Stark'
    pprint = {}

    @classproperty
    def name(cls):
        return cls.__name__.lower()

    def __init__(self, client, message):
        self.client = client
        self.message = message
        self.user = message.author.id
        self.name = message.author.name
        self.members = message.server.members

    async def init(self, *args):
        argspec = inspect.getargspec(self.eval)
        if len(argspec.args) == len(args) + 1 or argspec.varargs:
            try:
                self.check_permissions()
                self.output = await self.eval(
                    *args) if inspect.iscoroutinefunction(
                        self.eval) else self.eval(*args)
            except CommandFailure as e:
                self.output = e.args[0]
        elif self.tag_prefix_list:
            self.output = "Invalid usage of command. Usage:\n" + self.tag_markup
        else:
            self.output = "Invalid command\n" + self.help
        return self.output

    def eval(self):
        return self.help

    @classproperty
    def tag_prefix_list(cls):
        if cls.__base__ == object:
            return []
        return cls.__base__.tag_prefix_list + [cls.name]

    @classproperty
    def tag_markup(cls):
        func_args = inspect.getargspec(
            cls.eval).args[1:] + [inspect.getargspec(cls.eval).varargs]
        if func_args[-1] is None: func_args.pop()
        prefix = cls.tag_prefix_list
        prefix[0] = PREFIX + prefix[0]
        return ' '.join(bold(code(item)) for item in prefix) + ' ' + \
               ' '.join(underline(code(cls.pprint.get(item, item))) for item in func_args)

    @classproperty
    def help(cls):
        if cls.subcommands:
            lines = [
                cls.desc, '',
                bold('Commands' if cls.__base__ == object else 'Subcommands')
            ]
            if cls.__base__ != object:
                lines = [cls.tag_markup] + lines
            for command in cls.subcommands.values():
                lines.append(command.tag_markup)
                lines.append(command.desc)
        else:
            lines = [cls.tag_markup, cls.desc]
        return '\n'.join(lines)

    def get_member(self, id):
        return discord.utils.get(self.members, id=str(id))

    def check_permissions(self):
        if self.roles_required is not None:
            for role in self.message.author.roles:
                if role.name.lower() in self.roles_required:
                    return
            raise CommandFailure("You need to be a %s to use that command" % \
                                 " or ".join(self.roles_required))

    audio_playing = False

    async def play_audio(self, file):
        channel = self.message.author.voice_channel
        if channel is None:
            raise CommandFailure(
                "You need to join a voice channel to use this command")
        if Command.audio_playing:
            raise CommandFailure("Can only play one audio file at once")
        Command.audio_playing = True  # coroutines, no mutex required
        voice = await self.client.join_voice_channel(channel)
        player = voice.create_ffmpeg_player('files/' + file)

        player.start()
        duration = MP3('files/' + file).info.length
        await asyncio.sleep(duration)
        await voice.disconnect()
        Command.audio_playing = False