Beispiel #1
0
    async def view(self, CommandArgs):
        """view your server settings"""

        guild = CommandArgs.guild
        guild_data = CommandArgs.guild_data
        response = CommandArgs.response
        trello_board = CommandArgs.trello_board
        prefix = CommandArgs.prefix

        embed = Embed(title="Bloxlink Settings")
        text_buffer = []
        options_trello_data = {}

        donator_profile, _ = await get_features(Object(id=guild.owner_id),
                                                guild=guild)
        premium = donator_profile.features.get("premium")

        if premium:
            text_buffer.append(
                "**This is a [Premium Server](https://www.patreon.com/join/bloxlink?)**\n"
            )
            embed.colour = GOLD_COLOR

        if trello_board:
            options_trello_data, _ = await get_options(trello_board)
            guild_data.update(options_trello_data)

        for option_name, option_data in OPTIONS.items():
            value = None

            if option_data[0]:
                value = str(option_data[0](guild, guild_data))  # pylint: disable=not-callable
            else:
                try:
                    value = str(
                        guild_data.get(option_name,
                                       DEFAULTS.get(option_name, "False")))
                except KeyError:
                    value = str(
                        guild_data.get(option_name,
                                       DEFAULTS.get(option_name, "False")))

            if option_data[3] and not premium:
                value = str(DEFAULTS.get(option_name, "False"))

            value = value.replace("{prefix}", prefix)
            text_buffer.append(f"**{option_name}** {ARROW} {value}")

        embed.description = "\n".join(text_buffer)
        embed.set_footer(text="Powered by Bloxlink",
                         icon_url=Bloxlink.user.avatar.url)
        embed.set_author(name=guild.name,
                         icon_url=guild.icon.url if guild.icon else "")

        await response.send(embed=embed)
Beispiel #2
0
    async def __main__(self, CommandArgs):
        response = CommandArgs.response

        author = CommandArgs.author

        guild = CommandArgs.guild
        guild_data = CommandArgs.guild_data

        toggle = not guild_data.get("dynamicRoles",
                                    DEFAULTS.get("dynamicRoles"))

        guild_data["dynamicRoles"] = toggle

        await self.r.table("guilds").insert(guild_data,
                                            conflict="update").run()

        if toggle:
            await post_event(
                guild, guild_data, "configuration",
                f"{author.mention} ({author.id}) has **enabled** `dynamicRoles`.",
                BROWN_COLOR)
            await response.success("Successfully **enabled** Dynamic Roles!")
        else:
            await post_event(
                guild, guild_data, "configuration",
                f"{author.mention} ({author.id}) has **disabled** `dynamicRoles`.",
                BROWN_COLOR)
            await response.success("Successfully **disabled** Dynamic Roles!")
Beispiel #3
0
    async def unverified(self, CommandArgs):
        """set the DM message of people who are UNVERIFIED on Bloxlink"""

        author = CommandArgs.author
        guild = CommandArgs.guild

        unverified_DM = await get_guild_value(
            guild,
            ["unverifiedDM", DEFAULTS.get("unverifiedDM")])

        response = CommandArgs.response

        if unverified_DM:
            response.delete(await response.send(
                "When people join your server and are **UNVERIFIED** on Bloxlink, they will "
                f"receive this DM:"))
            response.delete(await response.send(f"```{unverified_DM}```"))

        parsed_args_1 = (await CommandArgs.prompt([{
            "prompt":
            "Would you like to **change** the DM people get when they join and are unverified, or "
            "would you like to **disable** this feature?\n\nPlease specify: (change, disable)",
            "name":
            "option",
            "type":
            "choice",
            "choices": ("change", "disable")
        }]))["option"]

        if parsed_args_1 == "change":
            parsed_args_2 = (await CommandArgs.prompt([{
                "prompt":
                "What would you like the text of the Unverified Join DM to be? You may use "
                f"these templates: ```{UNVERIFIED_TEMPLATES}```",
                "name":
                "text",
                "formatting":
                False
            }],
                                                      last=True))["text"]

            await set_guild_value(guild, unverifiedDM=parsed_args_2)

        elif parsed_args_1 == "disable":
            await set_guild_value(guild, unverifiedDM=None)

        await post_event(
            guild, "configuration",
            f"{author.mention} ({author.id}) has **changed** the `joinDM` option for `unverified` members.",
            BROWN_COLOR)

        raise Message(f"Successfully **{parsed_args_1}d** your DM message.",
                      type="success")
