Esempio n. 1
0
 def pretty_role_list(self, roles, destination):
     out = ", ".join(f"`{role.name}`" for role in roles)
     if len(out) > 900:
         out = Translator.translate('too_many_roles_to_list', destination)
     return out
Esempio n. 2
0
    async def forceban(self,
                       ctx: commands.Context,
                       user_id: UserID,
                       *,
                       reason: Reason = ""):
        """forceban_help"""
        if reason == "":
            reason = Translator.translate("no_reason", ctx.guild.id)
        try:
            member = await commands.MemberConverter().convert(
                ctx, str(user_id))
        except BadArgument:
            user = await ctx.bot.get_user_info(user_id)
            self.bot.data["forced_exits"].add(f"{ctx.guild.id}-{user.id}")
            await ctx.guild.ban(
                user,
                reason=Utils.trim_message(
                    f"Moderator: {ctx.author.name}#{ctx.author.discriminator} ({ctx.author.id}) Reason: {reason}",
                    500),
                delete_message_days=0)
            await ctx.send(
                f"{Emoji.get_chat_emoji('YES')} {Translator.translate('forceban_confirmation', ctx.guild.id, user=Utils.clean_user(user), user_id=user_id, reason=reason)}"
            )
            GearbotLogging.log_to(
                ctx.guild.id, "MOD_ACTIONS",
                f":door: {Translator.translate('forceban_log', ctx.guild.id, user=Utils.clean_user(user), user_id=user_id, moderator=Utils.clean_user(ctx.author), moderator_id=ctx.author.id, reason=reason)}"
            )

            tempbans = list(Infraction.select().where(
                (Infraction.user_id == user.id)
                & (Infraction.type == "Tempban")
                & (Infraction.guild_id == ctx.guild.id)))
            if len(tempbans) > 0:
                inf = tempbans[0]
                timeframe = datetime.datetime.utcfromtimestamp(
                    inf.end.timestamp()) - datetime.datetime.utcfromtimestamp(
                        time.time())
                hours, remainder = divmod(int(timeframe.total_seconds()), 3600)
                minutes, seconds = divmod(remainder, 60)
                tt = Translator.translate("hours",
                                          ctx,
                                          hours=hours,
                                          minutes=minutes)
                await GearbotLogging.send_to(ctx,
                                             "WARNING",
                                             "forceban_override_tempban",
                                             user=Utils.clean_user(user),
                                             timeframe=tt,
                                             inf_id=inf.id)

            Infraction.update(active=False).where(
                (Infraction.user_id == user.id)
                & ((Infraction.type == "Unban")
                   | (Infraction.type == "Tempban"))
                & (Infraction.guild_id == ctx.guild.id)).execute()
            InfractionUtils.add_infraction(ctx.guild.id, user.id,
                                           ctx.author.id, "Forced ban", reason)
        else:
            await ctx.send(
                f"{Emoji.get_chat_emoji('WARNING')} {Translator.translate('forceban_to_ban', ctx.guild.id, user=Utils.clean_user(member))}"
            )
            await ctx.invoke(self.ban, member, reason=reason)
Esempio n. 3
0
    async def on_raw_message_edit(self, event: RawMessageUpdateEvent):
        cid = int(event.data["channel_id"])
        if cid == Configuration.get_master_var("BOT_LOG_CHANNEL"):
            return
        c = self.bot.get_channel(cid)
        if c is None or isinstance(
                c, DMChannel) or c.guild is None or (not Features.is_logged(
                    c.guild.id,
                    "MESSAGE_LOGS")) or cid in Configuration.get_var(
                        c.guild.id, "MESSAGE_LOGS", "IGNORED_CHANNELS_OTHER"):
            return
        message = await MessageUtils.get_message_data(self.bot,
                                                      event.message_id)
        if message is not None and "content" in event.data:
            channel: discord.TextChannel = self.bot.get_channel(
                int(event.data["channel_id"]))
            if channel.guild is None:
                return
            user: discord.User = self.bot.get_user(message.author)
            hasUser = user is not None
            if message.content == event.data["content"]:
                # either pinned or embed data arrived, if embed data arrives it's gona be a recent one so we'll have the cached message to compare to
                old = message.pinned
                new = event.data["pinned"]
                if old == new:
                    return
                else:
                    parts = dict(channel=Utils.escape_markdown(c.name),
                                 channel_id=c.id)
                    if new:
                        # try to find who pinned it
                        key = "message_pinned"
                        m = await c.history(limit=5
                                            ).get(type=MessageType.pins_add)
                        if m is not None:
                            key += "_by"
                            parts.update(user=Utils.escape_markdown(m.author),
                                         user_id=m.author.id)
                    else:
                        # impossible to determine who unpinned it :meowsad:
                        key = "message_unpinned"
                    GearbotLogging.log_key(c.guild.id, key, **parts)
                    GearbotLogging.log_raw(
                        c.guild.id, key,
                        f'```\n{Utils.trim_message(event.data["content"], 1990)}\n```'
                    )
                    GearbotLogging.log_raw(
                        c.guild.id, key,
                        f"{Translator.translate('jump_link', c.guild.id)}: {MessageUtils.construct_jumplink(c.guild.id, c.id, event.message_id)}"
                    )
                    await MessageUtils.update_message(self.bot,
                                                      event.message_id,
                                                      message.content, new)
                    return

            mc = message.content
            if mc is None or mc == "":
                mc = f"<{Translator.translate('no_content', channel.guild.id)}>"
            after = event.data["content"]
            if after is None or after == "":
                after = f"<{Translator.translate('no_content', channel.guild.id)}>"
            if hasUser and user.id not in Configuration.get_var(
                    channel.guild.id, "MESSAGE_LOGS",
                    "IGNORED_USERS") and user.id != channel.guild.me.id:
                _time = Utils.to_pretty_time(
                    (datetime.datetime.utcnow() -
                     snowflake_time(message.messageid)).total_seconds(),
                    channel.guild.id)
                with_id = Configuration.get_var(channel.guild.id,
                                                "MESSAGE_LOGS", "MESSAGE_ID")
                reply_str = ""
                if message.reply_to is not None:
                    reply_str = f"\n**{Translator.translate('in_reply_to', c.guild.id)}: **<{assemble_jumplink(c.guild.id, channel.id, message.reply_to)}>"
                GearbotLogging.log_key(
                    channel.guild.id,
                    'edit_logging_with_id' if with_id else 'edit_logging',
                    user=Utils.clean_user(user),
                    user_id=user.id,
                    channel=channel.mention,
                    message_id=message.messageid,
                    time=_time.strip(),
                    reply=reply_str)
                if Configuration.get_var(channel.guild.id, "MESSAGE_LOGS",
                                         "EMBED"):
                    embed = discord.Embed()
                    embed.set_author(
                        name=user if hasUser else message.author,
                        icon_url=user.avatar_url if hasUser else EmptyEmbed)
                    embed.set_footer(
                        text=Translator.translate('sent_in',
                                                  channel.guild.id,
                                                  channel=f"#{channel.name}"))
                    embed.add_field(name=Translator.translate(
                        'before', channel.guild.id),
                                    value=Utils.trim_message(mc, 1024),
                                    inline=False)
                    embed.add_field(name=Translator.translate(
                        'after', channel.guild.id),
                                    value=Utils.trim_message(after, 1024),
                                    inline=False)
                    GearbotLogging.log_raw(channel.guild.id,
                                           "edit_logging",
                                           embed=embed)
                else:
                    clean_old = await Utils.clean(mc, channel.guild)
                    clean_new = await Utils.clean(after, channel.guild)
                    GearbotLogging.log_raw(channel.guild.id, "edit_logging",
                                           f"**Old:** {clean_old}")
                    GearbotLogging.log_raw(channel.guild.id, "edit_logging",
                                           f"**New:** {clean_new}")
            await MessageUtils.update_message(self.bot, event.message_id,
                                              after, event.data["pinned"])
