Пример #1
0
async def on_command_error(bot, ctx: commands.Context, error):
    if isinstance(error, commands.BotMissingPermissions):
        GearbotLogging.error(f"Encountered a permission error while executing {ctx.command}: {error}")
        await ctx.send(error)
    elif isinstance(error, commands.CheckFailure):
        if ctx.command.qualified_name is not "latest" and ctx.guild is not None and Configuration.get_var(ctx.guild.id, "GENERAL", "PERM_DENIED_MESSAGE"):
            await MessageUtils.send_to(ctx, 'LOCK', 'permission_denied')
    elif isinstance(error, commands.CommandOnCooldown):
        await ctx.send(error)
    elif isinstance(error, commands.MissingRequiredArgument):
        param = list(ctx.command.params.values())[min(len(ctx.args) + len(ctx.kwargs), len(ctx.command.params))]
        bot.help_command.context = ctx
        await ctx.send(
            f"{Emoji.get_chat_emoji('NO')} {Translator.translate('missing_arg', ctx, arg=param._name, error=Utils.replace_lookalikes(str(error)))}\n{Emoji.get_chat_emoji('WRENCH')} {Translator.translate('command_usage', ctx, usage=bot.help_command.get_command_signature(ctx.command))}")
    elif isinstance(error, PostParseError):
        bot.help_command.context = ctx
        await ctx.send(f"{Emoji.get_chat_emoji('NO')} {Translator.translate('bad_argument', ctx, type=error.type, error=Utils.replace_lookalikes(str(error.error)))}\n{Emoji.get_chat_emoji('WRENCH')} {Translator.translate('command_usage', ctx, usage=bot.help_command.get_command_signature(ctx.command))}")
    elif isinstance(error, commands.BadArgument):
        param = list(ctx.command.params.values())[min(len(ctx.args) + len(ctx.kwargs), len(ctx.command.params))]
        bot.help_command.context = ctx
        await ctx.send(f"{Emoji.get_chat_emoji('NO')} {Translator.translate('bad_argument', ctx, type=param._name, error=Utils.replace_lookalikes(str(error)))}\n{Emoji.get_chat_emoji('WRENCH')} {Translator.translate('command_usage', ctx, usage=bot.help_command.get_command_signature(ctx.command))}")
    elif isinstance(error, commands.CommandNotFound):
        return
    elif isinstance(error, PeeweeException):
        await handle_database_error(bot)

    else:
        await handle_exception("Command execution failed", bot, error.original if hasattr(error, "original") else error, ctx=ctx)
        # notify caller
        e = Emoji.get_chat_emoji('BUG')
        if ctx.channel.permissions_for(ctx.me).send_messages:
            await ctx.send(f"{e} Something went wrong while executing that command {e}")
Пример #2
0
 async def note(self, ctx, member: DiscordUser, *, reason: Reason):
     i = await InfractionUtils.add_infraction(ctx.guild.id, member.id, ctx.author.id, "Note", reason)
     name = Utils.clean_user(member)
     await MessageUtils.send_to(ctx, 'YES', 'note_added', user=name, inf=i.id)
     aname = Utils.clean_user(ctx.author)
     GearbotLogging.log_key(ctx.guild.id, 'note_added_modlog', user=name, moderator=aname, reason=reason,
                            user_id=member.id, moderator_id=ctx.author.id, inf=i.id)
Пример #3
0
 async def execute(self, bot, member, data, raid_id, raider_ids, shield):
     await bot.redis_pool.psetex(
         f"forced_exits:{member.guild.id}-{member.id}", 8000, 1)
     reason = f"Raider banned by raid shield {shield['name']} in raid {raid_id}"
     try:
         await member.ban(
             reason=reason,
             delete_message_days=1 if data["clean_messages"] else 0)
     except Forbidden:
         log(member.guild.id,
             'raid_ban_forbidden',
             shield,
             user_name=Utils.escape_markdown(member),
             user_id=member.id)
     except Exception as ex:
         log(member.guild.id,
             'raid_ban_unknown_error',
             shield,
             user_name=Utils.escape_markdown(member),
             user_id=member.id)
         await TheRealGearBot.handle_exception('RAID BAN FAILURE', bot, ex)
     finally:
         i = await InfractionUtils.add_infraction(member.guild.id,
                                                  member.id, bot.user.id,
                                                  "Ban", reason)
         GearbotLogging.log_key(member.guild.id,
                                'ban_log',
                                user=Utils.clean_user(member),
                                user_id=member.id,
                                moderator=Utils.clean_user(bot.user),
                                moderator_id=bot.user.id,
                                reason=reason,
                                inf=i.id)