Beispiel #4
0
    async def __main__(self, CommandArgs):
        response = CommandArgs.response
        author = CommandArgs.author
        guild = CommandArgs.guild

        toggle = not (await get_guild_value(guild, "dynamicRoles") or DEFAULTS.get("dynamicRoles"))

        await set_guild_value(guild, dynamicRoles=toggle)

        if toggle:
            await post_event(guild, "configuration", f"{author.mention} ({author.id}) has **enabled** `dynamicRoles`.", BROWN_COLOR)
            await response.success("Successfully **enabled** Dynamic Roles!")
        else:
            await post_event(guild, "configuration", f"{author.mention} ({author.id}) has **disabled** `dynamicRoles`.", BROWN_COLOR)
            await response.success("Successfully **disabled** Dynamic Roles!")
Beispiel #5
0
    async def verified(self, CommandArgs):
        """set the DM message of people who are VERIFIED on Bloxlink"""

        guild_data = CommandArgs.guild_data
        verifiedDM = guild_data.get("verifiedDM", DEFAULTS.get("welcomeMessage"))

        author = CommandArgs.author
        guild = CommandArgs.guild

        response = CommandArgs.response

        if verifiedDM:
            response.delete(await response.send("When people join your server and are **VERIFIED** on Bloxlink, they will "
                                               f"receive this DM:"))
            response.delete(await response.send(f"```{verifiedDM}```"))

        parsed_args_1 = (await CommandArgs.prompt([{
            "prompt": "Would you like to **change** the DM people get when they join and are verified, or "
                        "would you like to **disable** this feature?\n\nPlease specify: (change, disable)",
            "name": "option",
            "type": "choice",
            "choices": ("change", "disable")
        }]))["option"]

        if parsed_args_1 == "change":
            parsed_args_2 = (await CommandArgs.prompt([{
                "prompt": "What would you like the text of the Verified Join DM to be? You may use "
                            f"these templates: ```{NICKNAME_TEMPLATES}```",
                "name": "text",
                "formatting": False
            }], last=True))["text"]

            guild_data["verifiedDM"] = parsed_args_2
            await set_guild_value(guild, "verifiedDM", parsed_args_2)

            await self.r.table("guilds").insert(guild_data, conflict="update").run()

        elif parsed_args_1 == "disable":
            guild_data["verifiedDM"] = None
            await set_guild_value(guild, "verifiedDM", None)

            await self.r.table("guilds").insert(guild_data, conflict="replace").run()

        await post_event(guild, guild_data, "configuration", f"{author.mention} ({author.id}) has **changed** the `joinDM` option for `verified` members.", BROWN_COLOR)

        raise Message(f"Successfully **{parsed_args_1}d** your DM message.", type="success")
Beispiel #6
0
        def __init__(self, verify_button_text=None, intro_message=None):
            super().__init__(timeout=None)

            if intro_message != DEFAULTS.get("verifyChannelTextModal"):
                self.add_item(item=discord.ui.Button(label="The text above was set by the Server Admins. ONLY verify from https://blox.link.",
                                                     disabled=True,
                                                     custom_id="verify_view:warning_button",
                                                     row=0))

            verify_button = discord.ui.Button(label=verify_button_text,
                                              emoji="<:chain:970894927196209223>",
                                              style=discord.ButtonStyle.green,
                                              custom_id="verify_view:verify_button",
                                              row=1)
            verify_button.callback = self.verify_button_click
            self.add_item(item=verify_button)

            self.add_item(item=discord.ui.Button(style=discord.ButtonStyle.link, label="Need help?", emoji="❔",
                          url="https://www.youtube.com/playlist?list=PLz7SOP-guESE1V6ywCCLc1IQWiLURSvBE", row=1))
