0

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.

ChrisM
  • 505
  • 6
  • 18
Hyku
  • 3
  • 1
  • I'm not quite sure what you are trying to do here, but it seems like you might need to store you commands and messages in a List or Set. Right now you seem to be overwriting them each time around the loop? – Ryan Aug 05 '19 at 04:25

1 Answers1

1
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();
    }
Kris
  • 8,680
  • 4
  • 39
  • 67
  • This is a good method ty <3 but I never worked with HashMap so I dont know, how can I implement it in bot/command class? because msgMap.keySet() dont work. I mean the snippet is searching in the message for a single String not a Map of them. – Hyku Aug 05 '19 at 16:09
  • Map is a key value pair store. If you have the key you can get it with msgMap.get(key) – Kris Aug 06 '19 at 04:46