首页 > 解决方案 > 如何在 discord.js 中获得 twitch 流预览?

问题描述

目前我有这个代码来通知我的不和谐成员有人正在流式传输。当我将图像设置为 twitch url 时,由于某种原因它不会加载它......我怎样才能获得正确的 twitch 流预览?

client.on("presenceUpdate", (oldPresence, newPresence) => {
    if (!newPresence.activities) return false;
    newPresence.activities.forEach(activity => {
        if (activity.type == "STREAMING") {
            console.log(`${newPresence.user.tag} is streaming at ${activity.url}.`);
            const twitchAnnouncementChannel = newPresence.guild.channels.cache.find(ch => ch.id === `789277245617209354`)
            const twitchChannel = new Discord.MessageEmbed()
            .setColor("#400080")
            .setTitle(`${newPresence.user.tag} is now live on twitch`)
            .setURL(activity.url)
            .setDescription(`**Stream Started**`)
            .setImage(activity.url)
            .setTimestamp()
            .setFooter("Enigma")
            twitchAnnouncementChannel.send(`${newPresence.user.tag} IS NOW LIVE ON TWITCH GO CHECK HIM OUT! @everyone`, twitchChannel)
        };
    });
});

标签: javascriptdiscord.js

解决方案


在你的情况下,这应该这样做。要获得 Twitch 流的预览,您需要:https://static-cdn.jtvnw.net/previews-ttv/live_user_USERNAME-{width}x{height}.jpg,“activity.url”只是频道 url。

client.on("presenceUpdate", (oldPresence, newPresence) => {
    if (!newPresence.activities) return false;
    newPresence.activities.forEach(activity => {
        if (activity.type == "STREAMING") {
            console.log(`${newPresence.user.tag} is streaming at ${activity.url}.`);
            const twitchAnnouncementChannel = newPresence.guild.channels.cache.find(ch => ch.id === `789277245617209354`)
            const twitchChannel = new Discord.MessageEmbed()
                .setColor("#400080")
                .setTitle(`${newPresence.user.tag} is now live on twitch`)
                .setURL(activity.url)
                .setDescription(`**Stream Started**`)
                .setImage(`https://static-cdn.jtvnw.net/previews-ttv/live_user_${activity.url.split("twitch.tv/").pop()}-1920x1080.jpg`)
                .setTimestamp()
                .setFooter("Enigma");
            twitchAnnouncementChannel.send(`${newPresence.user.tag} IS NOW LIVE ON TWITCH GO CHECK HIM OUT! @everyone`, twitchChannel)
        };
    });
});

推荐阅读