Пример #4
0
 async def handle_simple_changes(self, before, after, base_key, action,
                                 attributes):
     for attr in attributes:
         if hasattr(before, attr):
             ba = getattr(before, attr)
             if isinstance(ba, str) and ba.strip() == "":
                 ba = None
             aa = getattr(after, attr)
             if isinstance(aa, str) and aa.strip() == "":
                 aa = None
             key = base_key
             if ba != aa:
                 entry = await self.find_log(
                     before.guild, action,
                     lambda e: e.target.id == before.id and hasattr(
                         e.changes.before, attr) and getattr(
                             e.changes.before, attr) == ba and getattr(
                                 e.changes.after, attr) == aa)
                 parts = dict(before=self.prep_attr(ba),
                              after=self.prep_attr(aa),
                              thing=after,
                              thing_id=after.id,
                              attr=attr)
                 if entry is not None:
                     parts.update(person=entry.user,
                                  person_id=entry.user.id)
                     key += "_by"
                 GearbotLogging.log_key(before.guild.id, key, **parts)
Пример #5
0
 async def on_user_update(self, before:discord.User, after):
     # Username and discriminator changes
     if before.name != after.name or before.discriminator != after.discriminator:
         for guild in self.bot.guilds:
             if guild.get_member(before.id) is not None:
                 after_clean_name = Utils.escape_markdown(Utils.replace_lookalikes(after.name))
                 GearbotLogging.log_key(guild.id, 'username_changed', after_clean=after_clean_name, before=before, user_id=after.id, after=after)
Пример #6
0
def getConfigVar(id, key):
    if not id in SERVER_CONFIGS.keys():
        GearbotLogging.info(
            f"Config entry requested before config was loaded for guild {id}, loading config for it"
        )
        loadConfig(id)
    return SERVER_CONFIGS[id][key]
Пример #7
0
 async def on_member_join(self, member: discord.Member):
     if Features.is_logged(member.guild.id, "TRAVEL_LOGS"):
         dif = (datetime.datetime.utcfromtimestamp(time.time()) -
                member.created_at)
         new_user_threshold = Configuration.get_var(member.guild.id,
                                                    "GENERAL",
                                                    "NEW_USER_THRESHOLD")
         minutes, seconds = divmod(dif.days * 86400 + dif.seconds, 60)
         hours, minutes = divmod(minutes, 60)
         age = (Translator.translate(
             'days', member.guild.id,
             amount=dif.days)) if dif.days > 0 else Translator.translate(
                 'hours', member.guild.id, hours=hours, minutes=minutes)
         if new_user_threshold > dif.total_seconds():
             GearbotLogging.log_key(member.guild.id,
                                    'join_logging_new',
                                    user=Utils.clean_user(member),
                                    user_id=member.id,
                                    age=age)
         else:
             GearbotLogging.log_key(member.guild.id,
                                    'join_logging',
                                    user=Utils.clean_user(member),
                                    user_id=member.id,
                                    age=age)
Пример #8
0
 async def db_cleaner(self):
     if Configuration.get_master_var("purge_db", True):
         # purge all messages older then 6 weeks
         snowflake = time_snowflake(datetime.datetime.utcfromtimestamp(time() - 60*60*24*7*6).replace(tzinfo=datetime.timezone.utc))
         purged_attachments = await LoggedAttachment.filter(id__lt=snowflake).delete()
         purged = await LoggedMessage.filter(messageid__lt=snowflake).delete()
         GearbotLogging.info(f"Purged {purged} old messages and {purged_attachments} attachments")
