Discord.NET 如何通过一个命令给每个人一个角色?
Discord.NET How can I give every person a role by one command?
如何仅通过一个命令就可以为服务器上的每个人分配特定的角色?
您可以使用下面的代码来完成。有多种方法可以改进命令的功能,所以不妨考虑一下。
[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();
}
如何仅通过一个命令就可以为服务器上的每个人分配特定的角色?
您可以使用下面的代码来完成。有多种方法可以改进命令的功能,所以不妨考虑一下。
[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();
}