コード例 #1
0
    async def sendactive(self, ctx, *, texts):
        """
            {command_prefix}sendactive [text]

        Sends a text to all my current voice users.
        @users will notify every members in the voice channel.
        """
        playing = self.bot.lavalink.players.find_all(lambda p: p.is_playing)

        for p in playing:
            channel = self.bot.get_channel(p.channel)
            if channel:
                log.info(
                    f"Send to {channel.guild} members in voice : {[g.name for g in p.connected_channel.members]}")
                try:
                    if "@users" in texts:
                        msg = texts.replace("@users", ' '.join(
                            [m.mention for m in p.connected_channel.members if not m.bot]))
                        await channel.send(msg)
                    elif "@user" in texts:
                        msg = texts.replace("@user", ' '.join(
                            [m.mention for m in p.connected_channel.members if not m.bot]))
                        await channel.send(msg)
                    else:
                        await channel.send(texts)
                except discord.Forbidden:
                    pass
                except discord.HTTPException:
                    pass
コード例 #2
0
    async def on_message(self, message):

        if not self.init_ok:
            return

        if message.author.bot:
            return

        if message.guild and not message.guild.me:  # should not happen no ?
            return

        if message.content in [f"<@!{self.user.id}>", self.user.mention]:
            message.content += " prefix now"

        prefixes = _prefix_callable(self, message)
        if not any(message.content.startswith(prefix) for prefix in prefixes):
            return

        for prefix in prefixes:
            if message.content.startswith(prefix):
                cmd_prefix = prefix  # Get the used prefix
                break

        if not isinstance(message.channel, discord.abc.PrivateChannel):
            settings = await SettingsDB.get_instance().get_guild_settings(
                message.guild.id)
            if not is_admin(message.author, message.channel):
                if not await self.on_message_check(message, settings,
                                                   cmd_prefix):
                    return

        message_content = unidecode.unidecode(str(message.content))
        message_author = unidecode.unidecode(str(message.author))

        if not message.content[len(cmd_prefix):].strip(
        ) or not message.content[len(cmd_prefix):].strip().split(' '):
            return

        if self.get_command(message.content.strip()
                            [len(cmd_prefix):].strip().split(' ')[0]):
            if message.author.id != owner_id and message.author.id in self.config.blacklisted:
                log.debug(
                    f"[User Blacklisted] {message.author.id}/{message_author} ({message_content.replace(cmd_prefix, globprefix, 1)[:50]})"
                )

            else:
                log.info(
                    f"[Command] {message.author.id}/{message_author} ({message_content.replace(cmd_prefix, globprefix, 1)[:100]})"
                )
                await self.process_commands(message)
                log.debug(
                    f"[Processed Command] {message.author.id}/{message_author} ({message_content.replace(cmd_prefix, globprefix, 1)[:100]})"
                )

        # check if custom command exists
        elif not isinstance(message.channel, discord.abc.PrivateChannel):
            if settings.customcommands:
                await self.on_customcommand(message, settings, message_content,
                                            message_author, cmd_prefix)
コード例 #3
0
 async def on_shard_ready(self, shard_id):
     log.info(f"Shard {shard_id} is ready")
コード例 #4
0
    async def on_ready(self):
        if self.init_ok:
            return
        # Store registred custom prefixes
        prefix_servers = SettingsDB.get_instance(
        ).guild_settings_collection.find({
            "$and": [{
                "prefix": {
                    "$exists": True
                }
            }, {
                "prefix": {
                    "$ne": globprefix
                }
            }]
        })

        async for server in prefix_servers:
            self.prefixes_map[server["_id"]] = server["prefix"]

        # Store registred custom languages
        language_servers = SettingsDB.get_instance(
        ).guild_settings_collection.find({
            "$and": [{
                "language": {
                    "$exists": True
                }
            }, {
                "language": {
                    "$ne": "english"
                }
            }]
        })

        async for lang in language_servers:
            self.languages_map[lang["_id"]] = lang["language"]

        # Store registred OwO mod
        owo_servers = SettingsDB.get_instance().guild_settings_collection.find(
            {"$and": [{
                "owo": {
                    "$exists": True
                }
            }, {
                "owo": {
                    "$ne": False
                }
            }]})

        async for server in owo_servers:
            self.owo_map[server["_id"]] = server["owo"]

        # Store registred autosongs
        autosongs_servers = SettingsDB.get_instance(
        ).guild_settings_collection.find({
            "$and": [{
                "autosongs": {
                    "$exists": True
                }
            }, {
                "autosongs": {
                    "$ne": {}
                }
            }]
        })

        async for server in autosongs_servers:
            self.autosongs_map[server["_id"]] = server["autosongs"]

        # Multiprocessing guild count
        self.owner_id = owner_id
        self.config = await SettingsDB.get_instance().get_glob_settings()
        if self.is_main_process and self.shard_count != len(
                self.config.server_count):
            self.config.server_count = {}
            await SettingsDB.get_instance().set_glob_settings(self.config)

        # Load cogs
        for extension in _list_cogs():
            try:
                self.load_extension("cogs." + extension)
            except Exception as e:
                exc = '{}: {}'.format(type(e).__name__, e)
                log.warning('Failed to load extension {}\n{}'.format(
                    extension, exc))

        total_cogs = len(_list_cogs())
        servers = len(self.guilds)
        owner = await self.safe_fetch('user', owner_id) or str(owner_id)

        log.info("-----------------")
        log.info("{} ({})".format(str(self.user), str(self.user.id)))
        log.info("{} server{}".format(servers, "s" if servers > 1 else ""))
        log.info("{} shard{}".format(self.shard_count,
                                     "s" if self.shard_count > 1 else ""))
        log.info("Prefix: {}".format(globprefix))
        log.info("Owner: {}".format(owner))
        log.info("{}/{} active cogs with {} commands".format(
            len(self.cogs), total_cogs, len(self.commands)))
        log.info("-----------------")

        if self.pipe and not self.pipe.closed:
            self.pipe.send(1)
            self.pipe.close()

        # Disable all loggers
        for name in ['launcher', 'lavalink', 'listenmoe']:
            logger = logging.getLogger(name)
            logger.disabled = not logger.disabled

        self.init_ok = True
コード例 #5
0
    async def on_command_error(self, ctx, error):

        if not isinstance(ctx.channel, discord.abc.PrivateChannel):
            if self.debug_mode == ctx.message.guild.id:
                try:
                    await ctx.channel.send("```py\n" + str(error) + "```")
                except discord.HTTPException:
                    log.info("Can't send debug messages - Missing Permissions")
                    return

        if isinstance(error, commands.MissingRequiredArgument) or isinstance(
                error, commands.BadArgument):
            try:
                log.debug(f"{error}.. Sending help...")
                return await self.send_cmd_help(ctx)
            except discord.HTTPException:
                log.debug("Can't send help - Missing Permissions")
                return

        elif isinstance(error, commands.errors.CommandOnCooldown):
            try:
                scds = str(error).replace('You are on cooldown. Try again in',
                                          '')
                return await ctx.channel.send("```c\n{}{}```".format(
                    get_str(ctx, "bot-cooldown"), scds),
                                              delete_after=10)
            except discord.HTTPException:
                log.debug("Can't send cooldown message - Missing Permissions")
                return

        elif isinstance(error, commands.errors.NoPrivateMessage):
            return await ctx.channel.send("```c\n{}```".format(
                get_str(ctx, "bot-not-mp")),
                                          delete_after=10)

        if isinstance(error, commands.errors.NotOwner):
            return

        elif isinstance(error, commands.errors.CheckFailure):
            try:
                return await ctx.channel.send(
                    "```c\n{} ({}permsinfo)```".format(
                        get_str(ctx, 'bot-not-enough-permissions'),
                        get_server_prefixes(ctx.bot, ctx.guild)),
                    delete_after=10)
            except discord.HTTPException:
                log.debug(
                    "Can't send permissions failure message - Missing Permissions"
                )
                return

        elif isinstance(error, commands.CommandNotFound):
            return

        elif NoVoiceChannel and isinstance(error, NoVoiceChannel):
            return

        else:
            if isinstance(error, commands.CommandInvokeError):
                if isinstance(error.original, discord.errors.Forbidden):
                    log.debug(
                        "discord.errors.Forbidden: FORBIDDEN (status code: 403): Missing Permissions"
                    )
                    return
                if isinstance(error.original, discord.errors.NotFound):
                    # log.info("discord.errors.NotFound: NotFound (status code: 404): Message not found")
                    return
                if isinstance(error.original, aiohttp.ClientError):
                    log.debug("Command raised an exception: ClientError")
                    return
                if isinstance(error.original, asyncio.futures.TimeoutError):
                    log.debug("Command raised an exception: TimeoutError")
                    return

            print('Ignoring exception in command {}:'.format(ctx.command),
                  file=sys.stderr)
            traceback.print_exception(type(error),
                                      error,
                                      error.__traceback__,
                                      file=sys.stderr)
            log.error(f'Exception in command {ctx.command.name}: {error}')