Beispiel #7
0
class VerifyChannelModal(discord.ui.Modal, title="Verification Channel"):
    verify_button_text = discord.ui.TextInput(
        label="What text do you want for your Verify button?",
        default="Verify with Bloxlink",
        max_length=80)
    bloxlink_post = discord.ui.TextInput(
        label="What would you like Bloxlink to write?",
        default=DEFAULTS.get("verifyChannelTextModal"),
        style=discord.TextStyle.paragraph,
        max_length=2000)

    def __init__(self, verify_channel, *args, **kwargs):
        self.verify_channel = verify_channel
        super().__init__(*args, **kwargs)

    async def on_submit(self, interaction: discord.Interaction):
        guild = interaction.guild

        try:
            await self.verify_channel.send(
                str(self.bloxlink_post).replace("{server-name}", guild.name),
                view=VerificationView(self.verify_button_text.value,
                                      self.bloxlink_post.value))
        except discord.errors.Forbidden:
            await interaction.response.send_message(
                "I was unable to post in your verification channel. Please make sure I have the correct permissions."
            )
        else:
            await interaction.response.send_message(
                f"Your new verification channel has been created! {self.verify_channel.mention}"
            )
            for child in self.children:
                if child.custom_id == "verify_channel_modal:welcome_message":
                    guild_welcome_message = await get_guild_value(
                        guild, "welcomeMessage")

                    if child.value != guild_welcome_message:
                        await set_guild_value(guild,
                                              welcomeMessage=child.value)

                    break
Beispiel #8
0
    async def restore(self, CommandArgs):
        """restore your Server Data"""

        message = CommandArgs.message
        author = CommandArgs.message.author
        guild = CommandArgs.message.guild
        response = CommandArgs.response
        prefix = CommandArgs.prefix

        if author.id == OWNER:
            if message.attachments:
                attachment = message.attachments[0]

                if not attachment.height:
                    file_data = await attachment.read()
                    json_data = file_data.decode("utf8").replace("'", '"')
                    json_data = json.loads(json_data)
                    json_data["id"] = str(guild.id)

                    if json_data.get("roleBinds"):
                        role_map = {}

                        for bind_type, bind_data in json_data.get("roleBinds", {}).items():
                            if bind_type == "groups":
                                for group_id, group_data in bind_data.items():
                                    for rank, rank_data in group_data.get("binds", {}).items():
                                        for role_id in rank_data.get("roles", []):
                                            if not guild.get_role(int(role_id)):
                                                role_map_find = role_map.get(role_id)

                                                if not role_map_find:
                                                    role = await guild.create_role(name=rank*6)
                                                    role_map[role_id] = str(role.id)
                                                    role_map_find = str(role.id)

                                                json_data["roleBinds"]["groups"][group_id]["binds"][rank]["roles"].remove(role_id)
                                                json_data["roleBinds"]["groups"][group_id]["binds"][rank]["roles"].append(role_map_find)

                    await self.r.table("guilds").insert(json_data, conflict="replace").run()

                    return await response.success("Successfully **restored** this server's data.")
                else:
                    raise Error("You must supply a non-image file for data restore.")


        user_data = await self.r.db("bloxlink").table("users").get(str(author.id)).run() or {}
        user_backups = user_data.get("backups", [])

        if not user_backups:
            raise Message(f"You don't have any backups created! You may create them with ``{prefix}data backup``.", type="silly")

        embed = Embed(title="Bloxlink Data Restore", description="Please select the backup you could like to restore with the reactions.")

        for i, backup in enumerate(user_backups):
            guild_data = backup["data"]
            backup_name = backup["backupName"]
            timestamp = datetime.datetime.fromtimestamp(backup["timestamp"])

            trello_board = await get_board(guild_data=guild_data, guild=guild)
            prefix, _ = await get_prefix(guild=guild, trello_board=trello_board)

            backup["prefix"] = prefix
            backup["trello_board"] = trello_board,
            backup["timestamp"] = timestamp
            backup["nickname_template"] = guild_data.get("nicknameTemplate", DEFAULTS.get("nicknameTemplate"))

            if trello_board:
                trello_options, _ = await get_options(trello_board)
                guild_data.update(trello_options)

            len_role_binds = count_binds(guild_data)
            backup["len_role_binds"] = len_role_binds

            embed.add_field(name=f"{INT_REACTIONS[i]} {ARROW} {backup_name}", value="\n".join([
                f"**Role Binds** {ARROW} {len_role_binds}",
                f"**Prefix** {ARROW} {prefix}",
                f"**Nickname Template** {ARROW} {backup['nickname_template']}",
                f"**Created on ** {timestamp.strftime('%b. %d, %Y (%A)')}"
            ]))

        message = await response.send(embed=embed)

        if message:
            response.delete(message)

            for i, _ in enumerate(user_backups):
                emote_string = INT_REACTIONS[i]

                try:
                    await message.add_reaction(emote_string)
                except Forbidden:
                    raise PermissionError("I'm missing permission to add reactions to your message!")

            try:
                reaction, _ = await Bloxlink.wait_for("reaction_add", timeout=PROMPT["PROMPT_TIMEOUT"], check=self._reaction_check(author))
            except TimeoutError:
                raise CancelledPrompt(f"timeout ({PROMPT['PROMPT_TIMEOUT']}s)")
            else:
                chosen_backup = None
                str_reaction = str(reaction)

                for i, reaction_string in enumerate(INT_REACTIONS):
                    if str_reaction == reaction_string:
                        chosen_backup = user_backups[i]

                if chosen_backup:
                    parsed_args = await CommandArgs.prompt([
                        {
                            "prompt": "**Warning!** This will **__restore__ ALL OF YOUR SETTINGS** including:\n"
                                      f"**{chosen_backup['len_role_binds']}** Role Binds\n"
                                      f"**{chosen_backup['prefix']}** prefix\n"
                                      f"**{chosen_backup['nickname_template']}** Nickname Template\n"
                                      "Continue? ``Y/N``",
                            "name": "confirm",
                            "type": "choice",
                            "formatting": False,
                            "choices": ("yes", "no"),
                            "embed_title": "Warning!",
                            "embed_color": ORANGE_COLOR,
                            "footer": "Say **yes** to continue, or **no** to cancel."
                        }
                    ])

                    if parsed_args["confirm"] == "yes":
                        await self._restore(guild, chosen_backup)
                        await response.success("Successfully **restored** your backup!")
                    else:
                        raise CancelledPrompt("cancelled restore")
Beispiel #9
0
    async def __main__(self, CommandArgs):
        author = CommandArgs.author
        response = CommandArgs.response
        prefix = CommandArgs.prefix

        if not SELF_HOST:
            author_data = await self.r.db("bloxlink").table("users").get(str(author.id)).run() or {"id": str(author.id)}

            try:
                primary_account, accounts = await get_user("username", author=author, everything=False, basic_details=True)

                if accounts:
                    parsed_accounts = await parse_accounts(accounts)
                    parsed_accounts_str = ", ".join(parsed_accounts.keys())

                    parsed_args = await CommandArgs.prompt([
                        {
                            "prompt": "This command will allow you to switch into an account you verified as in the past.\n"
                                    f"If you would like to link __a new account__, then please use `{prefix}verify add`.\n\n"
                                    "**__WARNING:__** This will remove __all of your roles__ in the server and give you "
                                    "new roles depending on the server configuration.",
                            "footer": "Say **next** to continue.",
                            "type": "choice",
                            "choices": ["next"],
                            "name": "_",
                            "formatting": False
                        },
                        {
                            "prompt": "Are you trying to change your account for _this_ server? If so, simply say `next`.\nIf not, please provide "
                                    "the __Server ID__ of the server to switch as. Please see this article to find the Server ID: "
                                    "[click here](https://support.discordapp.com/hc/en-us/articles/206346498-Where-can-I-find-my-User-Server-Message-ID->).",
                            "name": "guild",
                            "validation": self.validate_server,
                        },
                        {
                            "prompt": "We'll switch your account for the server **{guild.name}**.\n"
                                    "Please select an account to switch into:```" + parsed_accounts_str + "```",
                            "name": "account",
                            "type": "choice",
                            "choices": parsed_accounts.keys()
                        },
                        {
                            "prompt": "Would you like to make this your __primary__ account? Please say **yes** or **no**.",
                            "name": "primary",
                            "type": "choice",
                            "choices": ("yes", "no")
                        }
                    ], last=True)

                    guild = parsed_args["guild"]
                    username = parsed_args["account"]
                    roblox_id = (parsed_accounts.get(username)).id

                    guild_data = await self.r.table("guilds").get(str(guild.id)).run() or {"id": str(guild.id)}

                    trello_board = await get_board(guild_data=guild_data, guild=guild)

                    if trello_board:
                        options_trello, _ = await get_options(trello_board)
                        guild_data.update(options_trello)

                    allow_reverify = guild_data.get("allowReVerify", DEFAULTS.get("allowReVerify"))
                    roblox_accounts = author_data.get("robloxAccounts", {})

                    if guild and not allow_reverify:
                        guild_accounts = roblox_accounts.get("guilds", {})
                        chosen_account = guild_accounts.get(str(guild.id))

                        if chosen_account and chosen_account != roblox_id:
                            raise Error("You already selected your account for this server. `allowReVerify` must be "
                                        "enabled for you to change it.")

                    try:
                        member = await guild.fetch_member(author.id)
                    except (Forbidden, NotFound):
                        await verify_member(author, roblox_id, guild=guild, author_data=author_data, allow_reverify=allow_reverify, primary_account=parsed_args["primary"] == "yes")
                        raise Message("You're not a member of the provided server, so I was only able to update your account internally.", type="success")

                    try:
                        username = await verify_as(
                            member,
                            guild,
                            response     = response,
                            primary      = parsed_args["primary"] == "yes",
                            roblox_id    = roblox_id,
                            trello_board = trello_board,
                            update_user  = False)

                    except Message as e:
                        if e.type == "error":
                            await response.error(e)
                        else:
                            await response.send(e)
                    except Error as e:
                        await response.error(e)
                    else:
                        role_binds, group_ids, _ = await get_binds(guild_data=guild_data, trello_board=trello_board)

                        if count_binds(guild_data, role_binds=role_binds, group_ids=group_ids) and not find(lambda r: r.name == "Bloxlink Bypass", member.roles):
                            for role in list(member.roles):
                                if role != guild.default_role and role.name != "Muted":
                                    try:
                                        await member.remove_roles(role, reason="Switched User")
                                    except Forbidden:
                                        pass
                        try:
                            added, removed, nickname, errors, roblox_user = await update_member(
                                member,
                                guild        = guild,
                                roles        = True,
                                nickname     = True,
                                response     = response,
                                cache        = False)

                        except BloxlinkBypass:
                            await response.info("Since you have the `Bloxlink Bypass` role, I was unable to update your roles/nickname; however, your account was still changed.")

                            return

                        except Blacklisted as b:
                            if str(b):
                                raise Error(f"{author.mention} has an active restriction for: `{b}`.")
                            else:
                                raise Error(f"{author.mention} has an active restriction from Bloxlink.")
                        else:
                            welcome_message = guild_data.get("welcomeMessage") or DEFAULTS.get("welcomeMessage")

                            welcome_message = await get_nickname(author, welcome_message, guild_data=guild_data, roblox_user=roblox_user, is_nickname=False)

                            await post_event(guild, guild_data, "verification", f"{author.mention} ({author.id}) has **switched their user** to `{username}`.", GREEN_COLOR)

                            await CommandArgs.response.send(welcome_message)

                else:
                    raise Message(f"You only have one account linked! Please use `{prefix}verify add` to add another.", type="silly")


            except UserNotVerified:
                raise Error(f"You're not linked to Bloxlink. Please use `{prefix}verify add`.")

        else:
            raise Message(f"{author.mention}, to verify with Bloxlink, please visit our website at " \
                          f"<{VERIFY_URL}>. It won't take long!\nStuck? See this video: <https://www.youtube.com/watch?v=hq496NmQ9GU>")
Beispiel #10
0
    async def change(self, CommandArgs):
        """change your Bloxlink settings"""

        if not CommandArgs.has_permission:
            raise PermissionError("You do not have the required permissions to change server settings.")

        prefix = CommandArgs.prefix
        response = CommandArgs.response

        message = CommandArgs.message
        author = CommandArgs.message.author

        guild = CommandArgs.message.guild
        guild_data = CommandArgs.guild_data

        parsed_args = await CommandArgs.prompt([{
            "prompt": "What value would you like to change? Note that some settings you can't change "
                      "from this command due to the extra complexity, but I will tell you the "
                      f"appropriate command to use.\n\nOptions: ``{options_strings}``\n\nPremium-only options: ``{premium_options_strings}``",
            "name": "choice",
            "type": "choice",
            "formatting": False,
            "footer": f"Use ``{prefix}settings help`` to view a description of all choices.",
            "choices": options_combined
        }])

        choice = parsed_args["choice"]

        if choice == "trelloID":
            raise Message(f"You can link your Trello board from ``{prefix}setup``!", type="success")
        elif choice == "Linked Groups":
            raise Message(f"You can link your group from ``{prefix}bind``!", type="success")
        elif choice == "joinDM":
            message.content = f"{prefix}joindm"
            return await parse_message(message)
        elif choice == "groupShoutChannel":
            message.content = f"{prefix}shoutproxy"
            return await parse_message(message)
        elif choice == "whiteLabel":
            message.content = f"{prefix}whitelabel"
            return await parse_message(message)


        option_find = OPTIONS.get(choice)

        if option_find:
            if option_find[3]:
                profile, _ = await get_features(Object(id=guild.owner_id), guild=guild)

                if not profile.features.get("premium"):
                    raise Error("This option is premium-only! The server owner must have premium for it to be changed.\n"
                                f"Use ``{prefix}donate`` for more instructions on getting premium.")

            option_type = option_find[1]
            trello_board = CommandArgs.trello_board
            card = success_text = parsed_value = None
            desc = option_find[4].format(prefix=CommandArgs.prefix, templates=NICKNAME_TEMPLATES)

            if trello_board:
                options_trello_data, trello_binds_list = await get_options(trello_board, return_cards=True)
                options_trello_find = options_trello_data.get(choice)

                if options_trello_find:
                    card = options_trello_find[1]


            if option_type == "boolean":
                parsed_value = await CommandArgs.prompt([{
                    "prompt": f"Would you like to **enable** or **disable** ``{choice}``?\n\n"
                              f"**Option description:**\n{desc}",
                    "name": "choice",
                    "type": "choice",
                    "footer": "Say **clear** to set as the default value.",
                    "formatting": False,
                    "choices": ("enable", "disable", "clear")
                }])

                parsed_bool_choice = parsed_value["choice"]

                if parsed_bool_choice == "clear":
                    parsed_value = DEFAULTS.get(choice)
                else:
                    parsed_value = parsed_bool_choice == "enable"

                await self.r.table("guilds").insert({
                    "id": str(guild.id),
                    choice: parsed_value
                }, conflict="update").run()

                success_text = f"Successfully **{parsed_bool_choice}d** ``{choice}``!"

            elif option_type == "string":
                parsed_value = (await CommandArgs.prompt([{
                    "prompt": f"Please specify a new value for ``{choice}``.\n\n"
                              f"**Option description:**\n{desc}",
                    "name": "choice",
                    "type": "string",
                    "footer": "Say **clear** to set as the default value.",
                    "formatting": False,
                    "max": option_find[2]
                }]))["choice"]

                if parsed_value == "clear":
                    parsed_value = DEFAULTS.get(choice)

                await self.r.table("guilds").insert({
                    "id": str(guild.id),
                    choice: parsed_value
                }, conflict="update").run()

                success_text = f"Successfully saved your new {choice}!"

            elif option_type == "role":
                parsed_value = (await CommandArgs.prompt([{
                    "prompt": f"Please specify a role for ``{choice}``.\n\n"
                              f"**Option description:**\n{desc}",
                    "name": "role",
                    "type": "role",
                    "exceptions": ("clear",),
                    "footer": "Say **clear** to set as the default value.",
                    "formatting": False
                }]))["role"]

                if parsed_value == "clear":
                    parsed_value = DEFAULTS.get(choice)
                else:
                    parsed_value = str(parsed_value.id)

                await self.r.table("guilds").insert({
                    "id": str(guild.id),
                    choice: parsed_value
                }, conflict="update").run()

                success_text = f"Successfully saved your new ``{choice}``!"

            elif option_type == "number":
                parsed_value = (await CommandArgs.prompt([{
                    "prompt": f"Please specify a new integer for ``{choice}``.\n\n"
                              f"**Option description:**\n{desc}",
                    "name": "choice",
                    "type": "number",
                    "footer": "Say **clear** to set as the default value.",
                    "formatting": False,
                    "exceptions": ("clear",),
                    "max": option_find[2]
                }]))["choice"]

                if parsed_value == "clear":
                    parsed_value = DEFAULTS.get(choice)

                await self.r.table("guilds").insert({
                    "id": str(guild.id),
                    choice: parsed_value
                }, conflict="update").run()

                success_text = f"Successfully saved your new ``{choice}``!"

            elif option_type == "choice":
                choices = ", ".join(option_find[2])
                parsed_value = (await CommandArgs.prompt([{
                    "prompt": f"Please pick a new value for ``{choice}``: ``{choices}``\n\n"
                              f"**Option description:**\n{desc}",
                    "name": "choice",
                    "type": "choice",
                    "footer": "Say **clear** to set as the default value.",
                    "formatting": False,
                    "exceptions": ["clear"],
                    "choices": option_find[2]
                }]))["choice"]

                if parsed_value == "clear":
                    parsed_value = DEFAULTS.get(choice)

                await self.r.table("guilds").insert({
                    "id": str(guild.id),
                    choice: parsed_value
                }, conflict="update").run()

                success_text = f"Successfully saved your new ``{choice}``!"
            else:
                raise Error("An unknown type was specified.")
        else:
            raise Error("An unknown option was specified.")

        if trello_board:
            try:
                if card:
                    if card.name == choice:
                        await card.edit(desc=str(parsed_value))
                    else:
                        await card.edit(name=f"{choice}:{parsed_value}")
                else:
                    trello_settings_list = await trello_board.get_list(lambda L: L.name == "Bloxlink Settings") \
                                           or await trello_board.create_list(name="Bloxlink Settings")

                    await trello_settings_list.create_card(name=choice, desc=str(parsed_value))

                if trello_binds_list:
                    await trello_binds_list.sync(card_limit=TRELLO["CARD_LIMIT"])

            except TrelloUnauthorized:
                await response.error("In order for me to edit your Trello settings, please add ``@bloxlink`` to your "
                                     "Trello board.")

            except (TrelloNotFound, TrelloBadRequest):
                pass

        await set_guild_value(guild, choice, parsed_value)

        await post_event(guild, guild_data, "configuration", f"{author.mention} ({author.id}) has **changed** the ``{choice}`` option.", BROWN_COLOR)

        raise Message(success_text, type="success")
