Пример #1
0
    def __init__(self, *args, cogs, config, **kwargs):

        super().__init__(*args, **kwargs)

        self.add_command(commands.Command(
            self.load,
            brief='Load an extension',
        ))
        self.add_command(commands.Command(
            self.unload,
            brief='Unload an extension',
        ))
        self.add_command(commands.Command(
            self.reload,
            brief='Reload an extension',
        ))
        self.add_command(commands.Command(
            self.ping,
            brief='Check in on Nic',
        ))
        self.add_command(commands.Command(
            self.say,
            brief='Have Nic repeat what you say',
        ))

        self.config = Configuration(config)

        self.database = db.Database(self)

        self.cogs_location = cogs
        for filename in os.listdir(self.cogs_location):
            if filename.endswith('.py'):
                self.load_extension(f'cogs.{filename[:-3]}')

        self.roles = {}
Пример #2
0
    def __init__(self, bot):
        super().__init__()
        self.bot = bot

        for name in self.bot.markov_chains.keys():
            self.bot.add_command(commands.Command(self.get_name_guess_func(name), name=name))
            self.bot.add_command(commands.Command(self.get_line_func(name), name=f"Line {name}",))
        self.bot.add_command(commands.Command(self.get_skip(), name="Je passe"))
Пример #3
0
 def build_privacy_policy_command(self) -> commands.Command:
     ## Manually build command to be added
     return commands.Command(
         self.privacy_policy,
         name="privacy_policy",
         help=f"Gives the user a link to {self.name}'s privacy policy.",
         hidden=True)
Пример #4
0
def auto_help(func):
    """Automatically registers a help command for this group."""
    if not isinstance(func, commands.Group):
        raise TypeError('Auto help can only be applied to groups.')
    cmd = commands.Command(_call_help, name='help', hidden=True)
    func.add_command(cmd)
    return func
Пример #5
0
def setup(bot: aoi.AoiBot) -> None:
    fun = Fun(bot)

    async def exec_customcmd(_, ctx: aoi.AoiContext, user: discord.Member):
        command = ctx.command.name
        await ctx.embed(
            title=random.choice(fun.custom_reactions[command].responses)
                .replace("{user}", ctx.author.display_name)  # noqa
                .replace("{target}", user.display_name),
            image=random.choice(fun.custom_reactions[command].images)
        )

    bot.add_cog(fun)

    with open("loaders/custreact.yaml") as fp:
        doc = YAML().load(fp)
        for key in doc:
            fun.custom_reactions[key] = CustomReaction(doc[key]["responses"], doc[key]["images"])

            cmd = commands.Command(
                name=key,
                func=exec_customcmd,
                brief=f"{key} custom command",
            )

            cmd.cog = fun

            fun.bot.add_command(cmd)

            fun.__cog_commands__ += (cmd,)
Пример #6
0
    def init_phrases(self):
        phrase_file_paths = self.scan_phrases(self.phrases_folder_path)
        counter = 0
        for phrase_file_path in phrase_file_paths:
            starting_count = counter
            phrase_group = self._build_phrase_group(phrase_file_path)

            for phrase in self.load_phrases(phrase_file_path):
                try:
                    self.add_phrase(phrase)
                    phrase_group.add_phrase(phrase)
                except Exception as e:
                    utilities.debug_print(e, "Skipping...", debug_level=2)
                else:
                    counter += 1

            ## Ensure we don't add in empty phrase files into the groupings
            if(counter > starting_count):
                self.phrase_groups[phrase_group.key] = phrase_group

                ## Set up a dummy command for the category, to help with the help interface. See help_formatter.py
                help_command = commands.Command(phrase_group.key, lambda noop: None, hidden=True, no_pm=True)
                self.bot.add_command(help_command)
                self.command_names.append(phrase_group.key) # Keep track of the 'parent' commands for later use

        print("Loaded {} phrase{}.".format(counter, "s" if counter != 1 else ""))
        return counter