Esempio n. 4
0
 async def info(self, ctx, infraction:ServerInfraction):
     """inf_info_help"""
     embed = discord.Embed(color=0x00cea2, description=f"**{Translator.translate('reason', ctx)}**\n{infraction.reason}", timestamp=infraction.start)
     user = await Utils.get_user(infraction.user_id)
     mod = await Utils.get_user(infraction.mod_id)
     key = f"inf_{infraction.type.lower().replace(' ', '_')}"
     if infraction.end is None:
         duration = Translator.translate("unknown_duration", ctx)
     else:
         time = (infraction.end - infraction.start).total_seconds()
         if time % (60 * 60 * 24 * 7) == 0:
             duration = Translator.translate('weeks', ctx, weeks=int(time / (60 * 60 * 24 * 7)))
         elif time % (60 * 60 * 24) == 0:
             duration = Translator.translate('days', ctx, days=int(time / (60 * 60 * 24)))
         elif time % (60 * 60) == 0:
             duration = Translator.translate('hours_solo', ctx, hours=int(time / (60 * 60)))
         elif time % 60 == 0:
             duration = Translator.translate('minutes', ctx, minutes=int(time / 60))
         else:  # if you wana mute for someone for an arbitrary amount of seconds that isn't round minute, hour, day or week then it's not my problem it shows arbitrary amount of seconds
             duration = Translator.translate('seconds', ctx, seconds=int(time))
     embed.set_author(name=Translator.translate(key, ctx, mod=Utils.username_from_user(mod), user=Utils.username_from_user(user), duration=duration),
                      icon_url=mod.avatar_url)
     embed.set_thumbnail(url=user.avatar_url)
     embed.add_field(name=Translator.translate('moderator', ctx), value=Utils.clean_user(mod))
     embed.add_field(name=Translator.translate('user', ctx), value=Utils.clean_user(user))
     embed.add_field(name=Translator.translate('mod_id', ctx), value=infraction.mod_id)
     embed.add_field(name=Translator.translate('user_id', ctx), value=infraction.user_id)
     embed.add_field(name=Translator.translate('inf_added', ctx), value=infraction.start)
     if infraction.end is not None:
         embed.add_field(name=Translator.translate('inf_end', ctx), value=infraction.end)
     embed.add_field(name=Translator.translate('inf_active', ctx), value=MessageUtils.assemble(ctx, 'YES' if infraction.active else 'NO', str(infraction.active).lower()))
     images = self.IMAGE_MATCHER.findall(infraction.reason)
     if len(images) > 0:
         embed.set_image(url=images[0])
     await ctx.send(embed=embed)
Esempio n. 5
0
def day_difference(a, b, location):
    diff = a - b
    return Translator.translate('days_ago', location, days=diff.days, date=a)
Esempio n. 6
0
 def assemble_reason(v):
     return Translator.translate('spam_infraction_reason',
                                 v.guild,
                                 channel=f"#{v.channel}",
                                 friendly=v.friendly)
Esempio n. 7
0
async def try_edit(message, emoji: str, string_name: str, embed=None, **kwargs):
    translated = Translator.translate(string_name, message.channel, **kwargs)
    try:
        return await message.edit(content=f'{Emoji.get_chat_emoji(emoji)} {translated}', embed=embed)
    except HTTPException:
        return await send_to(message.channel, emoji, string_name, embed=embed, **kwargs)
Esempio n. 8
0
async def send_to(destination, emoji, message, delete_after=None, translate=True, **kwargs):
    translated = Translator.translate(message, destination.guild, **kwargs) if translate else message
    return await destination.send(f"{Emoji.get_chat_emoji(emoji)} {translated}", delete_after=delete_after)
Esempio n. 9
0
async def empty_list(ctx, action):
    message = await ctx.send(
        Translator.translate('m_nobody', ctx, action=action))
Esempio n. 10
0
async def send_to(destination, emoji, message, translate=True, embed=None, attachment=None, **kwargs):
    translated = Translator.translate(message, destination.guild, **kwargs) if translate else message
    return await destination.send(f"{Emoji.get_chat_emoji(emoji)} {translated}", embed=embed, allowed_mentions=AllowedMentions(everyone=False, users=True, roles=False), file=attachment)
Esempio n. 11
0
    async def override_handler(self, message, t, text, voice):
        guild = self.bot.get_guild(message["guild_id"])

        if not DashConfig.is_numeric(message["role_id"]):
            raise ValidationException(dict(role_id="Not a valid id"))

        role = guild.get_role(int(message["role_id"]))
        if role is None:
            raise ValidationException(dict(role_id="Not a valid id"))
        if role.id == guild.id:
            raise ValidationException(
                dict(
                    role_id="The @everyone role can't be used for muting people"
                ))
        if role.managed:
            raise ValidationException(
                dict(
                    role_id=
                    "Managed roles can not be assigned to users and thus won't work for muting people"
                ))
        user = await Utils.get_user(message["user_id"])
        parts = {
            "role_name": Utils.escape_markdown(role.name),
            "role_id": role.id,
            "user": Utils.clean_user(user),
            "user_id": user.id
        }
        GearbotLogging.log_key(guild.id, f"config_mute_{t}_triggered", **parts)
        failed = []
        for channel in guild.text_channels:
            try:
                if text is None:
                    await channel.set_permissions(role,
                                                  reason=Translator.translate(
                                                      f'mute_{t}', guild.id),
                                                  overwrite=None)
                else:
                    await channel.set_permissions(role,
                                                  reason=Translator.translate(
                                                      f'mute_{t}', guild.id),
                                                  **text)
            except Forbidden as ex:
                failed.append(channel.mention)
        for channel in guild.voice_channels:
            try:
                if voice is None:
                    await channel.set_permissions(role,
                                                  reason=Translator.translate(
                                                      f'mute_{t}', guild.id),
                                                  overwrite=None)
                else:
                    await channel.set_permissions(role,
                                                  reason=Translator.translate(
                                                      f'mute_{t}', guild.id),
                                                  **voice)
            except Forbidden as ex:
                failed.append(
                    Translator.translate('voice_channel',
                                         guild.id,
                                         channel=channel.name))

        await asyncio.sleep(
            1
        )  # delay logging so the channel overrides can get querried and logged
        GearbotLogging.log_key(guild.id, f"config_mute_{t}_complete", **parts)

        out = '\n'.join(failed)
        GearbotLogging.log_key(
            guild.id,
            f"config_mute_{t}_failed",
            **parts,
            count=len(failed),
            tag_on=None if len(failed) is 0 else f'```{out}```')
Esempio n. 12
0
    async def _lift_tempban(self, infraction):
        guild = self.bot.get_guild(infraction.guild_id)
        if guild is None:
            GearbotLogging.info(
                f"Got an expired tempban for server {infraction.guild_id} but am no longer on that server"
            )
            return self.end_infraction(infraction)

        user = await Utils.get_user(infraction.user_id)
        info = {
            "user": Utils.clean_user(user),
            "user_id": infraction.user_id,
            "inf_id": infraction.id
        }

        if not guild.me.guild_permissions.ban_members:
            translated = Translator.translate("tempban_expired_missing_perms",
                                              guild.id, **info)
            GearbotLogging.log_to(
                guild.id, "MOD_ACTIONS",
                f"{Emoji.get_chat_emoji('WARNING')} {translated}")
            return self.end_infraction(infraction)

        try:
            await guild.get_ban(user)
        except discord.NotFound:
            translated = Translator.translate("tempban_already_lifted",
                                              guild.id, **info)
            GearbotLogging.log_to(
                guild.id, "MOD_ACTIONS",
                f"{Emoji.get_chat_emoji('WARNING')} {translated}")
            return self.end_infraction(infraction)

        fid = f"{guild.id}-{infraction.user_id}"
        self.bot.data["unbans"].add(fid)
        try:
            await guild.unban(user)
        except discord.Forbidden:
            self.bot.data["unbans"].remove(fid)
            translated = Translator.translate("tempban_expired_missing_perms",
                                              guild.id, **info)
            GearbotLogging.log_to(
                guild.id, "MOD_ACTIONS",
                f"{Emoji.get_chat_emoji('WARNING')} {translated}")
        except Exception as ex:
            self.bot.data["unbans"].remove(fid)
            translated = Translator.translate("tempban_expired_missing_perms",
                                              guild.id, **info)
            GearbotLogging.log_to(
                guild.id, "MOD_ACTIONS",
                f"{Emoji.get_chat_emoji('WARNING')} {translated}")
            await GlobalHandlers.handle_exception("Lift tempban", self.bot, ex,
                                                  **info)
        else:
            translated = Translator.translate("tempban_lifted", guild.id,
                                              **info)
            GearbotLogging.log_to(
                guild.id, "MOD_ACTIONS",
                f"{Emoji.get_chat_emoji('WARNING')} {translated}")
        finally:
            self.end_infraction(infraction)
