JDA - 如何等待下一条消息

2023-12-07

我正在使用 JDA 制作一个不和谐的机器人,我想知道如何等待消息。像这样的东西

import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;

public class Listener extends ListenerAdapter {
    public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
        String message = event.getMessage().getContentRaw();
        boolean isBot = event.getAuthor().isBot();

        // Check if message is not from a bot
        if (!isBot) {
            if (message.equalsIgnoreCase("hi")) {
                event.getChannel().sendMessage("Hello, what's your name?").queue();
                // Wait for second message
                String name = event.getMessage().getContentRaw(); // Saving content from second message
                event.getChannel().sendMessage("Your name is: " + name).queue();
            }
        }
    }
}

User: Hi

机器人:你好,你叫什么名字?

User: 发送姓名

机器人:你的名字是:name

我如何收到第二条消息?


正如已经告诉过的Minn在评论中。您可以使用线程中给出的方法。不过,我建议使用 JDA-Utilities EventWaiter。

如果您使用 Maven 或 Gradle,请使用其中之一:

<!--- Place this in your repositories block --->
  <repository>
    <id>central</id>
    <name>bintray</name>
    <url>http://jcenter.bintray.com</url>
  </repository>
<!--- Place this in your dependencies block --->
  <dependency>
    <groupId>com.jagrosh</groupId>
    <artifactId>jda-utilities</artifactId>
    <version>JDA-UTILITIES-VERSION</version>  <!--- This will be the latest JDA-Utilities version. Currently: 3.0.4 --->
    <scope>compile</scope>
    <type>pom</type>
  </dependency>
  <dependency>
    <groupId>net.dv8tion</groupId>
    <artifactId>JDA</artifactId> <!--- This will be your JDA Version --->
    <version>JDA-VERSION</version>
  </dependency>

对于 gradle 来说更容易:


# Add this to the dependencies (What's inside this block, not the block itself.

dependencies {
    compile 'com.jagrosh:jda-utilities:JDA-UTILITIES-VERSION'
    compile 'net.dv8tion:JDA:JDA-VERSION'
}

# Same story for the repo's
repositories {
    jcenter()
}

加载后,我建议检查ExampleBot 主类。添加你自己的东西。因为我只会解释让 EventWaiter 工作的基础知识。

这将是机器人的主要类,当您运行它时,它将使用这些命令启动机器人。 ShutdownCommand 和 PingCommand 是实用程序的一部分。所以这些会自动添加。

public static void main(String[] args) throws IOException, LoginException, IllegalArgumentException, RateLimitedException
    {
        // the first is the bot token
        String token = "The token of your bot"
        // the second is the bot's owner's id
        String ownerId = "The ID of your user account"
        // define an eventwaiter, dont forget to add this to the JDABuilder!
        EventWaiter waiter = new EventWaiter();
        // define a command client
        CommandClientBuilder client = new CommandClientBuilder();
        // sets the owner of the bot
        client.setOwnerId(ownerId);
        // sets the bot prefix
        client.setPrefix("!!");
        // adds commands
        client.addCommands(
                // command to say hello
                new HelloCommand(waiter),
                // command to check bot latency
                new PingCommand(),
                // command to shut off the bot
                new ShutdownCommand());

        // start getting a bot account set up
        new JDABuilder(AccountType.BOT)
                // set the token
                .setToken(token)
                // set the game for when the bot is loading
                .setStatus(OnlineStatus.DO_NOT_DISTURB)
                .setActivity(Activity.playing("loading..."))
                // add the listeners
                .addEventListeners(waiter, client.build())
                // start it up!
                .build();
    }

现在,对于你好命令。首先创建一个名为“HelloCommand”的新类。在本课程中,您将扩展实用程序的“命令”部分。

public class HelloCommand extends Command
{
    private final EventWaiter waiter; // This variable is used to define the waiter, and call it from anywhere in this class.

    public HelloCommand(EventWaiter waiter)
    {
        this.waiter = waiter; // Define the waiter
        this.name = "hello"; // The command
        this.aliases = new String[]{"hi"}; // Any aliases about the command 
        this.help = "says hello and waits for a response"; // Description of the command
    }
    