Пример #9
0
 async def kick_punishment(self, v: Violation, member):
     reason = self.assemble_reason(v)
     i = await InfractionUtils.add_infraction(v.guild.id,
                                              member.id,
                                              self.bot.user.id,
                                              'Kick',
                                              reason,
                                              active=False)
     await self.bot.redis_pool.psetex(
         f"forced_exits:{v.guild.id}-{member.id}", 8000, "1")
     try:
         if Configuration.get_var(v.guild.id, "INFRACTIONS", "DM_ON_KICK"):
             asyncio.create_task(
                 Utils.send_infraction(self.bot, member, v.guild, 'BOOT',
                                       'kick', "Spam"))
         await v.guild.kick(member, reason=reason)
     except Forbidden:
         GearbotLogging.log_key(v.guild.id,
                                'kick_punishment_failure',
                                user=Utils.clean_user(member),
                                user_id=member.id,
                                moderator=Utils.clean_user(v.guild.me),
                                moderator_id=v.guild.me.id,
                                reason=reason,
                                inf=i.id)
     else:
         GearbotLogging.log_key(v.guild.id,
                                'kick_log',
                                user=Utils.clean_user(member),
                                user_id=member.id,
                                moderator=Utils.clean_user(v.guild.me),
                                moderator_id=v.guild.me.id,
                                reason=reason,
                                inf=i.id)
Пример #10
0
 async def update_site(self, ctx):
     GearbotLogging.info("Site update initiated")
     await DocUtils.update_docs(ctx)
     message = await ctx.send(
         f"{Emoji.get_chat_emoji('REFRESH')} Purging cloudflare cache")
     cloudflare_info = Configuration.get_master_var("CLOUDFLARE", {})
     if 'ZONE' in cloudflare_info:
         headers = {
             "X-Auth-Email": cloudflare_info["EMAIL"],
             "X-Auth-Key": cloudflare_info["KEY"],
             "Content-Type": "application/json"
         }
         async with self.bot.aiosession.post(
                 f"https://api.cloudflare.com/client/v4/zones/{cloudflare_info['ZONE']}/purge_cache",
                 json=dict(purge_everything=True),
                 headers=headers) as reply:
             content = await reply.json()
             GearbotLogging.info(f"Cloudflare purge response: {content}")
             if content["success"]:
                 await message.edit(
                     content=
                     f"{Emoji.get_chat_emoji('YES')} Cloudflare cache has been purged"
                 )
             else:
                 await message.edit(
                     content=
                     f"{Emoji.get_chat_emoji('NO')} Cloudflare cache purge failed"
                 )
Пример #11
0
async def send_infraction(bot, user, guild, emoji, type, reason, **kwargs):
    if await get_member(bot, guild, user.id) is None:
        return
    try:
        override = Configuration.get_var(guild.id, "INFRACTIONS", type.upper())
        kwargs.update(reason=reason, server=guild.name, guild_id=guild.id)
        if override is not None:
            message = f"{Emoji.get_chat_emoji(emoji)} {format(override, kwargs, Configuration.get_var(guild.id, 'GENERAL', 'LANG'))}```{reason}```"
        else:
            message = f"{Emoji.get_chat_emoji(emoji)} {Translator.translate(f'{type.lower()}_dm', guild.id, **kwargs)}```{reason}```"
        parts = message.split("```")
        out = ""
        wrap = False
        while len(parts) > 0:
            temp = parts.pop(0)
            added = 6 if wrap else 0
            chars = "```" if wrap else ""
            if (len(out) + len(temp) + added) > 2000:
                await user.send(out)
                temp = ""
            out = f"{out}{chars}{temp}{chars}"
            wrap = not wrap
        if len(out) > 0:
            await user.send(out)
    except (discord.HTTPException, AttributeError):
        GearbotLogging.log_key(guild.id,
                               f'{type}_could_not_dm',
                               user=clean_user(user),
                               userid=user.id)
Пример #12
0
    async def hotreload(self, ctx: commands.Context):
        message = await GearbotLogging.bot_log(
            f"{Emoji.get_chat_emoji('REFRESH')} Hot reload in progress...")
        ctx_message = await ctx.send(
            f"{Emoji.get_chat_emoji('REFRESH')}  Hot reload in progress...")
        GearbotLogging.info("Initiating hot reload")

        GearbotLogging.LOG_PUMP.running = False
        importlib.reload(Reloader)
        for c in Reloader.components:
            importlib.reload(c)
        GearbotLogging.info("Reloading all cogs...")
        temp = []
        for cog in self.bot.cogs:
            temp.append(cog)
        for cog in temp:
            self.bot.unload_extension(f"Cogs.{cog}")
            GearbotLogging.info(f'{cog} has been unloaded.')
            self.bot.load_extension(f"Cogs.{cog}")
            GearbotLogging.info(f'{cog} has been loaded.')
        to_unload = Configuration.get_master_var("DISABLED_COMMANDS", [])
        for c in to_unload:
            self.bot.remove_command(c)

        await TheRealGearBot.initialize(self.bot)
        GearbotLogging.info("Hot reload complete.")
        m = f"{Emoji.get_chat_emoji('YES')} Hot reload complete"
        await message.edit(content=m)
        await ctx_message.edit(content=m)
        await Translator.upload()
        self.bot.hot_reloading = False