Esempio n. 13
0
    async def _lift_mute(self, infraction: Infraction):
        # check if we're even still in the guild
        guild = self.bot.get_guild(infraction.guild_id)
        if guild is None:
            GearbotLogging.info(
                f"Got an expired mute for {infraction.guild_id} but i'm no longer in that server, marking mute as ended"
            )
            return self.end_infraction(infraction)

        role = Configuration.get_var(guild.id, "MUTE_ROLE")
        member = guild.get_member(infraction.user_id)
        role = guild.get_role(role)
        if role is None or member is None:
            return self.end_infraction(
                infraction)  # role got removed or member left

        info = {
            "user": Utils.clean_user(member),
            "user_id": infraction.user_id,
            "inf_id": infraction.id
        }

        if role not in member.roles:
            translated = Translator.translate('mute_role_already_removed',
                                              guild.id, **info)
            GearbotLogging.log_to(
                guild.id, "MOD_ACTIONS",
                f"{Emoji.get_chat_emoji('WARNING')} {translated}")
            return self.end_infraction(infraction)

        if not guild.me.guild_permissions.manage_roles:
            translated = Translator.translate('unmute_missing_perms', guild.id,
                                              **info)
            GearbotLogging.log_to(
                guild.id, "MOD_ACTIONS",
                f"{Emoji.get_chat_emoji('WARNING')} {translated}")
            return self.end_infraction(infraction)

        try:
            await member.remove_roles(role, reason="Mute expired")
        except discord.Forbidden:
            translated = Translator.translate('unmute_missing_perms', guild.id,
                                              **info)
            GearbotLogging.log_to(
                guild.id, "MOD_ACTIONS",
                f"{Emoji.get_chat_emoji('WARNING')} {translated}")
        except Exception as ex:
            translated = Translator.translate("unmute_unknown_error", guild.id,
                                              **info)
            GearbotLogging.log_to(
                guild.id, "MOD_ACTIONS",
                f"{Emoji.get_chat_emoji('WARNING')} {translated}")
            await GlobalHandlers.handle_exception("Automatic unmuting",
                                                  self.bot,
                                                  ex,
                                                  infraction=infraction)
        else:
            translated = Translator.translate('unmuted', guild.id, **info)
            GearbotLogging.log_to(
                guild.id, "MOD_ACTIONS",
                f"{Emoji.get_chat_emoji('INNOCENT')} {translated}")
        finally:
            self.end_infraction(infraction)
Esempio n. 14
0
    async def create(self,
                     ctx: commands.Context,
                     trigger: str,
                     *,
                     reply: str = None):
        """command_create_help"""
        if len(trigger) == 0:
            await ctx.send(
                f"{Emoji.get_chat_emoji('WHAT')} {Translator.translate('custom_command_empty_trigger', ctx.guild.id)}"
            )
        elif reply is None or reply == "":
            await ctx.send(
                f"{Emoji.get_chat_emoji('WHAT')} {Translator.translate('custom_command_empty_reply', ctx.guild.id)}"
            )
        elif len(trigger) > 20:
            await MessageUtils.send_to(ctx, 'WHAT',
                                       'custom_command_trigger_too_long')
        else:
            trigger = trigger.lower()
            trigger = await Utils.clean(trigger)
            command = await CustomCommand.get_or_none(serverid=ctx.guild.id,
                                                      trigger=trigger)
            if command is None:
                await CustomCommand.create(serverid=ctx.guild.id,
                                           trigger=trigger,
                                           response=reply,
                                           created_by=ctx.author.id)
                if ctx.guild.id not in self.commands:
                    self.commands[ctx.guild.id] = dict()
                self.commands[ctx.guild.id][trigger] = CommandInfo(
                    reply, ctx.author.id)
                await ctx.send(
                    f"{Emoji.get_chat_emoji('YES')} {Translator.translate('custom_command_added', ctx.guild.id, trigger=trigger)}"
                )
            else:
                message = None

                async def yes(interaction: disnake.Interaction):
                    await interaction.response.edit_message(
                        content=Translator.translate('updating', ctx.guild.id),
                        view=None)
                    await ctx.invoke(self.update, trigger, reply=reply)

                async def no(interaction):
                    await interaction.response.edit_message(
                        content=MessageUtils.assemble(ctx, 'NO',
                                                      'command_canceled'),
                        view=None)

                async def timeout():
                    if message is not None:
                        await message.edit(content=MessageUtils.assemble(
                            ctx, 'NO', 'command_canceled'),
                                           view=None)

                def check(interaction: Interaction):
                    return ctx.author.id == interaction.user.id and interaction.message.id == message.id

                message = await ctx.send(Translator.translate(
                    'custom_command_override_confirmation', ctx.guild.id),
                                         view=Confirm(ctx.guild.id,
                                                      on_yes=yes,
                                                      on_no=no,
                                                      on_timeout=timeout,
                                                      check=check))
Esempio n. 15
0
def server_info_embed(guild, request_guild=None):
    guild_features = ", ".join(guild.features)
    if guild_features == "":
        guild_features = None
    guild_made = guild.created_at.strftime("%d-%m-%Y")
    embed = discord.Embed(color=guild.roles[-1].color,
                          timestamp=datetime.utcfromtimestamp(time.time()))
    embed.set_thumbnail(url=guild.icon_url_as())
    embed.add_field(name=Translator.translate('server_name', request_guild),
                    value=guild.name,
                    inline=True)
    embed.add_field(name=Translator.translate('id', request_guild),
                    value=guild.id,
                    inline=True)
    embed.add_field(name=Translator.translate('owner', request_guild),
                    value=guild.owner,
                    inline=True)
    embed.add_field(name=Translator.translate('members', request_guild),
                    value=guild.member_count,
                    inline=True)

    embed.add_field(
        name=Translator.translate('channels', request_guild),
        value=
        f"{Emoji.get_chat_emoji('CATEGORY')} {Translator.translate('categories', request_guild)}: {str(len(guild.categories))}\n"
        f"{Emoji.get_chat_emoji('CHANNEL')} {Translator.translate('text_channels', request_guild)}: {str(len(guild.text_channels))}\n"
        f"{Emoji.get_chat_emoji('VOICE')} {Translator.translate('voice_channels', request_guild)}: {str(len(guild.voice_channels))}\n"
        f"{Translator.translate('total_channel', request_guild)}: {str(len(guild.text_channels) + len(guild.voice_channels))}",
        inline=True)
    embed.add_field(
        name=Translator.translate('created_at', request_guild),
        value=
        f"{guild_made} ({(datetime.fromtimestamp(time.time()) - guild.created_at).days} days ago)",
        inline=True)
    embed.add_field(name=Translator.translate('vip_features', request_guild),
                    value=guild_features,
                    inline=True)
    if guild.icon_url_as() != "":
        embed.add_field(
            name=Translator.translate('server_icon', request_guild),
            value=
            f"[{Translator.translate('server_icon', request_guild)}]({guild.icon_url_as()})",
            inline=True)

    roles = ", ".join(role.name for role in guild.roles)
    embed.add_field(
        name=Translator.translate('all_roles', request_guild),
        value=roles if len(roles) < 1024 else f"{len(guild.roles)} roles",
        inline=True)

    if guild.emojis:
        emoji = "".join(str(e) for e in guild.emojis)
        embed.add_field(
            name=Translator.translate('emoji', request_guild),
            value=emoji if len(emoji) < 1024 else f"{len(guild.emojis)} emoji")

    if guild.splash_url != "":
        embed.set_image(url=guild.splash_url)
    if guild.banner_url_as() != "":
        embed.set_image(url=guild.banner_url_as())

    return embed
