[英]Discord js bot: Cannot send DM to users with specific role
I seem to be having serious trouble sending DM's to all users with a specific role.我似乎在向具有特定角色的所有用户发送 DM 时遇到了严重的问题。
Here is my bot code:这是我的机器人代码:
bot.on('message', async message => {
members = message.guild.roles.cache.find(role => role.id === "12345678998765").members.map(m => m.user.id);
members.forEach(member_id => {
sleep(5000).then(() => {
message.users.fetch(member_id, false).then((user) => {
user.send("some message");
});
});
});
});
This code gives me the error:这段代码给了我错误:
Cannot read properties of null (reading 'roles')
无法读取 null 的属性(读取“角色”)
on this line:在这条线上:
members = message.guild.roles.cache.find(role => role.id ===....
成员 = message.guild.roles.cache.find(role => role.id ===....
However that is not the issue.然而,这不是问题。 When I comment out the sleep command to send the message and output the member roles using:
当我注释掉发送消息的睡眠命令和 output 成员角色使用:
members.forEach(member_id => {
console.log(member_id)
//sleep(5000).then(() => {
// bot.users.fetch(member_id, false).then((user) => {
// user.send("some message");
// });
//});
});
I get a list returned in the console of all the user ID's.. So it must be returning the roles.我在控制台中返回了所有用户 ID 的列表。所以它必须返回角色。
How do I send a message to all users with a specific role ID??如何向具有特定角色 ID 的所有用户发送消息? I want to be able to loop through them and put a wait in to reduce the API requests and spam trigger.
我希望能够遍历它们并等待以减少 API 请求和垃圾邮件触发器。
To fix your first issue, message.guild
will be null
in DM.要解决您的第一个问题,
message.guild
将是 DM 中的null
。 Make sure it isn't DM, or if it has to be, choose a guild with client.guilds.cache.get("id")
.确保它不是 DM,或者如果必须是,请使用
client.guilds.cache.get("id")
选择一个公会。
bot.on("message", async message => {
let { guild } = message
if (!guild) guild = bot.guilds.cache.get("id")
//...
})
To fix your other issue, you can run GuildMember#send()
rather than getting the IDs and fetching the users要解决您的其他问题,您可以运行
GuildMember#send()
而不是获取 ID 并获取用户
bot.on("message", async message => {
let { guild } = message
if (!guild) guild = bot.guilds.cache.get("id")
let members = guild.roles.cache.get("12345678998765").members
// I used .get here because it's getting by ID
members.forEach(member => {
sleep(5000).then(() => member.send("some message"));
});
})
The above code will get all the GuildMember
s and loop through every one of them, "sleeping" for 5 seconds (if the sleep parameter is milliseconds) and send the member a DM上面的代码将获取所有
GuildMember
并循环遍历每一个,“休眠”5 秒(如果 sleep 参数为毫秒)并向成员发送 DM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.