Example #1
0
    async def set_event(self, schema_name: str, save_to_config=True):
        """Set the current CoNDOR event

        Parameters
        ----------
        schema_name: str
            The schema name for the league
        save_to_config: bool
            Whether to make this the default league, i.e., save the schema name to the bot's config file

        Raises
        ------
        necrobot.database.leaguedb.LeagueDoesNotExist
            If the schema name does not refer to a registered league
        """
        if not await condordb.is_condor_event(Config.LEAGUE_NAME):
            raise necrobot.exception.SchemaDoesNotExist('Schema "{0}" does not exist.'.format(schema_name))

        self._event = await condordb.get_event(schema_name=schema_name)
        dbutil.league_schema_name = schema_name
        MatchGlobals().set_deadline_fn(lambda: self.deadline())

        if save_to_config:
            Config.LEAGUE_NAME = schema_name
            Config.write()
Example #2
0
    async def _do_execute(self, cmd):
        debug_str = ''
        if Config.debugging():
            debug_str = ' (DEBUG)'
        elif Config.testing():
            debug_str = ' (TEST)'

        await cmd.channel.send(
            'Necrobot v-{0}{1}. Type `.help` for a list of commands.'.format(
                Config.BOT_VERSION, debug_str))
Example #3
0
    async def set_league(schema_name: str, save_to_config=True):
        """Set the current league
        
        Parameters
        ----------
        schema_name: str
            The schema name for the league
        save_to_config: bool
            Whether to make this the default league, i.e., save the schema name to the bot's config file
    
        Raises
        ------
        necrobot.database.leaguedb.LeagueDoesNotExist
            If the schema name does not refer to a registered league
        """
        necrobot.league.the_league.league = await leaguedb.get_league(schema_name)

        if save_to_config:
            Config.LEAGUE_NAME = schema_name
            Config.write()
Example #4
0
    async def _do_execute(self, cmd):
        args = cmd.args
        # List commands
        if len(args) == 0:
            command_list_text = ''
            cmds_to_show = []
            for cmd_type in self.bot_channel.all_commands:
                if cmd_type.show_in_help \
                        and (not cmd_type.admin_only or self.bot_channel.is_admin(cmd.author)) \
                        and (not cmd_type.testing_command or Config.testing()):
                    cmds_to_show.append(cmd_type)

            if not cmds_to_show:
                await cmd.channel.send(
                    'No commands available in this channel.'
                )
                return

            cmds_to_show = sorted(
                cmds_to_show,
                key=lambda c: ('_' if not c.admin_only else '') + c.command_name
            )
            cutoff = 1900 // len(cmds_to_show)
            for cmd_type in cmds_to_show:
                this_cmd_text = '\n`{2}{0}` -- {1}'.format(
                    cmd_type.mention,
                    cmd_type.short_help_text,
                    '[A] ' if cmd_type.admin_only else ''
                )
                command_list_text += this_cmd_text[:cutoff]

            await cmd.channel.send(
                'Command list: {0}\n\nUse `{1} command` for more info about a '
                'particular command.'.format(command_list_text, self.mention)
            )

        # Get help text for a particular command
        elif len(args) == 1:
            for cmd_type in self.bot_channel.all_commands:
                if cmd_type.called_by(args[0]):
                    alias_str = ''
                    for alias in cmd_type.command_name_list[1:]:
                        alias_str += '`{alias}`, '.format(alias=Config.BOT_COMMAND_PREFIX + alias)
                    if alias_str:
                        alias_str = '(Aliases: {})'.format(alias_str[:-2])
                    await cmd.channel.send(
                        '`{cmd_name}`: {admin}{help_text} {aliases}'.format(
                            cmd_name=cmd_type.mention,
                            help_text=cmd_type.help_text,
                            admin='[Admin only] ' if cmd_type.admin_only else '',
                            aliases=alias_str
                        )
                    )
Example #5
0
        async def on_message(message: discord.Message):
            """Called whenever a new message is posted in any channel on any server"""
            if not self._initted:
                return

            if Config.testing():
                await msgqueue.send_message(message)

            if message.author.id == self.client.user.id:
                return

            cmd = Command(message)
            await self._execute(cmd)
Example #6
0
    async def create_league(schema_name: str, save_to_config=True):
        """Registers a new league
        
        Parameters
        ----------
        schema_name: str
            The schema name for the league
        save_to_config: bool
            Whether to make this the default league, i.e., save the schema name to the bot's config file
    
        Raises
        ------
        necrobot.database.leaguedb.LeagueAlreadyExists
            If the schema name refers to a registered league
        necrobot.database.leaguedb.InvalidSchemaName
            If the schema name is not a valid MySQL schema name
        """
        necrobot.league.the_league.league = await leaguedb.create_league(schema_name)

        if save_to_config:
            Config.LEAGUE_NAME = schema_name
            Config.write()
Example #7
0
    async def set_league(cls, schema_name: str, save_to_config=True):
        """Set the current league
        
        Parameters
        ----------
        schema_name: str
            The schema name for the league
        save_to_config: bool
            Whether to make this the default league, i.e., save the schema name to the bot's config file
    
        Raises
        ------
        necrobot.database.leaguedb.LeagueDoesNotExist
            If the schema name does not refer to a registered league
        """
        cls._the_league = await leaguedb.get_league(schema_name)
        dbutil.league_schema_name = schema_name

        MatchGlobals().set_deadline_fn(LeagueMgr.deadline)

        if save_to_config:
            Config.LEAGUE_NAME = schema_name
            Config.write()