Пример #7
0
def auto_help(func):
    if not isinstance(func, commands.Group):
        raise TypeError("bad deco order")

    cmd = commands.Command(_call_help, name="help", hidden=True)
    func.add_command(cmd)
    return func
Пример #8
0
    def init_phrases(self):
        phrase_file_paths = self.scan_phrases(self.phrases_folder_path)
        counter = 0
        for phrase_file_path in phrase_file_paths:
            starting_count = counter
            phrase_group = self._build_phrase_group(phrase_file_path)

            for phrase in self.load_phrases(phrase_file_path):
                try:
                    self.add_phrase(phrase)
                    phrase_group.add_phrase(phrase)
                except Exception as e:
                    logger.warning("Skipping...", e)
                else:
                    counter += 1

            ## Ensure we don't add in empty phrase files into the groupings
            if(counter > starting_count):
                self.phrase_groups[phrase_group.key] = phrase_group

                ## Set up a dummy command for the category, to help with the help interface. See help_formatter.py
                ## asyncio.sleep is just a dummy command since commands.Command needs some kind of async callback
                help_command = commands.Command(self._create_noop_callback(), name=phrase_group.key, hidden=True, no_pm=True)
                self.bot.add_command(help_command)
                self.command_names.append(phrase_group.key) # Keep track of the 'parent' commands for later use

        logger.info("Loaded {} phrase{}.".format(counter, "s" if counter != 1 else ""))
        return counter
Пример #9
0
    def _make_commands(self):
        group = commands.Group(
            name=self.service_name,
            callback=self._group_command,
            help=self._make_help_string(strings.group_command_help),
        )
        group.instance = self
        cmd = commands.Command(
            name='add',
            aliases=['subscribe'],
            callback=self._add_command,
            help=self._make_help_string(strings.add_command_help),
        )
        cmd.instance = self
        group.add_command(cmd)
        cmd = commands.Command(
            name='del',
            aliases=['unsubscribe', 'remove', 'delete'],
            callback=self._del_command,
            help=self._make_help_string(strings.del_command_help),
        )
        cmd.instance = self
        group.add_command(cmd)
        cmd = commands.Command(
            name='list',
            callback=self._list_command,
            help=self._make_help_string(strings.list_command_help),
        )
        cmd.instance = self
        group.add_command(cmd)
        cmd = commands.Command(
            name='enable',
            callback=self._enable_command,
            help=self._make_help_string(strings.enable_command_help),
        )
        cmd.instance = self
        group.add_command(cmd)
        cmd = commands.Command(
            name='disable',
            callback=self._disable_command,
            help=self._make_help_string(strings.disable_command_help),
        )
        cmd.instance = self
        group.add_command(cmd)

        return group
Пример #10
0
    def gen_command(name, text):
        async def func(ctx):
            await ctx.send(text)

        return commands.Command(name,
                                func,
                                help='This is a custom, static, command.',
                                hidden=True)
Пример #11
0
    def gen_command(name, text):
        # noinspection PyUnusedLocal
        async def func(ctx, *, args: commands.clean_content = '\u200b'):
            await ctx.send(eval(f"f\"{text}\""))

        return commands.Command(name,
                                func,
                                help='This is a custom, static, command.',
                                hidden=True)
Пример #12
0
    def create_customs(self):
        for item in self.data:
            group = commands.Group(self.group_callback(item),
                                   name=item["name"].replace(
                                       " ", "-").lower().strip(),
                                   aliases=item["aliases"],
                                   invoke_without_command=True,
                                   case_insensitive=True,
                                   help="Info about " + item["name"])

            reddit = commands.Command(self.reddit_callback(item),
                                      name="reddit",
                                      aliases=["subreddit", "r", "sub"])
            group.add_command(reddit)

            github = commands.Command(self.github_callback(item),
                                      name="github",
                                      aliases=["git", "gh"])
            group.add_command(github)

            page = commands.Command(self.page_callback(item),
                                    name="page",
                                    aliases=[
                                        "url", "product", "site", "website",
                                        "jb", "jetbrains", "link"
                                    ])
            group.add_command(page)

            issue = commands.Command(self.issue_callback(item),
                                     name="issue",
                                     aliases=[
                                         "issues", "track", "tracker",
                                         "youtrack", "yt", "bug", "bugs",
                                         "report", "reports"
                                     ])
            group.add_command(issue)

            channel = commands.Command(
                self.channel_callback(item),
                name="channel",
                aliases=["chan", "chat", "text", "discord"])
            group.add_command(channel)

            self.add_command(group)