Пример #13
0
    async def censor_message(self, message, bad, key=""):
        if message.channel.permissions_for(message.guild.me).manage_messages:
            try:
                self.bot.data["message_deletes"].add(message.id)
                await message.delete()
            except discord.NotFound as ex:
                pass
            else:
                clean_message = await Utils.clean(message.content,
                                                  message.guild,
                                                  markdown=False)
                GearbotLogging.log_key(message.guild.id,
                                       f'censored_message{key}',
                                       user=message.author,
                                       user_id=message.author.id,
                                       message=clean_message,
                                       sequence=bad,
                                       channel=message.channel.mention)
                self.bot.dispatch("user_censored", message)
        else:

            clean_message = await Utils.clean(message.content,
                                              message.guild,
                                              markdown=False)
            GearbotLogging.log_key(message.guild.id,
                                   f'censor_message_failed{key}',
                                   user=message.author,
                                   user_id=message.author.id,
                                   message=clean_message,
                                   sequence=bad,
                                   link=message.jump_url)
            self.bot.dispatch("user_censored", message)
Пример #14
0
async def on_ready(bot):
    if not bot.STARTUP_COMPLETE:
        await initialize(bot, True)
        #shutdown handler for clean exit on linux
        try:
            for signame in ('SIGINT', 'SIGTERM'):
                asyncio.get_event_loop().add_signal_handler(getattr(signal, signame),
                                        lambda: asyncio.ensure_future(Utils.cleanExit(bot, signame)))
        except Exception:
            pass #doesn't work on windows

        bot.start_time = datetime.utcnow()
        GearbotLogging.info("Loading cogs...")
        for extension in Configuration.get_master_var("COGS"):
            try:
                bot.load_extension("Cogs." + extension)
            except Exception as e:
                await handle_exception(f"Failed to load cog {extension}", bot, e)
        GearbotLogging.info("Cogs loaded")

        to_unload = Configuration.get_master_var("DISABLED_COMMANDS", [])
        for c in to_unload:
            bot.remove_command(c)

        bot.STARTUP_COMPLETE = True
        info = await bot.application_info()
        bot.loop.create_task(keepDBalive(bot))  # ping DB every hour so it doesn't run off
        gears = [Emoji.get_chat_emoji(e) for e in ["WOOD", "STONE", "IRON", "GOLD", "DIAMOND"]]
        a = " ".join(gears)
        b = " ".join(reversed(gears))
        await GearbotLogging.bot_log(message=f"{a} All gears turning at full speed, {info.name} ready to go! {b}")
        await bot.change_presence(activity=Activity(type=3, name='the gears turn'))
    else:
        await bot.change_presence(activity=Activity(type=3, name='the gears turn'))
Пример #15
0
 async def warn_punishment(self, v: Violation):
     reason = v.bucket["PUNISHMENT"].get("REASON", self.assemble_reason(v))
     i = await InfractionUtils.add_infraction(v.guild.id, v.member.id,
                                              self.bot.user.id, 'Warn',
                                              reason)
     GearbotLogging.log_key(v.guild.id,
                            'warning_added_modlog',
                            user=Utils.clean_user(v.member),
                            moderator=Utils.clean_user(v.guild.me),
                            reason=reason,
                            user_id=v.member.id,
                            moderator_id=v.guild.me.id,
                            inf=i.id)
     try:
         dm_channel = await v.member.create_dm()
         await dm_channel.send(
             MessageUtils.assemble(dm_channel,
                                   'WARNING',
                                   'warning_dm',
                                   server=v.member.guild.name) +
             f"```{reason}```")
     except Forbidden:
         GearbotLogging.log_key(v.member.guild.id,
                                'warning_could_not_dm',
                                user=Utils.escape_markdown(v.member.name),
                                userid=v.member.id)
