client.user.setActivity 发现为空? (Node.js)

client.user.setActivity found as null? (Node.js)

我正在尝试将我的 Discord 机器人的 activity 设置为“游戏”,但是我在网上找到的示例根本没有帮助。

client.user.setActivity("what the bot is playing");

根本不起作用,它给了我这个错误,指出我正在尝试找到 null 的东西(不存在......在非编程术语中)

TypeError: Cannot read properties of null (reading 'setActivity')
at Object.<anonymous> (/home/runner/DiscordBot/index.js:46:13)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47

您可能试图在机器人上线之前更改它的状态。尝试将其放入 ready 事件中。

client.on("ready", () => {
    client.user.setActivity("what the bot is playing");
});

你好疯子 12

有各种更好的语法和函数。

你可以这样做:

//Make sure to define client and Discord.
client.on("ready", () => {
client.user.setPresence({ status: 'dnd' }) //Could also be "online" or "invisible" or even "idle"
const activities = [
    `${client.guilds.cache.size} Servers`, //How many servers bot is in
    `${client.channels.cache.size} Channels`, //How many channels do those servers have
    `${client.guilds.cache.reduce((a, b) => a + b.memberCount, 0)} Users`, //How many users are on those servers
    `custom add anything if you want or delete` //If you want more add , and then `custom2` and so on.
];
let i = 0;
setInterval(() => client.user.setActivity(`x!help | ${activities[i++ % activities.length]}`, { type: 'PLAYING' }), 10000); 
//Could also change to "WATCHING", "LISTENING" and "STREAMING" and you can also change the time for it to change to the next activity, warning: under 10000(10 seconds) will result in being rate limited.
//Output: Playing: x!help | 20 servers, after 10 sec: Playing: x!help | 5000 users and so on.
});
client.login("token")

希望这对您有所帮助:)