Пример #13
0
def api_list(bot, url):
    r = requests.get(url)
    resp = r.json()
    for endpoint in resp:
        function = make_command(endpoint)
        new_cmd = commands.Command(
            function,
            name=endpoint['name']
        )
        bot.add_command(new_cmd)
Пример #14
0
    def __init__(self, bot):
        self.bot: commands.Bot = bot
        if not os.path.isfile('./config/simple_command.json'):
            with open('./config/simple_command.json', 'w+') as outfile:
                data = {"commands": {"command_name": {"command_content": "Hello", "command_color": {"r": 255, "g": 0, "b": 0}}}}
                json.dump(data, outfile, indent=4)
        self.config = json.load(open('./config/simple_command.json', 'r'))

        for command in self.config['commands']:
            self.bot.add_command(commands.Command(self.simple_command, name=command))
        print("Simple_command %s extension loaded" % __version__)
Пример #15
0
 def get_message_alias(self, fixed_message_id):
     async def closure(ctx):
         await ctx.bot.get_command("message").callback(self, ctx, fixed_message_id)
     self.bot.add_command(commands.Command(
         brief="Show the '{}' message".format(fixed_message_id),
         name=fixed_message_id,
         description="description",
         usage="",
         help="help",
         func=closure
     ))
Пример #16
0
 def __init__(self, reddit_scraper, personal_picks_scraper):
     self.reddit_scraper = reddit_scraper
     self.personal_picks_scraper = personal_picks_scraper
     super().__init__(command_prefix="!", help_command=None)
     self.add_command(
         commands.Command(self.help,
                          name='help',
                          help='Shows this help message'))
     self.add_command(
         commands.Command(
             self.meme,
             name='meme',
             help='Responds with one of the internet\'s finest memes'))
     self.add_command(
         commands.Command(
             self.doman,
             name='doman',
             help=
             'Responds with a video from Johnathan Doman\'s Personal Picks')
     )
     self.log('Created Meme Bot')
Пример #17
0
    def _load_internal_commands(self):
        # add all of the predefined commands to the bot.
        all_cmds = []
        for cmd in cmds.__all__:
            all_cmds += importlib.import_module('cmds.{}'.format(cmd)).export
        for cmd in all_cmds:
            self._load_checks(cmd)

            new_cmd = commands.Command(cmd['function'],
                                       name=cmd['name'],
                                       checks=self._load_checks(cmd))
            self.bot.add_command(new_cmd)
Пример #18
0
    def __init__(self, bot: commands.Bot):
        self.bot = bot

        self.__authors__ = __authors__
        self.__maintainers__ = __maintainers__
        self.__level__ = __level__

        command = bot.get_command("help")
        self.old_help = commands.Command(command.callback,
                                         name="help",
                                         hidden=True)

        bot.remove_command("help")
Пример #19
0
 def set_library(self, library):
     """
     Carga una librería de sonidos en el bot
     """
     if getattr(self, 'library', False):
         for name in self.library.keys():
             self.remove_command(name)
     self.library = library
     for key, value in self.library.items():
         command = commands.Command(self.play_name,
                                    name=key,
                                    help=value['desc'])
         self.add_command(command)
