Как сделать систему уровней в дискорде
Перейти к содержимому

Как сделать систему уровней в дискорде

  • автор:

Name already in use

Work fast with our official CLI. Learn more about the CLI.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

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.

You can install the latest PyPI version of the library by doing:

$ pip install discordLevelingSystem

Or the development version:

$ pip install git+https://github.com/Defxult/discordLevelingSystem

Intents are required for proper functionality

class DiscordLevelingSystem(rate=1, per=60.0, awards=None, **kwargs)

Parameters of the DiscordLevelingSystem constructor

  • rate ( int ) The amount of messages each member can send before the cooldown triggers
  • per ( float ) The amount of seconds each member has to wait before gaining more XP, aka the cooldown
  • awards ( Optional[Dict[int, List[RoleAward]]] ) The role given to a member when they reach a RoleAward level requirement

Kwargs of the DiscordLevelingSystem constructor

Name Type Default Value Info
no_xp_roles Sequence[int] None A sequence of role ID’s. Any member with any of those roles will not gain XP when sending messages
no_xp_channels Sequence[int] None A sequence of text channel ID’s. Any member sending messages in any of those text channels will not gain XP
announce_level_up bool True If True , level up messages will be sent when a member levels up
stack_awards bool True If this is True , when the member levels up the assigned role award will be applied. If False , the previous role award will be removed and the level up assigned role will also be applied
level_up_announcement Union[LevelUpAnnouncement, Sequence[LevelUpAnnouncement]] LevelUpAnnouncement() The message that is sent when someone levels up. If this is a sequence of LevelUpAnnouncement , one is selected at random
bot Union[AutoShardedBot, Bot] None Your bot instance variable. Used only if you’d like to use the on_dls_level_up event
  • no_xp_roles
  • no_xp_channels
  • announce_level_up
  • stack_awards
  • level_up_announcement
  • bot
  • rate ( int ) Read only property from the constructor
  • per ( float ) Read only property from the constructor
  • database_file_path ( str ) Read only property
  • active ( bool ) Enable/disable the leveling system. If False , nobody can gain XP when sending messages unless this is set back to True

NOTE: All attributes can be set during initialization