Beispiel #11
0
    async def __main__(self, CommandArgs):
        response = CommandArgs.response
        guild_data = CommandArgs.guild_data
        prefix = CommandArgs.prefix

        guild = CommandArgs.message.guild

        try:
            category = find(lambda c: c.name == "Verification", guild.categories) or \
                       await guild.create_category("Verification")

            verify_info = find(lambda t: t.name == "verify-instructions", category.channels) or \
                          await guild.create_text_channel("verify-instructions", category=category)

            verify_channel = find(lambda t: t.name == "verify", category.channels) or \
                             await guild.create_text_channel("verify", category=category)

            sample_channel = await guild.create_text_channel("sample-channel")

        except Forbidden:
            raise PermissionError("I was unable to create the necessary channels. Please ensure I have the "
                                  "``Manage Channels`` permission.")

        except HTTPException:
            raise Error("You have too many channels or categories! Please delete some before continuing.")

        try:
            await verify_info.send("This server uses Bloxlink to manage Roblox verification. In "
                                   "order to unlock all the features of this server, you'll need "
                                   "to verify your Roblox account with your Discord account!\n\nTo "
                                   f"do this, run ``{prefix}verify`` in {verify_channel.mention} and follow the instructions.")

            await sample_channel.send("This is a sample channel that only Verified users " \
                                      "can read. This channel is not important, you may freely delete it.\n" \
                                      "To create another sample channel, right click this channel and click 'Clone " \
                                      "Text Channel', or just run this command again.")

        except (Forbidden, NotFound):
            raise PermissionError("I was unable to send messages to the created channels. Please give me the "
                                  "proper permissions.")


        try:
            await verify_info.set_permissions(guild.me, send_messages=True, read_messages=True)

            verified_role_name = guild_data.get("verifiedRoleName", DEFAULTS.get("verifiedRoleName"))

            for role in guild.roles:
                if role.name != guild.me.name:
                    await verify_info.set_permissions(role, send_messages=False, read_messages=True)
                    await verify_channel.set_permissions(role, send_messages=True, read_messages=True)

                if role.name == verified_role_name:
                    for target, overwrite in sample_channel.overwrites.items():
                        await sample_channel.set_permissions(target, overwrite=None)

                    await sample_channel.set_permissions(guild.default_role, send_messages=False, read_messages=False)
                    await sample_channel.set_permissions(role, send_messages=True, read_messages=True)


        except Forbidden:
            raise PermissionError("Unable to set permissions to the channels. Please ensure I have the "
                                  "``Manage Channels`` and ``Manage Roles`` permission.")

        except NotFound:
            raise Error("Please do not delete the created channels while I'm setting them up...")


        await self.r.table("guilds").insert({
            "id": str(guild.id),
            "verifyChannel": str(verify_channel.id)
        }, conflict="update").run()

        await response.success(f"All done! Your new verification channel is {verify_channel.mention} and " \
                                "is now managed by Bloxlink.")