Пример #20
0
    def __init__(self, bot):
        self._bot = bot
        self._conn = aiohttp.TCPConnector(limit=1)
        self._session = aiohttp.ClientSession()
        self._list = reader(f"{_dir}/list")

        self._bookstores = reader(f"{_dir}/bookstores")
        self._dining = reader(f"{_dir}/dining")
        self._libraries = reader(f"{_dir}/libraries")
        self._post_offices = reader(f"{_dir}/post_offices")

        self._loc_conditions = reader(f"{_dir}/loc_conditions")

        # I'd like to use this but POST requests make it dumb
        self._dining_oids = reader(f"{_dir}/dining_oids")

        self._bookstore_hours = hours_reader(f"{_dir}/bookstore_hours")
        self._post_office_hours = hours_reader(f"{_dir}/post_office_hours")

        # Swapped unit commands
        for loc in self._dining:
            command = commands.Command(
                self.hours_from_dining(loc),
                name=loc,
                help=f"Alias for ~hours {loc} and ~menu {loc}.",
                usage=f"hours [day=today]\n"
                f"~{loc} menu [day=today] [menu=next]\n"
                f"~{loc} menu [day] [meal=all]",
                hidden=True)
            command.after_invoke(self.hours_reset)
            self._bot.add_command(command)

        for loc in self._libraries:
            command = commands.Command(self.hours_from_library(loc),
                                       name=loc,
                                       help=f"Alias for ~hours {loc}.",
                                       usage=f"hours [day=today]\n",
                                       hidden=True)
            self._bot.add_command(command)
Пример #21
0
    def __init__(self, bot):
        self.bot: commands.Bot = bot
        if not os.path.isfile('./config/better_help_command.json'):
            with open('./config/better_help_command.json', 'w+') as outfile:
                data = {'enable_better_help_command': True}
                json.dump(data, outfile, indent=4)
        self.config = json.load(open('./config/better_help_command.json', 'r'))

        if self.config['enable_better_help_command']:
            self.bot.remove_command('help')
            self.bot.add_command(
                commands.Command(self.help_command, name="help"))
        print("Better_help_command %s extension loaded" % __version__)
Пример #22
0
    def add_phrase(self, phrase: Phrase):
        '''Adds a phrase command to the bot's command list.'''

        ## Manually build command to be added
        command = commands.Command(self._create_phrase_callback(
            phrase.message, phrase.is_music),
                                   name=phrase.name,
                                   **phrase.kwargs,
                                   **self.command_kwargs)
        ## Ensure that this command is linked to the Phrases cog
        command.cog = self

        self.bot.add_command(command)
Пример #23
0
    def _try_add_help(self):
        try:

            async def _help_subcommand(ctx):
                await ctx.send_help(ctx.command.parent)

            cmd = _commands.Command(
                _help_subcommand,
                name='--help',
                aliases=['-h'],
                help=f"Get help for the `{self.qualified_name}` command.")
            self.add_command(cmd)

        except _commands.CommandRegistrationError:
            pass
Пример #24
0
    def add_phrase(self, phrase):
        if(not isinstance(phrase, Phrase)):
            raise TypeError("{} not instance of Phrase.".format(phrase))

        ## Manually build command to be added
        command = commands.Command(
            self._create_phrase_callback(phrase.message, phrase.is_music),
            name = phrase.name,
            **phrase.kwargs,
            **self.command_kwargs
        )
        ## Ensure that this command is linked to the Phrases cog
        command.cog = self

        self.bot.add_command(command)
Пример #25
0
    def add_clip(self, clip):
        if (not isinstance(clip, Clip)):
            raise TypeError("{} not instance of Clip.".format(clip))

        ## Manually build command to be added
        command = commands.Command(self._create_clip_callback(clip.path),
                                   name=clip.name,
                                   **clip.kwargs,
                                   **self.command_kwargs)
        ## _clip_callback doesn't have an instance linked to it,
        ## (not technically a method of Clips?) so manually insert the correct instance anyway.
        ## This also fixes the broken category label in the default help page.
        command.instance = self

        self.bot.add_command(command)