    @Override
    protected void execute(CommandEvent event)
    {
        // ask what the user's name is
        event.reply("Hello. What is your name?"); // Respond to the command with a message.
        
        // wait for a response
        waiter.waitForEvent(MessageReceivedEvent.class, 
                // make sure it's by the same user, and in the same channel, and for safety, a different message
                e -> e.getAuthor().equals(event.getAuthor()) 
                        && e.getChannel().equals(event.getChannel()) 
                        && !e.getMessage().equals(event.getMessage()), 
                // respond, inserting the name they listed into the response
                e -> event.reply("Hello, `"+e.getMessage().getContentRaw()+"`! I'm `"+e.getJDA().getSelfUser().getName()+"`!"),
                // if the user takes more than a minute, time out
                1, TimeUnit.MINUTES, () -> event.reply("Sorry, you took too long."));
    }
    
}

现在,我们就到这里来看看有趣的东西了。使用事件服务员时。您需要检查几个区域。

        // wait for a response
        waiter.waitForEvent(MessageReceivedEvent.class, 
                // make sure it's by the same user, and in the same channel, and for safety, a different message
                e -> e.getAuthor().equals(event.getAuthor()) 
                        && e.getChannel().equals(event.getChannel()) 
                        && !e.getMessage().equals(event.getMessage()), 
                // respond, inserting the name they listed into the response
                e -> event.reply("Hello, `"+e.getMessage().getContentRaw()+"`! I'm `"+e.getJDA().getSelfUser().getName()+"`!"),
                // if the user takes more than a minute, time out
                1, TimeUnit.MINUTES, () -> event.reply("Sorry, you took too long."));

更详细地解释:

        waiter.waitForEvent(GuildMessageReceivedEvent.class, // What event do you want to wait for?
            p -> p.getAuthor().equals(message.getAuthor()) && p.getChannel().equals(message.getChannel()), // This is important to get correct, check if the user is the same as the one who executed the command. Otherwise you'll get a user who isn't the one who executed it and the waiter responds to it.
            run -> {
            // Run whatever stuff you want here.
        }, 1, // How long should it wait for an X amount of Y?
            TimeUnit.MINUTES, // Y == TimeUnit.<TIME> (Depending on the use case, a different time may be needed)
            () -> message.getChannel().sendMessage("You took longer then a minute to respond. So I've reverted this message.").queue()); // If the user never responds. Do this.

这应该是BASICS使用EventWaiter。这可能取决于您的用例。也可以仅使用 eventwaiter 类来完成。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JDA - 如何等待下一条消息 的相关文章

