【问题标题】:Java TwitchBot/PircBot can't read commands in a .txt file like it has to doJava TwitchBot/PircBot 不能像它必须做的那样读取 .txt 文件中的命令
【发布时间】:2019-12-12 13:26:51
【问题描述】:

我开始在java 中编写自己的TwitchBot。机器人工作正常,所以我的想法是用变量替换硬编码命令。保存在文本文件中的命令和消息。

BufferedReader类:

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();
        }

我的bot/command class的片段

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

我的.txt 文件:

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

当我的文本文档中只有 1 个command+message / line 时一切正常,但是当有多行时,我无法访问Twitch Chat 中的命令。我知道,这些命令像!test1 !test2 !test3 !test 这样堆叠起来。

所以我的问题是,我该如何避免这种情况?我担心的是,在我的实际代码中!test3 使用来自我的!test1 命令的消息。

【问题讨论】:

  • 我不太确定您在这里要做什么,但您似乎需要将命令和消息存储在列表或集合中。现在你似乎每次都在循环覆盖它们?

标签: java bots bufferedreader irc pircbot


【解决方案1】:
while (line != null) 
{
   String arr[] = line.split(" ", 2);
   command = arr[0];
   message = arr[1];
   line = reader.readLine();
}

这个循环不断地从文件中读取每一行并覆盖 commandmessage 的内容,这意味着当您在文件中有多个命令时 - 只有最后一行占上风。

如果要存储多个命令/消息,则 command/message 变量必须是 java.util.ListHashMap 类型。然后你可以根据内容进行匹配。

例如,

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();
    }

【讨论】:

  • 这是一个很好的方法 ty
  • Map 是一个键值对存储。如果你有钥匙,你可以用 msgMap.get(key)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
相关资源
最近更新 更多