javabotsbufferedreaderircpircbot

Java TwitchBot/PircBot can't read commands in a .txt file like it has to do


I start coding my own TwitchBot in java. The bot is working fine, so my idea was, to replace the hardcoded commands with variables. The commands and messages saved in a text file.

BufferedReader Class:

try {
            reader = new BufferedReader(new FileReader("censored//lucky.txt"));
            String line = reader.readLine();
            while (line != null) {

                String arr[] = line.split(" ", 2);

                command = arr[0];
                message = arr[1];

                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

Snippet of my bot/command class

if(message.toLowerCase().contains(BufferedReader.command)) {
            sendMessage(channel, BufferedReader.message);
        }

my .txt file:

!test1 Argument1 Argument2
!test2 Argument1 Argument2
!test3 Argument1 Argument2
!test4 Argument1 Argument2

Everything works fine when I have only 1 command+message / line in my text document, but when there are multiple lines, I can't access the commands in the Twitch Chat. I know, that the commands are stacking like !test1 !test2 !test3 !test this.

So my question is, how do I avoid this? And my fear is, that in my actual code !test3 uses the message from my !test1 command.


Solution

  • while (line != null) 
    {
       String arr[] = line.split(" ", 2);
       command = arr[0];
       message = arr[1];
       line = reader.readLine();
    }
    

    this loop keeps reading each line from the file and overwrites contents of command and message , that means when you have multiple commands in file - only the last line prevails.

    If you want to store multiple commands/messages then the command/message variables must be of type java.util.List or HashMap. And then you can match based on contents.

    Eg.,

    Map<String,String> msgMap = new HashMap<>();
    while (line != null) 
        {
           String arr[] = line.split(" ", 2);
           if(arr[0]!=null)
             msgMap.put(arr[0],arr[1]);
           line = reader.readLine();
        }