Package: discordLevelingSystem
A library to implement a leveling system into a discord bot. One of the most popular discord bots out there is MEE6 and it's leveling system. This library provides ways to easily implement one for yourself. It uses SQLite (aiosqlite) to locally query things such as their XP, rank, and level. Various amounts of other methods and classes are also provided so you can access or remove contents from the database file.InstallingYou can install the latestPyPI versionof the library by doing:$ pip install discordLevelingSystemOr the development version:$ pip install git+https://github.com/Defxult/discordLevelingSystemShowcaseHow to importfromdiscordLevelingSystemimportDiscordLevelingSystem,LevelUpAnnouncement,RoleAwardIntentsIntentsare required for proper functionalitybot=commands.Bot(...,intents=discord.Intents(messages=True,guilds=True,members=True))DiscordLevelingSystemclass DiscordLevelingSystem(rate=1, per=60.0, awards=None, **kwargs)Parameters of the DiscordLevelingSystem constructorrate(int) The amount of messages each member can send before the cooldown triggersper(float) The amount of seconds each member has to wait before gaining more XP, aka the cooldownawards(Optional[Dict[int, List[RoleAward]]]) The role given to a member when they reach aRoleAwardlevel requirementKwargs of the DiscordLevelingSystem constructorNameTypeDefault ValueInfono_xp_rolesSequence[int]NoneA sequence of role ID's. Any member with any of those roles will not gain XP when sending messagesno_xp_channelsSequence[int]NoneA sequence of text channel ID's. Any member sending messages in any of those text channels will not gain XPannounce_level_upboolTrueIfTrue, level up messages will be sent when a member levels upstack_awardsboolTrueIf this isTrue, when the member levels up the assigned role award will be applied. IfFalse, the previous role award will be removed and the level up assigned role will also be appliedlevel_up_announcementUnion[LevelUpAnnouncement, Sequence[LevelUpAnnouncement]]LevelUpAnnouncement()The message that is sent when someone levels up. If this is a sequence ofLevelUpAnnouncement, one is selected at randombotUnion[AutoShardedBot, Bot]NoneYour bot instance variable. Used only if you'd like to use theon_dls_level_upeventAttributesno_xp_rolesno_xp_channelsannounce_level_upstack_awardslevel_up_announcementbotrate(int) Read only property from the constructorper(float) Read only property from the constructordatabase_file_path(str) Read only propertyactive(bool) Enable/disable the leveling system. IfFalse, nobody can gain XP when sending messages unless this is set back toTrueNOTE: All attributes can be set during initializationInitial SetupWhen setting up the leveling system, a database file needs to be created in order for the library to function.Associated static methodDiscordLevelingSystem.create_database_file(path: str)The above static method is used to create the database file for you in the path you specify. This method only needs to be called once. Example:DiscordLevelingSystem.create_database_file(r'C:\Users\Defxult\Documents')Once created, there is no need to ever run that method again unless you want to create a new database file from scratch. Now that you have the database file, you can use the leveling system.Connecting to the DatabaseAssociated methodDiscordLevelingSystem.connect_to_database_file(path: str)Since the database file has already been created, all you need to do is connect to it.NOTE: When connecting to the database file, the event loop must not be runningEXAMPLEfromdiscord.extimportcommandsfromdiscordLevelingSystemimportDiscordLevelingSystembot=commands.Bot(...)lvl=DiscordLevelingSystem()lvl.connect_to_database_file(r'C:\Users\Defxult\Documents\DiscordLevelingSystem.db')bot.run(...)RoleAwardclass RoleAward(role_id: int, level_requirement: int, role_name=None)You can assign roles to the system so when someone levels up to a certain level, they are given that role.RoleAwardis how that is accomplished.Parameters of the RoleAward constructorrole_id(int) ID of the role that is to be awarded.level_requirement(int) What level is required for a member to be awarded the role.role_name(Optional[str]) A name you can set for the award. Nothing is done with this value, it is used for visual identification purposes only.Attributesrole_idlevel_requirementrole_namemention(str) The discord role mention stringWhen creating role awards, all role IDs and level requirements must be unique. Level requirements must also be in ascending order. It is also possible to assign different role awards for different guilds. If you don't want any role awards, set theawardsparameter toNone. When settingawards, it accepts adictwhere the keys are guild IDs and the values are alistofRoleAwardEXAMPLEfromdiscordLevelingSystemimportDiscordLevelingSystem,RoleAwardjohns_server=587937522043060224janes_server=850809412011950121my_awards={johns_server:[RoleAward(role_id=831672678586777601,level_requirement=1,role_name='Rookie'),RoleAward(role_id=831672730583171073,level_requirement=2,role_name='Associate'),RoleAward(role_id=831672814419050526,level_requirement=3,role_name='Legend')],janes_server:[RoleAward(role_id=851400453904400385,level_requirement=1,role_name='Silver'),RoleAward(role_id=851379776111116329,level_requirement=2,role_name='Gold'),RoleAward(role_id=851959077071880202,level_requirement=3,role_name='Diamond')]}lvl=DiscordLevelingSystem(...,awards=my_awards)LevelUpAnnouncementclass LevelUpAnnouncement(message=default_message, level_up_channel_ids=None, allowed_mentions=default_mentions, tts=False, delete_after=None)Level up announcements are for when you want to implement your own level up messages. It provides access to who leveled up, their rank, level and much more. It also uses some of discord.py's kwargs from it'sMessageable.sendsuch asallowed_mentions,tts, anddelete_afterto give you more control over the sent message.Parameters of the LevelUpAnnouncement constructormessage(Union[str, discord.Embed]) The message that is sent when someone levels up. Defaults to"<mention>, you are now **level <level>!**"level_up_channel_ids(Optional[Sequence[int]]) The text channel IDs where all level up messages will be sent for each server. IfNone, the level up message will be sent in the channel where they sent the message (example below).allowed_mentions(discord.AllowedMentions) Used to determine who can be pinged in the level up message. Defaults todiscord.AllowedMentions(everyone=False, users=True, roles=False, replied_user=False)tts(bool) When the level up message is sent, have discord read the level up message aloud.delete_after(Optional[float]) Delete the level up message after an x amount of seconds.Class AttributesTheLevelUpAnnouncementclass provides a set of markdown attributes for you to use so you can access certain information in a level up message.LevelUpAnnouncement.TOTAL_XPThe members current total XP amountLevelUpAnnouncement.LEVELThe members current levelLevelUpAnnouncement.RANKThe members current rankThe below markdown attributes takes the information from adiscord.Memberobject so you can access member information in the level up message.LevelUpAnnouncement.Member.avatar_urlLevelUpAnnouncement.Member.banner_urlLevelUpAnnouncement.Member.created_atLevelUpAnnouncement.Member.default_avatar_urlLevelUpAnnouncement.Member.discriminatorLevelUpAnnouncement.Member.display_avatar_urlLevelUpAnnouncement.Member.display_nameLevelUpAnnouncement.Member.idLevelUpAnnouncement.Member.joined_atLevelUpAnnouncement.Member.mentionLevelUpAnnouncement.Member.nameLevelUpAnnouncement.Member.nickLevelUpAnnouncement.Member.Guild.icon_urlLevelUpAnnouncement.Member.Guild.idLevelUpAnnouncement.Member.Guild.nameEXAMPLEfromdiscordLevelingSystemimportDiscordLevelingSystem,LevelUpAnnouncementembed=discord.Embed()embed.set_author(name=LevelUpAnnouncement.Member.name,icon_url=LevelUpAnnouncement.Member.avatar_url)embed.description=f'Congrats{LevelUpAnnouncement.Member.mention}! You are now level{LevelUpAnnouncement.LEVEL}😎'announcement=LevelUpAnnouncement(embed)lvl=DiscordLevelingSystem(...,level_up_announcement=announcement)# NOTE: You can have multiple level up announcements by setting the parameter to a sequence of LevelUpAnnouncementlvl=DiscordLevelingSystem(...,level_up_announcement=[announcement_1,announcement_2,...])When it comes tolevel_up_channel_ids, you can set a designated channel for each server. If you don't set a level up channel ID for a specific server, the level up message will be sent in the channel where the member leveled up. You don't have to specify a level up channel ID for each server unless you'd like to.johns_bot_commands=489374746737648734# text channel ID from server Ajanes_levelup_channel=58498304930493094# text channel ID from server Bannouncement=LevelUpAnnouncement(...,level_up_channel_ids=[johns_bot_commands,janes_levelup_channel])lvl=DiscordLevelingSystem(...,level_up_announcement=announcement)Handling XPMethodaward_xpis how members gain XP. This method is placed inside theon_messageevent of your bot. Members will gain XP if they send a message and if they'renoton cooldown. Spamming messages will not give them XP.NOTE: Members cannot gain XP in DM'sAssociated methodsawait DiscordLevelingSystem.add_xp(member: Member, amount: int)await DiscordLevelingSystem.remove_xp(member: Member, amount: int)await DiscordLevelingSystem.set_level(member: Member, level: int)await DiscordLevelingSystem.award_xp(*, amount=[15, 25], message: Message, refresh_name=True, **kwargs)Parameters for award_xpamount(Union[int, Sequence[int]]) The amount of XP to award to the member per message. Must be from 1-25. Can be a sequence with a minimum and maximum length of two. Ifamountis a sequence of two integers, it will randomly pick a number in between those numbers including the numbers provided.message(discord.Message) A discord message objectrefresh_name(bool) Everytime the member sends a message, check if their name still matches the name in the database. If it doesn't match, update the database to match their current name. It is suggested to leave this asTrueso the database can always have the most up-to-date record.Kwargs for award_xpbonus(DiscordLevelingSystem.Bonus) Used to set the roles that will be awarded bonus XP.class Bonus(role_ids: Sequence[int], bonus_amount: int, multiply: bool)Parameters of the DiscordLevelingSystem.Bonus constructorrole_ids(Sequence[int]) The role(s) a member must have to be able to get bonus XP. They only need to have one of these roles to get the bonusbonus_amount(int) Amount of extra XP to be awardedmultiply(bool) If set toTrue, this will operate on a x2, x3 basis. Meaning if you have the awarded XP amount set to 10 and you want the bonus XP role to be awarded 20, it must be set to 2, not 10. IfFalse, it operates purely on the given value. Meaning if you have the awarded XP set to 10 and you want the bonus XP role to be awarded 20, it must be set to 10.EXAMPLElvl=DiscordLevelingSystem(...)nitro_booster=851379776111116329associate_role=851400453904400385@bot.eventasyncdefon_message(message):awaitlvl.award_xp(amount=[15,25],message=message,bonus=DiscordLevelingSystem.Bonus([nitro_booster,associate_role],20,multiply=False))MemberDataAccessing the raw information inside the database file can look a bit messy if you don't know exactly what you're looking at. To make things easier, this library comes with theMemberDataclass. A class which returns information about a specific member in the database.Associated methodsawait DiscordLevelingSystem.get_data_for(member: Member) -> MemberDataawait DiscordLevelingSystem.each_member_data(guild: Guild, sort_by=None, limit=None) -> List[MemberData]Attributesid_number(int) The members IDname(str) The members namelevel(int) The members levelxp(int) The members xptotal_xp(int) The members total xprank(Optional[int]) The members rankmention(str) The discord member mention stringMethodsMemberData.to_dict() -> dictEXAMPLElvl=DiscordLevelingSystem(...)@bot.command()asyncdefrank(ctx):data=awaitlvl.get_data_for(ctx.author)awaitctx.send(f'You are level{data.level}and your rank is{data.rank}')@bot.command()asyncdefleaderboard(ctx):data=awaitlvl.each_member_data(ctx.guild,sort_by='rank')# show the leaderboard whichever way you'd likeEventsYou can set an event to be called when a member levels up. Using the event is considered as an enhancedLevelUpAnnouncementbecause it provides more capabilities rather than simply sending a message with only text/an embed. Theon_dls_level_upevent takes three parameters:member(discord.Member) The member that leveled upmessage(discord.Message) The message that triggered the level updata(MemberData) The database information for that memberbot=commands.Bot(...)lvl=DiscordLevelingSystem(...,bot=bot)# your bot instance variable is needed@bot.eventasyncdefon_dls_level_up(member:discord.Member,message:discord.Message,data:MemberData):# You can do a lot more here compared to LevelUpAnnouncement# - create a level up image and send it with discord.File# - call additional functions that you may need# - access to all attributes/methods that are available within discord.Member and discord.MessageNOTE:LevelUpAnnouncementandon_dls_level_upare not the same. Level up messages are sent by default by the library. If you'd like to only useon_dls_level_up, you need to disable level up announcements (lvl.announce_level_up = False)Full ExampleWith all classes and core methods introduced, here is a basic implementation of this library.fromdiscord.extimportcommandsfromdiscordLevelingSystemimportDiscordLevelingSystem,RoleAward,LevelUpAnnouncementbot=commands.Bot(...)main_guild_id=850809412011950121my_awards={main_guild_id:[RoleAward(role_id=831672678586777601,level_requirement=1,role_name='Rookie'),RoleAward(role_id=831672730583171073,level_requirement=2,role_name='Associate'),RoleAward(role_id=831672814419050526,level_requirement=3,role_name='Legend')]}announcement=LevelUpAnnouncement(f'{LevelUpAnnouncement.Member.mention}just leveled up to level{LevelUpAnnouncement.LEVEL}😎')# DiscordLevelingSystem.create_database_file(r'C:\Users\Defxult\Documents') database file already createdlvl=DiscordLevelingSystem(awards=my_awards,level_up_announcement=announcement)lvl.connect_to_database_file(r'C:\Users\Defxult\Documents\DiscordLevelingSystem.db')@bot.eventasyncdefon_message(message):awaitlvl.award_xp(amount=15,message=message)bot.run(...)All methods for DiscordLevelingSystemClick to show all methodsawaitadd_record(guild_id, member_id, member_name, level) - Manually add a record to the database. If the record already exists (theguild_idandmember_idwas found), only the level will be updated. If there were no records that matched those values, all provided information will be addedParametersguild_id(int) The guild ID to registermember_id(int) The member ID to registermember_name(str) The member name to registerlevel(int) The member level to register. Must be from 0-100RaisesDiscordLevelingSystemError- The value given from a parameter was not of the correct type or "level" was not 0-100awaitadd_xp(member, amount) - Give XP to a member. This also changes their level so it matches the associated XPParametersmember(discord.Member) The member to give XP toamount(int) Amount of XP to give to the memberRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileDiscordLevelingSystemError- Parameter "amount" was less than or equal to zero. The minimum value is 1awaitaward_xp(*, amount = [15, 25], message, refresh_name = True, **kwargs) - Give XP to the member that sent a messageParametersamount(Union[int, Sequence[int]])message(discord.Message) A message objectrefresh_name(bool) Everytime the member sends a message, check if their name still matches the name in the database. If it doesn't match, update the database to match their current name. It is suggested to leave this asTrueso the database can always have the most up-to-date recordKwargsbonus(DiscordLevelingSystem.Bonus) Set the bonus values. Read theDiscordLevelingSystem.Bonusdoc string for more details (defaults toNone)RaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database filebackup_database_file(path, with_timestamp = False) - Create a copy of the database file to the specified path. If a copy of the backup file is already in the specified path it will be overwrittenParameterspath(str) The path to copy the database file towith_timestamp(bool) Creates a unique file name that has the date and time of when the backup file was created. This is useful when you want multiple backup filesRaisesDiscordLevelingSystemError- Path doesn't exist or points to another fileNotConnected- Attempted to use a method that requires a connection to a database fileawaitchange_cooldown(rate, per) - Update the cooldown rateParametersrate(int) The amount of messages each member can send before the cooldown triggersper(float) The amount of seconds each member has to wait before gaining more XP, aka the cooldownRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileDiscordLevelingSystemError- The rate or per value was not greater than zeroawaitclean_database(guild) - Removes the data for members that are no longer in the guild, thus reducing the database file size. It is recommended to have this method in a background loop in order to keep the database file free of records that are no longer in useParametersguild(discord.Guild) The guild records to cleanReturns(Optional[int]) The amount of records that were removed from the databaseRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileconnect_to_database_file(path) - Connect to the existing database file in the specified pathParameterspath(str) The location of the database fileRaisesConnectionFailure- Attempted to connect to the database file when the event loop is already runningDatabaseFileNotFound- The database file was not foundstatic methodcreate_database_file(path = None) - Create the database file and implement the SQL data for the databaseParameterspath(Optional[str]) The location to create the database file. IfNone, the file is created in the current working directoryRaisesConnectionFailure- Attempted to create the database file when the event loop is already runningDiscordLevelingSystemError- The path does not exist or the path points to a file instead of a directoryawaiteach_member_data(guild, sort_by = None, limit = None) - Return each member in the database as aMemberDataobject for easy access to their XP, level, etc. You can sort the data withsort_bywith the below valuesParametersguild(discord.Guild) A guild objectsort_by(Optional[str]) Return each member sorted by: "name", "level", "xp", "rank". IfNone, it will return in the order they were added to the databaselimit(Optional[int]) Restrict the amount of records returned to the specified amountReturnsList[MemberData]RaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileDiscordLevelingSystemError- The value ofsort_bywas not recognized orguildwas not of typediscord.Guildawaitexport_as_json(path, guild) - Export a json file that represents the database to the path specifiedParameterspath(str) Path to copy the json file toguild(discord.Guild) The guild for which the data should be extracted from. IfNone, all guild information will be extracted from the databaseRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileDiscordLevelingSystemError- The path does not exist or does not point to a directoryget_awards(guild = None) - Get allRoleAward's or only theRoleAward's assigned to the specified guildParametersguild(Optional[Union[discord.Guild, int]]) A guild object or a guild IDReturns(Union[Dict[int, List[RoleAward]], List[RoleAward]]) IfguildisNone, this return the awardsdictthat was set in constructor. Ifguildis specified, it returns a List[RoleAward] that matches the specified guild ID. Can also returnNoneif awards were never set or if the awards for the specified guild was not foundawaitget_data_for(member) - Get theMemberDataobject that represents the specified memberParametersmember(discord.Member) The member to get the data forReturns(MemberData) Can beNoneif the member isn't in the databaseRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileawaitget_level_for(member) - Get the level for the specified memberParametersmember(discord.Member) Member to get the level forReturns(int) Can beNoneif the member isn't in the databaseRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileawaitget_rank_for(member) - Get the rank for the specified memberParametersmember(discord.Member) Member to get the rank forReturns(int) Can beNoneif the member isn't ranked yetRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileawaitget_record_count(guild = None) - Get the amount of members that are registered in the database. Ifguildis set toNone, ALL members in the database will be countedParametersguild(Optional[discord.Guild]) The guild for which to count the amount of recordsReturns(int)RaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileawaitget_total_xp_for(member) - Get the total XP for the specified memberParametersmember(discord.Member) Member to get the total XP forReturns(int) Can beNoneif the member isn't in the databaseRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileawaitget_xp_for(member) - Get the XP for the specified memberParametersmember(discord.Member) Member to get the XP forReturns(int) Can beNoneif the member isn't in the databaseRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database filestatic methodget_xp_for_level(level) - Returns the total amount of XP needed for the specified level. Levels go from 0-100Parameterslevel(int) The level XP information to retrieveReturns(int)RaisesDiscordLevelingSystemError- The level specified does not existawaitinsert(bot, guild_id, users, using, overwrite = False, show_results = True) - Insert the records from your own leveling system into the library. A lot of leveling system tutorials out there use json files to store information. Although it might work, it is insufficient because json files are not made to act as a database. Using an actual database file has many benefits over a json fileParametersbot(Union[discord.ext.commands.Bot, discord.ext.commands.AutoShardedBot]) Your bot instance variableguild_id(int) ID of the guild that you used your leveling system withusers(Dict[int, int]) This is the information that will be added to the database. The keys are user ID's, and the values are the users total XP or level. Note: This library only uses levels 0-100 and XP 0-1899250. If any number in this dict are over the levels/XP threshold, it is implicitly set back to this libraries maximum valueusing(str) What structure your leveling system used. Options: "xp" or "levels". Some leveling systems give users only XP and they are ranked up based on that XP value. Others use a combination of levels and XP. If all the values in theusersdict are based on XP, set this to "xp". If they are based on a users level, set this to "levels"overwrite(bool) If a user you've specified in theusersdict already has a record in the database, overwrite their current record with the one your insertingshow_results(bool) Print the results for how many of theuserswere successfully added to the database file. If any are unsuccessful, their ID along with the value you provided will also be shownRaisesDiscordLevelingSystemError- The value given from a parameter was not of the correct type. Theusersdict was empty. Or your bot is not in the guild associated withguild_idawaitis_in_database(member, guild = None) - A quick check to see if a member is in the database. This is not guild specific although it can be ifguildis specifiedParametersmember(Union[discord.Member, int]) The member to check for. Can be the member object or that members IDguild(Optional[discord.Guild]) The guild to check if the member is registered inReturns(bool)RaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileDiscordLevelingSystemError- Parametermemberwas not of typediscord.Memberorintstatic methodlevels_and_xp( ) -  Get the rawdictrepresentation for the amount of levels/XP in the system. The keys in thedictreturned is each level, and the values are the amount of XP needed to be awarded that levelReturns(Dict[str, int])awaitnext_level(member) - Get the next level for the specified memberParametersmember(discord.Member) Member to get the next level forReturns(int) If the member is currently max level (100), it will return 100. This can also returnNoneif the member is not in the databaseRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileawaitnext_level_up(member) - Get the amount of XP needed for the specified member to level upParametersmember(discord.Member) Member to get the amount of XP needed for a level upReturns(int) Returns 0 if the member is currently at max level. Can returnNoneif the member is not in the database.RaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileawaitraw_database_contents(guild = None) - Returns everything in the database. Can specify which guild information will be extractedParametersguild(Optional[discord.Guild]) The guild to extract the raw database contents from. IfNone, information about all guilds will be extractedReturnsList[Tuple[int, int, str, int, int, int]]The tuples inside the list represents each row of the database:Index 0 is the guild IDIndex 1 is their IDIndex 2 is their nameIndex 3 is their levelIndex 4 is their XPIndex 5 is their total xpCan be an empty list if nothing is in the databaseRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileawaitrefresh_names(guild) - Update names inside the database. This does not add anything new. It simply verifies if the name in the database matches their current name, and if they don't match, update the database nameParametersguild(discord.Guild) A guild objectReturns(Optional[int])The amount of records in the database that were updatedRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileawaitremove_from_database(member, guild = None) - Remove a member from the database. This is not guild specific although it can be ifguildis specifiedParametersmember(Union[discord.Member, int]) The member to remove. Can be the member object or that members IDguild(Optional[discord.Guild]) If this parameter is given, it will remove the record of the specified member only from the specified guild record. IfNone, it will remove all records no matter the guildReturns(Optional[bool]) ReturnsTrueif the member was successfully removed from the database.Falseif the member was not in the database so there was nothing to removeRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedDiscordLevelingSystemError- Parametermemberwas not of typediscord.MemberorintNotConnected- Attempted to use a method that requires a connection to a database fileawaitremove_xp(member, amount) - Remove XP from a member. This also changes their level so it matches the associated XPParametersmember(discord.Member) The member to remove XP fromamount(int) Amount of XP to remove from the memberRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileDiscordLevelingSystemError- Parameter "amount" was less than or equal to zero. The minimum value is 1awaitreset_everyone(guild, *, intentional = False) - Sets EVERYONES XP, total XP, and level to zero in the database. Can specify which guild to resetParametersguild(Union[discord.Guild, None]) The guild for which everyone will be reset. If this is set toNone, everyone in the entire database will be resetintentional(bool) A simple kwarg to try and ensure that this action is indeed what you want to do. Once executed, this cannot be undoneRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileFailSafe- "intentional" argument for this method was set toFalsein case you called this method by mistakeawaitreset_member(member) - Sets the members XP, total XP, and level to zeroParametersmember(discord.Member) The member to resetRaisesDatabaseFileNotFoundThe database file was not foundLeaderboardNotFoundTable "leaderboard" in the database file is missingImproperLeaderboardLeaderboard table was altered. Components changed or deletedNotConnectedAttempted to use a method that requires a connection to a database fileawaitset_level(member, level) - Sets the level for the member. This also changes their total XP so it matches the associated levelParametersmember(discord.Member) The member who's level will be setlevel(int) Level to set. Must be from 0-100RaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileDiscordLevelingSystemError- Parameter "level" was not from 0-100awaitsql_query_get(sql, parameters = None, fetch = 'ALL') - Query and return something from the database using SQL. The following columns are apart of the "leaderboard" table: guild_id, member_id, member_name, member_level, member_xp, member_total_xpParameterssql(str) SQL string used to query the databaseparameters(Optional[Tuple[Union[str ,int]]]) The parameters used for the database queryfetch(Union[str, int]) The amount of rows you would like back from the query. Options: 'ALL', 'ONE', or an integer value that is greater than zeroReturns(Union[List[tuple], tuple])Usingfetch='ALL'returnsList[tuple]Usingfetch='ONE'returnstupleUsingfetch=4returnsList[tuple]with only four valuesCan also return an empty list if the query was valid but got nothing from itRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileDiscordLevelingSystemError- Argument "fetch" was the wrong type or used an invalid valueaiosqlite.Error- Base aiosqlite error. Multiple errors can arise from this if the SQL query was invalidawaitswitch_connection(path) - Connect to a different leveling system database fileParameterspath(str) The location of the database fileRaisesDatabaseFileNotFound- The database file was not foundstatic methodtransfer(old, new, guild_id) - Transfer the database records from a database file created from v0.0.1 to a blank database file created using v0.0.2+. If you were already using a v0.0.2+ database file, there's no need to use this methodParametersold(str) The path of the v0.0.1 database filenew(str) The path of the v0.0.2+ database fileguild_id(int) ID of the guild that was originally used with this libraryRaisesConnectionFailure- The event loop is already runningDatabaseFileNotFound- "old" or "new" database file was not foundDiscordLevelingSystemError- One of the databases is missing the "leaderboard" table. A v0.0.2+ database file contains records, or there was an attempt to transfer records from a v0.0.2+ file to another v0.0.2+ fileawaitwipe_database(guild = None, *, intentional = False) - Delete EVERYTHING from the database. Ifguildis specified, only the information related to that guild will be deletedParametersguild(Optional[discord.Guild]) The guild for which all information that is related to that guild will be deleted. IfNone, everything will be deletedintentional(bool) A simple kwarg to try and ensure that this action is indeed what you want to do. Once executed, this cannot be undoneRaisesDatabaseFileNotFound- The database file was not foundLeaderboardNotFound- Table "leaderboard" in the database file is missingImproperLeaderboard- Leaderboard table was altered. Components changed or deletedNotConnected- Attempted to use a method that requires a connection to a database fileFailSafe- "intentional" argument for this method was set toFalsein case you called this method by mistakeMigrating from v0.0.1 to v0.0.2+Click to show detailsThis library was not originally designed with the use of multiple servers in mind, so all the data you might have currently (your database file was created inv0.0.1) should be from a single server. Withv0.0.2, the structure of the database file was changed to accommodate this fix. That means if you are currently using av0.0.1database file and update tov0.0.2+, a vast majority of the library will be broken. To avoid this, you need to transfer all yourv0.0.1database file records to av0.0.2+database file. This can be done using thetransfermethod.Associated static methodDiscordLevelingSystem.transfer(old: str, new: str, guild_id: int)Parametersold(str) The path of thev0.0.1database filenew(str) The path of thev0.0.2+database file (a brand new file from usingDiscordLevelingSystem.create_database_file(path: str))guild_id(int) ID of the guild that was originally used with this libraryEXAMPLEfromdiscordLevelingSystemimportDiscordLevelingSystemold=r'C:\Users\Defxult\Documents\DiscordLevelingSystem.db'new=r'C:\Users\Defxult\Desktop\DiscordLevelingSystem.db'DiscordLevelingSystem.transfer(old,new,guild_id=850809412011950121)Inserting your own leveling system informationClick to show detailsInsert the records from your leveling system into this one. A lot of leveling system tutorials out there use json files to store information. Although it might work, it is insufficient because json files are not made to act as a database. Using a database file has many benefits over a json file. If you previously watched a tutorial for your leveling system and would like to import your records over to use with this library, you can do so with the below method.Associated static methodawait DiscordLevelingSystem.insert(bot: Union[Bot, AutoShardedBot], guild_id: int, users: Dict[int, int], using: str, overwrite=False, show_results=True)Parametersbot(Union[discord.ext.commands.Bot, discord.ext.commands.AutoShardedBot]) Your bot instance variableguild_id(int) ID of the guild that you used your leveling system withusers(Dict[int, int]) This is the information that will be added to the database. The keys are user ID's, and the values are the users total XP or level. Note: This library only uses levels 0-100 and XP 0-1899250. If any number in this dict are over the levels/XP threshold, it is implicitly set back to this libraries maximum valueusing(str) What structure your leveling system used. Options: "xp" or "levels". Some leveling systems give users only XP and they are ranked up based on that XP value. Others use a combination of levels and XP. If all the values in theusersdict are based on XP, set this to "xp". If they are based on a users level, set this to "levels"overwrite(bool) If a user you've specified in theusersdict already has a record in the database, overwrite their current record with the one your insertingshow_results(bool) Print the results for how many of theuserswere successfully added to the database file. If any are unsuccessful, their ID along with the value you provided will also be shownNOTE: If the users you've provided in theusersdict is not currently in the guild (guild_id), their information will not be inserted. If you'd like, you can manually add those records with methodDiscordLevelingSystem.add_record(), but that is discouraged because it is better to discard information that is no longer in use (the user is no longer in the guild)EXAMPLE# leveling_system.json[{"5748392849348934":{"xp":373,"level":4}},{"89283659820948923":{"xp":23,"level":1}}]# bot.pyimportjsonfromdiscord.extimportcommandsfromdiscordLevelingSystemimportDiscordLevelingSystembot=commands.Bot(...)lvl=DiscordLevelingSystem(...)lvl.connect_to_database_file(...)defjson_to_dict()->dict:withopen('leveling_system.json')asfp:data=json.load(fp)formatted:Dict[int,int]=...# format the data so all keys and values are associated with the user ID and level"""In the end, the formatted dict should look like so:formatted = {5748392849348934 : 4,89283659820948923 : 1}"""returnformatted@bot.command()asyncdefinsert(ctx):awaitlvl.insert(ctx.bot,guild_id=12345678901234,users=json_to_dict(),using='levels')bot.run(...)