Exemple #1
0
async def set_prefix(ctx: MrvnCommandContext, command: command_option, prefix: str):
    if prefix not in PREFIX_LIST:
        await ctx.respond_embed(Style.ERROR, ctx.format("std_command_override_prefix_not_in_list", " ".join(PREFIX_LIST)))
        return

    override = (await CommandOverride.get_or_create(guild_id=ctx.guild_id, command_name=command.name))[0]

    override.prefix = prefix

    await override.save()

    await ctx.respond_embed(Style.OK, ctx.format("std_command_override_prefix_changed", command.name))
Exemple #2
0
async def unban(ctx: MrvnCommandContext, member: Member):
    try:
        await member.unban()
    except Forbidden:
        await ctx.respond_embed(Style.ERROR, ctx.translate("moderation_bot_insufficient_perms"))
    else:
        await ctx.respond_embed(Style.OK, ctx.format("moderation_command_unban_successful", member.mention))
Exemple #3
0
async def wiki(ctx: MrvnCommandContext, query: ParseUntilEndsOption(str)):
    await ctx.defer()

    session = ClientSession(timeout=ClientTimeout(20))

    params = {"action": "query",
              "format": "json",
              "list": "search",
              "srsearch": query}

    try:
        response = await session.get("https://ru.wikipedia.org/w/api.php",
                                     params=params)
    except (asyncio.TimeoutError, ClientConnectionError):
        await ctx.respond_embed(Style.ERROR, ctx.translate("search_connection_error"))

        return

    data = await response.json()

    await session.close()
    response.close()

    items = [x["title"] for x in data["query"]["search"]]

    if not len(items):
        await ctx.respond_embed(Style.ERROR, ctx.format("search_command_not_found", query))

        return

    paginator = WikiPaginator("ru", tr=ctx, author=ctx.author, original_author=ctx.author, timeout=30, pages=items,
                              guild=ctx.guild)

    await paginator.respond_ctx(ctx)
Exemple #4
0
async def prefix_disable(ctx: MrvnCommandContext, command: command_option):
    override = (await CommandOverride.get_or_create(guild_id=ctx.guild_id, command_name=command.name))[0]

    override.prefix = ""

    await override.save()

    await ctx.respond_embed(Style.OK, ctx.format("std_command_custom_prefix_disabled", command.name))
Exemple #5
0
async def command_set_enabled(ctx: MrvnCommandContext, command: command_option, enable: bool):
    override = (await CommandOverride.get_or_create(guild_id=ctx.guild_id, command_name=command.name))[0]

    override.disabled = not enable

    await override.save()

    await ctx.respond_embed(Style.OK, ctx.format(
        f"std_command_override_command_{'enabled' if enable else 'disabled'}", command.name))
Exemple #6
0
async def unmute(ctx: MrvnCommandContext, member: Member):
    try:
        await member.edit(communication_disabled_until=None)
    except Forbidden:
        await ctx.respond_embed(
            Style.ERROR, ctx.translate("moderation_bot_insufficient_perms"))
    else:
        await ctx.respond_embed(
            Style.OK,
            ctx.format("moderation_command_unmute_successful", member.mention))
Exemple #7
0
async def info(ctx: MrvnCommandContext, command: command_option):
    override = await CommandOverride.get_or_none(guild_id=ctx.guild_id, command_name=command.name)

    if not override:
        await ctx.respond_embed(Style.ERROR, ctx.translate("std_command_override_no_override"))

        return

    empty = ctx.translate("std_command_override_empty")

    enabled = not override.disabled
    prefix = override.prefix if len(override.prefix) else empty
    perm_list = ", ".join(override.discord_permissions) if len(override.discord_permissions) else empty
    channel_list = ", ".join([channel.mention if (channel := runtime.bot.get_channel(x)) else str(x) for x in
                              override.whitelist_channel_ids]) if len(override.whitelist_channel_ids) else empty

    await ctx.respond_embed(Style.INFO,
                            ctx.format("std_command_override_info", enabled, prefix, perm_list, channel_list),
                            ctx.format("std_command_override_info_title", command.name))
Exemple #8
0
    async def send_command_exception_message(ctx: MrvnCommandContext, exc):
        logger.error(traceback.format_exc())

        await ctx.respond_embed(
            Style.ERROR,
            ctx.format(
                "mrvn_api_command_execution_error_desc", "".join(
                    traceback.format_exception(value=exc,
                                               etype=type(exc),
                                               tb=exc.__traceback__))),
            ctx.translate("mrvn_api_command_execution_error_title"))
