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 - 如何等待下一条消息 的相关文章

  • 在discord.js 中,我可以使用 Discord Bot 向用户发送直接消息吗?

    我想使用 Discord 机器人向用户发送私人消息 用户与机器人不在同一服务器中 如果我可以使用author sendMessage 我如何初始化 查找 author变量 我可以通过 User id 找到该用户吗 感谢您的阅读 对于任何有兴
  • 如何通过代理连接不和谐机器人

    我正在尝试使用discord py 并通过代理运行discord 机器人 这关于此的不一致文档 https discordpy readthedocs io en latest api html highlight proxy discor
  • 如何创建频道然后找到ID

    我正在创建一个频道message guild channels create 我该如何找到该频道的消息 ID 并在新创建的频道中发送消息 message guild channels create bug priority reportPr
  • 如何使用 Discord,py 的用户 ID 获取特定用户的头像

    I used discord py制作一个将用户 ID 存储在数据库中以识别他们的机器人 但我不知道如何仅通过使用他们的用户来获取特定用户的头像id 我四处搜寻 发现了这样的事情 Client get user 但它对我不起作用 因为我无法
  • Discord js / 检查用户是否在特定语音频道中

    我希望我的机器人使用 const voiceChannel message member voice channel const voiceChannelID message member voice channelID if voiceC
  • 如何使用 Discord.py 向所有文本频道发送消息?

    我想向服务器上的每个通道发送一条消息 比如说 Hello 我预计它会有点滞后 因为 afaik 有大约 5 条消息 3 秒的限制 但仍然比手动将消息发送到每个通道更容易等待 无法真正弄清楚是否可以做到这一点 您可以使用协程的组合await
  • 如何将随机的 subreddit 图像发送到我的 Discord.py 机器人?

    我正在用异步 python 制作一个不和谐的机器人 我希望机器人发布random当我执行命令时的图片 前缀 示例 meme 这会从 Reddit 子版块中调出一张随机图片 在本例中是 Reddit 模因子版块 我已经开始实现我想要的 但我需
  • Discord.py 获取自定义状态

    如何通过discord py获取Discord用户自定义状态 我看过discord py 文档 我唯一能找到的是Member status https discordpy readthedocs io en latest api html
  • 当有人加入时创建规则协议

    我想要一个机器人将新成员设置为只能查看一个频道并且必须就规则达成一致才能使用服务器的角色 我已经写了这个来做到这一点 但我不断收到此错误 Ignoring exception in on member join Traceback most
  • 从站点中抓取验证链接 Href

    我想从以下位置获取验证hrefGmailnator 收件箱 https www gmailnator com geralddoreyestmp messageid 179b454b4c482c4d并且此站点包含 href 不和谐验证 如下所
  • 如何使用带有空格的命令名称?

    当 python bot 中的命令之间有空格时 如何使 bot 工作 我知道我们可以使用子命令或on message但是是否还有其他选项可以仅对选定的命令而不是对所有命令执行此操作 下面的代码将不起作用 bot command pass c
  • 为什么我可以使用 bot.get_user 函数获取一些用户,但不能获取其他用户? [不和谐.py]

    我当时正在忙着一天的事情并做学校作业 我去了我的不和谐服务器来检查一天中声誉和排行榜进度如何变化 当我使用该命令时 我收到错误 Nonetype object has no attribute display name 所以我很自然地转到运
  • 允许 Discord Rewrite 机器人响应其他机器人

    我有一个 Discord 机器人和一个用于 Discord 频道的 Webhook 设置 用于每小时准时发送一条命令 然而 Discord Rewrite 默认情况下似乎会忽略从其他机器人发送的命令 我该如何禁用此功能 我是否需要修改每个命
  • 如何在数组中获取在 Discord.js 中具有角色的所有用户

    我正在努力让所有成员都扮演一定的角色 例如 我的 Discord 服务器中有 gurdian 角色 ID 为 872029521484873779 我想要数组中所有在我的服务器中拥有 gurdian 角色的用户 Name 的列表 我的代码如
  • Discord Webhook 消息无法发送

    所以我有一段不久前有人发布的代码 到现在已经完美运行一年了 它采用谷歌表单答案并将其作为网络钩子发布到不和谐频道 现在从昨天开始就不再起作用了 脚本没有任何改变 function onSubmit e var form FormApp ge
  • 消息 discord.py 中的可点击链接

    我希望我的机器人将消息发送到聊天中 如下所示 await ctx send This country is not supported you can ask me to add it here 但是为了使 这里 成为可点击的链接 在 HT
  • 我的 on_member_join 事件不起作用。我尝试了意图,但它给出了这个错误

    考虑 最近一次通话最后 文件 randomgg py 第 1271 行 位于 u003cmodule u003e 中客户端 运行 令牌 文件 usr local lib python3 8 site packages discord cli
  • 自动更改 github 文件

    我制作了一个带有白名单的应用程序 withelist 位于 github 存储库上 只有一个文件 即 withelist 每次下载我的应用程序的用户想要被允许使用该应用程序时 都必须向我发送一个消息插入白名单 现在这个过程真的很慢 我想加快
  • 从 json 文件加入时添加角色 (autorole)

    我对 JS 相当陌生 为了学习 我决定为 Discord 制作一个机器人 我学到了很多并且正在继续学习 我有一个 autorole 的想法 我知道传统的做法 bot on guildMemberAdd member gt var role
  • Discord.net 无法在 Linux 上运行

    我正在尝试让在 Linux VPS 上运行的 Discord net 中编码的不和谐机器人 我通过单声道运行 但我不断收到此错误 Unhandled Exception System Exception Connection lost at

随机推荐

  • 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