Пример #16
0
 async def temp_ban_punishment(self, v: Violation, member):
     reason = self.assemble_reason(v)
     duration = v.bucket["PUNISHMENT"]["DURATION"]
     until = time.time() + duration
     await self.bot.redis_pool.psetex(
         f"forced_exits:{v.guild.id}-{member.id}", 8000, 1)
     await v.guild.ban(member, reason=reason, delete_message_days=0)
     i = await InfractionUtils.add_infraction(v.guild.id,
                                              member.id,
                                              self.bot.user.id,
                                              'Tempban',
                                              reason,
                                              end=until)
     if Configuration.get_var(v.guild.id, "INFRACTIONS", "DM_ON_TEMPBAN"):
         dur = Utils.to_pretty_time(duration, None)
         asyncio.create_task(
             Utils.send_infraction(self.bot,
                                   member,
                                   v.guild,
                                   'BAN',
                                   'tempban',
                                   "Spam",
                                   duration=dur))
     GearbotLogging.log_key(
         v.guild.id,
         'tempban_log',
         user=Utils.clean_user(member),
         user_id=member.id,
         moderator=Utils.clean_user(v.guild.me),
         moderator_id=v.guild.me.id,
         reason=reason,
         until=datetime.datetime.utcfromtimestamp(until).replace(
             tzinfo=datetime.timezone.utc),
         inf=i.id)
Пример #17
0
 async def kick_punishment(self, v: Violation):
     reason = self.assemble_reason(v)
     i = await InfractionUtils.add_infraction(v.guild.id,
                                              v.member.id,
                                              self.bot.user.id,
                                              'Kick',
                                              reason,
                                              active=False)
     self.bot.data["forced_exits"].add(f"{v.guild.id}-{v.member.id}")
     try:
         await v.guild.kick(v.member, reason=reason)
     except Forbidden:
         GearbotLogging.log_key(v.guild.id,
                                'kick_punishment_failure',
                                user=Utils.clean_user(v.member),
                                user_id=v.member.id,
                                moderator=Utils.clean_user(v.guild.me),
                                moderator_id=v.guild.me.id,
                                reason=reason,
                                inf=i.id)
     else:
         GearbotLogging.log_key(v.guild.id,
                                'kick_log',
                                user=Utils.clean_user(v.member),
                                user_id=v.member.id,
                                moderator=Utils.clean_user(v.guild.me),
                                moderator_id=v.guild.me.id,
                                reason=reason,
                                inf=i.id)
Пример #18
0
 async def get_info(self, ctx, project_name, log):
     while project_name in self.fetching:
         # already fetching, wait for data to arrive
         await asyncio.sleep(1)
     if not project_name in self.cf_cache.keys():
         self.fetching.append(project_name)
         if log:
             message = await ctx.send(
                 f"<a:gearLoading:468054357724889089> {Translator.translate('fetching_info', ctx)} <a:gearLoading:468054357724889089>"
             )
         info = await self.fetch_info(project_name)
         if info is False:
             if log:
                 await ctx.send(Translator.translate(
                     'cf_fetch_failed', ctx))
         else:
             GearbotLogging.info(
                 f"Retrieved project data for {project_name}, adding to cache."
             )
             self.cf_cache[project_name] = {
                 "info": info,
                 "time": datetime.datetime.utcnow()
             }
         self.fetching.remove(project_name)
         if log:
             await message.delete()
         return info
     else:
         return self.cf_cache[project_name]["info"]
Пример #19
0
    async def taco_eater(self):
        """A person can eat a taco every 5 mins, we run every 15s"""
        GearbotLogging.info("Time to start munching on some ЁЯМо")
        while self.running:
            self.bot.eaten += len(self.bot.users) / 20

            # update stats in redis
            await self.bot.redis_pool.hmset_dict(
                "botstats", {
                    "start_time":
                    str(self.bot.start_time),
                    "user_mesages":
                    str(self.bot.user_messages),
                    "bot_messages":
                    str(self.bot.bot_messages),
                    "own_messages":
                    str(self.bot.self_messages),
                    "total_members":
                    str(sum(len(guild.members) for guild in self.bot.guilds)),
                    "unique_members":
                    str(len(self.bot.users)),
                    "taco_count":
                    str(round(self.bot.eaten)),
                    "random_number":
                    random.randint(0, 5000),
                    "commands_executed":
                    str(self.bot.commandCount),
                    "custom_commands_executed":
                    str(self.bot.custom_command_count),
                    "guilds":
                    len(self.bot.guilds)
                })

            await asyncio.sleep(15)
        GearbotLogging.info("Cog terminated, guess no more ЁЯМо for people")