Exemple #9
0
async def messages_command(ctx: MrvnCommandContext):
    await ctx.defer()

    data = await get_monthly_messages(ctx.guild_id)
    legend_text = ctx.format("statistics_command_messages_legend",
                             ctx.guild.name)

    result = await asyncio.get_event_loop().run_in_executor(
        None, functools.partial(plot.get_plot, data, legend_text))

    await ctx.respond(file=File(result, filename="Chart.png"))
Exemple #10
0
async def channel_edit(ctx: MrvnCommandContext, command: SlashCommand, channel: TextChannel, add_: bool):
    override = (await CommandOverride.get_or_create(guild_id=ctx.guild_id, command_name=command.name))[0]

    channel_id = channel.id

    if add_ and channel_id not in override.whitelist_channel_ids:
        override.whitelist_channel_ids.append(channel_id)

        await override.save()
    elif not add_ and channel_id in override.whitelist_channel_ids:
        override.whitelist_channel_ids.remove(channel_id)

        await override.save()

    await ctx.respond_embed(Style.OK, ctx.format(
        f"std_command_override_channel_{'added' if add_ else 'removed'}", channel.mention, command.name))
Exemple #11
0
async def purge(ctx: MrvnCommandContext,
                number: Option(int, min_value=1, max_value=200),
                member: Member = None):
    try:
        deleted = await ctx.channel.purge(
            limit=number,
            check=lambda msg: member is None or msg.author == member,
            bulk=True)
    except Forbidden:
        await ctx.respond_embed(
            Style.ERROR, ctx.translate("moderation_bot_insufficient_perms"))
    else:
        await ctx.respond_embed(
            Style.OK,
            ctx.format("moderation_command_purge_messages_removed",
                       ctx.author.mention, deleted))
Exemple #12
0
async def mute(ctx: MrvnCommandContext, member: Member, time: int,
               unit: Option(str,
                            choices=[
                                OptionChoice("Seconds", "s"),
                                OptionChoice("Minutes", "m"),
                                OptionChoice("Hours", "h"),
                                OptionChoice("Days", "d"),
                                OptionChoice("Weeks", "w"),
                                OptionChoice("Months", "mo"),
                                OptionChoice("Years", "y")
                            ])):
    if member == runtime.bot.user:
        await ctx.respond_embed(
            Style.ERROR, ctx.translate("moderation_cant_do_this_to_bot"))

        return
    elif member == ctx.author:
        await ctx.respond_embed(
            Style.ERROR, ctx.translate("moderation_cant_do_this_to_self"))

        return
    elif member.guild_permissions.administrator:
        await ctx.respond_embed(
            Style.ERROR,
            ctx.translate("moderation_command_mute_cant_mute_administrator"))

        return
    elif ctx.author.top_role.position < member.top_role.position or ctx.author.guild_permissions < member.guild_permissions:
        await ctx.respond_embed(
            Style.ERROR, ctx.translate("moderation_cant_do_this_to_this_user"))

        return

    timestamp = datetime.datetime.utcnow() + datetime.timedelta(
        0, time * TIME_DICT[unit])

    try:
        await member.edit(communication_disabled_until=timestamp)
    except Forbidden:
        await ctx.respond_embed(
            Style.ERROR, ctx.translate("moderation_bot_insufficient_perms"))
    else:
        await ctx.respond_embed(
            Style.OK,
            ctx.format("moderation_command_mute_successful", member.mention))
Exemple #13
0
async def ban(ctx: MrvnCommandContext, member: Member):
    if member == runtime.bot.user:
        await ctx.respond_embed(Style.ERROR, ctx.translate("moderation_cant_do_this_to_bot"))

        return
    elif member == ctx.author:
        await ctx.respond_embed(Style.ERROR, ctx.translate("moderation_cant_do_this_to_self"))

        return
    elif ctx.author.top_role.position < member.top_role.position or ctx.author.guild_permissions < member.guild_permissions:
        await ctx.respond_embed(Style.ERROR, ctx.translate("moderation_cant_do_this_to_this_user"))

        return

    try:
        await member.ban(delete_message_days=0)
    except Forbidden:
        await ctx.respond_embed(Style.ERROR, ctx.translate("moderation_bot_insufficient_perms"))
    else:
        await ctx.respond_embed(Style.OK, ctx.format("moderation_command_ban_success", member.mention))