Пример #26
0
 def __new__(cls, *args, **kwargs):
     self = super().__new__(cls)
     files = os.listdir("data/social/")
     loaded_commands = list(cls.__cog_commands__)
     for file in files:
         description = f"send a {file.replace('.json', '')} to a user or to yourself"
         new_command = commands.Command(make_social_command(self, file),
                                        name=file.replace(".json", ""),
                                        hidden=False,
                                        cog=self,
                                        description=description,
                                        help=description)
         loaded_commands.append(new_command)
     self.__cog_commands__ = tuple(loaded_commands)
     return self
Пример #27
0
    def __add_bible_commands(self, command: str, name: str, /) -> None:
        lookup = commands.Command(
            Bible.__version_lookup,
            name=command,
            brief=f'Look up a verse in {name}',
            help=_version_lookup_help.format(prefix='{prefix}', command=command),
            hidden=True,
            # Share cooldown across commands
            cooldown=self._user_cooldown,
        )
        lookup.cog = self
        search = commands.Command(
            Bible.__version_search,
            name=f's{command}',
            brief=f'Search in {name}',
            help=_version_search_help.format(prefix='{prefix}', command=f's{command}'),
            hidden=True,
            # Share cooldown across commands
            cooldown=self._user_cooldown,
        )
        search.cog = self

        self.bot.add_command(lookup)
        self.bot.add_command(search)
Пример #28
0
    def command(self, bot_or_group, function, error_handler=None, **kwargs):
        """
        Adds a command to the specified bot or group. Uses
        `discord.ext.commands.Command` to wrap the `function` handler, all extra
        `**kwargs` are passed through. If no error handler is specified, the
        default one is attached.
        """
        command_obj = commands.Command(function, **kwargs)

        if error_handler is None:
            error_handler = self.default_error

        command_obj.error(error_handler)
        bot_or_group.add_command(command_obj)

        return command_obj
Пример #29
0
    def __init__(self, db, **kwargs):
        super().__init__(command_prefix=self.prefix_resolver,
                         owner_id=OWNER_ID,
                         description=DESCRIPTION,
                         help_command=EditedMinimalHelpCommand(),
                         max_messages=20000,
                         activity=BOT_ACTIVITY,
                         **kwargs)

        self.db = db
        self.config = ConfigTable(self,
                                  table='config',
                                  primary='guild_id',
                                  record_class=GuildConfigRecord)

        self.ready = asyncio.Event()
        self.startup_time = datetime.utcnow()

        aiohttp_log = logging.getLogger('aiotrace')

        async def on_request_end(session, ctx, end):
            resp = end.response
            aiohttp_log.info('[%s %s] %s %s (%s)', str(resp.status),
                             resp.reason, end.method.upper(), end.url,
                             resp.content_type)

        trace_config = aiohttp.TraceConfig()
        trace_config.on_request_end.append(on_request_end)

        self.aiohttp = aiohttp.ClientSession(
            loop=self.loop,
            timeout=aiohttp.ClientTimeout(total=5),
            trace_configs=[trace_config],
        )

        self.modified_times = dict()

        # help command. this is messy but it has to be because the lib doesn't really like you having
        # two different help commands. maybe I will see if I can clean this up in the future
        self.static_help_command = self.help_command
        command_impl = self.help_command._command_impl
        self.help_command = PaginatedHelpCommand()
        self.static_help_command._command_impl = command_impl

        self.remove_command('help')
        self.add_command(commands.Command(self._help, name='help'))
Пример #30
0
    def add_phrase(self, phrase):
        if(not isinstance(phrase, Phrase)):
            raise TypeError("{} not instance of Phrase.".format(phrase))

        ## Manually build command to be added
        command = commands.Command(
            phrase.name,
            self._create_phrase_callback(phrase.message, phrase.is_music),
            **phrase.kwargs,
            **self.command_kwargs
        )
        ## _phrase_callback doesn't have an instance linked to it, 
        ## (not technically a method of Phrases?) so manually insert the correct instance anyway.
        ## This also fixes the broken category label in the help page.
        command.instance = self

        self.bot.add_command(command)