随机将人配对到不和谐的rewri频道

2024-07-08 17:15:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

到目前为止,我的代码能够获取用户列表,但是每当我运行它时,如果传入用户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)

Tags: of用户inaddforlencontextusers
1条回答
网友
1楼 · 发布于 2024-07-08 17:15:58

我们可以使用zip聚类习惯用法(zip(*[iter(users)]*2))来生成对。我们还可以使用converter直接从命令中获取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")

相关问题 更多 >

    热门问题