When setting up the leveling system, a database file needs to be created in order for the library to function.

  • Associated static method
    • DiscordLevelingSystem.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:

    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 Database

    • Associated method
      • DiscordLevelingSystem.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 running

      class 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. RoleAward is how that is accomplished.

      Parameters of the RoleAward constructor

      • role_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.
      • role_id
      • level_requirement
      • role_name
      • mention ( str ) The discord role mention string

      When 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 the awards parameter to None . When setting awards , it accepts a dict where the keys are guild IDs and the values are a list of RoleAward

      class 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’s Messageable.send such as allowed_mentions , tts , and delete_after to give you more control over the sent message.

      Parameters of the LevelUpAnnouncement constructor

      message ( 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. If None , 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 to discord.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.

      The LevelUpAnnouncement class provides a set of markdown attributes for you to use so you can access certain information in a level up message.

      • LevelUpAnnouncement.TOTAL_XP The members current total XP amount
      • LevelUpAnnouncement.LEVEL The members current level
      • LevelUpAnnouncement.RANK The members current rank

      The below markdown attributes takes the information from a discord.Member object so you can access member information in the level up message.

      • LevelUpAnnouncement.Member.avatar_url
      • LevelUpAnnouncement.Member.banner_url
      • LevelUpAnnouncement.Member.created_at
      • LevelUpAnnouncement.Member.default_avatar_url
      • LevelUpAnnouncement.Member.discriminator
      • LevelUpAnnouncement.Member.display_avatar_url
      • LevelUpAnnouncement.Member.display_name
      • LevelUpAnnouncement.Member.id
      • LevelUpAnnouncement.Member.joined_at
      • LevelUpAnnouncement.Member.mention
      • LevelUpAnnouncement.Member.name
      • LevelUpAnnouncement.Member.nick
      • LevelUpAnnouncement.Member.Guild.icon_url
      • LevelUpAnnouncement.Member.Guild.id
      • LevelUpAnnouncement.Member.Guild.name

      When it comes to level_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.

      Method award_xp is how members gain XP. This method is placed inside the on_message event of your bot. Members will gain XP if they send a message and if they’re not on cooldown. Spamming messages will not give them XP.

      NOTE: Members cannot gain XP in DM’s

      • Associated methods
        • await 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_xp

        • amount ( 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. If amount is 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 object
        • refresh_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 as True so the database can always have the most up-to-date record.

        Kwargs for award_xp

        • bonus ( 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 constructor
            • role_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 bonus
            • bonus_amount ( int ) Amount of extra XP to be awarded
            • multiply ( bool ) If set to True , 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. If False , 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.

            Accessing 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 the MemberData class. A class which returns information about a specific member in the database.

            • Associated methods
              • await DiscordLevelingSystem.get_data_for(member: Member) -> MemberData
              • await DiscordLevelingSystem.each_member_data(guild: Guild, sort_by=None, limit=None) -> List[MemberData]
              • id_number ( int ) The members ID
              • name ( str ) The members name
              • level ( int ) The members level
              • xp ( int ) The members xp
              • total_xp ( int ) The members total xp
              • rank ( Optional[int] ) The members rank
              • mention ( str ) The discord member mention string
              • MemberData.to_dict() -> dict

              You can set an event to be called when a member levels up. Using the event is considered as an enhanced LevelUpAnnouncement because it provides more capabilities rather than simply sending a message with only text/an embed. The on_dls_level_up event takes three parameters:

              • member ( discord.Member ) The member that leveled up
              • message ( discord.Message ) The message that triggered the level up
              • data ( MemberData ) The database information for that member

              NOTE: LevelUpAnnouncement and on_dls_level_up are not the same. Level up messages are sent by default by the library. If you’d like to only use on_dls_level_up , you need to disable level up announcements ( lvl.announce_level_up = False )

              With all classes and core methods introduced, here is a basic implementation of this library.

              All methods for DiscordLevelingSystem

              await add_record( guild_id, member_id, member_name, level ) — Manually add a record to the database. If the record already exists (the guild_id and member_id was found), only the level will be updated. If there were no records that matched those values, all provided information will be added

              • Parameters
                • guild_id ( int ) The guild ID to register
                • member_id ( int ) The member ID to register
                • member_name ( str ) The member name to register
                • level ( int ) The member level to register. Must be from 0-100
                • DiscordLevelingSystemError — The value given from a parameter was not of the correct type or «level» was not 0-100

                await add_xp( member, amount ) — Give XP to a member. This also changes their level so it matches the associated XP

                • Parameters
                  • member ( discord.Member ) The member to give XP to
                  • amount ( int ) Amount of XP to give to the member
                  • DatabaseFileNotFound — The database file was not found
                  • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                  • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                  • NotConnected — Attempted to use a method that requires a connection to a database file
                  • DiscordLevelingSystemError — Parameter «amount» was less than or equal to zero. The minimum value is 1

                  await award_xp( *, amount = [15, 25], message, refresh_name = True, **kwargs ) — Give XP to the member that sent a message

                  • Parameters
                    • amount ( Union[int, Sequence[int]] )
                    • message ( discord.Message ) A message object
                    • refresh_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 as True so the database can always have the most up-to-date record
                    • bonus ( DiscordLevelingSystem.Bonus ) Set the bonus values. Read the DiscordLevelingSystem.Bonus doc string for more details (defaults to None )
                    • DatabaseFileNotFound — The database file was not found
                    • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                    • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                    • NotConnected — Attempted to use a method that requires a connection to a database file

                    backup_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 overwritten

                    • Parameters
                      • path ( str ) The path to copy the database file to
                      • with_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 files
                      • DiscordLevelingSystemError — Path doesn’t exist or points to another file
                      • NotConnected — Attempted to use a method that requires a connection to a database file

                      await change_cooldown( rate, per ) — Update the cooldown rate

                      • Parameters
                        • rate ( int ) The amount of messages each member can send before the cooldown triggers
                        • per ( float ) The amount of seconds each member has to wait before gaining more XP, aka the cooldown
                        • DatabaseFileNotFound — The database file was not found
                        • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                        • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                        • NotConnected — Attempted to use a method that requires a connection to a database file
                        • DiscordLevelingSystemError — The rate or per value was not greater than zero

                        await clean_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 use

                        • Parameters
                          • guild ( discord.Guild ) The guild records to clean
                          • ( Optional[int] ) The amount of records that were removed from the database
                          • DatabaseFileNotFound — The database file was not found
                          • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                          • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                          • NotConnected — Attempted to use a method that requires a connection to a database file

                          connect_to_database_file( path ) — Connect to the existing database file in the specified path

                          • Parameters
                            • path ( str ) The location of the database file
                            • ConnectionFailure — Attempted to connect to the database file when the event loop is already running
                            • DatabaseFileNotFound — The database file was not found

                            static method create_database_file( path = None ) — Create the database file and implement the SQL data for the database

                            • Parameters
                              • path ( Optional[str] ) The location to create the database file. If None , the file is created in the current working directory
                              • ConnectionFailure — Attempted to create the database file when the event loop is already running
                              • DiscordLevelingSystemError — The path does not exist or the path points to a file instead of a directory

                              await each_member_data( guild, sort_by = None, limit = None ) — Return each member in the database as a MemberData object for easy access to their XP, level, etc. You can sort the data with sort_by with the below values

                              • Parameters
                                • guild ( discord.Guild ) A guild object
                                • sort_by ( Optional[str] ) Return each member sorted by: «name», «level», «xp», «rank». If None , it will return in the order they were added to the database
                                • limit ( Optional[int] ) Restrict the amount of records returned to the specified amount
                                • List[MemberData]
                                • DatabaseFileNotFound — The database file was not found
                                • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                • NotConnected — Attempted to use a method that requires a connection to a database file
                                • DiscordLevelingSystemError — The value of sort_by was not recognized or guild was not of type discord.Guild

                                await export_as_json( path, guild ) — Export a json file that represents the database to the path specified

                                • Parameters
                                  • path ( str ) Path to copy the json file to
                                  • guild ( discord.Guild ) The guild for which the data should be extracted from. If None , all guild information will be extracted from the database
                                  • DatabaseFileNotFound — The database file was not found
                                  • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                  • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                  • NotConnected — Attempted to use a method that requires a connection to a database file
                                  • DiscordLevelingSystemError — The path does not exist or does not point to a directory

                                  get_awards( guild = None ) — Get all RoleAward ‘s or only the RoleAward ‘s assigned to the specified guild

                                  • Parameters
                                    • guild ( Optional[Union[discord.Guild, int]] ) A guild object or a guild ID
                                    • ( Union[Dict[int, List[RoleAward]], List[RoleAward]] ) If guild is None , this return the awards dict that was set in constructor. If guild is specified, it returns a List[ RoleAward ] that matches the specified guild ID. Can also return None if awards were never set or if the awards for the specified guild was not found

                                    await get_data_for( member ) — Get the MemberData object that represents the specified member

                                    • Parameters
                                      • member ( discord.Member ) The member to get the data for
                                      • ( MemberData ) Can be None if the member isn’t in the database
                                      • DatabaseFileNotFound — The database file was not found
                                      • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                      • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                      • NotConnected — Attempted to use a method that requires a connection to a database file

                                      await get_level_for( member ) — Get the level for the specified member

                                      • Parameters
                                        • member ( discord.Member ) Member to get the level for
                                        • ( int ) Can be None if the member isn’t in the database
                                        • DatabaseFileNotFound — The database file was not found
                                        • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                        • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                        • NotConnected — Attempted to use a method that requires a connection to a database file

                                        await get_rank_for( member ) — Get the rank for the specified member

                                        • Parameters
                                          • member ( discord.Member ) Member to get the rank for
                                          • ( int ) Can be None if the member isn’t ranked yet
                                          • DatabaseFileNotFound — The database file was not found
                                          • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                          • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                          • NotConnected — Attempted to use a method that requires a connection to a database file

                                          await get_record_count( guild = None ) — Get the amount of members that are registered in the database. If guild is set to None , ALL members in the database will be counted

                                          • Parameters
                                            • guild ( Optional[discord.Guild] ) The guild for which to count the amount of records
                                            • ( int )
                                            • DatabaseFileNotFound — The database file was not found
                                            • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                            • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                            • NotConnected — Attempted to use a method that requires a connection to a database file

                                            await get_total_xp_for( member ) — Get the total XP for the specified member

                                            • Parameters
                                              • member ( discord.Member ) Member to get the total XP for
                                              • ( int ) Can be None if the member isn’t in the database
                                              • DatabaseFileNotFound — The database file was not found
                                              • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                              • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                              • NotConnected — Attempted to use a method that requires a connection to a database file

                                              await get_xp_for( member ) — Get the XP for the specified member

                                              • Parameters
                                                • member ( discord.Member ) Member to get the XP for
                                                • ( int ) Can be None if the member isn’t in the database
                                                • DatabaseFileNotFound — The database file was not found
                                                • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                • NotConnected — Attempted to use a method that requires a connection to a database file

                                                static method get_xp_for_level( level ) — Returns the total amount of XP needed for the specified level. Levels go from 0-100

                                                • Parameters
                                                  • level ( int ) The level XP information to retrieve
                                                  • ( int )
                                                  • DiscordLevelingSystemError — The level specified does not exist

                                                  await insert( 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 file

                                                  • Parameters
                                                    • bot ( Union[discord.ext.commands.Bot, discord.ext.commands.AutoShardedBot] ) Your bot instance variable
                                                    • guild_id ( int ) ID of the guild that you used your leveling system with
                                                    • users ( 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 value
                                                    • using ( 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 the users dict 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 the users dict already has a record in the database, overwrite their current record with the one your inserting
                                                    • show_results ( bool ) Print the results for how many of the users were successfully added to the database file. If any are unsuccessful, their ID along with the value you provided will also be shown
                                                    • DiscordLevelingSystemError — The value given from a parameter was not of the correct type. The users dict was empty. Or your bot is not in the guild associated with guild_id

                                                    await is_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 if guild is specified

                                                    • Parameters
                                                      • member ( Union[discord.Member, int] ) The member to check for. Can be the member object or that members ID
                                                      • guild ( Optional[discord.Guild] ) The guild to check if the member is registered in
                                                      • ( bool )
                                                      • DatabaseFileNotFound — The database file was not found
                                                      • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                      • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                      • NotConnected — Attempted to use a method that requires a connection to a database file
                                                      • DiscordLevelingSystemError — Parameter member was not of type discord.Member or int

                                                      static method levels_and_xp( ) — Get the raw dict representation for the amount of levels/XP in the system. The keys in the dict returned is each level, and the values are the amount of XP needed to be awarded that level

                                                      • Returns
                                                        • ( Dict[str, int] )

                                                        await next_level( member ) — Get the next level for the specified member

                                                        • Parameters
                                                          • member ( discord.Member ) Member to get the next level for
                                                          • ( int ) If the member is currently max level (100), it will return 100. This can also return None if the member is not in the database
                                                          • DatabaseFileNotFound — The database file was not found
                                                          • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                          • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                          • NotConnected — Attempted to use a method that requires a connection to a database file

                                                          await next_level_up( member ) — Get the amount of XP needed for the specified member to level up

                                                          • Parameters
                                                            • member ( discord.Member ) Member to get the amount of XP needed for a level up
                                                            • ( int ) Returns 0 if the member is currently at max level. Can return None if the member is not in the database.
                                                            • DatabaseFileNotFound — The database file was not found
                                                            • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                            • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                            • NotConnected — Attempted to use a method that requires a connection to a database file

                                                            await raw_database_contents( guild = None ) — Returns everything in the database. Can specify which guild information will be extracted

                                                            • Parameters
                                                              • guild ( Optional[discord.Guild] ) The guild to extract the raw database contents from. If None , information about all guilds will be extracted
                                                              • List[Tuple[int, int, str, int, int, int]] The tuples inside the list represents each row of the database:
                                                                • Index 0 is the guild ID
                                                                • Index 1 is their ID
                                                                • Index 2 is their name
                                                                • Index 3 is their level
                                                                • Index 4 is their XP
                                                                • Index 5 is their total xp
                                                                • Can be an empty list if nothing is in the database
                                                                • DatabaseFileNotFound — The database file was not found
                                                                • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                                • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                                • NotConnected — Attempted to use a method that requires a connection to a database file

                                                                await refresh_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 name

                                                                • Parameters
                                                                  • guild ( discord.Guild ) A guild object
                                                                  • (Optional[int]) The amount of records in the database that were updated
                                                                  • DatabaseFileNotFound — The database file was not found
                                                                  • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                                  • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                                  • NotConnected — Attempted to use a method that requires a connection to a database file

                                                                  await remove_from_database( member, guild = None ) — Remove a member from the database. This is not guild specific although it can be if guild is specified

                                                                  • Parameters
                                                                    • member ( Union[discord.Member, int] ) The member to remove. Can be the member object or that members ID
                                                                    • guild ( Optional[discord.Guild] ) If this parameter is given, it will remove the record of the specified member only from the specified guild record. If None , it will remove all records no matter the guild
                                                                    • ( Optional[bool] ) Returns True if the member was successfully removed from the database. False if the member was not in the database so there was nothing to remove
                                                                    • DatabaseFileNotFound — The database file was not found
                                                                    • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                                    • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                                    • DiscordLevelingSystemError — Parameter member was not of type discord.Member or int
                                                                    • NotConnected — Attempted to use a method that requires a connection to a database file

                                                                    await remove_xp( member, amount ) — Remove XP from a member. This also changes their level so it matches the associated XP

                                                                    • Parameters
                                                                      • member ( discord.Member ) The member to remove XP from
                                                                      • amount ( int ) Amount of XP to remove from the member
                                                                      • DatabaseFileNotFound — The database file was not found
                                                                      • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                                      • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                                      • NotConnected — Attempted to use a method that requires a connection to a database file
                                                                      • DiscordLevelingSystemError — Parameter «amount» was less than or equal to zero. The minimum value is 1

                                                                      await reset_everyone( guild, *, intentional = False ) — Sets EVERYONES XP, total XP, and level to zero in the database. Can specify which guild to reset

                                                                      • Parameters
                                                                        • guild ( Union[discord.Guild, None] ) The guild for which everyone will be reset. If this is set to None , everyone in the entire database will be reset
                                                                        • intentional ( bool ) A simple kwarg to try and ensure that this action is indeed what you want to do. Once executed, this cannot be undone
                                                                        • DatabaseFileNotFound — The database file was not found
                                                                        • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                                        • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                                        • NotConnected — Attempted to use a method that requires a connection to a database file
                                                                        • FailSafe — «intentional» argument for this method was set to False in case you called this method by mistake

                                                                        await reset_member( member ) — Sets the members XP, total XP, and level to zero

                                                                        • Parameters
                                                                          • member ( discord.Member ) The member to reset
                                                                          • DatabaseFileNotFound The database file was not found
                                                                          • LeaderboardNotFound Table «leaderboard» in the database file is missing
                                                                          • ImproperLeaderboard Leaderboard table was altered. Components changed or deleted
                                                                          • NotConnected Attempted to use a method that requires a connection to a database file

                                                                          await set_level( member, level ) — Sets the level for the member. This also changes their total XP so it matches the associated level

                                                                          • Parameters
                                                                            • member ( discord.Member ) The member who’s level will be set
                                                                            • level ( int ) Level to set. Must be from 0-100
                                                                            • DatabaseFileNotFound — The database file was not found
                                                                            • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                                            • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                                            • NotConnected — Attempted to use a method that requires a connection to a database file
                                                                            • DiscordLevelingSystemError — Parameter «level» was not from 0-100

                                                                            await sql_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_xp

                                                                            • Parameters
                                                                              • sql ( str ) SQL string used to query the database
                                                                              • parameters ( Optional[Tuple[Union[str ,int]]] ) The parameters used for the database query
                                                                              • fetch ( 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 zero
                                                                              • ( Union[List[tuple], tuple] )
                                                                                • Using fetch=’ALL’ returns List[tuple]
                                                                                • Using fetch=’ONE’ returns tuple
                                                                                • Using fetch=4 returns List[tuple] with only four values
                                                                                • Can also return an empty list if the query was valid but got nothing from it
                                                                                • DatabaseFileNotFound — The database file was not found
                                                                                • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                                                • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                                                • NotConnected — Attempted to use a method that requires a connection to a database file
                                                                                • DiscordLevelingSystemError — Argument «fetch» was the wrong type or used an invalid value
                                                                                • aiosqlite.Error — Base aiosqlite error. Multiple errors can arise from this if the SQL query was invalid

                                                                                await switch_connection( path ) — Connect to a different leveling system database file

                                                                                • Parameters
                                                                                  • path ( str ) The location of the database file
                                                                                  • DatabaseFileNotFound — The database file was not found

                                                                                  static method transfer( 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 method

                                                                                  • Parameters
                                                                                    • old ( str ) The path of the v0.0.1 database file
                                                                                    • new ( str ) The path of the v0.0.2+ database file
                                                                                    • guild_id ( int ) ID of the guild that was originally used with this library
                                                                                    • ConnectionFailure — The event loop is already running
                                                                                    • DatabaseFileNotFound — «old» or «new» database file was not found
                                                                                    • DiscordLevelingSystemError — 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+ file

                                                                                    await wipe_database( guild = None, *, intentional = False ) — Delete EVERYTHING from the database. If guild is specified, only the information related to that guild will be deleted

                                                                                    • Parameters
                                                                                      • guild ( Optional[discord.Guild] ) The guild for which all information that is related to that guild will be deleted. If None , everything will be deleted
                                                                                      • intentional ( bool ) A simple kwarg to try and ensure that this action is indeed what you want to do. Once executed, this cannot be undone
                                                                                      • DatabaseFileNotFound — The database file was not found
                                                                                      • LeaderboardNotFound — Table «leaderboard» in the database file is missing
                                                                                      • ImproperLeaderboard — Leaderboard table was altered. Components changed or deleted
                                                                                      • NotConnected — Attempted to use a method that requires a connection to a database file
                                                                                      • FailSafe — «intentional» argument for this method was set to False in case you called this method by mistake

                                                                                      Migrating from v0.0.1 to v0.0.2+

                                                                                      This 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 in v0.0.1 ) should be from a single server. With v0.0.2 , the structure of the database file was changed to accommodate this fix. That means if you are currently using a v0.0.1 database file and update to v0.0.2+ , a vast majority of the library will be broken. To avoid this, you need to transfer all your v0.0.1 database file records to a v0.0.2+ database file. This can be done using the transfer method.

                                                                                      • Associated static method
                                                                                        • DiscordLevelingSystem.transfer(old: str, new: str, guild_id: int)
                                                                                        • old ( str ) The path of the v0.0.1 database file
                                                                                        • new ( str ) The path of the v0.0.2+ database file (a brand new file from using DiscordLevelingSystem.create_database_file(path: str) )
                                                                                        • guild_id ( int ) ID of the guild that was originally used with this library

                                                                                        Inserting your own leveling system information

                                                                                        Insert 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 method
                                                                                          • await DiscordLevelingSystem.insert(bot: Union[Bot, AutoShardedBot], guild_id: int, users: Dict[int, int], using: str, overwrite=False, show_results=True)

                                                                                          bot ( Union[discord.ext.commands.Bot, discord.ext.commands.AutoShardedBot] ) Your bot instance variable

                                                                                          guild_id ( int ) ID of the guild that you used your leveling system with

                                                                                          users ( 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 value

                                                                                          using ( 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 the users dict 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 the users dict already has a record in the database, overwrite their current record with the one your inserting

                                                                                          show_results ( bool ) Print the results for how many of the users were successfully added to the database file. If any are unsuccessful, their ID along with the value you provided will also be shown

                                                                                          Как можно сделать систему уровней в дискорд? [закрыт]

                                                                                          Хотите улучшить этот вопрос? Добавьте больше подробностей и уточните проблему, отредактировав это сообщение.

                                                                                          Закрыт 1 год назад .

                                                                                          Каким образом я могу сделать систему уровней за актив в чата(много сообщений)?

                                                                                          ChessPro's user avatar

                                                                                          Вы можете использовать DiscordSuperUtils. Вот простой пример, в котором уровни участников хранятся в базе данных:

                                                                                          Ma3rX's user avatar

                                                                                          Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.5.12.43428

                                                                                          Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

                                                                                          Как мне создать систему уровней в discord.py или просто любую подходящую систему уровней rpg?

                                                                                          Как сделать систему прокачки в discord.py? В настоящее время я использую базу данных для хранения информации о пользователях. Однако я хочу создать бесконечную / бесконечную систему уровней. Это означает, что когда они проходят первый уровень, количество очков опыта, которые они должны получить, чтобы перейти на следующий уровень, умножается. Например:

                                                                                          Входит новый пользователь. Они начинают с уровня 1, это их текущий уровень опыта. Статистика: Уровень 1, 1/20 очков опыта

                                                                                          Как только они наберут 20 очков опыта, я хочу, чтобы их уровень был уровня 2, а чтобы перейти на третий уровень, они должны получить 40 очков опыта. Таким образом, количество контрольных точек / отметок для перехода на следующий уровень увеличивается. Текущая статистика для нового пользователя: уровень 2, 1/40 опыта. После достижения уровня 3 статистика: уровень 3, 1/80 опыта.

                                                                                          А потом я просто хочу, чтобы это был бесконечный цикл. Просто продолжайте обновлять их уровень и умножайте их отметку уровня опыта на 2.

                                                                                          Я использую базу данных mysql. У меня уже есть 2 функции, которые нужно обновить и показать их уровни. Мне просто нужно узнать, как все зациклить. Я не очень знаком с петлями.

                                                                                          Я хочу, чтобы их система уровней была основана на событиях on_message. Это означает, что за каждое сообщение они получают одно очко опыта.

                                                                                          7 лучших ботов Discord для улучшения вашего сервера

                                                                                          Есть много того, что вам может понравиться в Discord. Он бесплатен в использовании и управлении, имеет поддержку VOIP, и благодаря поддержке ботов, очень хорошо настраивается. Вот лучшие боты Discord, о которых вы должны знать.

                                                                                          7 лучших ботов Discord для улучшения вашего сервера 1

                                                                                          1. Carl Bot

                                                                                          Одна из наиболее полезных функций в Discord — это роли реакции, которые позволяют вводить команды и смайлики в Discord, позволяя вносить различные изменения на сервере.

                                                                                          Роли за реакции:
                                                                                          • Высокие ограничения (до 250 ролей).
                                                                                          • Много режимов (уникальный, верификация, наоборот, временный и другие).
                                                                                          • Можно использовать любой эмодзи (даже те, к которым у бота нет доступа).
                                                                                          • Самоуничтожающиеся сообщения.
                                                                                          • Черный и белый списки.
                                                                                          Логирование:
                                                                                          • Сообщения (удаленные и отредактированные).
                                                                                          • Приглашения на сервера.
                                                                                          • Обновления участников (изменение ролей, ников, аватаров, банов).
                                                                                          • Приходящие и уходящие участники.
                                                                                          • Обновление каналов, ролей и эмодзи.
                                                                                          • Игнорирование каналов, участников и префиксов (спамящие боты теперь не будут засорять логи).
                                                                                          • Разбиение логов на разные каналы.
                                                                                          Модерация:
                                                                                          • Лог модерации.
                                                                                          • Множество команд для модерации.
                                                                                          • Канал, чтобы модераторы могли видеть всех нарушителей.

                                                                                          7 лучших ботов Discord для улучшения вашего сервера 2

                                                                                          2. Groovy

                                                                                          Новичок на сцене музыкальных ботов Discord — Groovy — позволяет пользователям на канале в Discord ставить в очередь плейлисты песен из самых популярных музыкальных источников в интернете.

                                                                                          7 лучших ботов Discord для улучшения вашего сервера 3

                                                                                          3. MEE6

                                                                                          Есть причина, по которой MEE6 в настоящее время — один из лучших ботов Discord. Он обладает обширными возможностями и поддержкой. Вы также можете обновиться до премиум пакета подписки для еще большего количества функций.

                                                                                          Множество ботов Disord предназначены для модерации сервера, и MEE6 не вызовет разочарования. Вы можете настроить автоматические правила для защиты от таких проблем, как спам на сервере. Администраторы MEE6 также могут настроить систему «страйков» для автоматизации наказаний, если пользователи регулярно нарушают правила.

                                                                                          Бот настраиваемый, так что вы можете создавать свои собственные команды для пользователей, а также персонализированные приветственные сообщения. Если вы хотите, чтобы пользователи могли устанавливать собственные роли, вы можете настроить команды для этого.

                                                                                          Существует также система регулировки уровней для пользователей. Обычные пользователи могут «подняться» на более высокий уровень в зависимости от активности их работы. Вы можете установить награды, такие как дополнительный доступ в комнату или новые роли.

                                                                                          Если вы уже знаете, как добавлять боты Discord на ваш сервер, вам не составит труда столкнуться с проблемой, используя MEE6. Просто пригласите бота на свой сервер, чтобы начать работу.

                                                                                          7 лучших ботов Discord для улучшения вашего сервера 4

                                                                                          4. RED

                                                                                          Если вы хотите, чтобы бот действительно настраивался, то RED должен быть на вашем радаре. Учтите, что для его размещения вам понадобится собственный сервер.

                                                                                          Модульный подход RED означает, что нет двух одинаковых серверов, работающих под управлением RED, но есть и некоторые ключевые особенности. Как и MEE6, модерация является центральной функцией, с командами страйков или запретов, а также фильтрацией сообщений.

                                                                                          Здесь также есть боты и игры, воспроизведение музыки, поиск подарков, автосерверные сообщения и многое другое. Как и в MEE6, вы также можете настраивать команды ботов, настраивать имя и аватар вашего бота в соответствии с индивидуальным стилем вашего сервера.

                                                                                          Если вы не нашли нужной функции, вы можете расширить RED с помощью плагинов, которые кодируются на питоне. Вы можете искать созданные сообществом плагины на сайте RED.

                                                                                          7 лучших ботов Discord для улучшения вашего сервера 5

                                                                                          5. Dyno

                                                                                          Еще одним достойным внимания ботом является Dyno, который используется на более чем 1,6 миллионах серверов. Одним из его главных преимуществ является большая информационная веб-панель, позволяющая полностью контролировать процесс настройки.

                                                                                          Вам не нужно быть владельцем хостинга, так как все размещается на сервере Dyno, который управляется через веб-инструментарий. Инструменты модерации обширны, с настраиваемыми автоматическими триггерами.

                                                                                          Dyno облегчает создание ролей, позволяя администраторам сервера создавать новые звания (связанные с ролями сервера). Вы также можете выполнить настройку каналов сервера с помощью команд «очистки», которые массово удаляют сообщения в зависимости от пользователя, сервера или возраста.

                                                                                          Но дело не только в модерации. Вы можете настроить DJ-бота с индивидуальными плейлистами, играть в слот-игры, искать случайные факты и даже фотографии.

                                                                                          7 лучших ботов Discord для улучшения вашего сервера 6

                                                                                          6. Tatsumaki

                                                                                          Fun — это модное слово, которое лучше всего ассоциируется с ботом Tatsumaki. Он яркий, с множеством интересных функций, которыми могут воспользоваться пользователи вашего сервера, чтобы повысить активность пользователей.

                                                                                          Это бот, который охватывает все основные функции для улучшения модерации и более эффективного использования сервера, а также для того, чтобы дать пользователям веселые и удобные командные игры.

                                                                                          Функции модерации Tatsumaki не требуют настройки. Они готовы к использованию, с командами для управления пользователями (запрет, отключение звука и т.д.), обрезки сообщений, настройки приветственных сообщений и других.

                                                                                          Вы также можете осуществлять поиск на YouTube, искать факты о кошках, играть в различные игры, а также проводить опросы по всему серверу. Существует обширная система уровней с XP, доступная для пользователей в зависимости от их активности.

                                                                                          7 лучших ботов Discord для улучшения вашего сервера 7

                                                                                          7. Pancake

                                                                                          Более 300 000 серверов используют Pancake на дискордах, и по уважительной причине. Простота в использовании, хороший баланс между командами развлечений для пользователей и расширенной модерацией для администраторов. Отдельный хостинг не нужен.

                                                                                          Настраиваемая система модерации позволяет управлять всем, начиная с голосового чата и заканчивая блокировкой пользователей с системой разрешений для настройки команд модераторов с разными полномочиями.

                                                                                          Кстати, если вам нужно изменить голос в Disord, то вот тут есть подробная инструкция, как это сделать и несколько программ на выбор.

                                                                                          Существует простая в использовании система воспроизведения музыки с поддержкой нескольких источников, включая SoundCloud и YouTube. Социальные функции, такие как игры, поиск изображений и команды шуток, также помогут сделать ваш сервер немного более ярким.

                                                                                          Имея сотни доступных команд, на сервере Pancake Disord найдется что-то для каждого.

                                                                                          7 лучших ботов Discord для улучшения вашего сервера 8

                                                                                          Спасибо, что читаете! На данный момент большинство моих заметок, статей и подборок выходит в telegram канале «Левашов». Обязательно подписывайтесь, чтобы не пропустить новости мира ИТ, полезные инструкции и нужные сервисы.

                                                                                          Респект за пост! Спасибо за работу!

                                                                                          Хотите больше постов в блоге? Подборок софта и сервисов, а также обзоры на гаджеты? Сейчас, чтобы писать регулярно и радовать вас большими обзорами, мне требуется помощь. Чтобы поддерживать сайт на регулярной основе, вы можете оформить подписку на российском сервисе Boosty. Или воспользоваться ЮMoney (бывшие Яндекс Деньги) для разовой поддержки:

                                                                                          Заранее спасибо! Все собранные средства будут пущены на развитие сайта. Поддержка проекта является подарком владельцу сайта.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *