C# Discord.NET如何通过一个命令赋予每个人一个角色?
如何通过一个命令赋予服务器上的每个人一个特定的角色?您可以使用下面的代码。有多种方法可以改进命令的功能,所以不妨考虑一下C# Discord.NET如何通过一个命令赋予每个人一个角色?,c#,discord,roles,discord.net,C#,Discord,Roles,Discord.net,如何通过一个命令赋予服务器上的每个人一个特定的角色?您可以使用下面的代码。有多种方法可以改进命令的功能,所以不妨考虑一下 [Command("addrole all"), Summary("Adds the Star role to all users")] public async Task AddRoleStarCommand() { // Gets all the users of the guild. Note that this may not completely /
[Command("addrole all"), Summary("Adds the Star role to all users")]
public async Task AddRoleStarCommand()
{
// Gets all the users of the guild. Note that this may not completely
// work for extremely large guilds (thousands of users).
var users = await Context.Guild.GetUsersAsync();
// Gets the role "Star".
var role = Context.Guild.Roles.FirstOrDefault(x => x.Name == "Star");
// Adds the role "Star" to each user in the guild.
foreach (IGuildUser user in users)
{
await user.AddRoleAsync(role);
}
}
请记住,要使用GetUsersAsync()
,您需要的是IGuild
,而不是SocketGuild
public async Task SocketGuildDemoCommand()
{
// Don't do this.
// Does not exist, error returned.
SocketGuild guild = Context.Guild;
var users = await guild.GetUsersAsync();
}
public async Task IGuildDemoCommand()
{
// Do this.
// Exists, should work perfectly.
IGuild guild = Context.Guild;
var users = await guild.GetUsersAsync();
}
我是Discord.NET的新手,所以我不知道如何正确编写这部分代码,我试图查找信息,但什么也没找到。我的错误是,误读了标签,并想到了另一个Discord库。将问题分解为几个部分。了解如何循环服务器的所有成员,以及如何向成员添加角色。然后将它们结合在一起。正如我所说,我是Discord.NET的新手,所以我真的不知道在哪里可以使用
GetUsersAsync()
,文档中也没有这方面的内容。@Niko我理解。我已经编辑了我的邮件并提供了解决方案。我希望这能有所帮助。是的,我试过var users=wait Context.Guild.GetUsersAsync()代码>我在GetUsersAsync()
部分出错,它说:“SocketGuiId”不包含“GetUsersAsync”的定义,并且找不到可访问的扩展方法“GetUsersAsync”接受类型为“SocketGuiId”的第一个参数是的,只是尝试了一下,现在它工作正常。非常感谢你,你真的帮助了我,而不是像其他人一样对我的问题给予-rep,祝你度过愉快的一天;)如果您有一个SocketGuild
,只需执行guild.Users
…无需将其强制转换为IGuild
,只需使用GetUsersAsync
。