Esempio n. 16
0
    async def mwarn(self, ctx, targets: Greedy[PotentialID], *,
                    reason: Reason):
        """mwarn_help"""

        reason += ",".join(
            Utils.assemble_attachment(ctx.message.channel.id, attachment.id,
                                      attachment.filename)
            for attachment in ctx.message.attachments)
        if len(reason) > 1800:
            raise TranslatedBadArgument('reason_too_long', ctx)

        message = None

        async def yes(interaction: Interaction):
            await interaction.response.edit_message(
                content=MessageUtils.assemble(ctx, "REFRESH", "processing"),
                view=None)
            failures = await Actions.mass_action(ctx,
                                                 "warning",
                                                 targets,
                                                 self._warn,
                                                 max_targets=10,
                                                 allow_bots=False,
                                                 message=False,
                                                 reason=reason,
                                                 dm_action=True)

            await interaction.edit_original_message(
                content=MessageUtils.assemble(ctx,
                                              "YES",
                                              "mwarn_confirmation",
                                              count=len(targets) -
                                              len(failures)))
            if len(failures) > 0:
                f = "\n".join(failures)
                pipe = self.bot.redis_pool.pipeline()
                k = f'mass_failures:{ctx.message.id}'
                pipe.set(k, f)
                pipe.expire(k, 7 * 24 * 60 * 60)
                await pipe.execute()
                pages = Pages.paginate(f, prefix='```\n', suffix='```')
                content, view, _ = SimplePager.get_parts(
                    pages, 0, ctx.guild.id,
                    f'mass_failures:{ctx.message.id}:warn')
                await ctx.send(
                    f"**{Translator.translate('mass_failures_warn', ctx, page_num=1, pages=len(pages))}**{content}",
                    view=view)

        async def no(interaction):
            await interaction.response.edit_message(
                content=MessageUtils.assemble(ctx, 'NO', 'command_canceled'),
                view=None)

        async def timeout():
            if message is not None:
                await message.edit(content=MessageUtils.assemble(
                    ctx, 'NO', 'command_canceled'),
                                   view=None)

        def check(interaction: Interaction):
            return ctx.author.id == interaction.user.id and interaction.message.id == message.id

        if len(targets) > 10:
            await MessageUtils.send_to(ctx,
                                       "NO",
                                       "mass_action_too_many_people",
                                       max=10)
            return
        if len(targets) > 0:
            message = await ctx.send(Translator.translate(
                "mwarn_confirm", ctx),
                                     view=Confirm(ctx.guild.id,
                                                  on_yes=yes,
                                                  on_no=no,
                                                  on_timeout=timeout,
                                                  check=check))
        else:
            await Utils.empty_list(ctx, "warn")