Пример #20
0
 async def _warn(ctx, target, *, reason, message=True):
     i = InfractionUtils.add_infraction(ctx.guild.id, target.id,
                                        ctx.author.id, "Warn", reason)
     name = Utils.clean_user(target)
     if message:
         await MessageUtils.send_to(ctx,
                                    'YES',
                                    'warning_added',
                                    user=name,
                                    inf=i.id)
     aname = Utils.clean_user(ctx.author)
     GearbotLogging.log_key(ctx.guild.id,
                            'warning_added_modlog',
                            user=name,
                            moderator=aname,
                            reason=reason,
                            user_id=target.id,
                            moderator_id=ctx.author.id,
                            inf=i.id)
     if Configuration.get_var(ctx.guild.id, "INFRACTIONS", "DM_ON_WARN"):
         try:
             dm_channel = await target.create_dm()
             await dm_channel.send(
                 f"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('warning_dm', ctx.guild.id, server=ctx.guild.name)}```{reason}```"
             )
         except discord.Forbidden:
             GearbotLogging.log_key(ctx.guild.id,
                                    'warning_could_not_dm',
                                    user=name,
                                    userid=target.id)
Пример #21
0
 async def on_voice_state_update(self, member, before, after):
     if Features.is_logged(member.guild.id, "VOICE_CHANGES_DETAILED"):
         simple = ["deaf", "mute", "self_mute", "self_deaf", "afk"]
         for s in simple:
             old = getattr(before, s)
             new = getattr(after, s)
             if old != new:
                 key = f"voice_change_{s}_{str(new).lower()}"
                 GearbotLogging.log_key(member.guild.id,
                                        key,
                                        user=Utils.clean_user(member),
                                        user_id=member.id)
     if Features.is_logged(member.guild.id, "VOICE_CHANGES"):
         if before.channel != after.channel:
             parts = dict(user=Utils.clean_user(member), user_id=member.id)
             if before.channel is None:
                 key = "connected_to_voice"
                 parts.update(channel_name=after.channel.name,
                              channel_id=after.channel.id)
             elif after.channel is None:
                 key = "disconnected_voice"
                 parts.update(channel_name=before.channel.name,
                              channel_id=before.channel.id)
             else:
                 key = "moved_voice"
                 parts.update(old_channel_name=before.channel.name,
                              old_channel_id=before.channel.id,
                              new_channel_name=after.channel.name,
                              new_channel_id=after.channel.id)
             GearbotLogging.log_key(member.guild.id, key, **parts)
Пример #22
0
    async def violate(self, v: Violation):
        # deterining current punishment
        punish_info = v.bucket["PUNISHMENT"]
        t = punish_info["TYPE"]
        self.bot.dispatch('spam_violation', v)
        key = f"{v.guild.id}-{v.member.id}-{v.bucket['TYPE']}"
        a = self.get_extra_actions(key)
        a.count += v.count

        # Punish and Clean
        GearbotLogging.log_key(v.guild.id, 'spam_violate', user=Utils.clean_user(v.member), user_id=v.member.id,
                               check=v.check.upper(), friendly=v.friendly, channel=v.channel.mention, punishment_type=t)

        await self.punishments[t](v)

        if v.bucket.get("CLEAN", True):
            to_clean = AntiSpam._process_bucket_entries(v.offending_messages)
            by_channel = {}
            for (chan, msg) in to_clean:
                by_channel.setdefault(chan, []).append(msg)

            for (chan, msgs) in by_channel.items():
                guild_chan = v.guild.get_channel(int(chan))
                msgs = [Object(id=x) for x in msgs]
                if guild_chan is not None:
                    # Ensure we only delete 100 at a time. Probably not necessary but you never know with people
                    for group in Utils.chunks(msgs, 100):
                        try:
                            await guild_chan.delete_messages(group)
                        except NotFound:
                            pass
        await asyncio.sleep(v.bucket["SIZE"]["PERIOD"])
        a = self.get_extra_actions(key)
        a.count -= v.count