随机推荐

  • C# 对象数组,非常大,寻找更好的方法

    好的 所以在我的一个项目中 我试图重新设计它存储某些变量的方式 我有一个简单的对象数组 这些对象引用的类是 class Blocks public byte type Block Empty byte lastblock Block Zer
  • Wix:通过在立即操作中设置属性来访问延迟操作中的属性:字典中不存在给定的键

    我正在关注几个来源 SO 帖子 甚至是 Wix 安装程序书 这就是我目前在立即自定义操作中设置两个属性 然后尝试在延迟操作中读取它的方式 但是 它不起作用 失败并回滚 并且我不断收到System Collections Generic Ke
  • 在 Mac OS X 上以编程方式为 Matplotlib 选择正确的后端

    我有一个程序集成了 tkinter GUI 和 matplotlib 图 使用 pyplot 为了让这个程序在各种 Mac 平台上正常工作 我遇到了无尽的麻烦 主要问题似乎是后端的适当选择 在某些情况下 程序运行良好没有问题 在其他情况下
  • 为低于 31 的 API 创建 LocationRequest

    我有compileSdkVersion 32 现在我可以创建LocationRequest仅使用LocationRequest Builder LocationRequest create 目前不可用 这意味着我什至无法调用这个已弃用的静态
  • 将指数分布叠加到直方图上

    如何在时间间隔直方图上叠加指数分布 直方图看起来像指数分布 当我尝试以与叠加法线曲线类似的方式创建直方图时 我得到以下结果 Error in xy coords x y x and y lengths differ 我可以自己创建直方图 它
  • 用于 Caffe 的 Python 还是 Matlab?

    我将致力于在 Caffe 中实现 DQN 和 Google DeepMind 的最新扩展 为此 我将编写一个模拟器 代替 Atari 模拟器 来为代理创建培训体验 我的问题是 Matlab 或 Python 的 Caffe 接口中哪一个最成
  • 有没有办法通过sql获取Windows任务管理器详细信息?

    我无法访问客户端的 Windows 远程计算机 我仅通过 tsql 连接他们的数据库服务器 我需要检查哪些进程占用了更多内存并通知他们 有没有tsql查询来获取windows进程 对的 这是可能的 您可以致电TASKLIST命令通过xp c
  • 错误:未定义对“cv::imread(std::string const&, int)”的引用

    我是 Qt 新手 我有一个需要在 Qt 中配置 OpenCV 的项目 我尝试在 Qt 中运行一个简单的代码 但出现此错误 未定义的引用 cv imread std string const int 这是我的代码 include opencv
  • 当键为数字时,如何从多维数组中回显单个值?

    以此数组为例 Array events gt Array 0 gt Array event gt Array category gt seminars sales status gt Live 如何检索类别的值 我尝试过各种组合 例如 ec
  • PHP 将重复行插入数据库

    我使用以下代码将用户插入到名为 accounts 的表中 session start include include connect php Posted information from the form put into variabl
  • jQuery 事件:检测 div 的 html/文本的更改

    我有一个 div 它的内容一直在变化 是吗 ajax requests jquery functions blur等等等等 有没有办法可以随时检测到 div 上的任何变化 我不想使用任何间隔或检查的默认值 像这样的事情会做 mydiv co
  • 如何测试 dockerignore 文件?

    读完后 dockerignore文档 我想知道有没有办法测试一下 Examples node modules 如何检查我的 dockerfile 忽略正确的文件和目录 扩展至VonC的建议 这是一个示例构建命令 您可以使用它来使用当前文件夹
  • Spring Data Rest @EmbeddedId 无法从 Post Request 构造

    我有一个 JPA 实体Person和一个实体Team 两者都由一个实体连接人与团队 该连接实体与以下对象保持多对一关系Person和一到Team 它有一个由 id 组成的多列键Person和Team 由 EmbeddedId 表示 为了将嵌
  • Endpoint 与 Windows 沉浸式项目版本 1 不兼容

    由于某种原因 我使用 添加服务引用 向导为 wcf 服务生成代码时出错 Custom tool warning No endpoints compatible with version 1 of windows immersive proj
  • 如何在复选框单击时选择 jqGrid 行?

    下面是我的 jqGrid 代码 我想选择行或突出显示当前行 当我checkjqgrid 行内的特定复选框 现在onSelectRow我正在检查复选框 var xmlDoc parseXML xml configDiv empty div w
  • 是否可以让“命名构造函数”返回私有构造的、不可移动、不可复制的 std::Optional

    我主要从事不允许抛出异常的系统级 C 项目 但 理所应当 强烈鼓励使用 RAII 现在 我们使用许多 C 程序员熟悉的臭名昭著的技巧来处理构造函数失败的问题 例如 简单的构造函数 然后调用bool init Args 做困难的事情 真正的构
  • 阿帕奇的条件

    I have KOHANA ENV环境变量设置为DEVELOPMENT例如 现在有一组规则 仅当该 var 设置为PRODUCTION 打开 mod deflate 设置过期标头默认值 关闭 ETag 等 例如 if KOHANA ENV
  • 如何在 pyOpenSSL 中获取 DTLS 的当前密码

    我需要在 pyOpenSSL 中获得 DTLS 协议的协商密码 我成功地为 TCP 套接字做到了这一点 但当涉及到数据报时 情况就不那么明显了 请提供 C 或 Python 语言的示例 这是我到目前为止所尝试过的 import socket
  • Microsoft Excel 会破坏 .csv 文件中的变音符号?

    我正在以编程方式将数据 使用 PHP 5 2 导出到 csv 测试文件中 示例数据 Num ro 1 注意带重音的 e 数据是utf 8 无前置 BOM 当我在 MS Excel 中打开此文件时 显示为Num ro 1 我可以在文本编辑器
  • JDA - 如何等待下一条消息

    我正在使用 JDA 制作一个不和谐的机器人 我想知道如何等待消息 像这样的东西 import net dv8tion jda api events message guild GuildMessageReceivedEvent import