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)
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", ), )
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)
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)
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)
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)
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)
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]
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)
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)
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
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)
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)
async def programs_add( ctx: discord.ext.commands.Context, client: discord.ClientUser.bot, programs: list, user: int, ) -> Tuple[bool, discord.Embed]: """Creates a request to add programs for a user Args: ctx (discord.ext.commands.Context): Context client (discord.ClientUser.bot): Discord Bot programs (list): List of programs to add user (int): User's ID to add Returns: Tuple(bool, discord.Embed): [Status: bool, Embed: discord.Embed] """ db_guild = await Guild_DB(ctx.guild.id) # Channel for verification settings = await db_guild.grab_settings() if settings is None or settings["programs_channel"] is None: return ( False, create_embed_template( "No Programs Channel", "The admins haven't created a programs channel. Have an admin run /programs setup.", "error", ), ) programs_channel = settings["programs_channel"] # Creates an embed embed = create_embed("Programs Verification Required", "", "magenta") add_field(embed, "User", client.get_user(user).mention, False) # Message with all of the programs programs_msg = "" len_programs = len(programs) for program in range(len_programs): programs_msg += (programs[program] + "\n" if program != len_programs - 1 else programs[program]) add_field(embed, "Program Additions", programs_msg, True) # Sends the message to the verification channel verify_channel = client.get_channel(programs_channel) verification_msg = await verify_channel.send(embed=embed) # Adds the verification emoji for emoji in ["✅", "❌"]: await verification_msg.add_reaction(emoji) return ( True, create_embed("Programs successfully sent to Moderators.", programs_msg, "light_green"), )
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)
async def help_command(ctx: discord.ext.commands.Context, bot: discord.ClientUser.bot): """Help Command Args: ctx (discord.ext.commands.Context): Context bot (discord.ClientUser.bot): Bot instance """ def check(reaction, user): """Checks if the original reaction was added by the user provided.""" return user == ctx.author and str(reaction) in ["◀️", "▶️"] pages = [] embed = create_embed( "Help: Table of Contents", "Page `1/4`\nPage 1: Table of Contents\nPage 2: General Commands\nPage 3: University Commands\nPage 4: Setup Commands", "orange", ) pages.append(embed) embed = create_embed("Help: General Commands", "Page `2/4`", "orange") add_field( embed, "Commands", "Allow you to use this server's custom commands.\n!commands - Lists the commands.", False, ) pages.append(embed) embed = create_embed("Help: University Commands", "Page `3/4`", "orange") add_field( embed, "Programs", "Allows you to interact with programs lists.\n!programs - Allows you to see a user's programs.\n/programs add - Add programs.\n/programs remove - Remove programs.\n/programs edit - Edit one of your programs.\n", False, ) add_field( embed, "Courses", "Allows you to lookup a University's course.\n/course - Lookup a course.", False, ) pages.append(embed) embed = create_embed("Help: Setup Commands", "Page `4/4`", "orange") add_field( embed, "Programs", "Allows you to setup the channel for programs verification.\n/programs setup {channel}\n", False, ) add_field( embed, "Commands", "Allows you to add and remove your server's custom commands.\n/command add - Adds a command.\n/command remove - Removes a command.", False, ) pages.append(embed) # Send the original message w/ reactions await send_page_command(ctx, bot, pages)
async def programs_reaction_handling(ctx: discord.RawReactionActionEvent, client: discord.ClientUser.bot) -> bool: """Handles Reactions for programs verification Args: ctx (discord.ext.commands.Context): Context client (discord.ClientUser.bot): Bot Returns: bool: If it was a programs related reaction """ db = await Programs_DB(ctx.guild_id) db_guild = await Guild_DB(ctx.guild_id) # Grabs the verification channel settings = await db_guild.grab_settings() if settings is None or settings["programs_channel"] is None: return False mod_channel_id = settings["programs_channel"] if mod_channel_id != ctx.channel.id: return False # Grabs the message & embeds m = await client.get_channel(ctx.channel.id).fetch_message(ctx.message.id) embeds = m.embeds[0] reactions = m.reactions # Checks to ensure no one else has already added the reactions if not ((reactions[0].count == 1 and reactions[1].count == 2) or (reactions[0].count == 2 and reactions[1].count == 1)): # An administrator/moderator has already reacted, no need to perform the action twice return False # Deals with programs if m.embeds[0].title == "Programs Verification Required": if ctx.emoji.name == "❌": # Delete await m.delete() return True elif ctx.emoji.name == "✅": user_id = parse_id(embeds.fields[0].value) if not user_id: return True # Checks to see if the user already has a programs list # If they don't count = await db.check_programs_exists(user_id) if count != 1: # Delete the message programs = embeds.fields[1].value await m.delete() if not programs: return False # Add the programs await db.add_programs(user_id, programs) # If they do else: # Delete the message program_additions = embeds.fields[1].value.split("\n") await m.delete() if not program_additions: return False # Grabs the current programs current_programs = await db.grab_programs(user_id) current_programs += "\n" # Adds the additions len_program_additions = len(program_additions) for program in range(len_program_additions): current_programs += program_additions[program] + ( "\n" if program + 1 != len_program_additions else "") # Updates the database to the newer longer version await db.update_programs(user_id, current_programs) # Grabs the user & makes a DM channel user = client.get_user(user_id) dm_channel = user.dm_channel if dm_channel is None: await user.create_dm() dm_channel = user.dm_channel # Sends an embed w/ the new programs embed = create_embed("!Programs Command Created Successfully", "", "light_green") add_field(embed, "Programs", current_programs, True) try: await dm_channel.send(embed=embed) except: return True return True elif m.embeds[0].title == "Programs (Edit) Verification Required": if ctx.emoji.name == "❌": # Delete await m.delete() return True elif ctx.emoji.name == "✅": # User user_id = parse_id(embeds.fields[0].value) if not user_id: await m.delete() return True # New addition & Current program_change = embeds.fields[1].value programs_newmsg = embeds.fields[2].value # Delete await m.delete() # Invalid if not programs_newmsg or not program_change: return True # Grabs current programs current_programs = await db.grab_programs(user_id) # All programs into a dictionary programs = {} i = 1 for p in current_programs.split("\n"): if p == program_change: programs[i] = programs_newmsg else: programs[i] = p i += 1 # Creates a message w/ the programs final_programs = "" p_values = list(programs.values()) len_p_values = len(p_values) for i in range(len_p_values): final_programs += p_values[i] + ("\n" if i + 1 != len_p_values else "") # Update in the databse await db.update_programs(user_id, final_programs) # Open a DM user = client.get_user(user_id) dm_channel = user.dm_channel if dm_channel is None: await user.create_dm() dm_channel = user.dm_channel # Send a status message embed = create_embed("Programs Edit Was Successful", "", "light_green") add_field(embed, "Programs", final_programs, True) try: await dm_channel.send(embed=embed) except: return True return True
async def programs_edit(ctx, client): content = shlex.split(ctx.content) db = await database_connection(ctx.guild.id) if len(content) < 3: embed = create_embed("Programs_edit", "!programs_edit {program to edit} {new text}", "orange") add_field( embed, "Program to edit", "The number of the program you would like to edit.", True, ) add_field(embed, "New text", "The text that you would like that program to say.", True) add_field(embed, "Example", "!programs_edit 1 New Text Here", True) await ctx.channel.send(embed=embed) return programs_channel = (db["db"].execute( "SELECT programs_channel FROM settings").fetchone()[0]) if programs_channel is None: embed = create_embed( "Error", "The admins have not setup !programs. Ask them to run !programs_setup.", "red", ) await ctx.channel.send(embed=embed) return programs_channel = int(programs_channel) # Finding the user_id to use user_id = find_user(content[1]) if len(str(user_id)) == 18: program_to_edit = content[2] new_content = "".join(content[3::]) if ctx.author.guild_permissions.administrator != True: user_id = ctx.author.id else: user_id = ctx.author.id program_to_edit = content[1] new_content = " ".join(content[2::]) current_programs = (db["db"].execute( "SELECT description FROM programs WHERE user_id = (?)", (user_id, )).fetchone())[0] if current_programs is None: embed = create_embed( "You don't have a !programs", "Create a !programs with !programs_add before trying to edit.", "red", ) await ctx.channel.send(embed=embed) return programs = {} i = 1 for p in current_programs.split("\n"): programs[i] = p i += 1 if int(program_to_edit) not in programs.keys(): embed = create_embed( "Invalid program to edit.", "You've selected an invalid program to edit, try another one.", "red", ) await ctx.channel.send(embed=embed) return programs[int(program_to_edit)] = new_content programs_print = "" for key, value in programs.items(): programs_print += value + "\n" user = client.get_user(user_id) embed = create_embed("Programs Edit Verification Required", "", "magenta") add_field(embed, "User", user.mention, False) add_field(embed, "New Text", new_content, True) add_field(embed, "Program to Change", program_to_edit, True) add_field(embed, "Programs", programs_print, True) channel = client.get_channel(programs_channel) verification_msg = await channel.send(embed=embed) emojis = ["✅", "❌"] for emoji in emojis: await verification_msg.add_reaction(emoji) embed = create_embed( "Successfully Sent to Moderators", "Your !programs additions have been sent to the administrators for review. Please sit tight!", "light_green", ) add_field(embed, "User", user.mention, True) add_field(embed, "Programs List", programs_print, True) await ctx.channel.send(embed=embed)
async def programs_remove(ctx, client): content = shlex.split(ctx.content) db = await database_connection(ctx.guild.id) if len(content) <= 1: embed = create_embed("Programs_remove", "!programs_remove {user: admin only} {program}", "orange") add_field( embed, "Optional Argument: user", "Admin Only: You can supply a user and their programs for them.", True, ) add_field( embed, "Program", "Provide the program you would like to remove (use the number), or use * to remove all programs.", True, ) add_field(embed, "Example", "!programs_remove 1, 2", True) add_field(embed, "Example 2", "!programs_remove all", True) await ctx.channel.send(embed=embed) content = ctx.content[16::] # Finding the user_id to use user_id = find_user(content.strip().split(" ")[0]) if user_id: content = "".join(content.strip().split(" ")[1::]) if ctx.author.guild_permissions.administrator != True: user_id = ctx.author.id else: user_id = ctx.author.id remove_list = [] if content.strip().lower() in ["*", "all"]: db["db"].execute("DELETE FROM programs WHERE user_id = (?)", (user_id, )) db["con"].commit() embed = create_embed("Removed **all** programs successfully.", "", "dark_blue") await ctx.channel.send(embed=embed) return if "\n" in content: for i in content.split("\n"): if "," in i: for z in i.split(","): remove_list.append(int(z.strip())) else: remove_list.append(int(i.strip())) elif "," in content: for i in content.split(","): remove_list.append(int(i.strip())) else: remove_list = content.strip() # Remove duplicates remove_list = list(dict.fromkeys(remove_list)) remove_list = [int(i) for i in remove_list] programs_raw = (db["db"].execute( "SELECT description FROM programs WHERE user_id = (?)", (user_id, )).fetchone()[0].split("\n")) programs = {} i = 1 for p in programs_raw: programs[i] = p i += 1 new_programs = { key: val for key, val in programs.items() if key not in remove_list } description = "" description_display = "" i = 1 space_amount = (len(new_programs) // 10) + 1 for key, val in new_programs.items(): if val == "": continue number = f"{i}".rjust(space_amount, " ") description_display += f"{number}. {val.strip()}\n" description += val.strip() + "\n" i += 1 if not description: db["db"].execute("DELETE FROM programs WHERE user_id = (?)", (user_id, )) embed = create_embed("Removed **all** programs successfully.", "", "dark_blue") await ctx.channel.send(embed=embed) else: db["db"].execute( "UPDATE programs SET description = (?) WHERE user_id = (?)", (description, user_id), ) embed = create_embed("Updated Programs List", "", "dark_blue") add_field(embed, "Programs", f"```{description_display}```", True) await ctx.channel.send(embed=embed) db["con"].commit()
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)
async def program_reaction_handling(ctx, client): db = await database_connection(ctx.guild_id) mod_channel_id = (db["db"].execute( "SELECT programs_channel FROM settings").fetchone()[0]) if mod_channel_id is None: return False mod_channel_id = int(mod_channel_id) if mod_channel_id != ctx.channel_id: return m = await client.get_channel(ctx.channel_id).fetch_message(ctx.message_id) m_embeds = m.embeds[0] if m.embeds[0].title == "Programs Verification Required": if ctx.emoji.name == "❌": await m.delete() return True elif ctx.emoji.name == "✅": user_id = find_user(m_embeds.fields[0].value) if not user_id: return False if (db["db"].execute( "SELECT COUNT(user_id) FROM programs WHERE user_id = (?)", (user_id, ), ).fetchone()[0] != 1): programs_list = m_embeds.fields[2].value await m.delete() if not programs_list: return False db["db"].execute( "INSERT INTO programs (user_id, description) VALUES (?, ?)", (user_id, programs_list), ) db["con"].commit() else: programs_additions = m_embeds.fields[2].value await m.delete() if not programs_additions: return False current_programs = (db["db"].execute( "SELECT description FROM programs WHERE user_id = (?)", (user_id, ), ).fetchone())[0] current_programs += "\n" for p in programs_additions.split("\n"): current_programs += p + "\n" programs_list = current_programs db["db"].execute( "UPDATE programs SET description = ? WHERE user_id = ?", (current_programs, user_id), ) db["con"].commit() user = client.get_user(user_id) dm_channel = user.dm_channel if dm_channel is None: await user.create_dm() dm_channel = user.dm_channel embed = create_embed("!Programs Command Created Successfully", "", "light_green") add_field(embed, "Programs", programs_list, True) try: await dm_channel.send(embed=embed) except: return True return True elif m.embeds[0].title == "Programs Edit Verification Required": if ctx.emoji.name == "❌": await m.delete() return True elif ctx.emoji.name == "✅": user_id = find_user(m_embeds.fields[0].value) if not user_id: await m.delete() return False programs_newmsg = m_embeds.fields[1].value program_change = m_embeds.fields[2].value await m.delete() if not programs_newmsg or not program_change: return False current_programs = (db["db"].execute( "SELECT description FROM programs WHERE user_id = (?)", (user_id, ), ).fetchone())[0] #! HERE programs = {} i = 1 for p in current_programs.split("\n"): programs[i] = p i += 1 programs[int(program_change)] = programs_newmsg final_programs = "" for key, value in programs.items(): final_programs += value + "\n" db["db"].execute( "UPDATE programs SET description = ? WHERE user_id = ?", (final_programs, user_id), ) db["con"].commit() user = client.get_user(user_id) dm_channel = user.dm_channel if dm_channel is None: await user.create_dm() dm_channel = user.dm_channel embed = create_embed("!Programs Edit Was Successful", "", "light_green") add_field(embed, "Programs", final_programs, True) try: await dm_channel.send(embed=embed) except: return True return True return False
async def programs_add(ctx, client): if len(ctx.content.split(" ")) <= 1 and len(ctx.content.split("\n")) <= 1: embed = create_embed( "Programs_add", "!programs_add {user: admin only} Program #1, Program #2, Program #3 ...", "orange", ) add_field( embed, "Optional Argument: user", "Admin Only: You can supply a user and their programs for them.", True, ) add_field( embed, "Program #1, Program #2, etc.", "Provide a list of programs to be added. You can use *commas* or *new lines* to denote.", True, ) add_field(embed, "Example", "!programs_add UW - CS, UW - SE, UW - CE", True) add_field( embed, "Note", "!programs_add is **additive** meaning you don't have to remove all of your programs to add new ones.", True, ) add_field(embed, "Example 2", "!programs_add\nUW - CS\nUW - SE", True) await ctx.channel.send(embed=embed) return db = await database_connection(ctx.guild.id) programs_channel = (db["db"].execute( "SELECT programs_channel FROM settings").fetchone()[0]) if programs_channel is None: embed = create_embed( "Error", "The admins have not setup !programs. Ask them to run !programs_setup.", "red", ) await ctx.channel.send(embed=embed) return programs_channel = int(programs_channel) content = ctx.content[14::] user_id = find_user(content.strip().split(" ")[0]) if user_id: content = " ".join(content.strip().split(" ")[1::]) if ctx.author.guild_permissions.administrator != True: user_id = ctx.author.id else: user_id = ctx.author.id add_programs = [] if "\n" in content: for program in content.split("\n"): if "," in program: for p in program.split(","): add_programs.append(p) continue add_programs.append(program) else: for program in content.split(","): add_programs.append(program.strip()) current_programs = (db["db"].execute( "SELECT description FROM programs WHERE user_id = (?)", (user_id, )).fetchone()) embed = create_embed("Programs Verification Required", "", "magenta") add_field(embed, "User", client.get_user(user_id).mention, False) clist = "" if current_programs is not None: for p in current_programs[0].split("\n"): if p != "": clist += p + "\n" add_field(embed, "Current Programs", clist, True) plist = "" for p in add_programs: plist += p.strip() + "\n" add_field(embed, "Program Additions", plist, True) add_field(embed, "Final Programs", clist + plist, True) verify_channel = client.get_channel(programs_channel) verification_msg = await verify_channel.send(embed=embed) emojis = ["✅", "❌"] for emoji in emojis: await verification_msg.add_reaction(emoji) embed = create_embed( "Successfully Sent to Moderators", "Your !programs additions have been sent to the administrators for review. Please sit tight!", "light_green", ) add_field(embed, "User", client.get_user(int(user_id)).mention, True) add_field(embed, "Added Programs", f"```\n{plist}\n```", True) await ctx.channel.send(embed=embed)
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)
async def programs_edit( ctx: discord.ext.commands.Context, client: discord.ClientUser.bot, user: int, before: str, after: str, ) -> Tuple[bool, discord.Embed]: """Edits one of a user's programs Args: ctx (discord.ext.commands.Context): Context client (discord.ClientUser.bot): Bot instance user (int): User's ID before (str): The program to edit after (str): The new text to replace the program Returns: Tuple[bool, discord.Embed]: [Status: bool, Embed: discord.Embed] """ # Check user if user is None: return ( False, create_embed_template("Invalid Arguments", "User was null.", "error"), ) # Check before and after if before is None or after is None: return ( False, create_embed_template("Invalid Arguments", "*Before* or *after* value is invalid.", "error"), ) try: before = int(before) except: return ( False, create_embed_template( "Invalid Arguments", "*Before* value is invalid (not a number).", "error", ), ) user = parse_id(user) db = await Programs_DB(ctx.guild.id) db_guild = await Guild_DB(ctx.guild.id) # Channel for verification settings = await db_guild.grab_settings() if settings is None or settings["programs_channel"] is None: return ( False, create_embed_template( "Invalid Channel", "The admins haven't created a programs channel. Have an admin run /programs setup.", "error", ), ) programs_channel = settings["programs_channel"] programs = (await db.grab_programs(user)).split("\n") # Entire programs list p = {} i = 1 for program in programs: p[i] = program i += 1 if before not in p.keys(): return ( False, create_embed_template( "Invalid Program", "You do not have a program with that *before* value.", "error", ), ) # Create a verification Embed embed = create_embed("Programs (Edit) Verification Required", "", "magenta") add_field(embed, "User", f"{(await client.fetch_user(user)).mention}", True) add_field(embed, "Before", p[before], True) add_field(embed, "After", after, True) verify_channel = client.get_channel(int(programs_channel)) verify_msg = await verify_channel.send(embed=embed) # Add emojis for emoji in ["✅", "❌"]: await verify_msg.add_reaction(emoji) embed = create_embed("Program Edit successfully sent to the moderators.", "", "light_green") add_field(embed, "Before", p[before], True) add_field(embed, "After", after, True) return True, embed