Esempio n. 17
0
    async def on_interaction(self, interaction):
        guild = self.bot.get_guild(interaction.guild_id)
        if interaction.type == InteractionType.component:
            cid = interaction.data.custom_id
            if cid.startswith('self_role'):
                parts = cid.split(':')
                if parts[1] == 'role':
                    rid = parts[2]
                    if rid.isnumeric():
                        rid = int(rid)
                        roles = Configuration.get_var(interaction.guild_id,
                                                      "ROLES", "SELF_ROLES")
                        if rid in roles:
                            role = guild.get_role(rid)
                            if role is None:
                                roles.remove(rid)
                                Configuration.set_var(interaction.guild_id,
                                                      "ROLES", "SELF_ROLES",
                                                      roles)
                                v = SelfRoleView(guild=guild, page=0)
                                interaction.response.edit_message(
                                    content=Translator.translate(
                                        "assignable_roles",
                                        interaction.guild_id,
                                        server_name=guild.name,
                                        page_num=1,
                                        page_count=v.pages),
                                    view=v)
                                interaction.followup.send_message(
                                    MessageUtils.assemble(
                                        interaction.guild_id, 'WARNING',
                                        'self_role_missing'),
                                    ephemeral=True)
                            else:
                                try:
                                    if role in interaction.user.roles:
                                        await interaction.user.remove_roles(
                                            role)
                                        await interaction.response.send_message(
                                            Translator.translate(
                                                "role_left",
                                                interaction.guild_id,
                                                role_name=role.name,
                                                user=interaction.user),
                                            ephemeral=True)
                                    else:
                                        await interaction.user.add_roles(role)
                                        await interaction.response.send_message(
                                            Translator.translate(
                                                "role_joined",
                                                interaction.guild_id,
                                                role_name=role.name,
                                                user=interaction.user),
                                            ephemeral=True)
                                except disnake.Forbidden:
                                    await interaction.response.send_message(
                                        f"{Emoji.get_chat_emoji('NO')} {Translator.translate('role_too_high_add', interaction.guild_id, role=role.name)}",
                                        ephemeral=True)
                elif parts[1] == "page":
                    v = SelfRoleView(guild=interaction.guild,
                                     page=int(parts[2]))
                    await interaction.response.edit_message(
                        content=Translator.translate(
                            "assignable_roles",
                            interaction.guild_id,
                            server_name=interaction.guild.name,
                            page_num=int(parts[2]) + 1,
                            page_count=v.pages),
                        view=v)
            elif cid.startswith('help:'):
                parts = cid.split(':')
                if parts[1] == 'page':
                    q = parts[3] if parts[3] != 'None' else None
                    content, view = await Help.message_parts(
                        self.bot, q, guild, interaction.user, int(parts[2]))
                    await interaction.response.edit_message(content=content,
                                                            view=view)
                elif parts[1] == 'selector':
                    q = interaction.values[0]
                    q = q if q != 'None' else None
                    content, view = await Help.message_parts(
                        self.bot, q, guild, interaction.user, 0)
                    await interaction.response.edit_message(content=content,
                                                            view=view)
            elif cid.startswith('pager:'):
                parts = cid.split(':')
                t = parts[2]
                if t == 'eval':
                    if interaction.user.id not in Configuration.get_master_var(
                            'BOT_ADMINS'):
                        return
                    output = await self.bot.redis_pool.get(f'eval:{parts[3]}')
                    if output is None:
                        await interaction.response.send_message(
                            "Eval output no longer available", ephemeral=True)
                    else:
                        pages = Pages.paginate(output,
                                               prefix='```py\n',
                                               suffix='```')
                        content, view, page_num = SimplePager.get_parts(
                            pages, int(parts[1]), interaction.guild_id,
                            f'eval:{parts[3]}')
                        await interaction.response.edit_message(
                            content=
                            f'Eval output {page_num + 1}/{len(pages)}{content}',
                            view=view)
                elif t == 'commands':
                    cog = self.bot.get_command("CustCommands")
                    if cog is not None:
                        pages = cog.get_command_pages(interaction.guild_id)
                        content, view, page_num = SimplePager.get_parts(
                            pages, int(parts[1]), guild.id, 'commands')
                        page = cog.gen_command_page(pages, page_num,
                                                    interaction.guild)
                        await interaction.response.edit_message(embed=page,
                                                                view=view)
                elif t == 'emoji':
                    cog = self.bot.get_cog('Emoji')
                    if cog is not None:
                        amount = len(guild.emojis) + 1
                        content, view, page_num = SimplePager.get_parts(
                            range(amount), int(parts[1]), interaction.guild.id,
                            'emoji')
                        await interaction.response.edit_message(
                            embed=cog.gen_emoji_page(guild, page_num),
                            view=view)
                elif t == 'role_list':
                    cog = self.bot.get_cog('Moderation')
                    if cog is not None:
                        pages = cog.gen_roles_pages(interaction.guild,
                                                    parts[3])
                        content, view, page_num = SimplePager.get_parts(
                            pages, int(parts[1]), guild.id,
                            f'role_list:{parts[3]}')
                        await interaction.response.edit_message(
                            content=
                            f"**{Translator.translate('roles', interaction.guild_id, server_name=guild.name, page_num=page_num + 1, pages=len(pages))}**```\n{pages[page_num]}```",
                            view=view)
                elif t == 'censor_list':
                    cog = self.bot.get_cog('Moderation')
                    if cog is not None:
                        censor_list = Configuration.get_var(
                            interaction.guild.id, "CENSORING",
                            "TOKEN_CENSORLIST")
                        pages = Pages.paginate("\n".join(censor_list))
                        page, view, page_num = SimplePager.get_parts(
                            pages, int(parts[1]), interaction.guild.id,
                            'censor_list')
                        await interaction.response.edit_message(
                            content=
                            f"**{Translator.translate(f'censor_list', guild, server=guild.name, page_num=page_num + 1, pages=len(pages))}**```\n{page}```",
                            view=view)
                elif t == 'word_censor_list':
                    cog = self.bot.get_cog('Moderation')
                    if cog is not None:
                        censor_list = Configuration.get_var(
                            guild.id, "CENSORING", "WORD_CENSORLIST")
                        pages = Pages.paginate("\n".join(censor_list))
                        page, view, page_num = SimplePager.get_parts(
                            pages, int(parts[1]), guild.id, 'word_censor_list')
                        await interaction.response.edit_message(
                            content=
                            f"**{Translator.translate(f'word_censor_list', guild, server=guild.name, page_num=page_num + 1, pages=len(pages))}**```\n{page}```",
                            view=view)
                elif t == 'full_censor_list':
                    cog = self.bot.get_cog('Moderation')
                    if cog is not None:
                        censor_list = Configuration.get_var(
                            guild.id, "CENSORING", "FULL_MESSAGE_LIST")
                        pages = Pages.paginate("\n".join(censor_list))
                        page, view, page_num = SimplePager.get_parts(
                            pages, int(parts[1]), guild.id, 'full_censor_list')
                        await interaction.response.edit_message(
                            content=
                            f"**{Translator.translate(f'full_censor_list', guild, server=guild.name, page_num=page_num + 1, pages=len(pages))}**```\n{page}```",
                            view=view)
                elif t == 'flag_list':
                    cog = self.bot.get_cog('Moderation')
                    if cog is not None:
                        censor_list = Configuration.get_var(
                            guild.id, "FLAGGING", "TOKEN_LIST")
                        pages = Pages.paginate("\n".join(censor_list))
                        page, view, page_num = SimplePager.get_parts(
                            pages, int(parts[1]), guild.id, 'flag_list')
                        await interaction.response.edit_message(
                            content=
                            f"**{Translator.translate(f'flagged_list', guild, server=guild.name, page_num=page_num + 1, pages=len(pages))}**```\n{page}```",
                            view=view)
                elif t == 'word_flag_list':
                    cog = self.bot.get_cog('Moderation')
                    if cog is not None:
                        censor_list = Configuration.get_var(
                            guild.id, "FLAGGING", "WORD_LIST")
                        pages = Pages.paginate("\n".join(censor_list))
                        page, view, page_num = SimplePager.get_parts(
                            pages, int(parts[1]), guild.id, 'word_flag_list')
                        await interaction.response.edit_message(
                            content=
                            f"**{Translator.translate(f'flagged_word_list', guild, server=guild.name, page_num=page_num + 1, pages=len(pages))}**```\n{page}```",
                            view=view)
                elif t == 'mass_failures':
                    output = await self.bot.redis_pool.get(
                        f'mass_failures:{parts[3]}')
                    if output is None:
                        await interaction.response.send_message(
                            MessageUtils.assemble(interaction.guild_id, 'NO',
                                                  'view_expired'),
                            ephemeral=True)
                    else:
                        pages = Pages.paginate(output,
                                               prefix='```\n',
                                               suffix='```')
                        content, view, page_num = SimplePager.get_parts(
                            pages, int(parts[1]), interaction.guild_id,
                            f'mass_failures:{parts[3]}:{parts[4]}')
                        await interaction.response.edit_message(
                            content=
                            f"**{Translator.translate(f'mass_failures_{parts[4]}', interaction.guild_id, page_num=page_num+1, pages=len(pages))}**{content}",
                            view=view)
            elif cid.startswith('einf_search:'):
                parts = cid.split(':')
                uid = int(parts[1])
                old_page = int(parts[2])
                t = parts[3]

                if t == 'first_page':
                    page, current, pages, query, fields = await get_ephemeral_cached_page(
                        interaction, uid, 0)
                    await interaction.response.edit_message(
                        content=await InfractionUtils.assemble_message(
                            interaction.guild_id, page, query, current, pages),
                        view=EphemeralInfSearch(filters=fields,
                                                pages=pages,
                                                current_page=current,
                                                guild_id=interaction.guild_id,
                                                userid=uid))
                elif t == 'prev_page':
                    page, current, pages, query, fields = await get_ephemeral_cached_page(
                        interaction, uid, old_page - 1)
                    await interaction.response.edit_message(
                        content=await InfractionUtils.assemble_message(
                            interaction.guild_id, page, query, current, pages),
                        view=EphemeralInfSearch(filters=fields,
                                                pages=pages,
                                                current_page=current,
                                                guild_id=interaction.guild_id,
                                                userid=uid))
                elif t == 'blank':
                    await interaction.response.send_message(
                        Emoji.get_chat_emoji('AE'), ephemeral=True)
                elif t == 'next_page':
                    page, current, pages, query, fields = await get_ephemeral_cached_page(
                        interaction, uid, old_page + 1)
                    await interaction.response.edit_message(
                        content=await InfractionUtils.assemble_message(
                            interaction.guild_id, page, query, current, pages),
                        view=EphemeralInfSearch(filters=fields,
                                                pages=pages,
                                                current_page=current,
                                                guild_id=interaction.guild_id,
                                                userid=uid))
                elif t == 'last_page':
                    page, current, pages, query, fields = await get_ephemeral_cached_page(
                        interaction, uid, 1000)
                    await interaction.response.edit_message(
                        content=await InfractionUtils.assemble_message(
                            interaction.guild_id, page, query, current, pages),
                        view=EphemeralInfSearch(filters=fields,
                                                pages=pages,
                                                current_page=current,
                                                guild_id=interaction.guild_id,
                                                userid=uid))
        elif interaction.type == InteractionType.application_command:
            if interaction.data.name == "Extract user IDs":
                self.bot.metrics.uid_usage.labels(
                    type="channel", cluster=self.bot.cluster).inc()
                await interaction.response.defer(ephemeral=True)
                parts = await Utils.get_user_ids(
                    interaction.data.resolved.messages[
                        interaction.data.target_id].content)
                if len(parts) > 0:
                    for chunk in Pages.paginate("\n".join(parts), 200):
                        await interaction.followup.send(chunk)
                else:
                    await interaction.followup.send(
                        MessageUtils.assemble(interaction.guild, "NO",
                                              "no_uids_found"))
            elif interaction.data["name"] == "Send user IDs to DM":
                self.bot.metrics.uid_usage.labels(
                    type="DM", cluster=self.bot.cluster).inc()
                await interaction.response.defer(ephemeral=True)
                parts = await Utils.get_user_ids(
                    interaction.data["resolved"]["messages"][
                        interaction.data["target_id"]]["content"])
                if len(parts) > 0:
                    try:
                        for chunk in Pages.paginate("\n".join(parts), 200):
                            await interaction.user.send(chunk)
                    except Forbidden:
                        await interaction.followup.send("Unable to send DM")
                    else:
                        await interaction.followup.send("IDs sent in DM")
                else:
                    try:
                        await interaction.user.send(
                            MessageUtils.assemble(interaction.guild, "NO",
                                                  "no_uids_found"))
                    except Forbidden:
                        await interaction.followup.send("Unable to send DM")
                    else:
                        await interaction.followup.send("IDs sent in DM")
            elif interaction.data.name == "Userinfo":
                if await Permissioncheckers.check_permission(
                        self.bot.get_command("userinfo"), interaction.guild,
                        interaction.user, self.bot):
                    t = "allowed"
                    target = interaction.data["target_id"]
                    member = None
                    user_dict = interaction.data["resolved"]["users"][target]
                    user = User(data=user_dict, state=interaction._state)
                    if "members" in interaction.data[
                            "resolved"] and target in interaction.data[
                                "resolved"]["members"]:
                        member_dict = interaction.data["resolved"]["members"][
                            target]
                        member_dict["user"] = user_dict
                        member = Member(data=member_dict,
                                        guild=interaction.guild,
                                        state=interaction._state)
                    embed = await Utils.generate_userinfo_embed(
                        user, member, interaction.guild, interaction.user)
                    await interaction.response.send_message(embed=embed,
                                                            ephemeral=True)
                else:
                    t = "denied"
                    await interaction.response.send_message(
                        MessageUtils.assemble(interaction.guild, 'LOCK',
                                              'permission_denied'),
                        ephemeral=True)
                self.bot.metrics.userinfo_usage.labels(
                    type=t, cluster=self.bot.cluster).inc()
            elif interaction.data.name == "Search Infractions":
                if await Permissioncheckers.check_permission(
                        self.bot.get_command("inf search"), interaction.guild,
                        interaction.user, self.bot):
                    uid = int(interaction.data["target_id"])
                    t = "allowed"
                    await interaction.response.send_message(
                        MessageUtils.assemble(interaction.guild, 'SEARCH',
                                              'inf_search_compiling'),
                        ephemeral=True)

                    pages = await InfractionUtils.fetch_infraction_pages(
                        interaction.guild.id, uid, 100,
                        ["[user]", "[mod]", "[reason]"], 0)
                    page = await self.bot.wait_for(
                        'page_assembled',
                        check=lambda l: l['key'] == get_key(
                            interaction.guild.id, uid, [
                                "[user]", "[mod]", "[reason]"
                            ], 100) and l['page_num'] == 0)
                    await interaction.edit_original_message(
                        content=await InfractionUtils.assemble_message(
                            interaction.guild.id, page['page'], uid, 0, pages),
                        view=EphemeralInfSearch(
                            filters=["[user]", "[mod]", "[reason]"],
                            pages=pages,
                            guild_id=interaction.guild.id,
                            userid=uid))
                else:
                    t = "denied"
                    await interaction.response.send_message(
                        MessageUtils.assemble(interaction.guild, 'LOCK',
                                              'permission_denied'),
                        ephemeral=True)
                self.bot.metrics.inf_search_usage.labels(
                    type=t, cluster=self.bot.cluster).inc()
