在不和谐重写中随机将人与频道配对



我目前正在尝试为机器人制作一个命令,该命令允许我在 Discord 中获取用户列表,随机配对,然后将每对分配给他们自己的频道,只有他们可以访问。

到目前为止,我有代码能够获取用户列表,但是每当我运行它,传入用户 ID 时,它都会给出错误"Nonetype 没有属性'add_roles'"。

这是有问题的函数:

async def startDraft(context, *users):
#Take a list of users of an even number, and assign them randomly in pairs
#Give each of these pairs a private #, then use that to assign them roles, and thereby rooms.
if not users or len(users)%2 is not 0:
context.say("Malformed command. Please see the help for this command. (Type !help startDraft)")
pass
userList = []
for user in users:
userList.append(client.get_user(user))
random.shuffle(userList)
pairList = []
guild = context.guild
for i in range(int(len(users)/2)):
pairList.append((userList[i*2], userList[i*2+1]))
for i in range(len(pairList)):
pairRole = await guild.create_role(name="draft"+str(i))
pairList[i][0].add_roles(pairRole)
pairList[i][1].add_roles(pairRole)
overwrites = {guild.default_role: discord.PermissionOverwrite(read_messages=False),
pairRole: discord.PermissionOverwrite(read_messages=True)}
await guild.create_text_channel(name="draft"+str(i),overwrites=overwrites)

我们可以使用zip聚类习语(zip(*[iter(users)]*2)(来生成对。我们还可以使用转换器直接从命令中获取Member对象

import discord
from dicord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.command()
async def startDraft(ctx, *users: discord.Member):
if not users or len(users)%2:
await ctx.send("Malformed command. Please see the help for this command. "
"(Type !help startDraft)")  # send not say
return  # return to end execution
guild = ctx.guild
users = random.sample(users, k=len(users))  # users is a tuple so can't be shuffled
pairs = zip(*[iter(users)]*2)  # Could also be it = iter(users); zip(it, it)
for i, (user1, user2) in enumerate(pairs):
name = "draft{}".format(i)
pairRole = await guild.create_role(name=name)
await user1.add_roles(pairRole)  # add_roles is a coroutine, so you must use await
await user2.add_roles(pairRole)
overwrites = {guild.default_role: discord.PermissionOverwrite(read_messages=False),
pairRole: discord.PermissionOverwrite(read_messages=True)}
await guild.create_text_channel(name=name, overwrites=overwrites)
bot.run("Token")

最新更新