Exemple #14
0
async def edit_(ctx: MrvnCommandContext, key: str, value: str,
                global_setting: bool):
    cls = GlobalSetting if global_setting else GuildSetting

    try:
        setting = next(filter(lambda it: it.key == key, cls.__subclasses__()))
    except StopIteration:
        await ctx.respond_embed(
            Style.ERROR,
            ctx.translate("std_command_settings_edit_invalid_key"))
        return

    if global_setting:
        model = (await setting.get_or_create())[0]
    else:
        model = (await setting.get_or_create(guild_id=ctx.guild_id))[0]

    value_type = type(model.value_field)

    if value_type == bool:
        value = value.lower() == "true"

    try:
        model.value = value
    except SettingsValueWriteError as e:
        await ctx.respond_embed(
            Style.ERROR, ctx.translate(e.message),
            ctx.translate("std_command_settings_edit_invalid_value"))
        return

    try:
        await model.save()
    except ValueError:
        await ctx.respond_embed(
            Style.ERROR,
            ctx.format("std_command_settings_edit_invalid_value_for_type",
                       value_type.__name__))
        return

    await ctx.respond_embed(
        Style.OK, ctx.translate("std_command_settings_edit_value_set"))
Exemple #15
0
async def permissions_edit(ctx: MrvnCommandContext, command: command_option, permission: str, add_: bool):
    permission = permission.lower()

    if permission not in Permissions.VALID_FLAGS.keys():
        await ctx.respond_embed(Style.ERROR, ctx.translate("std_command_override_invalid_permission"))

        return

    override = (await CommandOverride.get_or_create(guild_id=ctx.guild_id, command_name=command.name))[0]

    if add_ and permission not in override.discord_permissions:
        override.discord_permissions.append(permission)

        await override.save()
    elif not add_ and permission in override.discord_permissions:
        override.discord_permissions.remove(permission)

        await override.save()

    await ctx.respond_embed(Style.OK, ctx.format(
        f"std_command_override_permission_{'added' if add_ else 'removed'}", permission, command.name))
Exemple #16
0
async def edit_owner(ctx: MrvnCommandContext, user: User, add_: bool):
    mrvn_user = (await MrvnUser.get_or_create(user_id=user.id))[0]

    if add_ and mrvn_user.is_owner:
        await ctx.respond_embed(
            Style.ERROR, ctx.translate("std_command_owner_already_an_owner"))

        return
    elif not add_ and not mrvn_user.is_owner:
        await ctx.respond_embed(
            Style.ERROR, ctx.translate("std_command_owner_not_an_owner"))

        return

    mrvn_user.is_owner = add_

    await mrvn_user.save()

    await ctx.respond_embed(
        Style.OK,
        ctx.format(
            "std_command_owner_add" if add_ else "std_command_owner_remove",
            user.mention))
Exemple #17
0
async def search(ctx: MrvnCommandContext, q: str, search_type: SearchType):
    if not env.cse_cx or not env.cse_api_key:
        await ctx.respond_embed(
            Style.ERROR, ctx.translate("search_command_img_api_data_missing"))

        return

    await ctx.defer()

    safe = "active" if ctx.guild_id and (
        await SettingEnableSafeSearch.get_or_create(
            guild_id=ctx.guild_id))[0].value else "off"

    session = ClientSession(timeout=ClientTimeout(20))

    params = {
        "q": q,
        "num": ITEMS_NUM,
        "start": 1,
        "key": env.cse_api_key,
        "cx": env.cse_cx,
        "safe": safe
    }

    params.update(search_type.value)

    try:
        response = await session.get(
            "https://www.googleapis.com/customsearch/v1", params=params)
    except (asyncio.TimeoutError, ClientConnectionError):
        await ctx.respond_embed(Style.ERROR,
                                ctx.translate("search_connection_error"))

        return

    data = await response.json()

    await session.close()
    response.close()

    if response.status != 200:
        if data["error"]["status"] == "RESOURCE_EXHAUSTED":
            await ctx.respond_embed(
                Style.ERROR,
                ctx.translate("search_command_resource_exhausted"))
        else:
            await ctx.respond_embed(
                Style.ERROR,
                ctx.format("search_command_api_error",
                           data["error"]["status"]))

        return

    if data["searchInformation"]["totalResults"] == "0":
        await ctx.respond_embed(Style.ERROR,
                                ctx.format("search_command_not_found", q))

        return

    items = [
        SearchItem(
            x["title"], x["link"], x["image"]["contextLink"]
            if search_type == SearchType.IMAGES else x["link"], x["snippet"])
        for x in data["items"]
    ]

    count = len(items)

    if search_type == SearchType.GOOGLE:
        num_pages = math.ceil(
            count / GOOGLE_PAGE_SIZE) if count > GOOGLE_PAGE_SIZE else 1
    else:
        num_pages = count

    paginator = CSEPaginator(
        q,
        items,
        search_type,
        tr=ctx,
        author=ctx.author,
        original_author=None if ctx.interaction else ctx.author,
        timeout=30,
        num_pages=num_pages,
        guild=ctx.guild)

    await paginator.respond_ctx(ctx)