【问题标题】:Get user banner in discord.js在 discord.js 中获取用户横幅
【发布时间】:2021-09-20 20:33:26
【问题描述】:

有没有什么方法可以使用 discord.js 在 discord 上获取用户横幅?用户横幅是新功能,所以我不确定到目前为止是否有任何方法。我在文档中没有找到任何东西。例如。服务器横幅可用:

https://cdn.discordapp.com/banners/GUILD_ID/GUILD_BANNER.png.

类似于用户横幅的东西会很棒。

【问题讨论】:

  • the official documentation 中没有关于获取用户横幅的内容,所以到目前为止我不相信有办法。但是,此功能仍处于不和谐的 BETA 中,因此请密切注意,因为他们可能很快会发布端点。

标签: javascript discord discord.js


【解决方案1】:

经过几个小时的开发,我设法恢复了一个不和谐的横幅,代码如下:

(你需要安装"node-fetch" => npm i node-fetch)

const fetch = require('node-fetch')

let uid = "user_id"

let response = fetch(`https://discord.com/api/v8/users/${uid}`, {
    method: 'GET',
    headers: {
        Authorization: `Bot ${client.token}`
    }
})

let receive = ''
let banner = 'https://cdn.discordapp.com/attachments/829722741288337428/834016013678673950/banner_invisible.gif' // invisible image ( you can change the link if you want )

response.then(a => {
if(a.status !== 404) {
a.json().then(data => {
receive = data['banner']

if(receive !== null) {

let format = 'png'
if(receive.substring(0,2) === 'a_') {
format = 'gif'
}

banner = `https://cdn.discordapp.com/banners/${uid}/${receive}.${format}`

}})

.setTimeout(() => {

// To retrieve the value "banner" we put a timeout otherwise it will return us the first definition of "banner" that is to say the invisible image, I let you modify the code as you wish, good evening to you (and also I just wanted to make it clear I'm French)

// Put the rest of your code here :

}, 1000)

【讨论】:

  • 不客气^^,祝你有美好的一天,Michal,祝你发展顺利! :D
【解决方案2】:

简单的解决方案

我想出的discord.js v12最简单的解决方案:

async function getUserBannerUrl(userId) {
    const user = await client.api.users(userId).get();
    return user.banner ? `https://cdn.discordapp.com/banners/${userId}/${user.banner}?size=512` : null;
}

但是,这不能很好地处理 mime 类型。除非您阅读 content-type 标头,否则您不知道 mime 类型是什么。这可能会破坏一些要求您在 URL 中具有文件扩展名的内容。这就是为什么我想出了更复杂的解决方案。

复杂的解决方案

下面的代码依赖于axios

const axios = require("axios");
async function getUserBannerUrl(userId, { dynamicFormat = true, defaultFormat = "webp", size = 512 } = {}) {

    // Supported image sizes, inspired by 'https://discord.js.org/#/docs/main/stable/typedef/ImageURLOptions'.
    if (![16, 32, 64, 128, 256, 512, 1024, 2048, 4096].includes(size)) {
        throw new Error(`The size '${size}' is not supported!`);
    }

    // We don't support gif as a default format,
    // because requesting .gif format when the original image is not a gif,
    // would result in an error 415 Unsupported Media Type.
    // If you want gif support, enable dynamicFormat, .gif will be used when is it available.
    if (!["webp", "png", "jpg", "jpeg"].includes(defaultFormat)) {
        throw new Error(`The format '${defaultFormat}' is not supported as a default format!`);
    }

    // We use raw API request to get the User object from Discord API,
    // since the discord.js v12's one doens't support .banner property.
    const user = await client.api.users(userId).get();
    if (!user.banner) return null;

    const query = `?size=${size}`;
    const baseUrl = `https://cdn.discordapp.com/banners/${userId}/${user.banner}`;

    // If dynamic format is enabled we perform a HTTP HEAD request,
    // so we can use the content-type header to determine,
    // if the image is a gif or not.
    if (dynamicFormat) {
        const { headers } = await axios.head(baseUrl);
        if (headers && headers.hasOwnProperty("content-type")) {
            return baseUrl + (headers["content-type"] == "image/gif" ? ".gif" : `.${defaultFormat}`) + query;
        }
    }

    return baseUrl + `.${defaultFormat}` + query;

}

示例用法

实现简单的!banner 命令,将显示消息发送者的横幅。

client.on("message", async (message) => {

    if (message.author.bot) return;

    if (message.content == "!banner") {
        const bannerUrl = await getUserBannerUrl(message.author.id, { size: 4096 });
        if (bannerUrl) {
            const embed = new Discord.MessageEmbed()
                .setTitle(`${message.author.username}'s banner`)
                .setDescription("Look at my banner, how cool is that?")
                .setImage(bannerUrl);
            message.channel.send(embed);
        } else {
            message.channel.send("You don't have money to buy Discord Nitro... How sad...");
        }
    }

});

【讨论】:

    【解决方案3】:

    您可以使用discord-banner npm 包获取不和谐用户横幅

    它使用起来非常简单,现在无需 Discord.js v13 即可获得它

    【讨论】:

      【解决方案4】:

      根据对this GitHub issuethe official documentation 的回复,目前没有读取用户简介和横幅的方法。

      正如 Tyler 所说,该功能仍处于测试阶段。添加后,您应该能够序列化用户对象上的横幅图像哈希,从而允许机器人被动接收字段。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-03
        • 1970-01-01
        • 2015-01-14
        • 2015-05-20
        相关资源
        最近更新 更多