Exemple #1
0
    async def unban(self, ctx, user_s):
        if not has_permissions(ctx.author, ["ban_members"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               "> Банить участников"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            bans = await ctx.guild.bans()
            text = None
            for case in bans:
                if case.user.id == carve_int(
                        user_s) or f"{case.user}" == user_s:
                    user = case.user
                    text = f"{case.reason}"
                    break
            if text == None:
                reply = discord.Embed(
                    title="💢 Упс",
                    description=f"Пользователя {user_s} нет в списке банов",
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            else:
                bruh = text.split("|", maxsplit=1)
                case = None
                if len(bruh) > 1 and bruh[0].isdigit():
                    collection = db["bans"]
                    result = collection.find_one({
                        "_id": ctx.guild.id,
                        f"{user.id}": {
                            "$exists": True
                        }
                    })
                    if result != None:
                        case = result[f"{user.id}"]
                        log_emb = await withdraw.tempban(
                            ctx.guild, user.id, case, 0)

                if case == None:
                    await ctx.guild.unban(user)
                    log_emb = discord.Embed(
                        title="🚫 Пользователь разбанен",
                        description=("**Подробнее о снятом бане:**\n"
                                     f"> **Пользователь:** {user}\n"
                                     f"> **Модератор:** {ctx.author}\n"
                                     f"> **Причина:** {text}"),
                        color=discord.Color.red())

                if log_emb != None:
                    await post_log(ctx.guild, log_emb)
                    await ctx.send(embed=log_emb, delete_after=3)
                await ctx.message.delete()
Exemple #2
0
    async def auto_role_remove(self, ctx, bound, role_s):
        bound = bound.lower()
        if not has_permissions(ctx.author, ["administrator"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               "> Администратор"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        elif bound != "delete" and not bound.isdigit():
            reply = discord.Embed(
                title="💢 Упс",
                description=
                f"Аргумент \"{bound}\" должен быть целым числом или параметром `delete`",
                color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            role = detect.role(ctx.guild, role_s)
            if role is None:
                reply = discord.Embed(
                    title="💢 Упс",
                    description=
                    f"Вы ввели {role_s}, подразумевая роль, но она не была найдена.",
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            else:
                collection = db["tokens"]
                if bound == "delete":
                    collection.find_one_and_update(
                        {"_id": ctx.guild.id},
                        {"$unset": {
                            f"remove.{role.id}": ""
                        }})
                    desc = f"Роль <@&{role.id}> больше не снимается автоматически"
                else:
                    collection.find_one_and_update(
                        {"_id": ctx.guild.id},
                        {"$set": {
                            f"remove.{role.id}": int(bound)
                        }},
                        upsert=True)
                    desc = f"Роль <@&{role.id}> теперь снимается при достижении {bound}+ токенов"

                reply = discord.Embed(title="✅ Выполнено",
                                      description=desc,
                                      color=col("dg"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)
Exemple #3
0
    async def unmute(self, ctx, member_s):
        if not has_permissions(ctx.author, ["manage_messages"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               "> Управлять сообщениями"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            member = detect.member(ctx.guild, member_s)

            if member == None:
                reply = discord.Embed(
                    title="💢 Упс",
                    description=
                    f"Вы указали {member_s}, подразумевая участника, но он не был найден",
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            elif ctx.author.top_role.position <= member.top_role.position and ctx.author.id != ctx.guild.owner_id:
                reply = discord.Embed(
                    title="💢 Позиция",
                    description=f"Ваша наивысшая роль не выше роли {member}",
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            elif ctx.guild.me.top_role.position <= member.top_role.position:
                reply = discord.Embed(
                    title="⚠ У меня нет прав",
                    description=(
                        f"Моя наивысшая роль не выше роли {member}\n"
                        "Чтобы исправить это, перетащите мою роль выше"),
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            elif mute_role_name not in [r.name for r in member.roles]:
                reply = discord.Embed(
                    title="💢 Ошибка",
                    description=f"На участника {member_s} не наложен мут",
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            else:
                log = await withdraw.mute(member, sec=0)
                await post_log(ctx.guild, log)
                await ctx.send(embed=log, delete_after=3)
                await ctx.message.delete()
Exemple #4
0
    async def kick(self, ctx, member_s, *, reason="не указана"):
        member = detect.member(ctx.guild, member_s)

        if not has_permissions(ctx.author, ["kick_members"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               "> Кикать участников"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        elif member == None:
            reply = discord.Embed(
                title="💢 Упс",
                description=
                f"Вы указали {member_s}, подразумевая участника, но он не был найден",
                color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        elif member.top_role.position >= ctx.author.top_role.position and ctx.author.id != ctx.guild.owner_id:
            reply = discord.Embed(
                title="💢 Позиция",
                description=f"Ваша наивысшая роль не выше роли {member}",
                color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        elif ctx.guild.me.top_role.position <= member.top_role.position:
            reply = discord.Embed(
                title="⚠ У меня нет прав",
                description=(f"Моя наивысшая роль не выше, чем роль {member}\n"
                             "Чтобы исправить это, перетащите мою роль выше"),
                color=discord.Color.dark_gold())
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            log_emb = discord.Embed(
                title="⚖ Участник исключён",
                description=(f"**Участник:** {member}\n"
                             f"**Модератор:** {ctx.author}\n"
                             f"**Причина:** {reason}"),
                color=col(50, 50, 50))

            await ctx.guild.kick(member, reason=reason)
            await post_log(ctx.guild, log_emb)
            await ctx.send(embed=log_emb, delete_after=3)
            await ctx.message.delete()
Exemple #5
0
    async def log_channel(self, ctx, c_search):
        channel = detect.channel(ctx.guild, c_search)

        args_passed = False
        if not has_permissions(ctx.author, ["administrator"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               f"> Администратор"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        elif c_search.lower() == "delete":
            args_passed = True
            value = None

        elif channel == None:
            reply = discord.Embed(
                title="💢 Ошибка",
                description=
                f"Вы ввели {c_search}, подразумевая канал, но он не был найден",
                color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            args_passed = True
            value = channel.id

        if args_passed:
            collection = db["channels"]
            collection.find_one_and_update({"_id": ctx.guild.id},
                                           {"$set": {
                                               "mod_log": value
                                           }},
                                           upsert=True)
            if value == None:
                text = "Канал для отчётов удалён"
            else:
                text = f"Канал для отчётов настроен как {channel.mention}"

            reply = discord.Embed(title="✅ Выполнено",
                                  description=text,
                                  color=col("dg"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)
Exemple #6
0
    async def server_stats(self, ctx, option="None"):
        p = ctx.prefix
        option = option.lower()
        true_options = ["on", "вкл", "1"]
        false_options = ["off", "выкл", "0"]

        if not has_permissions(ctx.author, ["administrator"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               f"> Администратор"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        elif option not in true_options and option not in false_options:
            reply = discord.Embed(
                title="⚙ Отображение статистики сервера",
                description=(f"• Включить: `{p}server-stats on`\n"
                             f"• Выключить: `{p}server-stats off`\n"
                             "Введите один из параметров `on`, `off`"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            if option in true_options:
                option = True
                desc = "Отображение статистики сервера включено ✅"
            else:
                option = False
                desc = "Отображение статистики сервера выключено ❎"
            collection = db["levers"]

            collection.find_one_and_update({"_id": ctx.guild.id},
                                           {"$set": {
                                               "stats_on": option
                                           }},
                                           upsert=True)
            reply = discord.Embed(
                title="⚙ Выполнено",
                description=(f"{desc}\n"
                             f"-> Текущие настройки: `{p}how-set`"),
                color=col("dg"))
            await ctx.send(embed=reply)
Exemple #7
0
    async def token_operator(self, ctx, *, role_s):
        if not has_permissions(ctx.author, ["administrator"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               f"> Администратор"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            correct_role_arg = True
            if role_s.lower() == "delete":
                role = None
                desc = "Роль переводчика токенов удалена"
            else:
                role = detect.role(ctx.guild, role_s)
                if role is None:
                    correct_role_arg = False

                    reply = discord.Embed(
                        title="💢 Упс",
                        description=
                        f"Вы ввели {role_s}, подразумевая роль, но она не была найдена.",
                        color=col("dr"))
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)
                else:
                    desc = f"Роль переводчика токенов настроена как <@&{role.id}>"

            if correct_role_arg:
                collection = db["tokens"]
                collection.find_one_and_update(
                    {"_id": ctx.guild.id}, {"$set": {
                        "master_role": role.id
                    }},
                    upsert=True)
                reply = discord.Embed(title="✅ Выполнено",
                                      description=desc,
                                      color=col("dg"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)
Exemple #8
0
    async def unwarn(self, ctx, member_s, number):
        p = ctx.prefix
        number = number.lower()
        if not has_permissions(ctx.author, ["ban_members"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               f"> Банить участников"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            member = detect.member(ctx.guild, member_s)
            if member is None:
                reply = discord.Embed(
                    title="💢 Упс",
                    description=
                    f"Вы указали {member_s}, подразумевая участника, но он не был найден",
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            elif number != "all" and not number.isdigit():
                reply = discord.Embed(
                    title="💢 Ошибка",
                    description=
                    (f"Номер варна должен быть целым числом или параметром `all`. Введено: {number}\n"
                     f"Подробнее: `{p}unwarn`"),
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)
            else:
                collection = db["warns"]
                desc = None
                if number == "all":
                    collection.find_one_and_update(
                        {
                            "_id": ctx.guild.id,
                            f"{member.id}": {
                                "$exists": True
                            }
                        }, {"$unset": {
                            f"{member.id}": ""
                        }})
                    desc = (f"**Участник:** {member}\n"
                            f"**Модератор:** {ctx.author}\n"
                            f"**Все предупреждения** сняты")
                else:
                    number = int(number)
                    result = collection.find_one(
                        {
                            "_id": ctx.guild.id,
                            f"{member.id}": {
                                "$exists": True
                            }
                        },
                        projection={f"{member.id}": True})
                    member_warns = get_field(result, f"{member.id}")

                    if member_warns is None or member_warns == []:
                        error_desc = f"У участника {member} нет предупреждений"
                    elif len(member_warns) < number or number < 1:
                        error_desc = f"Варн не найден. Всего варнов: {len(member_warns)}"
                    else:
                        member_warns.pop(number - 1)
                        collection.find_one_and_update(
                            {
                                "_id": ctx.guild.id,
                                f"{member.id}": {
                                    "$exists": True
                                }
                            }, {"$set": {
                                f"{member.id}": member_warns
                            }})
                        desc = (f"**Участник:** {member}\n"
                                f"**Модератор:** {ctx.author}\n"
                                f"**Номер:** {number}")

                if desc is None:
                    reply = discord.Embed(title="💢 Ошибка",
                                          description=error_desc)
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

                else:
                    log_emb = discord.Embed(title="♻ Сняты предупреждения",
                                            description=desc,
                                            color=col("dg"))
                    log_emb.set_footer(text=f"{ctx.author}",
                                       icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=log_emb, delete_after=3)
                    await post_log(ctx.guild, log_emb)
                    await ctx.message.delete()
Exemple #9
0
    async def warn(self, ctx, member_s, *, reason="не указана"):
        if not has_permissions(ctx.author, ["ban_members"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               f"> Банить участников"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            member = detect.member(ctx.guild, member_s)
            if member is None:
                reply = discord.Embed(
                    title="💢 Упс",
                    description=
                    f"Вы указали {member_s}, подразумевая участника, но он не был найден",
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            elif member.top_role.position >= ctx.author.top_role.position and ctx.author.id != ctx.guild.owner_id:
                reply = discord.Embed(
                    title="💢 Упс",
                    description="Роль этого участника не ниже Вашей",
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            else:
                collection = db["warns"]

                result = collection.find_one({
                    "_id": ctx.guild.id,
                    f"{member.id}": {
                        "$exists": True
                    }
                })
                member_warns = get_field(result, f"{member.id}")
                if member_warns is None:
                    total_warns = 0
                else:
                    total_warns = len(member_warns)

                if total_warns >= 5:
                    reply = discord.Embed(
                        title="💢 Лимит",
                        description=
                        "У участника не может быть больше **5** предупреждений",
                        color=col("dr"))
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

                elif total_warns >= 4:
                    sec = 24 * 3600
                    log_emb = discord.Embed(
                        title="⛔ Пользователь временно забанен",
                        description=
                        (f"**Пользователь:** {member}\n"
                         f"**Модератор:** {ctx.author}\n"
                         f"**Длительность:** {visual_delta(datetime.timedelta(seconds=sec))}\n"
                         f"**Причина:** набрал 5 или более предупреждений"),
                        color=discord.Color.red())
                    await do_tempban(member, ctx.author, sec, reason)

                    await post_log(ctx.guild, log_emb)
                    await ctx.send(embed=log_emb, delete_after=3)
                    await ctx.message.delete()
                    await try_send(member, embed=log_emb)

                    log_emb = await withdraw_tempban(ctx.guild, member.id)
                    if log_emb != None:
                        await post_log(ctx.guild, log_emb)

                else:
                    warn_json = {
                        "mod_id": ctx.author.id,
                        "reason": reason,
                        "timestamp": datetime.datetime.utcnow()
                    }

                    collection.find_one_and_update(
                        {"_id": ctx.guild.id},
                        {"$addToSet": {
                            f"{member.id}": warn_json
                        }},
                        upsert=True)

                    warn_log = discord.Embed(
                        title="🔸 Предупреждение",
                        description=(f"**Участник:** {member}\n"
                                     f"**Модератор:** {ctx.author}\n"
                                     f"**Причина:** {reason}\n"),
                        color=col("o"))
                    await ctx.send(embed=warn_log, delete_after=3)
                    await post_log(ctx.guild, warn_log)
                    await ctx.message.delete()
                    await try_send(member, embed=warn_log)
Exemple #10
0
    async def how_set(self, ctx):
        p = ctx.prefix
        if not has_permissions(ctx.author, ["administrator"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               f"> Администратор"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            collection = db["welcome"]
            w_data = collection.find_one({"_id": ctx.guild.id})

            collection = db["levers"]
            on_off = collection.find_one({"_id": ctx.guild.id})

            wc_id = get_field(w_data, "channel_id")
            wm = get_field(w_data, "message")
            wr = get_field(w_data, "roles")

            antis_on = get_field(on_off, "antispam")
            if antis_on == None:
                antis_on = False
            stats_on = get_field(on_off, "stats_on")
            if stats_on == None:
                stats_on = False

            if wc_id == None:
                wc_desc = "Отключен"
            else:
                wc_desc = f"<#{wc_id}>"
            if wm == None:
                wm_desc = "Отсутствует"
            else:
                wm_desc = wm
            if wr == None:
                wr_desc = "> Отключены\n"
            else:
                wr_desc = ""
                for r_id in wr:
                    wr_desc += f"> <@&{r_id}>\n"

            if antis_on:
                antis_desc = "✅ Включен"
            else:
                antis_desc = "❌ Выключен"
            if stats_on:
                stats_desc = "✅ Включена"
            else:
                stats_desc = "❌ Выключена"

            reply = discord.Embed(
                title="Текущие настройки бота",
                description=("**Действия с новичками**\n"
                             "Сообщение:\n"
                             f"> {wm_desc}\n"
                             "Канал:\n"
                             f"> {wc_desc}\n"
                             "Роли:\n"
                             f"{wr_desc}\n"
                             "**Статистика сервера:**\n"
                             f"> {stats_desc}\n\n"
                             "**Антиспам:**\n"
                             f"> {antis_desc}\n\n"
                             f"Таблица ролей за токены: `{p}auto-role-info`"),
                color=col(30, 30, 130))
            reply.set_thumbnail(url=f"{ctx.guild.icon_url}")
            await ctx.send(embed=reply)
Exemple #11
0
    async def welcome(self, ctx, param, *, text=None):
        p, cmd = ctx.prefix, ctx.command.name

        params = {
            "message": ["message", "msg", "m"],
            "channel": ["channel", "c"],
            "roles": ["roles", "role", "r"]
        }

        key = find_alias(params, param.lower())

        if not has_permissions(ctx.author, ["administrator"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               f"> Администратор"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        elif key == None:
            reply = discord.Embed(
                title="💢 Параметр не найден",
                description=(f"Параметр `{param}` не найден. Параметры:\n"
                             "> `message`\n"
                             "> `channel`\n"
                             "> `roles`\n"
                             "Подробнее о параметре:\n"
                             f"`{p}{cmd} message / channel / roles`\n"),
                color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        elif key == "message":
            if text == None:
                reply = discord.Embed(
                    title=f"💬 `{p}{cmd}`: сообщение",
                    description=
                    ("**Описание:** настраивает приветственное сообщение.\n"
                     "-> Если хотите упомянуть зашедшего, впишите `{user}`\n"
                     f"**Использование:** `{p}{cmd} {key} Текст сообщения`\n"
                     f"**Сброс:** `{p}{cmd} {key} delete`\n"
                     f"**Пример:** `{p}{cmd} {key} Добро пожаловать, " +
                     "{user}`"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            else:
                if text.lower() == "delete":
                    value = None
                    desc = "Сообщение удалено"
                else:
                    value = text[:+500]
                    desc = f"**Новое сообщение:** {value}"

                collection = db["welcome"]
                collection.find_one_and_update({"_id": ctx.guild.id},
                                               {"$set": {
                                                   "message": value
                                               }},
                                               upsert=True)

                reply = discord.Embed(title="✅ Настроено",
                                      description=desc,
                                      color=col("dg"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

        elif key == "channel":
            if text == None:
                reply = discord.Embed(
                    title=f"#️⃣ `{p}{cmd}`: канал",
                    description=(
                        "**Описание:** настраивает канал для приветствий.\n"
                        f"**Использование:** `{p}{cmd} {key} #канал`\n"
                        f"**Сброс:** `{p}{cmd} {key} delete`\n"
                        f"**Пример:** {p}{cmd} {key} {ctx.channel.mention}"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            else:
                channel = detect.channel(ctx.guild, text)

                if text.lower() != "delete" and channel == None:
                    reply = discord.Embed(
                        title="💢 Ошибка",
                        description=
                        f"Вы указали {text}, подразумевая канал, но он не был найден",
                        color=col("dr"))
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

                else:
                    if text.lower() == "delete":
                        value = None
                        desc = "Канал сброшен"

                    else:
                        value = channel.id
                        desc = f"**Канал:** {channel.mention}"

                    collection = db["welcome"]
                    collection.find_one_and_update(
                        {"_id": ctx.guild.id}, {"$set": {
                            "channel_id": value
                        }},
                        upsert=True)

                    reply = discord.Embed(title="✅ Настроено",
                                          description=desc,
                                          color=col("dg"))
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

        elif key == "roles":
            if text == None:
                reply = discord.Embed(
                    title=f"🎗 `{p}{cmd}`: роли",
                    description=
                    ("**Описание:** настраивает роли, дающиеся при входе.\n"
                     f"**Использование:** `{p}{cmd} {key} @Роль1 @Роль2 ...`\n"
                     f"**Сброс:** `{p}{cmd} {key} delete`\n"
                     f"**Пример:** `{p}{cmd} {key} @Новичёк`"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            else:
                raw_roles = text.split()
                roles = [detect.role(ctx.guild, rs) for rs in raw_roles]

                if text.lower() != "delete" and None in roles:
                    reply = discord.Embed(
                        title="💢 Ошибка",
                        description=
                        f"Среди указанных ролей есть те, которые не удалось найти",
                        color=col("dr"))
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

                else:
                    if text.lower() == "delete":
                        value = None
                        desc = "Роли сброшены"

                    else:
                        value = [r.id for r in roles]

                        desc = "**Роли:**"
                        for ID in value:
                            desc += f"\n> <@&{ID}>"

                    collection = db["welcome"]
                    collection.find_one_and_update({"_id": ctx.guild.id},
                                                   {"$set": {
                                                       "roles": value
                                                   }},
                                                   upsert=True)

                    reply = discord.Embed(title="✅ Настроено",
                                          description=desc,
                                          color=col("dg"))
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)
Exemple #12
0
    async def ban(self, ctx, user_s, *, reason="не указана"):
        if not has_permissions(ctx.author, ["administrator"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               "> Банить участников"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            user = detect.user(self.client, user_s)
            if user == None:
                reply = discord.Embed(
                    title="💢 Упс",
                    description=
                    f"Вы указали {user_s}, подразумевая пользователя, но он не был найден",
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            else:
                member = ctx.guild.get_member(user.id)
                perms_owned = True

                if member != None:
                    perms_owned = False

                    if ctx.author.top_role.position <= member.top_role.position and ctx.author.id != ctx.guild.owner_id:
                        reply = discord.Embed(
                            title="💢 Позиция",
                            description=
                            f"Ваша наивысшая роль не выше роли {member}",
                            color=col("dr"))
                        reply.set_footer(text=f"{ctx.author}",
                                         icon_url=f"{ctx.author.avatar_url}")
                        await ctx.send(embed=reply)

                    elif ctx.guild.me.top_role.position <= member.top_role.position:
                        reply = discord.Embed(
                            title="⚠ У меня нет прав",
                            description=
                            (f"Моя наивысшая роль не выше, чем роль {member}\n"
                             "Чтобы исправить это, перетащите мою роль выше"),
                            color=discord.Color.dark_gold())
                        reply.set_footer(text=f"{ctx.author}",
                                         icon_url=f"{ctx.author.avatar_url}")
                        await ctx.send(embed=reply)

                    else:
                        perms_owned = True

                elif await in_bans(ctx.guild, user):
                    perms_owned = False

                    reply = discord.Embed(title="🛠 Упс",
                                          description=f"{user} уже забанен")
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

                if perms_owned:
                    log_emb = discord.Embed(
                        title="⛔ Пользователь забанен",
                        description=(f"> **Пользователь:** {user}\n"
                                     f"> **Модератор:** {ctx.author}\n"
                                     f"> **Причина:** {reason}"),
                        color=discord.Color.red())
                    await ctx.guild.ban(user, reason=reason[:+400])

                    await post_log(ctx.guild, log_emb)
                    await ctx.send(embed=log_emb, delete_after=3)
                    await ctx.message.delete()
Exemple #13
0
    async def tempban(self, ctx, user_s, raw_dur, *, reason="не указана"):
        if not has_permissions(ctx.author, ["ban_members"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Необходимые права:**\n"
                                               "> Банить участников"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            user = detect.user(user_s, self.client)
            if user == None:
                reply = discord.Embed(
                    title="💢 Упс",
                    description=
                    f"Вы указали {user_s}, подразумевая пользователя, но он не был найден",
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            else:
                member = ctx.guild.get_member(user.id)
                perms_owned = True

                t_code = raw_dur[-1:].lower()
                t_weight = raw_dur[:-1]
                if t_code not in time_codes or not t_weight.isdigit():
                    perms_owned = False

                    reply = discord.Embed(
                        title="💢 Неверный аргумент",
                        description=
                        ("Пожалуйста, укажите длительность в таком формате:\n"
                         "`5m` - 5 минут\n"
                         "`s - сек` `m - мин` `h - час` `d - сут` `w - нед`"),
                        color=col("dr"))
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

                elif member != None:
                    perms_owned = False

                    if ctx.author.top_role.position <= member.top_role.position and ctx.author.id != ctx.guild.owner_id:
                        reply = discord.Embed(
                            title="💢 Позиция",
                            description=
                            f"Ваша наивысшая роль не выше роли {member}",
                            color=col("dr"))
                        reply.set_footer(text=f"{ctx.author}",
                                         icon_url=f"{ctx.author.avatar_url}")
                        await ctx.send(embed=reply)

                    elif ctx.guild.me.top_role.position <= member.top_role.position:
                        reply = discord.Embed(
                            title="⚠ У меня нет прав",
                            description=
                            (f"Моя наивысшая роль не выше, чем роль {member}\n"
                             "Чтобы исправить это, перетащите мою роль выше"),
                            color=discord.Color.dark_gold())
                        reply.set_footer(text=f"{ctx.author}",
                                         icon_url=f"{ctx.author.avatar_url}")
                        await ctx.send(embed=reply)

                    else:
                        perms_owned = True

                elif await in_bans(ctx.guild, user):
                    perms_owned = False
                    reply = discord.Embed(title="🛠 Упс",
                                          description=f"{user} уже забанен")
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

                if perms_owned:
                    sec = int(t_weight) * time_codes[t_code]

                    delta = datetime.timedelta(seconds=sec)
                    if delta.days >= 35:
                        reply = discord.Embed(
                            title="💢 Превышен лимит",
                            description=
                            "Бан не может длиться дольше, чем 5 недель",
                            color=col("dr"))
                        reply.set_footer(text=f"{ctx.author}",
                                         icon_url=f"{ctx.author.avatar_url}")
                        await ctx.send(embed=reply)

                    else:
                        log_emb = discord.Embed(
                            title="⛔ Пользователь временно забанен",
                            description=
                            (f"**Пользователь:** {user}\n"
                             f"**Модератор:** {ctx.author}\n"
                             f"**Длительность:** {visual_delta(datetime.timedelta(seconds=sec))}\n"
                             f"**Причина:** {reason}"),
                            color=discord.Color.red())
                        await do_action.tempban(user, ctx.author, sec, reason)

                        await post_log(ctx.guild, log_emb)
                        await ctx.send(embed=log_emb, delete_after=3)
                        await ctx.message.delete()
                        await try_send(user, embed=log_emb)

                        log_emb = await withdraw.tempban(ctx.guild, user.id)
                        if log_emb != None:
                            await post_log(ctx.guild, log_emb)
Exemple #14
0
    async def mute(self, ctx, member_s, raw_dur, *, reason="не указана"):
        if not has_permissions(ctx.author, ["manage_messages"]):
            reply = discord.Embed(title="❌ Недостаточно прав",
                                  description=("**Требуемые права:**\n"
                                               "> Управлять сообщениями"),
                                  color=col("dr"))
            reply.set_footer(text=f"{ctx.author}",
                             icon_url=f"{ctx.author.avatar_url}")
            await ctx.send(embed=reply)

        else:
            member = detect.member(ctx.guild, member_s)
            if member == None:
                reply = discord.Embed(
                    title="💢 Упс",
                    description=
                    f"Вы указали {member_s}, подразумевая участника, но он не был найден",
                    color=col("dr"))
                reply.set_footer(text=f"{ctx.author}",
                                 icon_url=f"{ctx.author.avatar_url}")
                await ctx.send(embed=reply)

            else:
                t_code = raw_dur[-1:].lower()
                t_weight = raw_dur[:-1]
                if t_code not in time_codes or not t_weight.isdigit():
                    reply = discord.Embed(
                        title="💢 Неверный аргумент",
                        description=
                        ("Пожалуйста, укажите длительность в таком формате:\n"
                         "`5m` - 5 минут\n"
                         "`s - сек` `m - мин` `h - час` `d - сут` `w - нед`"),
                        color=col("dr"))
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

                elif mute_role_name in [r.name for r in member.roles]:
                    reply = discord.Embed(
                        title="💢 Ошибка",
                        description=f"Участник {member} уже ограничен",
                        color=col("dr"))
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

                elif ctx.author.top_role.position <= member.top_role.position and ctx.author.id != ctx.guild.owner_id:
                    reply = discord.Embed(
                        title="💢 Позиция",
                        description=
                        f"Ваша наивысшая роль не выше роли {member}",
                        color=col("dr"))
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

                elif ctx.guild.me.top_role.position <= member.top_role.position:
                    reply = discord.Embed(
                        title="⚠ У меня нет прав",
                        description=(
                            f"Моя наивысшая роль не выше, чем роль {member}\n"
                            "Чтобы исправить это, перетащите мою роль выше"),
                        color=discord.Color.dark_gold())
                    reply.set_footer(text=f"{ctx.author}",
                                     icon_url=f"{ctx.author.avatar_url}")
                    await ctx.send(embed=reply)

                else:
                    sec = int(t_weight) * time_codes[t_code]

                    delta = datetime.timedelta(seconds=sec)
                    if delta.days >= 14:
                        reply = discord.Embed(
                            title="💢 Превышен лимит",
                            description=
                            "Мут не может длиться дольше, чем 2 недели",
                            color=col("dr"))
                        reply.set_footer(text=f"{ctx.author}",
                                         icon_url=f"{ctx.author.avatar_url}")
                        await ctx.send(embed=reply)

                    else:
                        log_emb = discord.Embed(
                            title="🔒 Наложен мут",
                            description=
                            (f"**Участник:** {member}\n"
                             f"**Модератор:** {ctx.author}\n"
                             f"**Длительность:** {visual_delta(datetime.timedelta(seconds=sec))}\n"
                             f"**Причина:** {reason}"),
                            color=col("do"))
                        await do_action.mute(member, ctx.author, sec, reason)

                        await post_log(ctx.guild, log_emb)
                        await ctx.send(embed=log_emb, delete_after=3)
                        await ctx.message.delete()
                        await try_send(member, embed=log_emb)

                        log_emb = await withdraw.mute(member)
                        if log_emb != None:
                            await post_log(ctx.guild, log_emb)
Exemple #15
0
    async def on_message(self, message):
        if message.guild != None:

            if not has_permissions(message.author, ["manage_messages"]):
                server_id = message.guild.id
                collection = db["levers"]

                options = collection.find_one({"_id": server_id})
                antispam = get_field(options, "antispam")
                if antispam is None:
                    antispam = False

                if antispam:
                    global spam_buffer
                    user_id = message.author.id
                    weight = len(message.content)
                    reached_critical_point = False

                    if weight <= 10:
                        min_delay = datetime.timedelta(seconds=1)
                    elif weight >= 400:
                        min_delay = datetime.timedelta(seconds=10)
                    else:
                        min_delay = datetime.timedelta(seconds=2)

                    now = datetime.datetime.utcnow()
                    server_data = get_field(spam_buffer, server_id)
                    if server_data == None:
                        server_data = {user_id: {"last_at": now, "points": 1}}
                        spam_buffer.update([(server_id, server_data)])
                    else:
                        user_data = get_field(server_data, user_id)
                        if user_data == None:
                            spam_buffer[server_id].update([(user_id, {
                                "last_at": now,
                                "points": 1
                            })])
                        else:
                            last_at = user_data["last_at"]
                            delta = now - last_at
                            if delta < min_delay:
                                if user_data["points"] >= 4:
                                    spam_buffer[server_id].pop(user_id)
                                    reached_critical_point = True
                                else:
                                    spam_buffer[server_id][user_id][
                                        "points"] += 1
                                    spam_buffer[server_id][user_id][
                                        "last_at"] = now
                            else:
                                if user_data["points"] < 1:
                                    spam_buffer[server_id].pop(user_id)
                                else:
                                    spam_buffer[server_id][user_id][
                                        "points"] -= 1
                                    spam_buffer[server_id][user_id][
                                        "last_at"] = now

                    if reached_critical_point:
                        log_emb = discord.Embed(
                            title="🔒 Наложен автоматический мут",
                            description=
                            (f"**Участник:** {message.author}\n"
                             f"**Длительность:** {visual_delta(datetime.timedelta(seconds=3600))}\n"
                             f"**Причина:** спам"),
                            color=col("do"))
                        await do_action.mute(message.author, message.guild.me,
                                             3600, "спам")
                        await post_log(message.guild, log_emb)

                        await delete_recent(self.client,
                                            message.author,
                                            60,
                                            start_channel=message.channel)

                        await try_send(message.author, embed=log_emb)
                        log_emb = await withdraw.mute(message.author)
                        if log_emb != None:
                            await post_log(message.guild, log_emb)