Beispiel #1
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)
Beispiel #2
0
 async def post_stats(self, url, token, payload):
     headers = {
         'authorization': self.bot.tokens[token],
         'content-type': 'application/json'
     }
     async with self.session.post(url, data=payload,
                                  headers=headers) as resp:
         await resp.release()
         log.debug(f'[Web] {resp.url} returned {resp.status} for {payload}')
Beispiel #3
0
    async def get_token(self):
        """Gets the token or creates a new one if expired"""
        if self.token and not await self.check_token(self.token):
            return self.token['access_token']

        token = await self.request_token()
        if not token:
            raise SpotifyError(
                'Requested a token from Spotify, did not end up getting one')
        token['expires_at'] = int(time.time()) + token['expires_in']
        self.token = token
        log.debug('Created a new access token: {0}'.format(token))
        return self.token['access_token']
Beispiel #4
0
 async def on_guild_remove(self, guild):
     log.debug(
         f"[Guild] Removed : {guild.id}/{guild.name} (owner : {guild.owner})"
     )
     await self.message_status()
     await self.update()
Beispiel #5
0
    async def on_customcommand(self, message, settings, message_content,
                               message_author, cmd_prefix):
        if settings.customcommands:
            cmd = message.content.lower()[len(cmd_prefix):].split(" ")[0]
            rest = None
            if len(message.content.lower()[len(cmd_prefix):].strip().split(
                    " ")) > 1:
                rest = ' '.join(
                    message.content[len(cmd_prefix):].split(" ")[1:])
            if cmd in settings.customcommands:
                cmd = await self.format_cc(settings.customcommands[cmd],
                                           message)
                if message.author.id != owner_id and message.author.id in self.config.blacklisted:
                    log.debug(
                        f"[User Blacklisted CustomCommand] {message.author.id}/{message_author} ({message_content})"
                    )
                    return
                if ">>>" in cmd:
                    while ">>> " in cmd:
                        cmd = cmd.replace(">>> ", ">>>")

                    if "&&" in cmd:
                        if rest and "&&" in rest:
                            rest = rest.split("&&")
                        all = cmd.split("&&")
                        if len(all) > 9:
                            return await message.channel.send(get_str(
                                message.guild, "cmd-choice-too-much-cmds",
                                self),
                                                              delete_after=10)
                        for m in all:
                            if m[-3:] == '   ':
                                m = m.lstrip()
                            else:
                                m = m.strip()
                            m = m[3:]
                            if 'download' in m:
                                message.id = 123  # hacky way to say that is a custom command
                            message.content = f"{cmd_prefix}{m}"
                            if len(m.split(' ')) < 2 and rest:
                                message.content += f" {rest}"
                            log.debug(
                                f"[CustomCommandCallMultiple] {message.author.id}/{message_author} ({message.content[:50]})"
                            )
                            await self.process_commands(message)
                        return

                    else:
                        if 'download' in cmd:
                            message.id = 123  # hacky way to say that is a custom command
                        message.content = cmd[3:]
                        message.content = f"{cmd_prefix}{message.content}"
                        if len(message.content.split(' ')) < 2 and rest:
                            message.content += f" {rest}"
                        log.debug(
                            f"[CustomCommandCall] {message.author.id}/{message_author} ({message.content[:50]})"
                        )
                        return await self.process_commands(message)

                pic = get_image_from_url(cmd)

                if pic:
                    e = discord.Embed()
                    e.set_image(url=pic)
                    cmds = cmd.replace(pic, "")
                    try:
                        await message.channel.send(embed=e, content=cmds)
                    except discord.Forbidden:
                        try:
                            await message.channel.send(get_str(
                                message.guild, "need-embed-permission", self),
                                                       delete_after=10)
                        except discord.Forbidden:
                            pass
                else:
                    try:
                        await message.channel.send(cmd)
                    except discord.Forbidden:
                        pass

                log.debug("[CustomCommand] {}/{} ({})".format(
                    message.author.id, message_author, message_content))
Beispiel #6
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}')