lundi 14 janvier 2019

How to get my discord bot to generate random response

This is a generic bot that i made from watching a quick tutorial video.

public class App extends ListenerAdapter
{ 
    public static void main( String[] args ) throws Exception
  {
    JDA jda = new JDABuilder(AccountType.BOT).setToken(reference.token).buildBlocking();
    jda.addEventListener(new App());


    } 
    @Override
    public void onMessageReceived(MessageReceivedEvent evt)
    {

        User objUser = evt.getAuthor();
        MessageChannel obgMsgCh = evt.getChannel();
        Message obgMsg = evt.getMessage();

        //Ping bot
        if (obgMsg.getContentRaw().equalsIgnoreCase(reference.prefix+"ping")||(obgMsg.getContentRaw().contains("angry"))) 
                {


            // Response
             obgMsgCh.sendMessage(objUser.getAsMention()+" HI").queue();
      }  


   }

}

How do i have the bot respond with Strings in an array or arrayList? eg. earlier i tried doing

String [] responses = new String[5];
responses[0] = "HELLO";
responses[1] = "I'M ANGRY";
responses[2] = "STOP DOING THAT";
responses[3] = "DO NOT";
responses[4] = "NO";
Random randNum = new Random();

obgMsgCh.sendMessage(objUser.getAsMention()+responses[(randNum.nextInt(responses.length))]).queue();

However it keeps giving me the Array index out of bounds error. Do i need a for loop??? I'm currently studying the basics of java so do explain using // if you can solve this.

Edit: corrected my index from 5 to 4, so it stays within length of the array. My bot is actually responding but there is this error happening 10 times in the console. My bot has responded twice to one ping.

[JDA MainWS-ReadThread] ERROR JDA - One of the EventListeners had an uncaught exception
java.lang.ArrayIndexOutOfBoundsException: 5




Aucun commentaire:

Enregistrer un commentaire