Esempio n. 18
0
async def self_roles(bot, message, user_id, reaction, **kwargs):
    user = message.channel.guild.get_member(user_id)
    if user is None:
        if user_id is not 0:
            await remove_reaction(message, reaction, await bot.fetch_user(user_id))
            return kwargs
    bot.loop.create_task(remove_reaction(message, reaction, user))
    left = Emoji.get_chat_emoji('LEFT')
    right = Emoji.get_chat_emoji('RIGHT')
    refresh = Emoji.get_chat_emoji('REFRESH')
    r2 = "🔁"
    page_num = int(kwargs.get("page_num", 0))
    add = reaction not in [left, right, refresh, r2]
    if str(reaction) == left:
        page_num -= 1
        add = False
    elif str(reaction) == right:
        page_num += 1
        add = False
    elif str(reaction) in [refresh, r2]:
        if not message.channel.permissions_for(message.channel.guild.me).manage_messages:
            return kwargs
        await message.clear_reactions()
        await asyncio.sleep(0.2)
        add = False
    if add:
        for i in range(10):
            if str(reaction) == str(Emoji.get_emoji(str(i+1))):
                roles = Configuration.get_var(message.guild.id, "ROLES", "SELF_ROLES")
                if (i + 1) > len(roles):
                    return
                role = message.channel.guild.get_role(roles[page_num*10 + i])
                if role is None:
                    await Selfroles.validate_self_roles(bot, message.channel.guild)
                    return
                add_role = role not in user.roles
                try:
                    await (user.add_roles if add_role else user.remove_roles)(role)
                except Forbidden:
                    if message.channel.permissions_for(message.channel.guild.me).send_messages:
                        await MessageUtils.send_to(message.channel, "NO", "role_too_high_add", role=role.name)
                        return kwargs
                else:
                    if message.channel.permissions_for(message.channel.guild.me).send_messages:
                        await MessageUtils.send_to(message.channel, "YES", "role_joined" if add_role else "role_left", role_name=await Utils.clean(role.name), delete_after=10)
                        bot.loop.create_task(remove_reaction(message, reaction, user))
                        return kwargs

        return kwargs
    pages = Selfroles.gen_role_pages(message.channel.guild)

    if page_num >= len(pages):
        page_num = 0
    elif page_num < 0:
        page_num = len(pages) - 1
    kwargs["page_num"] = page_num
    embed = Embed(title=Translator.translate("assignable_roles", message.channel, server_name=message.channel.guild.name, page_num=page_num+1,
                                             page_count=len(pages)), colour=Colour(0xbffdd), description=pages[page_num])
    await message.edit(embed=embed)
    await Selfroles.update_reactions(message, pages[page_num], len(pages) > 1)
    bot.loop.create_task(bot.redis_pool.expire(f"self_role:{message.channel.guild.id}", int(kwargs.get("duration", 60 * 60 * 24 * 7))))
    return kwargs
Esempio n. 19
0
def server_info(guild, request_guild=None):
    guild_features = ", ".join(guild.features)
    if guild_features == "":
        guild_features = None
    guild_made = guild.created_at.strftime("%d-%m-%Y")
    embed = discord.Embed(color=guild.roles[-1].color,
                          timestamp=datetime.utcfromtimestamp(time.time()))
    embed.set_thumbnail(url=guild.icon_url)
    embed.add_field(name=Translator.translate('server_name', request_guild),
                    value=guild.name,
                    inline=True)
    embed.add_field(name=Translator.translate('id', request_guild),
                    value=guild.id,
                    inline=True)
    embed.add_field(name=Translator.translate('owner', request_guild),
                    value=guild.owner,
                    inline=True)
    embed.add_field(name=Translator.translate('members', request_guild),
                    value=guild.member_count,
                    inline=True)
    embed.add_field(name=Translator.translate('text_channels', request_guild),
                    value=str(len(guild.text_channels)),
                    inline=True)
    embed.add_field(name=Translator.translate('voice_channels', request_guild),
                    value=str(len(guild.voice_channels)),
                    inline=True)
    embed.add_field(
        name=Translator.translate('total_channel', request_guild),
        value=str(len(guild.text_channels) + len(guild.voice_channels)),
        inline=True)
    embed.add_field(
        name=Translator.translate('created_at', request_guild),
        value=
        f"{guild_made} ({(datetime.fromtimestamp(time.time()) - guild.created_at).days} days ago)",
        inline=True)
    embed.add_field(name=Translator.translate('vip_features', request_guild),
                    value=guild_features,
                    inline=True)
    if guild.icon_url != "":
        embed.add_field(
            name=Translator.translate('server_icon', request_guild),
            value=
            f"[{Translator.translate('server_icon', request_guild)}]({guild.icon_url})",
            inline=True)
    roles = ", ".join(role.name for role in guild.roles)
    embed.add_field(
        name=Translator.translate('all_roles', request_guild),
        value=roles if len(roles) < 1024 else f"{len(guild.roles)} roles",
        inline=True)
    if guild.emojis:
        emoji = "".join(str(e) for e in guild.emojis)
        embed.add_field(
            name=Translator.translate('emoji', request_guild),
            value=emoji if len(emoji) < 1024 else f"{len(guild.emojis)} emoji")
    statuses = dict(online=0, idle=0, dnd=0, offline=0)
    for m in guild.members:
        statuses[str(m.status)] += 1
    embed.add_field(
        name=Translator.translate('member_statuses', request_guild),
        value="\n".join(
            f"{Emoji.get_chat_emoji(status.upper())} {Translator.translate(status, request_guild)}: {count}"
            for status, count in statuses.items()))
    if guild.splash_url != "":
        embed.set_image(url=guild.splash_url)
    return embed
Esempio n. 20
0
def assemble(destination, emoji, m, translate=True, **kwargs):
    translated = Translator.translate(m, destination, **
                                      kwargs) if translate else m
    return f"{Emoji.get_chat_emoji(emoji)} {translated}"
Esempio n. 21
0
def server_info_embed(guild, request_guild=None):
    guild_features = ", ".join(guild.features).title().replace("_", " ")
    if guild_features == "":
        guild_features = None
    guild_made = guild.created_at
    embed = disnake.Embed(
        color=guild.roles[-1].color,
        timestamp=datetime.datetime.utcfromtimestamp(
            time.time()).replace(tzinfo=datetime.timezone.utc))
    if guild.icon is not None:
        embed.set_thumbnail(url=guild.icon.url)
    embed.add_field(name=Translator.translate('server_name', request_guild),
                    value=guild.name,
                    inline=True)
    embed.add_field(name=Translator.translate('id', request_guild),
                    value=guild.id,
                    inline=True)
    embed.add_field(name=Translator.translate('owner', request_guild),
                    value=guild.owner,
                    inline=True)
    embed.add_field(name=Translator.translate('members', request_guild),
                    value=guild.member_count,
                    inline=True)

    embed.add_field(
        name=Translator.translate('channels', request_guild),
        value=
        f"{Emoji.get_chat_emoji('CATEGORY')} {Translator.translate('categories', request_guild)}: {str(len(guild.categories))}\n"
        f"{Emoji.get_chat_emoji('CHANNEL')} {Translator.translate('text_channels', request_guild)}: {str(len(guild.text_channels))}\n"
        f"{Emoji.get_chat_emoji('VOICE')} {Translator.translate('voice_channels', request_guild)}: {str(len(guild.voice_channels))}\n"
        f"{Translator.translate('total_channel', request_guild)}: {str(len(guild.text_channels) + len(guild.voice_channels))}",
        inline=True)
    embed.add_field(
        name=Translator.translate('created_at', request_guild),
        value=
        f"{utils.format_dt(guild_made, 'F')} ({utils.format_dt(guild_made, 'R')})",
        inline=True)
    embed.add_field(name=Translator.translate('vip_features', request_guild),
                    value=guild_features,
                    inline=True)
    if guild.icon is not None:
        embed.add_field(
            name=Translator.translate('server_icon', request_guild),
            value=
            f"[{Translator.translate('server_icon', request_guild)}]({guild.icon.url})",
            inline=True)

    roles = ", ".join(role.name for role in guild.roles)
    embed.add_field(
        name=Translator.translate('all_roles', request_guild),
        value=roles if len(roles) < 1024 else f"{len(guild.roles)} roles",
        inline=False)

    if guild.emojis:
        emoji = "".join(str(e) for e in guild.emojis)
        embed.add_field(
            name=Translator.translate('emoji', request_guild),
            value=emoji if len(emoji) < 1024 else f"{len(guild.emojis)} emoji")

    if guild.splash is not None:
        embed.set_image(url=guild.splash.url)
    if guild.banner is not None:
        embed.set_image(url=guild.banner.url)

    return embed
Esempio n. 22
0
 async def no():
     await ctx.send(
         Translator.translate('custom_command_not_updating',
                              ctx.guild.id))
Esempio n. 23
0
 def __init__(self, key, ctx, arg=None, **kwargs):
     super().__init__(Translator.translate(key, ctx, arg=Utils.trim_message(Utils.clean_name(str(arg)), 1000), **kwargs))
Esempio n. 24
0
    async def on_raw_message_delete(self, data: RawMessageDeleteEvent):
        if data.message_id in self.bot.data["message_deletes"]:
            self.bot.data["message_deletes"].remove(data.message_id)
            return
        c = self.bot.get_channel(data.channel_id)
        if c is None or isinstance(c, DMChannel) or c.guild is None or (
                not Features.is_logged(c.guild.id, "MESSAGE_LOGS")
        ) or data.channel_id in Configuration.get_var(
                c.guild.id, "MESSAGE_LOGS", "IGNORED_CHANNELS_OTHER"):
            return
        message = await MessageUtils.get_message_data(self.bot,
                                                      data.message_id)
        if message is not None:
            if message.channel in self.bot.being_cleaned:
                self.bot.being_cleaned[message.channel].add(data.message_id)
                return
            guild = self.bot.get_guild(message.server)
            user: discord.User = await Utils.get_user(message.author)
            hasUser = user is not None
            if not hasUser or user.id in Configuration.get_var(
                    guild.id, "MESSAGE_LOGS",
                    "IGNORED_USERS") or user.id == guild.me.id:
                return
            channel = self.bot.get_channel(message.channel)
            name = Utils.clean_user(user) if hasUser else str(message.author)
            _time = Utils.to_pretty_time(
                (datetime.datetime.utcnow() -
                 snowflake_time(data.message_id)).total_seconds(), guild.id)
            with_id = Configuration.get_var(guild.id, "MESSAGE_LOGS",
                                            "MESSAGE_ID")
            reply_str = ""
            if message.reply_to is not None:
                reply_str = f"\n**{Translator.translate('in_reply_to', guild.id)}: **<{assemble_jumplink(guild.id, channel.id, message.reply_to)}>"
            GearbotLogging.log_key(
                guild.id,
                'message_removed_with_id' if with_id else 'message_removed',
                name=name,
                user_id=user.id if hasUser else 'WEBHOOK',
                channel=channel.mention,
                message_id=data.message_id,
                time=_time.strip(),
                reply=reply_str)
            type_string = None
            if message.type is not None:
                if message.type == MessageType.new_member.value:
                    type_string = Translator.translate(
                        'system_message_new_member', guild)
                elif message.type == MessageType.pins_add.value:
                    type_string = Translator.translate(
                        'system_message_new_pin', guild)
                else:
                    type_string = Translator.translate(
                        'system_message_unknown', guild)

                type_string = Translator.translate('system_message',
                                                   guild,
                                                   type=type_string)
            if Configuration.get_var(channel.guild.id, "MESSAGE_LOGS",
                                     "EMBED"):
                embed_content = type_string or message.content

                if len(embed_content) == 0:
                    embed_content = Translator.translate(
                        'no_content_embed', guild)

                embed = discord.Embed(
                    timestamp=datetime.datetime.utcfromtimestamp(time.time()),
                    description=embed_content)
                embed.set_author(
                    name=user.name if hasUser else message.author,
                    icon_url=user.avatar_url if hasUser else EmptyEmbed)

                embed.set_footer(text=Translator.translate(
                    'sent_in', guild, channel=channel.name))
                if len(message.attachments) > 0:
                    embed.add_field(
                        name=Translator.translate('attachment_link', guild),
                        value='\n'.join(
                            Utils.assemble_attachment(
                                channel.id, attachment.id, attachment.name)
                            for attachment in message.attachments))
                GearbotLogging.log_raw(guild.id,
                                       "message_removed",
                                       embed=embed)
            else:
                if type_string is None:
                    if len(message.content) != 0:
                        cleaned_content = await Utils.clean(
                            message.content, channel.guild)
                        GearbotLogging.log_raw(
                            guild.id, 'message_removed',
                            Translator.translate('content',
                                                 guild.id,
                                                 content=cleaned_content))
                else:
                    GearbotLogging.log_raw(guild.id, "message_removed",
                                           type_string)

                count = 1
                multiple_attachments = len(message.attachments) > 1
                for attachment in message.attachments:
                    attachment_url = Utils.assemble_attachment(
                        channel.id, attachment.id, attachment.name)
                    if multiple_attachments:
                        attachment_str = Translator.translate(
                            'attachment_item',
                            guild,
                            num=count,
                            attachment=attachment_url)
                    else:
                        attachment_str = Translator.translate(
                            'attachment_single',
                            guild,
                            attachment=attachment_url)

                    GearbotLogging.log_raw(guild.id, "message_removed",
                                           attachment_str)
                    count += 1
