让机器人按住按钮一定时间而不停止程序

问题描述 投票:0回答:1

到目前为止,我有一个 Discord 机器人的代码,例如,当用户发送包含“up”的消息时,它会按下 W 键 3 秒钟。我出于举例的目的而将其包括在内

@Override
    public void onMessageReceived(MessageReceivedEvent event) {
        Message msg = event.getMessage();

        if (msg.getContentRaw().equals("up")) {
            MessageChannel channel = event.getChannel();
            channel.sendMessage("Going up!").queue();
            robot.keyPress(KeyEvent.VK_W);
            robot.delay(3 * 1000); // In milliseconds
            robot.keyRelease(KeyEvent.VK_W);
        }

        if (msg.getContentRaw().equals("right")) {
            MessageChannel channel = event.getChannel();
            channel.sendMessage("Going right!").queue();
            robot.keyPress(KeyEvent.VK_D);
            robot.delay(3 * 1000); // In milliseconds
            robot.keyRelease(KeyEvent.VK_D);
        }

我这里遇到的问题是,如果一个用户在 3 秒结束之前发送“up”,另一个用户发送“right”,它将对消息进行“排队”并按住“w”3 秒,然后按住“d”3 秒3秒,但我希望它在各自的时间中同时按住“w”和“d”。我怎样才能实现这一点,这样它就不会排队它们,并且实际上同时按下和读取消息(如果可能的话)?

java awtrobot discord-jda
1个回答
0
投票

使用Thread,它们将允许您异步运行代码,这意味着您的代码不会阻塞执行。当机器人调用延迟方法时,您的机器人无法执行任何操作。

下面是如何使用Thread的示例,如here所示。

public class Main implements Runnable {
  public static void main(String[] args) {
    Main obj = new Main();
    Thread thread = new Thread(obj);
    thread.start();
    System.out.println("This code is outside of the thread");
  }
  public void run() {
    System.out.println("This code is running in a thread");
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.