示例#1
0
async def warn(ctx, client):
    # TODO: Add support for ids
    if ctx.author.guild_permissions.administrator != True:
        return

    content = shlex.split(ctx.content)
    db = await database_connection(ctx.guild.id)

    if len(content) <= 2:
        embed = create_embed("!warn", "!warn {user} {reason here}", "orange")
        add_field(embed, "user", "@ the user you'd like to warn", True)
        add_field(embed, "reason", "The reason you're warning the user.", True)
        await ctx.channel.send(embed=embed)
        return

    user_id = content[1][3:-1]
    reason = "".join(content[2::])

    db["db"].execute(
        "INSERT INTO infractions (datetime, type, user_id, moderator_id, reason) VALUES (?, ?, ?, ?, ?)",
        (
            str(datetime.datetime.now()),
            "warn",
            int(user_id),
            int(ctx.author.id),
            reason,
        ),
    )
    db["con"].commit()

    warned_user = client.get_user(int(user_id))

    embed = create_embed(f"{warned_user} has been warned for: {reason}", "",
                         "light_green")
    await ctx.channel.send(embed=embed)
示例#2
0
async def welcome_toggle(ctx, client):
    if ctx.author.guild_permissions.administrator != True:
        return

    db = await database_connection(ctx.guild.id)
    content = shlex.split(ctx.content)

    if len(content) != 1:
        embed = create_embed("Welcome Toggle",
                             "Toggles the Welcome message on and off.",
                             "orange")
        await ctx.channel.send(embed=embed)
        return

    welcome_info = list(db["db"].execute("SELECT * FROM WELCOME").fetchone())
    if welcome_info[2] == 0:
        welcome_info[2] = 1
        embed = create_embed("Welcome Message Enabled", "", "light_green")
    else:
        welcome_info[2] = 0
        embed = create_embed("Welcome Message Disabled", "", "red")

    db["db"].execute(
        "UPDATE welcome SET channel = ?, message = ?, enabled = ?",
        (welcome_info[0], welcome_info[1], welcome_info[2]),
    )
    db["con"].commit()

    await ctx.channel.send(embed=embed)
示例#3
0
async def commands(ctx, client):
    # TODO
    db = await database_connection(ctx.guild.id)

    command_list = [
        i[0] for i in db["db"].execute(
            "SELECT command FROM custom_commands").fetchall()
    ]
    if len(command_list) >= 1:
        final = """```"""

        for command in command_list:
            final += command + "\n"

        final += "```"

        embed = create_embed("Commands", final, "orange")
        await ctx.channel.send(embed=embed)
    else:
        embed = create_embed(
            "Error",
            "There are currently no commands!  Ask an admin to use !create_command",
            "red",
        )
        await ctx.channel.send(embed=embed)
示例#4
0
async def remove_command(ctx, client):
    if ctx.author.guild_permissions.administrator != True:
        return

    content = shlex.split(ctx.content)

    db = await database_connection(ctx.guild.id)

    if len(content) != 2:
        embed = create_embed("Remove_command", "!remove_command {command}",
                             "orange")
        add_field(
            embed,
            "command",
            "The command you would like to remove (ie. !info or !hello)",
            True,
        )

        await ctx.channel.send(embed=embed)
        return

    command = content[1]

    if command[0] != "!":
        command = "!" + command

    command_list = [
        i
        for i in db["db"].execute("SELECT * FROM custom_commands").fetchall()
    ]

    for c in command_list:
        if c[0] == command:
            db["db"].execute("DELETE FROM custom_commands WHERE command = (?)",
                             (command, ))
            db["con"].commit()

            embed = create_embed("Command Removed Successfully.", "",
                                 "dark_blue")
            add_field(embed, "command", c[0], True)
            add_field(embed, "description", c[1], True)
            add_field(embed, "image", c[2], True)

            await ctx.channel.send(embed=embed)
            return

    embed = create_embed(
        "Error",
        "Invalid Command to Remove.  Try checking all of the commands with !commands",
        "red",
    )

    await ctx.channel.send(embed=embed)
示例#5
0
async def remove_role(ctx, client):
    db = await database_connection(ctx.guild.id)

    content = shlex.split(ctx.content)

    if len(content) != 2:
        embed = create_embed("Remove_role", "!remove_role {role}", "orange")
        add_field(
            embed,
            "role",
            "The actual role to remove from !roles (ie. Member or @Member)",
            True,
        )
        await ctx.channel.send(embed=embed)
        return

    role = content[1]
    if role[0:2] == "<@":
        # Actual Role @ provided
        role_id = role[3:-1]
    else:
        role_id = [i.id for i in ctx.guild.roles if i.name == role]

        if len(role_id) == 1:
            role_id = role_id[0]
        else:
            #! Error Message
            embed = create_embed(
                "Error",
                "The 'role' provided is invalid.  Make sure it's spelled correctly with proper capitalization (case sensitive) and consider trying to use the actual @ for the role.",
                "red",
            )
            await ctx.channel.send(embed=embed)

            return

    removal_role = (db["db"].execute(
        "SELECT * FROM normal_roles WHERE role_id = (?)",
        (int(role_id), )).fetchall()[0])

    db["db"].execute("DELETE FROM normal_roles WHERE role_id = (?)",
                     (int(removal_role[0]), ))
    db["con"].commit()

    embed = create_embed("Role Removed", "", "dark_blue")
    add_field(embed, "Role",
              f"{ctx.guild.get_role(int(removal_role[0])).mention}", True)
    add_field(embed, "Command", f"!role {removal_role[1]}", True)

    await ctx.channel.send(embed=embed)
示例#6
0
async def programs_setup(ctx, client):
    if ctx.author.guild_permissions.administrator != True:
        return
    content = shlex.split(ctx.content)
    db = await database_connection(ctx.guild.id)

    if len(content) != 2:
        embed = create_embed("Programs_setup", "!programs_setup {channel}",
                             "orange")
        add_field(
            embed,
            "channel",
            "The channel (ie. #mod-queue) or the name of the channel (ie. mod-queue).  When a user uses !programs_add, a moderator will have to 'accept' the submission for it to be useable with !programs.",
            True,
        )

        await ctx.channel.send(embed=embed)
        return

    channel = content[1]

    if channel[0:2] == "<#":
        # Real channel
        channel_id = channel[2:-1]
    else:
        # Name of a channel
        channel_id = [i.id for i in ctx.guild.channels if i.name == channel]

        if len(channel_id) == 1:
            channel_id = channel_id[0]
        else:
            #! Error Message
            embed = create_embed(
                "Error",
                "The channel provided is invalid.  Make sure it's spelled correctly with proper capitlization (case sensitive).  Consider trying to use the actual # for the channel (ie. #channel)",
                "red",
            )
            await ctx.channel.send(embed=embed)
            return

    db["db"].execute("UPDATE settings SET programs_channel = (?)",
                     (channel_id, ))
    db["con"].commit()

    embed = create_embed("Programs Setup Successfully", "", "light_green")
    add_field(embed, "channel",
              f"{ctx.guild.get_channel(int(channel_id)).mention}", True)
    await ctx.channel.send(embed=embed)
示例#7
0
async def custom_command_handling(ctx: discord.ext.commands.Context,
                                  command: str):
    """Handling for custom commands

    Args:
        ctx (discord.ext.commands.Context): Context
        command (str): The command that was called
    """

    db = await Commands_DB(ctx.guild.id)

    # List of commands
    command_list = await db.grab_commands()

    if command_list is None:
        return

    # Checks
    for c in command_list:
        if command.lower() == c[0]:

            embed = create_embed(f"{command.capitalize()}", f"{c[1]}",
                                 "orange")
            if c[2] is not None:
                embed.set_image(url=c[2])
            await ctx.channel.send(embed=embed)
示例#8
0
async def broadcast(ctx):
    if ctx.author.id != 178543252637483009:
        return

    msg = ctx.message.content.split("!broadcast")[1]

    embed = create_embed("Message from JZ", msg, "orange")

    for server in bot.guilds:
        channel_names = [channel.name for channel in server.channels]

        if "general" in channel_names or "chat" in channel_names:
            for channel in server.channels:
                if channel.name == "chat" or channel.name == "general":
                    try:
                        await channel.send(embed=embed)
                    except Exception:
                        print("Didn't work.")
                    else:
                        break

        else:
            for channel in server.channels:
                print(channel)
                try:
                    await channel.send(embed=embed)
                except Exception:
                    continue
                else:
                    break
示例#9
0
async def programs(ctx, bot, user: str) -> Tuple[bool, discord.Embed]:
    """Display's a user's programs

    Args:
        ctx (discord.ext.commands.Context): Context
        bot (discord.ClientUser.bot): Bot
        user (str): User's programs to display

    Returns:
        Tuple[bool, discord.Embed]: [Status: bool, Embed: discord.Embed]
    """

    # Check
    if user is None:
        return (
            False,
            create_embed_template("Invalid Arguments", "User was Null.",
                                  "error"),
        )

    # Gets the user's id
    user = parse_id(user)

    db = await Programs_DB(ctx.guild.id)

    # Grabs all of the programs
    programs_list = await db.grab_programs(user)

    # Empty list
    if programs_list is None:
        return (
            False,
            create_embed_template(
                "Invalid User",
                "That user doesn't have any programs, have them use /programs add.",
                "error",
            ),
        )

    programs_list = programs_list.split("\n")

    # Creates the message
    message = ""
    space_amount = (len(programs_list) // 10) + 1
    for i in range(len(programs_list)):
        if programs_list[i] != "" and programs_list[i] is not None:
            # Ensure the numbers line up
            number = f"{i + 1}".rjust(space_amount, " ")
            # Only add a newline if it's required
            message += f"{number}. {programs_list[i]}" + (
                "\n" if i != (len(programs_list) - 1) else "")

    user = bot.get_user(user)

    return (
        True,
        create_embed(f"{user.name}#{user.discriminator}'s Programs", message,
                     "orange"),
    )
示例#10
0
async def welcome_setup(ctx, client):
    if ctx.author.guild_permissions.administrator != True:
        return

    db = await database_connection(ctx.guild.id)
    content = shlex.split(ctx.content)

    if len(content) != 3:
        embed = create_embed("Welcome_setup",
                             "!welcome_setup {@channel} {description}",
                             "orange")
        add_field(
            embed,
            "@channel",
            "Provide the @ for the channel you want the welcome message to be in.",
            True,
        )
        add_field(
            embed,
            "description",
            'Create a welcome message for your server.  Example: "Welcome {{USER}} to the server!".',
            True,
        )
        add_field(
            embed,
            "Hint",
            "The {{USER}} charchter will be repleaced with the User's @ when they join the server.",
            True,
        )
        await ctx.channel.send(embed=embed)
        return

    channel = content[1][2:-1]
    message = content[2]

    db["db"].execute(
        "UPDATE welcome SET channel = ?, message = ?, enabled = ?",
        (channel, message, True),
    )
    db["con"].commit()

    embed = create_embed("Welcome Message Created Successfully", "",
                         "light_green")
    add_field(embed, "Message", message, True)
    add_field(embed, "Channel", channel, True)
    await ctx.channel.send(embed=embed)
示例#11
0
async def page_command(ctx, bot, items: list, title: str):
    """Creates a paged dialog for printing out large quantities of items

    Args:
        ctx (discord.Context): Context for the command call
        bot (discord.Bot): The actual bot instance
        items (list): A list of items to display
        title (str): Title of the page list
    """

    if type(items) != list:
        items = list(items)

    # Sort the items list
    items.sort()

    # Creates lists splitting every 20 values
    pages_lists = []
    for i in range(0, len(items), 20):
        pages_lists.append(items[i:i + 20])

    # If there is only one list, we can just print out the first page and then end
    if len(pages_lists) == 1:
        l1, l2 = pages_lists[0][0:10], pages_lists[0][10::]
        embed = create_embed(title, "", "orange")
        add_field(embed, "List 1:", "\n".join(l1), True)
        if l2:
            add_field(embed, "List 2:", "\n".join(l2), True)
        await ctx.send(embed=embed)
        return

    # Creates the different embeds for each of the pages in a dictionary
    # ie. messages[1], messages[2]... will be embeds
    messages = {}
    i = 1
    for m in pages_lists:
        embed = create_embed(title, "", "orange")
        add_field(embed, "List 1:", "\n".join(m[0:10]), True)
        if m[10::]:
            add_field(embed, "List 2:", "\n".join(m[10::]), True)
        messages[i] = embed
        i += 1

    # Send the original message w/ reactions
    await send_page_command(ctx, bot, messages)
示例#12
0
async def welcome_toggle(ctx):
    if ctx.author.guild_permissions.administrator is False:
        return

    db = await Guild_DB(ctx.guild.id)

    welcome_info = await db.grab_welcome()

    if welcome_info['enabled'] is False:
        embed = create_embed("Welcome Message Enabled", "", "light_green")
        welcome_info['enabled'] = True
    else:
        embed = create_embed("Welcome Message Disabled", "", "red")
        welcome_info['enabled'] = False

    await db.update_welcome(welcome_info)

    await ctx.channel.send(embed=embed, hidden=True)
示例#13
0
async def programs(ctx, client):
    content = shlex.split(ctx.content)

    db = await database_connection(ctx.guild.id)

    if len(content) != 2:
        embed = create_embed("Programs", "!programs {user}", "orange")
        add_field(embed, "user",
                  "The user's programs you'd like to see. (ie. @JZ)", True)
        add_field(embed, "Example", "!programs <@749359897405161522>")
        await ctx.channel.send(embed=embed)
        return

    # user_id = content[1][3:-1]
    # Finding the user_id to use
    user_id = find_user(content[1])

    db["db"].execute("SELECT * FROM programs WHERE user_id = (?)", (user_id, ))

    user_data = db["db"].fetchone()

    if user_data is None:
        embed = create_embed(
            "No Programs.",
            "That user hasn't created a !programs.  Create one with !programs_add.",
            "red",
        )
        await ctx.channel.send(embed=embed)
        return

    programs = user_data[1].split("\n")

    message = "```"
    space_amount = (len(programs) // 10) + 1
    for program in range(len(programs)):
        if programs[program] != "":
            number = f"{program + 1}".rjust(space_amount, " ")
            message += f"{number}. {programs[program]}\n"
    message += "```"
    embed = create_embed(f"Programs", "", "orange")
    add_field(embed, "User", f"{client.get_user(int(user_id)).mention}", False)
    add_field(embed, "Programs", message, True)

    await ctx.channel.send(embed=embed)
示例#14
0
文件: roles.py 项目: joshuajz/Borg
async def add_role(ctx: discord.ext.commands.Context, name: str, role_id: int):
    """Adds a role to the database

    Args:
        ctx (discord.ext.commands.Context): Context
        name (str): Name of the role (denominator)
        role_id (int): The role's ID
    """

    if ctx.author.guild_permissions.administrator is False:
        return (
            False,
            create_embed_template(
                "No Permission",
                "You do not have permission to add a role.  Contact an administrator.",
                "error",
            ),
        )

    db = await Roles_DB(ctx.guild.id)

    if await db.check_role(role_id, name):
        for role in ctx.guild.roles:
            if role.name == "Borg" or role.name == "Borg Test":
                borg_role = {"id": role.id, "position": role.position}

        actual_role = ctx.guild.get_role(role_id)

        if borg_role["position"] > actual_role.position:
            await db.add_role(role_id, name)

            embed = create_embed("Role Added", "", "light_green")
            add_field(embed, "Role", actual_role.mention, True)
            add_field(embed, "Command", f"!role {name}", True)

            return True, embed

        else:
            return (
                False,
                create_embed_template(
                    "Bot Doesn't have Permission.",
                    "The bot does not have permission to give that role to users.  Ensure the bot's role (@Borg) is **ABOVE** the role in the 'Roles' part of your server's dashboard.",
                    "error",
                ),
            )

    else:
        return (
            False,
            create_embed_template(
                "Already Created",
                "There is already a command associated with **either** that role or command name.  Check with !roles.",
                "error",
            ),
        )
示例#15
0
async def roles(ctx, client):
    db = await database_connection(ctx.guild.id)

    full_roles = [i for i in db["db"].execute("SELECT * FROM normal_roles")]

    embed = create_embed("Roles", "", "orange")
    for role in full_roles:
        add_field(embed, f"!role {role[1]}",
                  f"{ctx.guild.get_role(role[0]).mention}", True)

    await ctx.channel.send(embed=embed)
示例#16
0
async def help_command(ctx, client: discord.Client):
    """!help"""
    embed = create_embed("Help", "", "orange")

    add_field(embed, "!help", "Provides a list of all commands.", True)
    add_field(embed, "!roles",
              "Provides a list of the roles a user can add with !add.", True)
    add_field(
        embed,
        "!role",
        "Allows the user to add a role.  Example: !add Member.",
        True,
    )
    add_field(
        embed,
        "!create_role",
        "Allows an administrator to add a new role to be used with !role.",
        True,
    )
    add_field(
        embed,
        "!remove_role",
        "Allows an administrator to remove a role used with !role.",
        True,
    )
    add_field(
        embed,
        "!create_command",
        "Allows an administrator to create a custom command",
        True,
    )
    add_field(
        embed,
        "!remove_command",
        "Allows an administrator to remove a custom command",
        True,
    )
    add_field(embed, "!commands",
              "Provides a list of all of the custom commands", True)
    add_field(
        embed,
        "!programs_setup {channel}",
        "Allows an administrator to setup the !programs.",
        True,
    )
    add_field(embed, "!programs",
              "Allows someone to look up a user's commands.", True)
    add_field(embed, "!programs_add", "Allows a user to add their !programs.",
              True)
    add_field(embed, "!programs_remove", "Allows you to remove your programs.",
              True)
    await ctx.channel.send(embed=embed)
示例#17
0
async def role(ctx, client):
    users_roles = [i.id for i in ctx.author.roles]

    db = await database_connection(ctx.guild.id)
    content = shlex.split(ctx.content)

    if len(content) == 2:
        # Role
        role_name = content[1]
        role_id = 10
        role_id = (db["db"].execute(
            "SELECT role_id FROM normal_roles WHERE command = (?)",
            (role_name, )).fetchall()[0][0])
        print(role_id)

        if role_id in users_roles:
            # Remove the role
            await ctx.author.remove_roles(ctx.guild.get_role(role_id))

            embed = create_embed(
                "Removed Role",
                f"{ctx.author.mention} removed role {ctx.guild.get_role(role_id).mention}.",
                "orange",
            )
            await ctx.channel.send(embed=embed)
        else:
            # Add the role
            await ctx.author.add_roles(ctx.guild.get_role(role_id))

            embed = create_embed(
                "Added Role",
                f"{ctx.author.mention} added role {ctx.guild.get_role(role_id).mention}.",
                "orange",
            )
            await ctx.channel.send(embed=embed)
    else:
        await roles(ctx, client)
示例#18
0
async def userinfo(ctx, client):
    # TODO: User ID support
    content = shlex.split(ctx.content)

    if len(content) != 2:
        embed = create_embed("!user_info", "!user_info {user}", "orange")
        add_field(embed, "user",
                  "@ the user you'd like to display furthur information.",
                  True)
        await ctx.channel.send(embed=embed)
        return

    user_id = content[1][3:-1]

    user_targeted = client.get_user(int(user_id))
    user_targeted_member = ctx.guild.get_member(int(user_id))
    embed = create_embed(str(user_targeted), user_targeted.mention, "magenta")
    embed.set_thumbnail(url=user_targeted.avatar_url)
    add_field(
        embed,
        "Joined",
        f"{user_targeted_member.joined_at.strftime('%a, %b %d, %Y %I:%M %p')}",
        True,
    )
    add_field(
        embed,
        "Account Created",
        user_targeted_member.created_at.strftime("%a, %b %d, %Y %I:%M %p"),
        True,
    )

    roles = user_targeted_member.roles
    role_amount = len(roles)
    roles_string = ", ".join([i.mention for i in roles])

    add_field(embed, f"Roles [{role_amount}]", roles_string, False)
    await ctx.channel.send(embed=embed)
示例#19
0
async def check_custom_command(ctx, client, command):
    db = await database_connection(ctx.guild.id)

    command_list = [
        i
        for i in db["db"].execute("SELECT * FROM custom_commands").fetchall()
    ]

    for c in command_list:
        if f"!{command.lower()}" == c[0]:

            embed = create_embed(f"{command.capitalize()}", f"{c[1]}",
                                 "orange")
            if c[2] != None:
                embed.set_image(url=c[2])
            await ctx.channel.send(embed=embed)
示例#20
0
async def course_embed(course):
    requirements, academic_level, units, campus = False, False, False, False

    if course["school"] == "queens":
        requirements, academic_level, units = True, True, True
    elif course["school"] == "waterloo":
        requirements = True
    elif course["school"] == "uoft":
        requirements, units, campus = True, True, True

    embed = create_embed(
        f"{course['code']} - {course['name']}",
        course["description"],
        "cyan",
        thumbnail=COURSE_IMAGES[course["school"]],
    )

    if requirements:
        if course["school"] == "queens":
            requirements = course["requirements"]
            if requirements is None or requirements == "":
                requirements = "Unknown/No Requirements.  Check the website."
            else:
                requirements = requirements.replace(". ", ".\n")
        elif course["school"] == "waterloo":
            requirements = course["requirements"]
            if requirements is None:
                requirements = "Unknown/No Requirements.  Check the university website."
        else:
            requirements = course["requirements"]

        add_field(embed, "Requirements", requirements, False)

    if academic_level:
        add_field(embed, "Academic Level", course["academic_level"], True)

    if units:
        add_field(embed, "Units", course["units"], True)

    if campus:
        add_field(embed, "Campus", course["campus"], True)

    return embed
示例#21
0
async def welcome_setup(ctx, channel: int, description: str):
    """Sets up the welcome messages."""
    if ctx.author.guild_permissions.administrator is False:
        return

    db = await Guild_DB(ctx.guild.id)

    # Updates the DB
    await db.update_welcome({
        'channel': channel,
        'message': description,
        'enabled': True
    })

    # Send status message
    embed = create_embed("Welcome Message Created Successfully", "",
                         "light_green")
    add_field(embed, "Message", description, True)
    add_field(embed, "Channel", channel, True)
    await ctx.channel.send(embed=embed, hidden=True)
示例#22
0
文件: roles.py 项目: joshuajz/Borg
async def remove_role(ctx, role_id: int):
    """Removes a role from the database

    Args:
        ctx (discord.ext.commands.Context): Context
        role_id (int): The ID of the role
    """

    if ctx.author.guild_permissions.administrator is False:
        return (
            False,
            create_embed_template(
                "No Permission.",
                "You do not have permission to remove a role.  Ask an administrator.",
                "error",
            ),
        )

    db = await Roles_DB(ctx.guild.id)

    removal_role = await db.grab_role(role_id=role_id)

    if removal_role is None:
        return (
            False,
            create_embed_template(
                "No Command.",
                "There is no command associated with that role in this server.",
                "error",
            ),
        )

    await db.remove_role(role_id)

    embed = create_embed("Role Removed", "", "dark_blue")

    add_field(embed, "Role",
              f"{ctx.guild.get_role(removal_role['role_id']).mention}", True)
    add_field(embed, "Command", f"!role {removal_role['command']}", True)

    return [True, embed]
示例#23
0
async def stress(ctx, client):
    eng_round = datetime.datetime(2021, 3, 31, 12, 0, 0, 0)
    eng_round = eng_round.astimezone(pytz.timezone("US/Eastern"))

    now = datetime.datetime.utcnow()
    now = now.replace(tzinfo=pytz.UTC)
    now = now.astimezone(pytz.timezone("US/Eastern"))

    difference = eng_round - now
    seconds = difference.seconds
    hours = seconds // 60 // 60
    seconds -= hours * 60 * 60
    mins = seconds // 60
    seconds -= mins * 60

    embed = create_embed(
        "Engineering Round",
        f"There is {difference.days} days {hours} hours and {mins} minutes until the Engineering Round.  Time to cope :)",
        "orange",
    )
    await ctx.channel.send(embed=embed)
示例#24
0
async def programs_setup(ctx: discord.ext.commands.Context,
                         channel: int) -> Tuple[bool, discord.Embed]:
    """Allows an administrator to setup a programs channel

    Args:
        ctx (discord.ext.commands.Context): Context
        channel (int): The channel for programs verification commands

    Returns:
        Tuple[bool, discord.Embed]: [Status: bool, Embed: discord.Embed]
    """

    if ctx.author.guild_permissions.administrator is False:
        return

    if not channel:
        return False, "Invalid channel."

    db = await Guild_DB(ctx.guild.id)
    await db.update_settings("programs_channel", channel)

    return True, create_embed(f"Programs Setup Successfully.",
                              f"Channel: <#{channel}>", "light_green")
示例#25
0
async def create_command(ctx, client):
    # Todo: !create_command !commandname 'text here'

    if ctx.author.guild_permissions.administrator != True:
        return

    db = await database_connection(ctx.guild.id)

    content = shlex.split(ctx.content, posix=False)
    # x = 3, 4
    if len(content) != 3 and len(content) != 4:
        embed = create_embed(
            "Create_command",
            "!create_command {'!command name'} {'description'} {'image (optional)'}",
            "orange",
        )
        add_field(
            embed,
            "command name",
            "The 'name' of the command (ie. !info or !welcome).",
            True,
        )
        add_field(
            embed,
            "description",
            'The actual text provided by the command (ie. "Information can be found here: https://wikipedia.com")',
            True,
        )
        add_field(
            embed,
            "image (optional)",
            "An optional image to display with the command.",
            True,
        )
        example_list = """```
- item 1
- item 2
- item 3
- etc...```"""
        add_field(
            embed,
            "Hint",
            f'If you want to add multiple lines OR use a space (for example, as Code or as a list.  You\'ll need to use qutoation marks ("").  Example: !create_command !list "Here is a list: {example_list}',
            True,
        )

        await ctx.channel.send(embed=embed)
        return

    command = content[1]
    if command[0] == '"' and command[-1] == '"':
        command = command[1:-1]

    description = content[2]
    if len(content) == 3:
        image = None
    else:
        if content[3][0] == '"' and content[3][-1] == '"':
            image = content[3][1:-1]
        else:
            image = content[3]

    #! settings_location
    # with open(await settings_location(ctx.guild.id)) as f:
    #     l = yaml.safe_load(f)
    #     command_list = []
    #     for group in l["default_commands"]:
    #         for c in l["default_commands"][group]:
    #             if type(c) == str:
    #                 command_list.append(c)

    command_list = [
        i[0][1::] for i in db["db"].execute(
            "SELECT command FROM custom_commands").fetchall()
    ]

    if command[1::] in command_list:
        embed = create_embed(
            "Error",
            "That command is already a registerd command for this server.",
            "red",
        )
        await ctx.channel.send(embed=embed)
        return

    if description[0] == '"' and description[-1] == '"':
        description = description[1:-1]

    db["db"].execute(
        "INSERT INTO custom_commands VALUES (?, ?, ?)",
        (command, description, image),
    )
    db["con"].commit()

    embed = create_embed("Command Created Successfully.", "", "light_green")
    add_field(embed, "Command", command, True)
    add_field(embed, "Description", description, True)
    add_field(embed, "Image", image, True)

    await ctx.channel.send(embed=embed)
示例#26
0
    async def _programs(self, ctx):
        """!programs command"""
        content = ctx.message.content.split(" ")
        if len(content) == 1:
            embed = create_embed(
                "Command: !programs",
                "**Description**: Allows you to interact with programs commands.\n**Sub Commands**:\n!programs {user} - Allows you to see a user's programs. (ex: !programs <@749359897405161522>)\n!programs add - Allows you to add programs to your list.\n!programs remove - Allows you to remove programs from your list.\n!programs edit - Allows you to edit one of your programs.\n!commands setup - Allows an admin to setup a programs confirmation channel.",
                "orange",
            )
            await ctx.send(embed=embed)
            return

        subcommand = content[1]

        def grab_user(content):
            user = re.search(r"<@(?:&|!|)[0-9]{18}>", " ".join(content))
            if not user:
                return None, content
            else:
                content = " ".join(content).replace(user, "").split(" ")
                user = parse_id(user.group())
                return user, content

        if subcommand == "add" or subcommand == "a":
            #: !programs add Queens CS
            if len(content) == 2:
                embed = create_embed(
                    "Command: !programs add",
                    "**Description**: Allows you to add programs to your list.\n**Usage**:\n!programs add Queens CS, Mcgill CS, UW CS\n!programs add Queens CS, UW CS <@749359897405161522>",
                    "orange",
                )
                await ctx.send(embed=embed)
            else:
                content = content[2::]

                user, content = grab_user(content)
                if user is None:
                    user = ctx.author.id

                potential_programs = " ".join(content).split("\n")
                if len(potential_programs) == 1:
                    potential_programs = [
                        i.strip() for i in potential_programs[0].split(",")
                    ]
                else:
                    p = []
                    for i in potential_programs:
                        additions = [g.strip() for g in i.split(",")]
                        p.extend(additions)
                    potential_programs = p

                result = await programs_add(ctx, self.bot, potential_programs,
                                            user)
                await ctx.send(embed=result[1])

        elif subcommand == "remove" or subcommand == "r":
            if len(content) == 2:
                embed = create_embed(
                    "Command: !programs remove",
                    "**Description**: Allows you to remove programs from your list.  Provide a comma seperated list of numbers, or * to remove all of your programs.\n**Usage**:\n!programs remove 1, 2, 3\n!programs remove * <@749359897405161522>",
                    "orange",
                )
                await ctx.send(embed=embed)
                return

            content = content[2::]

            user, content = grab_user(content)
            if user is None:
                user = ctx.author.id

            result = await programs_remove(ctx, " ".join(content), user)
            await ctx.send(embed=result[1])

        elif subcommand == "edit" or subcommand == "e":
            #: !command edit 1 New Program
            if len(content) < 4:
                embed = create_embed(
                    "Command: !programs edit",
                    "**Description**: Allows you to edit a program in your list.  Provide the number for the program, and the new text.\n**Usage**:\n!programs edit 1 Queens CS\n!programs edit 1 Queens CS <@749359897405161522>",
                    "orange",
                )
                await ctx.send(embed=embed)
                return

            content = content[2::]

            user, content = grab_user(content)
            if user is None:
                user = ctx.author.id
            before = content[0]
            after = " ".join(content[1::])

            result = await programs_edit(ctx, self.bot, user, before, after)
            await ctx.send(embed=result[1])

        elif subcommand == "setup" or subcommand == "s":
            #: !command setup <#846962522065993768>
            if len(content) == 2 or len(content) > 3:
                embed = create_embed(
                    "Command: !programs setup",
                    "**Description**: Allows an administrator to setup a programs verification channel.\n**Usage**:\n!programs setup <@799848795050606607>",
                    "orange",
                )
                await ctx.send(embed=embed)
                return

            channel_id = parse_id(content[2])
            if not channel_id:
                embed = create_embed_template("Invalid Setup Channel", "",
                                              "error")
                await ctx.send(embed=embed)
                return

            result = await programs_setup(ctx, channel_id)
            await ctx.send(embed=result[1])
        else:
            attempt_user = parse_id(subcommand)
            if attempt_user:
                user_id = attempt_user
            else:
                user_id = ctx.guild.get_member_named(subcommand).id

            p = await programs(ctx, self.bot, user_id)

            await ctx.send(embed=p[1])
示例#27
0
async def custom_command_remove(ctx: discord.ext.commands.Context,
                                command: str) -> Tuple[bool, discord.Embed]:
    """Removes a custom command from the server's database

    Args:
        ctx (discord.ext.commands.Context): Context
        command (str): The name of the command to remove

    Returns:
        Tuple[bool, discord.Embed]: [Status: bool, Embed: discord.Embed]
    """

    # Permissions check
    if ctx.author.guild_permissions.administrator is False:
        return (
            False,
            create_embed_template(
                "No Permission",
                "You do not have permission to create commands.",
                "error",
            ),
        )

    db = await Commands_DB(ctx.guild.id)

    # Removes the ! from the command -> !hello turns into hello
    if command[0] == "!":
        command = command[1::]

    # Grabs all of the commands
    grab_commands = await db.grab_commands()
    if grab_commands is None:
        return (
            False,
            create_embed_template(
                "Invalid Command",
                "This server has no commands therefore you cannot remove one.",
                "error",
            ),
        )

    command_list = [i[0] for i in grab_commands]

    if command in command_list:
        # Grabs the info for the command to be deleted
        command_delete = await db.fetch_command(command)

        # Deletes
        await db.remove_command(command)

        return (
            True,
            create_embed(
                "Command Successfully Deleted",
                f"Command Deleted: !{command_delete[0]}",
                "light_green",
            ),
        )
    else:
        return (
            False,
            create_embed_template("Invalid Command",
                                  "Check the commands with !commands.",
                                  "error"),
        )
示例#28
0
async def custom_command_add(ctx: discord.ext.commands.Context, name: str,
                             description: str, image: str
                             or None) -> Tuple[bool, discord.Embed]:
    """Adds a command to the database

    Args:
        ctx (discord.ext.commands.Context): Context
        name (str): Name of the command to add
        description (str): Description of the command
        image (str or None): Image link for the command

    Returns:
        Tuple[bool, discord.Embed]: [Status: bool, Embed: discord.Embed]
    """
    name = name.lower()
    name = name[1::] if name[0] == "!" else name

    # Permissions check
    if ctx.author.guild_permissions.administrator is False:
        return (
            False,
            create_embed_template(
                "No Permission",
                "You do not have permission to create a command.",
                "error",
            ),
        )

    urls = []
    if image:
        # Checks for an actual photo in "image"
        photo_indicators = (
            "tenor",
            "jpeg",
            "jpg",
            "png",
            "gif",
            "webp",
            "giphy",
            "tiff",
            "nef",
            "cr2",
            "arw",
        )

        # Extracts the urls from the "image" variable
        urls = URLExtract().find_urls(image)

    if len(urls) == 1:
        # Check to ensure the single URL is actually an image
        image = urls[0]
        if not (image.startswith("http")
                and set(image.split(".")).intersection(set(photo_indicators))):
            return (
                False,
                create_embed_template("Invalid Image",
                                      "Make sure your link is to an image.",
                                      "error"),
            )
    elif len(urls) == 2:
        # Too many URLs
        return (
            False,
            create_embed_template(
                "Too many Links", "Borg can only support 1 image per command.",
                "error"),
        )
    else:
        urls = None

    db = await Commands_DB(ctx.guild.id)

    # Find all of the current commands
    grab_commands = await db.grab_commands()

    if grab_commands is not None:
        command_list = [i[0] for i in grab_commands]

        # Ensure the current command is unique
        if name in command_list:
            return (
                False,
                create_embed_template(
                    "Invalid Command Name",
                    "There is already a command with that denominator.",
                    "error",
                ),
            )

    # Add it to the database
    await db.add_command(name, description, image)

    return (
        True,
        create_embed(
            "Success",
            f"Command successfully created, run it with !{name}",
            "light_green",
        ),
    )
示例#29
0
文件: roles.py 项目: joshuajz/Borg
async def role_toggle(ctx: discord.ext.commands.Context,
                      role: str) -> Tuple[bool, discord.Embed]:
    """Handling for the !role command

    Args:
        ctx (discord.ext.commands.Context): Context
        role (str): The role's denominator

    Returns:
        Tuple[bool, discord.Embed]: [Status: bool, Embed: discord.Embed]
    """

    # Grab the user's roles
    user_roles = [i.id for i in ctx.author.roles]

    db = await Roles_DB(ctx.guild.id)

    # Grab this server's role commands
    role_id = await db.grab_role(command=role)

    if role_id is None:
        return (
            False,
            create_embed_template("Invalid Role",
                                  "Use !roles to see all of the roles.",
                                  "error"),
        )

    role_id = role_id[1]

    actual_role = ctx.guild.get_role(role_id)

    if role_id in user_roles:
        # Add the role
        try:
            await ctx.author.remove_roles(actual_role)
        except:
            return (
                False,
                create_embed_template(
                    "No Permission.",
                    "Borg doesn't have permission to add/remove that role.  Ensure Borg's role is **above** the role you're trying to toggle in the server settings (Contact an administrator)",
                    "error",
                ),
            )

        embed = create_embed("Removed Role",
                             f"You removed the {actual_role.mention} role.",
                             "dark_blue")
        return True, embed

    else:
        # Remove the role
        try:
            await ctx.author.add_roles(actual_role)
        except:
            return (
                False,
                create_embed_template(
                    "No Permission.",
                    "Borg doesn't have permission to add/remove that role.  Ensure Borg's role is **above** the role you're trying to toggle in the server settings (Contact an administrator).",
                    "error",
                ),
            )

        embed = create_embed("Added Role",
                             f"You added the {actual_role.mention} role.",
                             "light_green")
        return True, embed
示例#30
0
async def create_role(ctx, client):
    content = shlex.split(ctx.content)

    if ctx.author.guild_permissions.administrator != True:
        # Does not have permission
        return

    if len(content) != 3:
        # Provided no commandline arguments, print out a help message
        embed = create_embed("Create_role", "!create_role {role} {name}",
                             "orange")
        add_field(
            embed,
            "role",
            "Provide the @ for the role (ie. @Member) or the name of the role (ie. Member)",
            True,
        )
        add_field(
            embed,
            "name",
            "Provide the name for the user to add the role (ie. member or 'cool guy')",
            True,
        )
        await ctx.channel.send(embed=embed)
        return

    # Role as an @ <@&749382234829750392>
    # Otherwise: Member

    role = content[1]
    name = content[2]

    db = await database_connection(ctx.guild.id)

    if role[0:2] == "<@":
        # Actual Role @ provided
        role_id = role[3:-1]
    else:
        role_id = [i.id for i in ctx.guild.roles if i.name == role]

        if len(role_id) == 1:
            role_id = role_id[0]
        else:
            #! Error Message
            embed = create_embed(
                "Error",
                "The 'role' provided is invalid.  Make sure it's spelled correctly with proper capitalization (case sensitive) and consider trying to use the actual @ for the role.",
                "red",
            )
            await ctx.channel.send(embed=embed)

            return

    if int(role_id) not in [
            i[0] for i in db["db"].execute(
                "SELECT role_id FROM normal_roles").fetchall()
    ] and name not in [
            i[0] for i in db["db"].execute(
                "SELECT command FROM normal_roles").fetchall()
    ]:
        for role in ctx.guild.roles:
            if role.name == "Borg Test" or role.name == "Borg":
                BORG_ROLE = {"id": role.id, "position": role.position}

        if BORG_ROLE["position"] > ctx.guild.get_role(int(role_id)).position:
            db["db"].execute("INSERT INTO normal_roles VALUES (?, ?)",
                             (role_id, name))
            db["con"].commit()

            embed = create_embed("Role Added", "", "light_green")
            add_field(embed, "Role",
                      ctx.guild.get_role(int(role_id)).mention, True)
            add_field(embed, "Command", f"!role {name}", True)

            await ctx.channel.send(embed=embed)
        else:
            embed = create_embed(
                "Error",
                "The bot does not have permission to give that role to users.  Ensure that the 'Borg' role is ABOVE the role in the 'Roles' part of your settings.",
                "red",
            )
            await ctx.channel.send(embed=embed)

    else:
        # Error Message
        embed = create_embed(
            "Error",
            "The 'role' or 'name' already has a command associated.  Check the list of roles with !roles.",
            "red",
        )

        await ctx.channel.send(embed=embed)