Discord.js显示状态中的禁令数量



我有一个针对特定服务器的机器人程序,我想将状态设置为服务器的禁令数量。

我有以下代码,但我无法获得banned.size:

client.on("ready", () => {
message.guild.fetchBans().then(banned => {
let sizee = banned.size
})
setInterval(function() {
let lol = ['status 1', `status 2`, `Status 3`, `status 4`, `this guild has ${sizee} banned users `];
let f = ['LISTENING', 'WATCHING', 'LISTENING', 'PLAYING', 'WATCHING'];
let status = lol[Math.floor(Math.random()*lol.length)];
client.user.setActivity(status, {type: f[Math.floor(Math.random()*f.length)]})
}, 15000) 

client.user.setPresence({ status: 'online' })
console.log(`Logged in as ${client.user.tag}!`);
});

您在ready事件上没有或接收到message对象,因此您无法从中获得公会。你将需要找到公会的ID。client.guilds.cache.get()应该做到这一点。

一旦你有了公会,你需要将fetchBans()移动到setInterval中的回调,所以它每次都会获取它。如果你在它之外获取它,当你启动机器人时,它只会获取一次,除非你重新启动你的机器人,否则它不会更新。

您可以使用异步函数,只需await即可获得结果,而不必为thens而苦苦挣扎。

如果你添加你的公会ID,下面的例子会起作用。我也添加了一些评论:

client.on('ready', () => {
// get the guild once the bot is ready
// make sure you add the guild id
const guild = client.guilds.cache.get('ADD GUILD ID HERE');
client.user.setPresence({ status: 'online' });
// run the updateStatus function every 15s
// we need to pass the client and guild
setInterval(updateStatus, 15000, client, guild);
console.log(`Logged in as ${client.user.tag}!`);
});
// helper function to pick a random element from an array
function pickOne(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
// async function that fetches the current number of bans
// and updates the status
async function updateStatus(client, guild) {
const bans = await guild.fetchBans();
const statuses = [
'status 1',
'status 2',
'status 3',
'status 4',
`this guild has ${bans.size} banned users`,
];
const activities = [
'LISTENING',
'WATCHING',
'LISTENING',
'PLAYING',
'WATCHING',
];
client.user.setActivity(pickOne(statuses), {
type: pickOne(activities),
});
}

附言:一个改进是只有当你想在状态中显示禁令时才能获得禁令。

最新更新