Пример #23
0
    async def on_member_remove(self, member: discord.Member):
        if member.id == self.bot.user.id: return
        timestamp = datetime.datetime.now()
        exits = self.bot.data["forced_exits"]
        fid = f"{member.guild.id}-{member.id}"
        if fid in exits:
            exits.remove(fid)
            return
        if member.guild.me.guild_permissions.view_audit_log and Features.is_logged(member.guild.id, "MOD_ACTIONS"):
            try:
                async for entry in member.guild.audit_logs(action=AuditLogAction.kick, limit=25):
                    if member.joined_at is None or member.joined_at > entry.created_at or entry.created_at < datetime.datetime.utcfromtimestamp(
                             time.time() - 30):
                        break
                    if entry.target == member:
                        if entry.reason is None:
                            reason = Translator.translate("no_reason", member.guild.id)
                        else:
                            reason = entry.reason
                        i = await InfractionUtils.add_infraction(member.guild.id, entry.target.id, entry.user.id, "Kick", reason,
                                                       active=False)
                        GearbotLogging.log_key(member.guild.id, 'kick_log', user=Utils.clean_user(member), user_id=member.id, moderator=Utils.clean_user(entry.user), moderator_id=entry.user.id, reason=reason, inf=i.id, timestamp=timestamp)
                        return
            except discord.Forbidden:
                permissions = member.guild.me.guild_permissions
                perm_info = ", ".join(f"{name}: {value}" for name, value in permissions)
                await GearbotLogging.bot_log(
                    f"{Emoji.get_chat_emoji('WARNING')} Tried to fetch audit log for {member.guild.name} ({member.guild.id}) but got denied even though it said i have access, guild permissions: ```{perm_info}```")

        if Features.is_logged(member.guild.id, "TRAVEL_LOGS"):
            GearbotLogging.log_key(member.guild.id, 'leave_logging', user=Utils.clean_user(member), user_id=member.id, timestamp=timestamp)
Пример #24
0
    async def warn(self, ctx: commands.Context, member: discord.Member, *, reason: Reason):
        """warn_help"""
        if ctx.author != member and (ctx.author.top_role > member.top_role or ctx.guild.owner == ctx.author):
            if member.id == self.bot.user.id:
                async def yes():
                    channel = self.bot.get_channel(Configuration.get_master_var("inbox", 0))
                    if channel is not None:
                        await channel.send(f"[`{ctx.message.created_at.strftime('%c')}`] {ctx.message.author} (`{ctx.message.author.id}`) submitted feedback: {reason}")
                        await MessageUtils.send_to(ctx, 'YES', 'feedback_submitted')

                message = MessageUtils.assemble(ctx, "THINK", "warn_to_feedback")
                await Confirmation.confirm(ctx, message, on_yes=yes)
            else:
                if member.bot:
                    await MessageUtils.send_to(ctx, "THINK", "cant_warn_bot")
                    return

                i = InfractionUtils.add_infraction(ctx.guild.id, member.id, ctx.author.id, "Warn", reason)
                name = Utils.clean_user(member)
                await MessageUtils.send_to(ctx, 'YES', 'warning_added', user=name, inf=i.id)
                aname = Utils.clean_user(ctx.author)
                GearbotLogging.log_key(ctx.guild.id, 'warning_added_modlog', user=name, moderator=aname, reason=reason,
                                       user_id=member.id, moderator_id=ctx.author.id, inf=i.id)
                if Configuration.get_var(ctx.guild.id, "INFRACTIONS", "DM_ON_WARN"):
                    try:
                        dm_channel = await member.create_dm()
                        await dm_channel.send(
                            f"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('warning_dm', ctx.guild.id, server=ctx.guild.name)}```{reason}```")
                    except discord.Forbidden:
                        GearbotLogging.log_key(ctx.guild.id, 'warning_could_not_dm', user=name,
                                               userid=member.id)
        else:
            await ctx.send(f"{Emoji.get_chat_emoji('NO')} {Translator.translate('warning_not_allowed', ctx.guild.id, user=member)}")
Пример #25
0
 async def yes():
     await infraction.delete()
     await MessageUtils.send_to(ctx, "YES", "inf_delete_deleted", id=infraction.id)
     GearbotLogging.log_key(ctx.guild.id, 'inf_delete_log', id=infraction.id, target=Utils.clean_user(target),
                            target_id=target.id, mod=Utils.clean_user(mod), mod_id=mod.id if mod is not None else 0, reason=reason,
                            user=Utils.clean_user(ctx.author), user_id=ctx.author.id)
     InfractionUtils.clear_cache(ctx.guild.id)
