如何按名称查找角色并向其添加用户(discord.js) [英] How to find a role by name and add a user to it (discord.js)
问题描述
所以我正在尝试创建一个更通用并且可以添加到多个服务器的机器人.我已经设法通过使用 .find("name", "announcements")
重新格式化诸如宣布或加入消息等命令.
So I'm trying to create a bot that is more universal and can be added to more than one server. I've managed to reformat commands like announce or join messages etc. by using .find("name", "announcements")
.
我的问题是同样不适用于角色.
My problem is that the same does not work for roles.
我已经尝试了我在互联网上能找到的一些东西,例如 member.guild.roles.find("name", "Member")
或 member.guild.roles.find(role => role.name === "Member")
但这些都不起作用.各种不同的方式返回不同的错误,但他们通常会说一些类似的东西,而不是整数(我认为)或雪花.
I've tried what little I could find on the internet, such as member.guild.roles.find("name", "Member")
or member.guild.roles.find(role => role.name === "Member")
but none of these work. A variety of different ways return different errors, but they usually say something along the lines of it not being an integer (I think) or snowflake.
这是我目前正在努力的功能:
This is the function that I am currently wrestling with:
client.on('guildMemberAdd', (member) => {
var joinResponse = ("Hello **" + member.displayName + "**, welcome to **" + member.guild.name + "**!")
let role = member.guild.roles.find("name", "Member");
member.addRole(role).catch(console.error);
member.guild.channels.find('name', 'general').send(joinResponse);
简而言之,我正在寻找的是能够按名称获取角色并向其中添加用户.
In short summary, what I'm looking for is the ability to get a role by name and add a user to it.
(我几乎可以肯定这是可能的,因为像 Dyno 这样的流行机器人能够使用命令为用户添加角色.)
(I'm nearly certain it's possible, since popular bots like Dyno are capable of using commands to add roles to users.)
推荐答案
client.on('guildMemberAdd', (member) => {
const joinResponse = `Hello **${member.user.username}**, welcome to: **${member.guild.name}**!`
let role = member.guild.roles.get('Member');
if(!role) return console.log("Role doesen't exist.");
member.addRole(role);
const ch = member.guild.channels.get('general');
if(!ch) return console.log("Channel doesen't exist.");
ch.send(joinResponse);
});//You didn't have closing brackets (Could've been a problem)
首先你的字符串 joinResponse 是一个函数,你完全搞砸了合并它,我建议使用 模板文字.
First of all your string joinResponse was a function and you completely messed up merging it, I recommend using Template literal.
我使用 get 函数,因为它更易于使用和清洁,您只需将 ID 或名称作为 字符串.
I used get function since it's a lot easier to use and cleaner, you only pass ID or name as a string.
为了检查频道是否存在,我使用了 if 语句 和 感叹号 表示不存在/假.
To check if channel exists I used if statements and exclamation mark which means doesen't exist/false.
如果我帮助了你,请将此标记为答案,谢谢 <3.如果您需要任何内容,请添加评论以在 Discord 上回答或向我发送消息(您可以在我的 堆栈溢出配置文件上找到我的鉴别器).
If I helped you please mark this as answer, thanks <3. If you need anything add comment to answer or message me on Discord (You can find my discriminator on my stack overflow profile).
更多解释请点击蓝字.
这篇关于如何按名称查找角色并向其添加用户(discord.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!