Beispiel #12
0
    async def __main__(self, CommandArgs):
        response = CommandArgs.response
        guild = CommandArgs.guild

        is_premium = "premium" in (await has_premium(guild=guild)).features

        verify_category = discord.utils.find(
            lambda c: c.name == "Verification",
            guild.categories) or await guild.create_category(
                name="Verification")
        verify_channel = discord.utils.find(
            lambda c: c.name == "verify",
            guild.text_channels) or await guild.create_text_channel(
                name="verify", category=verify_category)

        await verify_channel.set_permissions(guild.me,
                                             send_messages=True,
                                             read_messages=True)

        verify_instructions = discord.utils.find(
            lambda c: c.name == "verify-instructions", guild.text_channels)

        try:
            if is_premium:
                verify_instructions = verify_instructions or verify_channel
                welcome_message = await get_guild_value(
                    guild, "welcomeMessage")

                modal = VerifyChannelModal(verify_channel)
                modal.add_item(item=discord.ui.TextInput(
                    label="Message after someone verifies",
                    default=welcome_message or DEFAULTS.get("welcomeMessage"),
                    style=discord.TextStyle.paragraph,
                    required=False,
                    max_length=2000,
                    custom_id="verify_channel_modal:welcome_message"))

                await verify_instructions.set_permissions(guild.me,
                                                          send_messages=True,
                                                          read_messages=True)
                await verify_instructions.set_permissions(guild.default_role,
                                                          send_messages=False,
                                                          read_messages=True)
                await response.send_modal(modal)

                await set_guild_value(guild, verifyChannel=None)

            else:
                await verify_channel.set_permissions(guild.default_role,
                                                     send_messages=True,
                                                     read_messages=True)

                if not verify_instructions:
                    verify_instructions = await guild.create_text_channel(
                        name="verify-instructions", category=verify_category)

                await verify_instructions.set_permissions(guild.default_role,
                                                          send_messages=False,
                                                          read_messages=True)
                await verify_instructions.set_permissions(guild.me,
                                                          send_messages=True,
                                                          read_messages=True)

                try:
                    await verify_instructions.move(before=verify_channel)
                except ValueError:
                    pass

                try:
                    await verify_instructions.send(
                        "This server uses Bloxlink to manage Roblox verification. To gain access to the rest of the server, you must verify with Bloxlink.\n"
                        f"To do so, simply say `/getrole` in {verify_channel.mention}.\n"
                    )
                except discord.errors.Forbidden:
                    await response.send(
                        "I was unable to send the instructions to verify. Please make sure I have the correct permissions."
                    )

                await response.send(
                    f"All done! Your new verification channel is {verify_channel.mention}.\n\n**Pro-tip:** Bloxlink Premium subscribers can "
                    "[add a verification button to their channel and can customize the text that Bloxlink posts!](<https://twitter.com/bloxlink/status/1521487474949857282>)\n"
                    f"Subscribe from our [Dashboard!](<https://blox.link/dashboard/guilds/{guild.id}/premium>)"
                )

                await set_guild_value(guild,
                                      verifyChannel=str(verify_channel.id))

        except discord.errors.Forbidden:
            await response.send(
                "I encountered a permission error. Please make sure I can create channels and set permissions."
            )