Пример #26
0
def translate(key, location, **kwargs):
    lid = None
    if location is not None:
        if hasattr(location, "guild"):
            location = location.guild
        if location is not None and hasattr(location, "id"):
            lid = location.id
        else:
            lid = location

    if lid is None:
        lang_key = "en_US"
    else:
        lang_key = Configuration.get_var(lid, "GENERAL", "LANG")
    translated = key
    if key not in LANGS[lang_key]:
        if key not in untranlatable:
            BOT.loop.create_task(tranlator_log('WARNING', f'Untranslatable string detected: {key}\n'))
            untranlatable.add(key)
        return key if key not in LANGS["en_US"] else format(LANGS['en_US'][key], kwargs, 'en_US')
    try:
        translated = format(LANGS[lang_key][key], kwargs, lang_key)
    except (KeyError, ValueError, ParseError, VisitationError) as ex:
        BOT.loop.create_task(tranlator_log('NO', f'Corrupt translation detected!\n**Lang code:** {lang_key}\n**Translation key:** {key}\n```\n{LANGS[lang_key][key]}```'))
        GearbotLogging.exception("Corrupt translation", ex)
        if key in LANGS["en_US"].keys():
            try:
                translated = format(LANGS['en_US'][key], kwargs, 'en_US')
            except (KeyError, ValueError, ParseError, VisitationError) as ex:
                BOT.loop.create_task(tranlator_log('NO', f'Corrupt English source string detected!\n**Translation key:** {key}\n```\n{LANGS["en_US"][key]}```'))
                GearbotLogging.exception('Corrupt translation', ex)
    return translated
Пример #27
0
 async def execute(self, bot, member, data, raid_id, raider_ids, shield):
     role = member.guild.get_role(
         Configuration.get_var(member.guild.id, "ROLES", "MUTE_ROLE"))
     if role is None:
         GearbotLogging.log_key(member.guild.id, 'raid_mute_failed_no_role')
     else:
         duration = data["duration"]
         reason = f"Raider muted by raid shield {shield['name']} in raid {raid_id}"
         try:
             await member.add_roles(role, reason=reason)
         except NotFound:
             pass
         except Forbidden:
             log(member.guild.id,
                 'raid_mute_forbidden',
                 shield,
                 user_name=Utils.escape_markdown(member),
                 user_id=member.id)
         except Exception as ex:
             log(member.guild.id,
                 'raid_mute_unknown_error',
                 shield,
                 user_name=Utils.escape_markdown(member),
                 user_id=member.id)
             await TheRealGearBot.handle_exception('RAID MUTE FAILURE', bot,
                                                   ex)
         finally:
             until = time.time() + duration
             i = await InfractionUtils.add_infraction(member.guild.id,
                                                      member.id,
                                                      member.guild.me.id,
                                                      "Mute",
                                                      reason,
                                                      end=until)
Пример #28
0
async def translation_task(bot):
    while not bot.is_closed():
        try:
            await Translator.update()
        except Exception as ex:
            GearbotLogging.error(
                "Something went wrong during translation updates")
            GearbotLogging.error(traceback.format_exc())
            embed = Embed(colour=Colour(0xff0000),
                          timestamp=datetime.utcfromtimestamp(time.time()))
            embed.set_author(
                name="Something went wrong during translation updates")
            embed.add_field(name="Exception", value=str(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 GearbotLogging.bot_log(embed=embed)

        try:
            await asyncio.sleep(6 * 60 * 60)
        except asyncio.CancelledError:
            pass  # bot shutting down
Пример #29
0
 async def taco_eater(self):
     """A person can eat a taco every 5 mins, we run every 5s"""
     GearbotLogging.info("Time to start munching on some 🌮")
     while self.running:
         self.bot.eaten += len(self.bot.users) / 60
         await asyncio.sleep(5)
     GearbotLogging.info("Cog terminated, guess no more 🌮 for people")
Пример #30
0
async def node_init(generation, resource_version):
    from database import DatabaseConnector
    from database.DatabaseConnector import Node
    await DatabaseConnector.init()
    hostname = os.uname()[1]
    GearbotLogging.info(
        f"GearBot clusternode {hostname} (generation {generation}). Trying to figure out where i fit in"
    )
    existing = await Node.filter(hostname=hostname,
                                 generation=generation).get_or_none()
    if existing is None:
        count = 0
        while count < 100:

            try:
                await Node.create(hostname=hostname,
                                  generation=generation,
                                  resource_version=resource_version,
                                  shard=count)
                return count
            except Exception as ex:
                GearbotLogging.exception("did something go wrong?", ex)
                count += 1
    else:
        return existing.shard