Esempio n. 25
0
    async def quote(self, ctx: commands.Context, *, message: Message):
        """quote_help"""
        await ctx.trigger_typing()
        member = message.guild.get_member(ctx.author.id)
        if member is None:
            await MessageUtils.send_to(ctx, 'NO', 'quote_not_visible_to_user')
        else:
            permissions = message.channel.permissions_for(member)
            if permissions.read_message_history and permissions.read_message_history:
                if message.channel.is_nsfw() and not ctx.channel.is_nsfw():
                    await MessageUtils.send_to(ctx, 'NO', 'quote_nsfw_refused')
                else:
                    attachment = None
                    attachments = LoggedAttachment.select().where(
                        LoggedAttachment.messageid == message.id)
                    if len(attachments) == 1:
                        attachment = attachments[0]
                    embed = discord.Embed(colour=discord.Color(0xd5fff),
                                          timestamp=message.created_at)
                    if message.content is None or message.content == "":
                        if attachment is not None:
                            url = Utils.assemble_attachment(
                                message.channel.id, attachment.id,
                                attachment.name)
                            if attachment.isImage:
                                embed.set_image(url=url)
                            else:
                                embed.add_field(name=Translator.translate(
                                    "attachment_link", ctx),
                                                value=url)
                    else:
                        description = message.content
                        embed = discord.Embed(colour=discord.Color(0xd5fff),
                                              description=description,
                                              timestamp=message.created_at)
                        embed.add_field(
                            name="тАЛ",
                            value=f"[Jump to message]({message.jump_url})")
                        if attachment is not None:
                            url = Utils.assemble_attachment(
                                message.channel.id, attachment.id,
                                attachment.name)
                            if attachment.isImage:
                                embed.set_image(url=url)
                            else:
                                embed.add_field(name=Translator.translate(
                                    "attachment_link", ctx),
                                                value=url)
                    user = message.author
                    embed.set_author(name=user.name, icon_url=user.avatar_url)
                    embed.set_footer(text=Translator.translate(
                        "quote_footer",
                        ctx,
                        channel=message.channel.name,
                        user=Utils.clean_user(ctx.author),
                        message_id=message.id))
                    await ctx.send(embed=embed)
                    if ctx.channel.permissions_for(ctx.me).manage_messages:
                        await ctx.message.delete()

            else:
                await MessageUtils.send_to(ctx, 'NO',
                                           'quote_not_visible_to_user')
Esempio n. 26
0
    async def about(self, ctx):
        """about_help"""
        uptime = datetime.utcnow() - self.bot.start_time
        hours, remainder = divmod(int(uptime.total_seconds()), 3600)
        days, hours = divmod(hours, 24)
        minutes, seconds = divmod(remainder, 60)
        tacos = "{:,}".format(round(self.bot.eaten))
        user_messages = "{:,}".format(self.bot.user_messages)
        bot_messages = "{:,}".format(self.bot.bot_messages)
        self_messages = "{:,}".format(self.bot.self_messages)
        total = "{:,}".format(
            sum(len(guild.members) for guild in self.bot.guilds))
        unique = "{:,}".format(len(self.bot.users))
        embed = discord.Embed(
            colour=discord.Colour(0x00cea2),
            timestamp=datetime.utcfromtimestamp(time.time()),
            description=MessageUtils.assemble(ctx,
                                              'DIAMOND',
                                              'about_spinning_gears',
                                              duration=Translator.translate(
                                                  'dhms',
                                                  ctx,
                                                  days=days,
                                                  hours=hours,
                                                  minutes=minutes,
                                                  seconds=seconds)) + "\n" +
            MessageUtils.assemble(ctx,
                                  'GOLD',
                                  'about_messages',
                                  user_messages=user_messages,
                                  bot_messages=bot_messages,
                                  self_messages=self_messages) + "\n" +
            MessageUtils.assemble(
                ctx, 'IRON', 'about_grinders', errors=self.bot.errors) + "\n" +
            MessageUtils.assemble(
                ctx,
                'STONE',
                'about_commands',
                commandCount=self.bot.commandCount,
                custom_command_count=self.bot.custom_command_count) + "\n" +
            MessageUtils.assemble(
                ctx, 'WOOD', 'about_guilds', guilds=len(self.bot.guilds)) +
            "\n" + MessageUtils.assemble(
                ctx, 'INNOCENT', 'about_users', total=total, unique=unique) +
            "\n" +
            MessageUtils.assemble(ctx, 'TACO', 'about_tacos', tacos=tacos) +
            "\n" + MessageUtils.assemble(
                ctx, 'ALTER', 'commit_hash', hash=self.bot.version) +
            MessageUtils.assemble(ctx, 'TODO', 'about_stats'))

        click_here = Translator.translate('click_here', ctx)
        embed.add_field(name=Translator.translate('support_server', ctx),
                        value=f"[{click_here}](https://discord.gg/vddW3D9)")
        embed.add_field(name=Translator.translate('website', ctx),
                        value=f"[{click_here}](https://gearbot.rocks)")
        embed.add_field(
            name=f"Github",
            value=f"[{click_here}](https://github.com/gearbot/GearBot)")
        embed.set_footer(text=self.bot.user.name,
                         icon_url=self.bot.user.avatar_url)

        await ctx.send(embed=embed)
Esempio n. 27
0
 async def yes(interaction: disnake.Interaction):
     await interaction.response.edit_message(
         content=Translator.translate('updating', ctx.guild.id),
         view=None)
     await ctx.invoke(self.update, trigger, reply=reply)
Esempio n. 28
0
 async def yes():
     await ctx.send(
         Translator.translate('updating', ctx.guild.id))
     await ctx.invoke(self.update, trigger, reply=reply)
Esempio n. 29
0
    async def censor_message(self, message: discord.Message):
        ctx = await self.bot.get_context(message)
        if message.guild is None or \
                message.webhook_id is not None or \
                message.author == message.guild.me or \
                not Configuration.get_var(message.guild.id, "CENSOR_MESSAGES") or \
                Permissioncheckers.get_user_lvl(ctx) >= 2:
            return

        blacklist = Configuration.get_var(message.guild.id, "WORD_BLACKLIST")
        max_mentions = Configuration.get_var(message.guild.id, "MAX_MENTIONS")
        guilds = Configuration.get_var(message.guild.id, "INVITE_WHITELIST")
        content = message.content.replace('\\', '')
        censored = False
        if len(guilds) is not 0:
            codes = INVITE_MATCHER.findall(content)
            for code in codes:
                try:
                    invite: discord.Invite = await self.bot.get_invite(code)
                except discord.NotFound:
                    await censor_invite(ctx, code, "INVALID INVITE")
                except KeyError:
                    await censor_invite(ctx, code, "DM group")
                    censored = True
                else:
                    if invite.guild is None or (not invite.guild.id in guilds and invite.guild.id != message.guild.id):
                        await censor_invite(ctx, code, invite.guild.name)
                        censored = True

        if not censored:
            content = content.lower()
            for bad in (w.lower() for w in blacklist):
                if bad in content:
                    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  # lost the race with another bot?
                        else:
                            clean_message = await clean_content().convert(ctx, message.content)
                            GearbotLogging.log_to(ctx.guild.id, "CENSORED_MESSAGES",
                                                  f":no_entry_sign: {Translator.translate('censored_message', ctx.guild.id, user=message.author, user_id=message.author.id, message=clean_message, sequence=bad, channel=message.channel.mention)}")
                    else:
                        clean_message = await clean_content().convert(ctx, message.content)
                        GearbotLogging.log_to(ctx.guild.id, "CENSORED_MESSAGES",
                                              f":no_entry_sign: {Translator.translate('censor_message_failed', ctx.guild.id, user=message.author, user_id=message.author.id, message=clean_message, sequence=bad, link=message.jump_url)}")

        mentions = len(message.mentions) + len(message.role_mentions)
        if mentions > max_mentions > 4:
            self.bot.data["forced_exits"].add(message.author.id)
            reason = Translator.translate('autoban_too_many_mentions', message.guild.id, count=mentions)

            if message.guild.me.guild_permissions.ban_members:
                await message.guild.ban(message.author, reason=reason)
                Infraction.update(active=False).where(
                    (Infraction.user_id == message.author.id) & (Infraction.type == "Unban") &
                    (Infraction.guild_id == ctx.guild.id)).execute()
                InfractionUtils.add_infraction(message.guild.id, message.author.id, self.bot.user.id, "AUTOBAN", reason)
                GearbotLogging.log_to(ctx.guild.id, "MOD_ACTIONS",
                                      f":door: {Translator.translate('ban_log', ctx.guild.id, user=message.author, user_id=message.author.id, moderator=self.bot.user, moderator_id=self.bot.user.id, reason=reason)}")
            else:
                self.bot.data["forced_exits"].remove(message.author.id)
                translated = Translator.translate('automod_ban_failed', message.guild.id, user=message.author,
                                                  user_id=message.author.id, reason=reason)
                GearbotLogging.log_to(message.guild.id, "MOD_ACTIONS",
                                      f"{Emoji.get_chat_emoji('WARNING')} {translated}")