【问题标题】:Make JDA Discord Bot send a random image让 JDA Discord Bot 发送随机图像
【发布时间】:2020-05-13 05:18:16
【问题描述】:

我目前正在为我的 Discord 服务器开发一个机器人,我想知道如何实现各种 图像命令(例如,!cat!meme)以使机器人发送一个每次调用命令时的随机图像。

我见过的几乎每个机器人都有这样的功能,但由于某种原因,我似乎无法在 JDA 中找到一种可行的方法来做到这一点。我发现的任何 JDA 示例要么已经过时,要么根本不起作用,所以我真的希望有人能帮我看看。

这是我已经做过的(非常基本的)示例,但问题是图片不会随每次调用而随机化,并且在我重新启动 discord 之前保持不变

public void sendCatImage() {
        EmbedBuilder result= new EmbedBuilder();
        result.setTitle("Here's a cat!");
        result.setImage("http://thecatapi.com/api/images/get?format=src&type=png");
        event.getChannel().sendMessage(result.build()).queue();
    }

如果有帮助,我正在使用 JDA 版本 4.1.0_100

任何帮助将不胜感激!

【问题讨论】:

    标签: image bots discord discord-jda


    【解决方案1】:

    Discord 将根据 URL 缓存图像。您可以附加一个随机数作为查询来防止这种情况:

    public String randomize(String url) {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        return url + "&" + random.nextInt() + "=" + random.nextInt();
    }
    
    ...
    result.setImage(randomize(url));
    ...
    

    此外,您还可以通过将图像与嵌入一起上传来避免不和谐更新图像。为此,您首先需要下载图像然后上传:

    // Use same HTTP client that jda uses
    OkHttpClient http = jda.getHttpClient();
    // Make an HTTP request to download the image
    Request request = new Request.Builder().url(imageUrl).build();
    Response response = http.newCall(request).execute();
    try {
        InputStream body = response.body().byteStream();
        result.setImage("attachment://image.png"); // Use same file name from attachment
        channel.sendMessage(result.build())
               .addFile(body, "image.png") // Specify file name as "image.png" for embed (this must be the same, its a reference which attachment belongs to which image in the embed)
               .queue(m -> response.close(), error -> { // Send message and close response when done
                   response.close();
                   RestAction.getDefaultFailure().accept(error);
               });
    } catch (Throwable ex) {
    // Something happened, close response just in case
        response.close();
    // Rethrow the throwable
        if (ex instanceof Error) throw (Error) ex;
        else throw (RuntimeException) ex;
    }
    

    【讨论】:

    • 非常感谢您的帮助!我刚刚尝试过,图像实际上是随机的!但是由于某种原因,当我单击图像以查看完整视图时,它显示的图像与嵌入中的图像不同。我知道这只会在有人真正点击图片时造成不便,但我想知道是否也有办法解决这个问题?
    • OkHttpClient http = jda.getHttpClient(); 我的IDE 说它无法解析符号jda。我正在使用 IntelliJ IDEA。对此有何建议?
    • 它指的是任何 JDA 实例,您可以通过大多数带有 x.getJDA() 的 JDA 实体获取一个,例如 event.getJDA()channel.getJDA()
    • 啊,现在可以了!感谢您花时间帮助我解决这个问题!我面临的另一个问题是Response response = http.newCall(request).execute(); 抛出了一个未处理的IOException。我通过将throws IOException 添加到我的方法中,然后用trycatch 包围方法调用来解决这个问题。虽然这解决了这个问题,但我仍然想知道是否有一种“更正确”的方法可以避免这个问题。
    猜你喜欢
    • 2022-11-23
    • 2020-08-18
    • 2021-07-06
    • 2021-06-05
    • 2019-02-13
    • 2019-10-19
    • 1970-01-01
    • 2021-06-25
    • 2020-05-11
    相关资源
    最近更新 更多