Thread: [Any Framework]AIO Discord Bot

Page 1 of 3 123 LastLast
Results 1 to 10 of 22
  1. #1 [Any Framework]AIO Discord Bot 
    *breaks walking*

    Cody_'s Avatar
    Join Date
    Dec 2010
    Posts
    717
    Thanks given
    198
    Thanks received
    189
    Discord
    View profile
    Rep Power
    267
    AIO Discord

    Hello all, I have been getting a few requests lately to update my old discord bot tutorial. It uses an outdated version of Discord4J, and does not work anymore. I started making a simple bot similar to the previous one using JDA, I've since gotten a little carried away.

    This is going to be a long tutorial, bare with me. I assure you most information IS needed to properly use the bot.

    Features
    In-game and Discord account linking (required for most other features, but allows for things like account recovery)
    Friends Chat and Discord channel linking (set the bot so any messages in a certain friends chat will appear in a discord channel, and vice versa)
    Dialogue System (very similar to Matrix's Dialogue system. Works through PMs)
    Games (3 games currently, more info on them below)
    Role Management System (Automatically manages Discord roles based on in-game rights or other stats, points gained from games, etc, more info below)

    Creating a Discord Application and Bot
    First we need to create the bot account and add it to your Discord.

    Follow [Only registered and activated users can see links. ] link and create a new application, giving it your desired name.

    Once finished, you will be at this screen: (take note of the client id)


    Go to the Bot section and click 'Add Bot', add your desired profile picture and also take note of the token.



    Adding to Discord

    Copy [Only registered and activated users can see links. ] link, paste it into a notepad, and edit the CLIENT_ID to the one we got earlier.

    You will be brought to a page allowing you to add the bot to your discord server. Note you must have the 'Manage Server' permission in the discord server to be able to add bots to it.

    Adding to Server
    Alrighty, now for the fun part. Adding it to our server and getting it up and running.

    Head over and grab the JAR from here: [Only registered and activated users can see links. ]
    I don't have it on maven yet, unfortunately

    Now, once added, the bot needs a few things to work.

    Spoiler for Properties JSON:

    The way the bot gets some settings, is through a 'props.json' file that must be in your root directory.
    This is a normal JSON file that must have the following key/values
    token - Token of the bot account we created earlier
    db-host - Host of the mysql server we're going to set up
    db-user - Database username
    db-pass - Database password
    prefix - desired prefix

    Example:
    Code:
    {
      "token": "token",
      "db-host": "localhost",
      "db-user": "username",
      "db-pass": "password",
      "prefix": "."
    }


    Spoiler for MySQL:

    As stated in last spoiler, we need a MySQL server to get this working. There are quite a few options available, use xampp if you're not sure. There are other tutorials on how to set it up.

    Once set up, here is a database skeleton: [Only registered and activated users can see links. ]


    Spoiler for Helper:

    In order to have this bot work on multiple frameworks, it needs to work off of a helper class that you provide it.
    This class contains a few methods the bot will need from the server.

    A helper class looks like this: (Will obviously vary but I think it's pretty easy to understand what the methods are supposed to do)
    Code:
    package com.cryo;
    
    import com.cryo.api.db.impl.GlobalConnection;
    import com.cryo.game.World;
    import com.cryo.game.content.friends.FriendsChat;
    import com.cryo.game.content.friends.FriendsChatManager;
    import com.cryo.game.entity.player.Player;
    import com.cryo.game.item.Item;
    import com.cryo.game.region.DynamicRegion;
    import com.cryo.game.region.Region;
    import com.cryo.game.region.WorldTile;
    import com.cryo.utils.AccountAction;
    import com.cryo.utils.DisplayNames;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class CryoBotHelper implements Helper {
    
        @Override
        public int getRights(String username) {
            return GlobalConnection.getRights(username);
        }
    
        @Override
        public String getDisplayName(String username) {
            return DisplayNames.getDisplayName(username);
        }
    
        @Override
        public void sendFriendsChatMessage(String owner, String username, String message) {
            FriendsChat chat = FriendsChatManager.getChat(owner);
            if(chat == null) return;
            AccountAction.LoadType type = AccountAction.loadPlayerAccount(username);
            if(type.getResult() == AccountAction.LoadResult.ONLINE)
                chat.sendMessage(type.getPlayer(), message);
            else if(type.getResult() == AccountAction.LoadResult.SUCCESS) {
                for(Player player : chat.getMembers())
                    player.getPackets().receiveFriendsChatMessage(DisplayNames.getDisplayName(username), GlobalConnection.getRights(username), chat.getSettings().getName(), message);
            }
        }
    
        @Override
        public int getPlayersOnline() {
            return World.getPlayersOnline();
        }
    
        @Override
        public int getLevel(String username, int skillId) {
            AccountAction.LoadType type = AccountAction.loadPlayerAccount(username);
            if(type.getPlayer() == null) return -1;
            return type.getPlayer().getSkillManager().getLevelForXp(skillId);
        }
    
        @Override
        public double getXp(String username, int skillId) {
            AccountAction.LoadType type = AccountAction.loadPlayerAccount(username);
            if(type.getPlayer() == null) return -1;
            return type.getPlayer().getSkillManager().getXp(skillId);
        }
    
        @Override
        public String getEquip(String username, int slot) {
            AccountAction.LoadType type = AccountAction.loadPlayerAccount(username);
            if(type.getPlayer() == null) return null;
            Item item = type.getPlayer().getEquipmentManager().getItem(slot);
            if(item == null) return null;
            return item.getName();
        }
    
        @Override
        public String[] getStatuses(String username) {
            AccountAction.LoadType type = AccountAction.loadPlayerAccount(username);
            if(type.getResult() == AccountAction.LoadResult.DOESNT_EXIST) return null;
            List<String> list = new ArrayList<>();
            Player player = type.getPlayer();
            if(player.getRights() > 0) list.add("moderator");
            if(player.getRights() > 1) list.add("admin");
            if(player.isDonator()) list.add("donator");
            if(player.isSuperDonator()) list.add("super_donator");
            if(player.isHighRoller()) list.add("high_roller");
            if(player.isOwner()) list.add("owner");
            return (String[]) list.toArray();
        }
    
        @Override
        public boolean isDynamicRegion(int x, int y, int z) {
            WorldTile tile = new WorldTile(x, y, z);
            Region region = World.getRegion(tile.getRegionId());
            if(region == null || !(region instanceof DynamicRegion)) return false;
            return true;
        }
    }


    Once all of these are complete, throw this somewhere in your server launching: (And pass in your own helper class)

    Code:
    DiscordBot.startBot(new CryoBotHelper());
    Start up your server, and if you've followed all the steps correctly, the bot should log into your discord server.

    Configuration/Features

    The first thing you want to do, is do the command '.setup' (without quotes) and follow through the dialogue. This will require you being the owner of the discord server.

    Once done, your basic configuration is all set, and the bot will now work.
    However, if you want games and such to work, there are some different things we must do.

    Spoilers for each game below will explain how to set them up.
    Before any game can be setup, you must first setup the linking of in-game and discord accounts.

    Spoiler for Account Linking:

    This bot has the ability to link accounts between discord and in-game.
    The discord part of this is all handled by the bot, the only thing you must do in-game is add a command called 'verify'

    This command must take in a 6 character string, and then call the method
    Code:
    Links.linkDiscordAccount(username, string);
    This should link their in-game and discord accounts which is used in games and linking friends chats

    As of release 11, There is now a method to begin linking accounts from in-game.

    Calling Links.beginDiscordLinkFromServer(username); will provide a random string if the accounts are not linked, or will return null if they're in-game account is already linked.
    Provide the player with this string, and a new command has been added in discord: .verify (random) that players can use to finish the link.


    Spoiler for Automatic Roles:

    As you may have already noticed by doing the .setup command, this bot can handle role management for you.

    It can handle multiple ways of giving someone a discord role:
    1. On points requirements (This should be well explained in the .setup dialogue)
    2. On in-game statuses

    In game statuses:
    This one's a little more confusing, so I'll explain it a little further. In your Helper class, you can define a list with different statuses for players based on their in-game ranks/statuses. For example, adding 'donator', 'super_donator', 'admin', 'mod', etc depending on whether they meet those requirements.

    Then, through the .setup dialogue, you can setup roles to be given to people who have certain statuses.
    So, if you setup the role to be given to people with the 'donator' status, then anyone that has 'donator' in the list you provide via your Helper class, will get said role in discord.

    You'll need to add the following code to your promote commands if you have them, or make a command to check manually. Should you promote someone in-game, or if they receive a 'status' through donating (donator, super donator, etc) you can call this method to loop through all linked discord accounts and recheck what roles they should have and give/remove applicable roles.
    Code:
    Links.recheckAllRoles()


    Spoiler for Linking Friends Chats:

    Admins can link in-game friends chats to certain channels within the discord bot.
    Any messages typed in the in-game friends chat will appear in this channel, and any messages typed in the channel by someone with a linked discord/in-game account will appear in the friends chat.

    The command for this is .link-chat (chat name) no parenthesis.

    In your server files, wherever messages for friends chats are processed, this method must be called:
    Code:
    checkFriendsChatMessage(String chatName, String displayName, String message);


    Spoiler for GuessThatItem Game:

    The first of our games is the GuessThatItem game. Exactly what it sounds like. You add a list of item pictures and their names to the bot, every now and then it creates a message with the picture, asks people the name, first to get it correct gets a few points.

    This game can be setup using the command .setup-item-guess


    Spoiler for Trivia Game:

    Second is a trivia game, also pretty self explanatory. Could be done better and will be getting updated, but works pretty good for now. Setup some multiple choice questions and the bot will ask them every so often. First one to answer correctly gets some points.

    This game can be setup using the command .setup-trivia


    Spoiler for GuessThatPlace Game:

    This one gets a little more complicated than the others.
    Screenshots from in-game are added to the bot with hints, and players must go in-game and do a command within 15x15 tiles of the area to guess.

    First create a command in your server called ::find that calls this method:
    Code:
    Links.handleInGamePlaceCommand(username, x, y, plane);
    Next do the command .setup-place-guess to setup the areas to guess from.

    Spoiler for Emojis:

    Some commands use emojis to make them look better. Whilst these aren't required, they are strongly suggested.
    TODO


    Spoiler for Custom Commands:

    In this part, we'll explain how to listen for commands used in discord. Examples can be found here: [Only registered and activated users can see links. ]

    Create a class implementing [Only registered and activated users can see links. ] and provide values for the implemented methods.

    int getPermissionsReq(String command); - give a rights requirement for each command, based off of in-game rights

    String[] getAliases(); - return an array of all commands you would like to listen for (No duplicate commands, do not include prefix, this is configured in your properties json)

    void handleCommand(Message message, String command, String[] cmd); - Pretty straight forward. 'message' is the Jda object, this is the object you will use to reply to the message, or delete the message, etc. See examples or JDA's documentation for more info. 'command' is pretty straight forward, 'cmd' is an array of all strings including parameters/arguments used.

    Note: 'command' nor 'cmd' will include the prefix you have set.

    Finally, there is a default method returning ArrayList<Command> called getExtraCommands in your Helper class that can be overwritten.
    Example:
    Code:
    @Override
                public ArrayList<Command> getExtraCommands() {
                    ArrayList<Command> list = new ArrayList<>();
                    list.add(new TestCommand());
                    return list;
                }


    Spoiler for Custom Games:

    Pretty much the same as custom commands, but instead we're going to extend [Only registered and activated users can see links. ]
    Examples can be found here: [Only registered and activated users can see links. ]

    String getName(); - Return the name of the game.

    abstract boolean startGame(); - Run when the game starts. You can return false if the game is not setup or an error occurs while starting it.

    void processGuessCommand(Message message, String command, String[] cmd); (optional) - Called when the 'guess' command is used. You can get the user's discord id through the message object, and use Links.getUsername if you would like their username. This will return null if the player does not have their in-game and discord accounts linked.

    void end(String... params); - This is a little confusing. This method is only called by the bot when a game ends from going on too long. It is called without any parameters when this happens.
    To end a game from within this class, you must use DiscordBot.getInstance().getGameManager().endGame( ); the end method is not called when you do this. Look at examples for more info.

    int getPoints(); - Returns the # of points given to the winning user. Only used within the games.

    Add them to the bot the same way you add extra commands.


    Spoiler for Custom Dialogues:

    Again, same as above. Extend [Only registered and activated users can see links. ]
    Examples can be found here: [Only registered and activated users can see links. ]


    Well, that about covers it.

    Here's a list of commands available to you: (default prefix is . and ranks are based off in-game rights)

    Code:
    .start-game (game) - Admin Only - Starts (game) immediately
    .set-points (points) - Admin Only - Manually set your discord points
    .set-total-points (points) - Admin Only - Manually set your total discord points
    .setup - Owner Only - Used to setup ranks and other core configuration for the bot
    .seup-item-guess - Admin Only - Starts the setup for GuessThatItem Game
    .setup-place-guess - Admin Only - Starts the setup for GuessThatPlace Game
    .setup-trivia - Admin Only - Starts the setup for the Trivia Game
    .finish-link (random) (name) - Admin Only - Used to manually link the in-game account (name) with whatever discord account got (random) when using .link command
    
    .get-levels (name) - Anyone - Returns the in-game stats for (name)
    .get-level (skillid) (name) - Anyone - Returns (name)'s level for skill (skillid)
    .get-equip (name) - Anyone - Returns the equipment layout for (name)
    .get-xp (name) - Anyone - Returns the skill xps for (name)
    
    .link - Anyone - Begins action of linking your in-game and discord accounts
    .unlink - Anyone - If linked, will unlink your in-game and discord accounts
    
    .link-chat (name) - Admin Only - Links discord channel with in-game friends chat (name)
    .unlink-chat - Admin Only - Unlinks discord channel with in-game friends chat
    
    .guess (guess) - Anyone - Guesses in current game, varies upon game
    
    .purge (all/#) - Moderator+ - Will purge either all or # amount of messages in discord channel
    .my-id - Moderator+ - Prints out ID of user who used command
    .channel-id - Moderator+ - Prints out ID of channel command was used in
    .guild-id - Moderator+ - Prints out ID of guild command was used in
    
    .add-news-channel - Admin Only - Sets channel command was used in to be used for in-game news
    .remove-news-channel - Admin Only - Removes channel from being used for in-game news
    .recheck-roles - Admin Only - Forces a recheck of all discord roles handled by the bot
    .list-roles - Admin Only - Lists all the roles handled by the bot and their conditions
    Alrighty. I'm done. I know it was long, but hopefully shouldn't take more than 20-30 minutes to setup, and then it's done forever. It's completely open sourced so feel free to fork and update to your desire. If there's any bugs, please open an issue on the github, it will be the best way to ensure I know of the bug.
    Reply With Quote  
     

  2. Thankful users:


  3. #2  
    Banned

    Join Date
    May 2017
    Age
    25
    Posts
    1,558
    Thanks given
    948
    Thanks received
    1,395
    Rep Power
    0
    Great job Cody!
    Reply With Quote  
     

  4. #3  
    Registered Member Shirayuki's Avatar
    Join Date
    Aug 2017
    Posts
    156
    Thanks given
    22
    Thanks received
    35
    Rep Power
    43
    Very nice tutorial, keep up the good work Cody.
    Reply With Quote  
     

  5. #4  
    Donator

    .css's Avatar
    Join Date
    Dec 2018
    Age
    26
    Posts
    291
    Thanks given
    46
    Thanks received
    93
    Discord
    View profile
    Rep Power
    114
    I have it running in its own source project, i'm looking to understand how to send basic message commands from the bot communicating to the server.
    I have it fully setup prior to seeing this tut thread, but still not getting it to work. I'll eventually add this to the actual server project but i wanna mess with some basic message commands first.

    [Only registered and activated users can see links. ] - [Only registered and activated users can see links. ]
    [Only registered and activated users can see links. ]

    Zed#3343
    Reply With Quote  
     

  6. Thankful user:


  7. #5  
    *breaks walking*

    Cody_'s Avatar
    Join Date
    Dec 2010
    Posts
    717
    Thanks given
    198
    Thanks received
    189
    Discord
    View profile
    Rep Power
    267
    Quote Originally Posted by .css View Post
    I have it running in its own source project, i'm looking to understand how to send basic message commands from the bot communicating to the server.
    I have it fully setup prior to seeing this tut thread, but still not getting it to work. I'll eventually add this to the actual server project but i wanna mess with some basic message commands first.
    Not a feature at the moment. I'll add that in when I get a chance.
    Reply With Quote  
     

  8. #6  
    You Own Me


    Join Date
    Jul 2015
    Posts
    192
    Thanks given
    68
    Thanks received
    33
    Rep Power
    181
    great work cody,

    Works fine for me

    took me like 40 min
    Reply With Quote  
     

  9. #7  
    Registered Member
    Join Date
    Dec 2019
    Posts
    5
    Thanks given
    0
    Thanks received
    1
    Rep Power
    0
    when doing .setup nothing happens, bot goes into discord server, and adds player count and everything, but cant get the setup or any .commands to work. anyone know what i could be doing wrong on it?
    Reply With Quote  
     

  10. #8  
    Registered Member
    Join Date
    May 2011
    Posts
    4
    Thanks given
    0
    Thanks received
    0
    Rep Power
    0
    Quote Originally Posted by Ejmartinez48 View Post
    when doing .setup nothing happens, bot goes into discord server, and adds player count and everything, but cant get the setup or any .commands to work. anyone know what i could be doing wrong on it?
    I'm having the same issue as you on this. Bot doesn't respond to any of the commands I've entered (maybe listener/wrong channel issue?) and I've got the player count accurate.

    Also getting this error:


    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See [Only registered and activated users can see links. ] for further details.
    SLF4J: Failed to load class "org.slf4j.impl.StaticMDCBinder".
    SLF4J: Defaulting to no-operation MDCAdapter implementation.
    SLF4J: See [Only registered and activated users can see links. ] for further details.
    Would anyone be willing to assist me on this please?
    Reply With Quote  
     

  11. #9  
    *breaks walking*

    Cody_'s Avatar
    Join Date
    Dec 2010
    Posts
    717
    Thanks given
    198
    Thanks received
    189
    Discord
    View profile
    Rep Power
    267
    Quote Originally Posted by RuinsOnline View Post
    I'm having the same issue as you on this. Bot doesn't respond to any of the commands I've entered (maybe listener/wrong channel issue?) and I've got the player count accurate.

    Also getting this error:




    Would anyone be willing to assist me on this please?
    The quote you posted is not an error and does not effect anything.
    I will look into not being able to type commands tomorrow after work, but it seems to work for me and others.
    Reply With Quote  
     

  12. #10  
    Registered Member
    Join Date
    May 2011
    Posts
    4
    Thanks given
    0
    Thanks received
    0
    Rep Power
    0
    Quote Originally Posted by Cody_ View Post
    The quote you posted is not an error and does not effect anything.
    I will look into not being able to type commands tomorrow after work, but it seems to work for me and others.
    Thanks for the response, I've just disregarded it. I can have the bot message from the server ingame, to the discord. I cannot get discord text to send to the server. Any recommendations at this point?
    Reply With Quote  
     

Page 1 of 3 123 LastLast

Thread Information
Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)


User Tag List

Similar Threads

  1. [718] [Any Revision]AIO Discord Bot
    By Cody_ in forum Projects
    Replies: 7
    Last Post: 06-08-2019, 07:07 AM
  2. [317] Is there any discord bot for Runescape 4 free
    By alexvdburg1 in forum Help
    Replies: 1
    Last Post: 10-12-2018, 07:02 AM
  3. Custom discord bots [previous work]
    By Phoenix in forum Selling
    Replies: 8
    Last Post: 06-07-2017, 07:05 PM
  4. Add a Discord Bot to your server!
    By Cody_ in forum Tutorials
    Replies: 5
    Last Post: 01-21-2017, 12:50 AM
  5. NPC Definitions [Any framework]
    By relex lawl in forum Snippets
    Replies: 12
    Last Post: 09-08-2012, 10:22 AM
Posting Permissions
  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •