Beispiel #1
0
 async def on_raw_message_delete(self, message_id, channel_id):
     if message_id in self.approved:
         BugLog.info("Caught a submision before it fell into the void!")
         return
     self.bot.DBC.query(
         f"DELETE FROM submissions WHERE message = {message_id} AND points = 0"
     )
     await self.updateScoreboard('Post Pick-Up Hug / Fight Strings!')
Beispiel #2
0
async def on_command_error(ctx: commands.Context, error):
    if isinstance(error, commands.NoPrivateMessage):
        await ctx.send("This command cannot be used in private messages.")
    elif isinstance(error, commands.BotMissingPermissions):
        BugLog.error(
            f"Encountered a permissions error while executing {ctx.command}.")
        await ctx.send(error)
    elif isinstance(error, commands.DisabledCommand):
        await ctx.send("Sorry. This command is disabled and cannot be used.")
    elif isinstance(error, commands.CheckFailure):
        await ctx.send(error)
    elif isinstance(error, commands.CommandOnCooldown):
        await ctx.send(error)
    elif isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(
            f"You are missing a required argument! (See {ctx.prefix}help {ctx.command.qualified_name} for info on how to use this command)."
        )
    elif isinstance(error, commands.BadArgument):
        await ctx.send(
            f"Invalid argument given! (See {ctx.prefix}help {ctx.command.qualified_name} for info on how to use this commmand)."
        )
    elif isinstance(error, commands.CommandNotFound):
        return
    else:
        await ctx.send(
            ":rotating_light: Something went wrong while executing that command. :rotating_light:"
        )
        # log to logger first just in case botlog logging fails as well
        BugLog.exception(
            f"Command execution failed:"
            f"    Command: {ctx.command}"
            f"    Message: {ctx.message.content}"
            f"    Channel: {'Private Message' if isinstance(ctx.channel, PrivateChannel) else ctx.channel.name}"
            f"    Sender: {ctx.author.name}#{ctx.author.discriminator}"
            f"    Exception: {error}", error)

        embed = discord.Embed(colour=discord.Colour(0xff0000),
                              timestamp=datetime.datetime.utcfromtimestamp(
                                  time.time()))

        embed.set_author(name="Command execution failed:")
        embed.add_field(name="Command", value=ctx.command)
        embed.add_field(name="Original message", value=ctx.message.content)
        embed.add_field(name="Channel",
                        value='Private Message' if isinstance(
                            ctx.channel, PrivateChannel) else ctx.channel.name)
        embed.add_field(name="Sender",
                        value=f"{ctx.author.name}#{ctx.author.discriminator}")
        embed.add_field(name="Exception", value=error)
        v = ""
        for line in traceback.format_tb(error.__traceback__):
            if len(v) + len(line) > 1024:
                embed.add_field(name="Stacktrace", value=v)
                v = ""
            v = f"{v}\n{line}"
        if len(v) > 0:
            embed.add_field(name="Stacktrace", value=v)
        await BugLog.logToBotlog(embed=embed)
Beispiel #3
0
def loadGlobalConfig():
    global MASTER_CONFIG
    try:
        with open('config/master.json', 'r') as jsonfile:
            MASTER_CONFIG = json.load(jsonfile)
    except FileNotFoundError:
        BugLog.error("Unable to load config, running with defaults.")
    except Exception as e:
        BugLog.error("Failed to parse configuration.")
        print(e)
        raise e
Beispiel #4
0
def loadConfigFile(id):
    global SERVER_CONFIGS
    try:
        with open(f'config/{id}.json', 'r') as jsonfile:
            config = json.load(jsonfile)
            for key in CONFIG_TEMPLATE:
                if key not in config:
                    config[key] = CONFIG_TEMPLATE[key]
            SERVER_CONFIGS[id] = config
    except FileNotFoundError:
        BugLog.info(f"No config available for ({guild.id}), creating blank one.")
        SERVER_CONFIGS[id] = copy.deepcopy(CONFIG_TEMPLATE)
        saveConfig(id)
Beispiel #5
0
 async def buildCache(self, guild: discord.Guild):
     start = time.perf_counter()
     BugLog.info(
         f"Populating modlog with missed messages during downtime for {guild.name} ({guild.id})."
     )
     newCount = 0
     editCount = 0
     count = 0
     for channel in guild.text_channels:
         if channel.permissions_for(guild.get_member(
                 self.bot.user.id)).read_messages:
             async for message in channel.history(limit=250, reverse=False):
                 if message.author == self.bot.user:
                     continue
                 logged = LoggedMessage.get_or_none(messageid=message.id)
                 if logged is None:
                     LoggedMessage.create(
                         messageid=message.id,
                         author=message.author.id,
                         content=self.bot.aes.encrypt(message.content),
                         timestamp=message.created_at.timestamp(),
                         channel=channel.id)
                     for a in message.attachments:
                         LoggedAttachment.create(
                             id=a.id,
                             url=self.bot.aes.encrypt(a.url),
                             isImage=(a.width is not None or a.width is 0),
                             messageid=message.id)
                     newCount = newCount + 1
                 elif self.bot.aes.decrypt(
                         logged.content) != message.content:
                     logged.content = self.bot.aes.encrypt(message.content)
                     logged.save()
                     editCount = editCount + 1
                 count = count + 1
     BugLog.info(
         f"Discovered {newCount} new messages and {editCount} edited in {guild.name} (checked {count}) in {time.perf_counter() - start }s."
     )