Example #8
0
    async def create_event(self, schema_name: str, save_to_config=True):
        """Registers a new CoNDOR event

        Parameters
        ----------
        schema_name: str
            The schema name for the event
        save_to_config: bool
            Whether to make this the default event, i.e., save the schema name to the bot's config file

        Raises
        ------
        necrobot.database.leaguedb.SchemaAlreadyExists
            If the schema name already exists in the database
        necrobot.database.leaguedb.InvalidSchemaName
            If the schema name is not a valid MySQL schema name
        """
        self._event = await condordb.create_event(schema_name)
        dbutil.league_schema_name = schema_name

        if save_to_config:
            Config.LEAGUE_NAME = schema_name
            Config.write()
Example #9
0
    async def execute(self, cmd: Command) -> None:
        """If the Command's command is this object's command, calls the (virtual) method _do_execute on it

        Parameters
        ----------
        cmd: Command
            The command to maybe execute.
        """
        if cmd.command in self.command_name_list \
                and ((not self.admin_only) or self.bot_channel.is_admin(cmd.author)) \
                and (not self.testing_command or Config.testing()):
            async with self.execution_id_lock:
                self.execution_id += 1
                this_id = self.execution_id

            if isinstance(cmd.channel, discord.TextChannel):
                # noinspection PyUnresolvedReferences
                channel_name = cmd.channel.name
            elif isinstance(cmd.channel, discord.DMChannel):
                # noinspection PyUnresolvedReferences
                channel_name = 'DM-{}'.format(
                    cmd.channel.recipient.display_name)
            else:
                channel_name = "<Unknown channel>"

            console.info(
                'Call {0}: <ID={1}> <Caller={2}> <Channel={3}> <Message={4}>'.
                format(
                    type(self).__name__, this_id, cmd.author.name,
                    channel_name, cmd.content))

            try:
                await self._do_execute(cmd)
                console.info('Exit {0}: <ID={1}>'.format(
                    type(self).__name__, this_id))
            except Exception as e:
                console.warning(
                    'Error exiting {name} <ID={id}>: {error_msg}'.format(
                        name=type(self).__name__,
                        id=this_id,
                        error_msg=repr(e)))
                asyncio.ensure_future(
                    cmd.channel.send(
                        "Unexpected error while executing command `{mention}`."
                        .format(mention=self.mention)))
                raise
Example #10
0
    def __enter__(self):
        if DBConnect._db_connection is None:
            DBConnect._db_connection = mysql.connector.connect(
                user=Config.MYSQL_DB_USER,
                password=Config.MYSQL_DB_PASSWD,
                host=Config.MYSQL_DB_HOST,
                database=Config.MYSQL_DB_NAME)
        elif not DBConnect._db_connection.is_connected():
            DBConnect._db_connection.reconnect()

        if not DBConnect._db_connection.is_connected():
            raise RuntimeError('Couldn\'t connect to the MySQL database.')

        if Config.debugging():
            self.cursor = LoggingCursor(DBConnect._db_connection.cursor())
        else:
            self.cursor = DBConnect._db_connection.cursor()
        return self.cursor
Example #11
0
    async def execute(self, command: Command) -> None:
        """If the Command's command is this object's command, calls the (virtual) method _do_execute on it
        
        Parameters
        ----------
        command: Command
            The command to maybe execute.
        """
        if command.command in self.command_name_list \
                and ((not self.admin_only) or self.bot_channel.is_admin(command.author)) \
                and (not self.testing_command or Config.testing()):
            async with self.execution_id_lock:
                self.execution_id += 1
                this_id = self.execution_id

            console.info(
                'Call {0}: <ID={1}> <Caller={2}> <Channel={3}> <Message={4}>'.
                format(
                    type(self).__name__, this_id, command.author.name,
                    command.channel.name, command.content))
            await self._do_execute(command)
            console.info('Exit {0}: <ID={1}>'.format(
                type(self).__name__, this_id))
Example #12
0
    async def execute(self, command: Command) -> None:
        """If the Command's command is this object's command, calls the (virtual) method _do_execute on it
        
        Parameters
        ----------
        command: Command
            The command to maybe execute.
        """
        if command.command in self.command_name_list \
                and ((not self.admin_only) or self.bot_channel.is_admin(command.author)) \
                and (not self.testing_command or Config.testing()):
            async with self.execution_id_lock:
                self.execution_id += 1
                this_id = self.execution_id

            console.info(
                'Call {0}: <ID={1}> <Caller={2}> <Channel={3}> <Message={4}>'.
                format(
                    type(self).__name__, this_id, command.author.name,
                    command.channel.name, command.content))

            try:
                await self._do_execute(command)
                console.info('Exit {0}: <ID={1}>'.format(
                    type(self).__name__, this_id))
            except Exception as e:
                console.warning(
                    'Error exiting {name} <ID={id}>: {error_msg}'.format(
                        name=type(self).__name__,
                        id=this_id,
                        error_msg=repr(e)))
                asyncio.ensure_future(
                    self.client.send_message(
                        command.channel,
                        "Unexpected error while executing command `{mention}`."
                        .format(mention=self.mention)))
                raise
Example #13
0
 def show_in_help(self) -> bool:
     """If False, this command type will not show up in the .help list"""
     return not self.testing_command or Config.testing()