首页 > 解决方案 > 在 Discord RPC 的 JavaScript 函数中使用变量

问题描述

我一直在尝试让 Discord RPC 正常工作,以便在获取时更新歌曲标题。我知道睡眠功能目前可能不起作用,但主要问题是能够使用“文本”变量作为 Discord RPC 的输出。有没有人对我如何在丰富的存在中使用“文本”变量有任何建议?

const clientId = 'REDACTED';
const scopes = ['rpc', 'rpc.api', 'messages.read'];

const client = require('discord-rich-presence')(clientId);

const website = 'https://jetstreamradio.com/scSongData'

//var text = '';

function updateRichPres() {
    fetch(website)
        .then(res => res.text())
        //.then(text => console.log(text))
        .then(text => res.text())
        .then(function (text) { return text })
        .then(client.updatePresence({
            state: text,
            details: 'Now listening to...',
            startTimestamp: Date.now(),

            largeImageKey: 'jetstream_logo_tunein',
            //smallImageKey: 'jetstream_logo_tunein',
            instance: true,
        }));
    while (true) {
        //await sleep(60000);
        console.log('x');
    }   
};
client.on('connected', () => {
    console.log('connected!');
    updateRichPres()

});```

标签: javascriptnode.jselectrondiscord

解决方案


您没有将函数传递给 .then()。这里发生的是 client.updatePresence 调用是在 fetch 完成之前进行的,因为您是直接调用它,而不是作为回调提供它。

它应该是:

fetch(website).then(res =>
    client.updatePresence({ 
        state: res.text(),
        details: 'Now listening to...',
        startTimestamp: Date.now(),
        largeImageKey: 'jetstream_logo_tunein',
        instance: true 
    })
);

箭头 (=>) 是用于创建函数的 JavaScript 语法。

在这个相当复杂的用例中使用它之前,我建议您了解更多关于基本 JavaScript 语法的知识。


推荐阅读