Beispiel #6
0
async def on_error(event, *args, **kwargs):
    #something went wrong and it might have been in on_command_error, make sure we log to the log file first
    BugLog.error(f"error in {event}\n{args}\n{kwargs}")
    BugLog.error(traceback.format_exc())
    embed = discord.Embed(colour=discord.Colour(0xff0000),
                          timestamp=datetime.datetime.utcfromtimestamp(time.time()))

    embed.set_author(name=f"Caught an error in {event}:")

    embed.add_field(name="args", value=str(args))
    embed.add_field(name="kwargs", value=str(kwargs))

    embed.add_field(name="Stacktrace", value=traceback.format_exc())
    #try logging to botlog, wrapped in an try catch as there is no higher lvl catching to prevent taking donwn the bot (and if we ended here it might have even been due to trying to log to botlog
    try:
        await BugLog.logToBotlog(embed=embed)
    except Exception as ex:
        BugLog.exception(f"Failed to log to botlog, either Discord broke or something is seriously wrong!\n{ex}", ex)
Beispiel #7
0
async def on_guild_join(guild: discord.Guild):
    BugLog.info(f"A new guild came up: {guild.name} ({guild.id}).")
    Configuration.loadConfig(guild)
Beispiel #8
0
    #try logging to botlog, wrapped in an try catch as there is no higher lvl catching to prevent taking donwn the bot (and if we ended here it might have even been due to trying to log to botlog
    try:
        await BugLog.logToBotlog(embed=embed)
    except Exception as ex:
        BugLog.exception(
            f"Failed to log to botlog, either Discord broke or something is seriously wrong!\n{ex}",
            ex)


# Adding the cogs to the bot
if __name__ == '__main__':
    for extension in initial_extensions:
        try:
            bot.load_extension(f"cogs.{extension}")
        except Exception as e:
            BugLog.startupError(f"Failed to load extention {extension}.", e)


@bot.event
async def on_guild_join(guild: discord.Guild):
    BugLog.info(f"A new guild came up: {guild.name} ({guild.id}).")
    Configuration.loadConfig(guild)


@bot.event
async def on_ready():
    if not bot.startup_done:
        await Configuration.onReady(bot)
        print(f'\n\nLogged in as: {bot.user.name} - {bot.user.id}' +
              f'\nVersion: {discord.__version__}\n')
        await BugLog.onReady(bot, config["Settings"]["botlog"])
Beispiel #9
0
async def onReady(bot: commands.Bot):
    BugLog.info(f"Loading configurations for {len(bot.guilds)} guilds")
    for guild in bot.guilds:
        BugLog.info(f"Loading info for {guild.name} ({guild.id})")
        loadConfig(guild)
Beispiel #10
0
async def unmuteTask(modcog: ModerationCog):
    while not modcog.bot.startup_done:
        await asyncio.sleep(1)
        BugLog.info("Started unmute background task")
    skips = []
    updated = False
    while modcog.running:
        userid = 0
        guildid = 0
        try:
            guildstoremove = []
            for guildid, list in modcog.mutes.items():
                guild: discord.Guild = modcog.bot.get_guild(int(guildid))
                toremove = []
                if Configuration.getConfigVar(int(guildid), "MUTE_ROLE") is 0:
                    guildstoremove.append(guildid)
                for userid, until in list.items():
                    if time.time() > until and userid not in skips:
                        member = guild.get_member(int(userid))
                        role = discord.utils.get(guild.roles,
                                                 id=Configuration.getConfigVar(
                                                     int(guildid),
                                                     "MUTE_ROLE"))
                        if guild.me.guild_permissions.manage_roles:
                            await member.remove_roles(role,
                                                      reason="Mute expired")
                            await BugLog.logToModLog(
                                guild,
                                f":innocent: {member.name}#{member.discriminator} (`{member.id}`) has automatically been unmuted"
                            )
                        else:
                            await BugLog.logToModLog(
                                guild,
                                f":no_entry: ERROR: {member.name}#{member.discriminator} (`{member.id}`) was muted earlier but i no longer have the permissions needed to unmute this person, please remove the role manually!"
                            )
                        updated = True
                        toremove.append(userid)
                for todo in toremove:
                    del list[todo]
                await asyncio.sleep(0)
            if updated:
                Util.saveToDisk("mutes", modcog.mutes)
                updated = False
            for id in guildstoremove:
                del modcog.mutes[id]
            await asyncio.sleep(10)
        except CancelledError:
            pass  #bot shutdown
        except Exception as ex:
            BugLog.error("Something went wrong in the unmute task")
            BugLog.error(traceback.format_exc())
            skips.append(userid)
            embed = discord.Embed(colour=discord.Colour(0xff0000),
                                  timestamp=datetime.datetime.utcfromtimestamp(
                                      time.time()))

            embed.set_author(name="Something went wrong in the unmute task:")
            embed.add_field(name="Current guildid", value=guildid)
            embed.add_field(name="Current userid", value=userid)
            embed.add_field(name="Exception", value=ex)
            v = ""
            for line in traceback.format_exc().splitlines():
                if len(v) + len(line) > 1024:
                    embed.add_field(name="Stacktrace", value=v)
                    v = ""
                v = f"{v}\n{line}"
            if len(v) > 0:
                embed.add_field(name="Stacktrace", value=v)
            await BugLog.logToBotlog(embed=embed)
            await asyncio.sleep(10)
    BugLog.info("Unmute background task terminated")