首页 > 解决方案 > 在 discord.py 中使用随机模块

问题描述

通过不和谐中的启动命令,我从作者语音频道获取用户列表并将它们存储在列表中,并从该列表中删除歌曲机器人和其他相关机器人,因为我只需要用户(人而不是机器人)。

将他们的 id 更改为他们的名字后,随机提及其中一个并将其保存在变量 ( userchoosed) 中,如下所示:

userchoosed = ""
@client.command()
async def start(ctx):
    channelVoice = ctx.author.voice.channel #getting author voice channel

    member_ids = channelVoice.members #finds members connected to the channel

    ids = [] #empty list
    for member in member_ids:
        ids.append(member.mention) #change the member's id to their names and list them in ids[]
    
    listToRemove = ['<@!547905866255433758>','<@!234395307759108106>','<@!614109280508968980>','<@!806618501041225728>','<@!228537642583588864>','<@!184405311681986560>','<@!428655825817567261>']
    finalList = list(set(ids) - set(listToRemove)) #final list is a list without bots with above ids
    print(finalList) #just to see the result until this line of code
    await ctx.send("`` Lets go! ``")
    userchoosed = random.choice(finalList)
    await ctx.send(userchoosed)
    global listTouse #making a global list of Final list to use it again in other command
    listTouse = finalList
    

好的,现在我们有一个随机用户的变量。

现在我想提及另一个用户,但不等于前一个用户,因为我不希望一个用户连续两次被随机调用,所以我这样做:

@client.command()
async def next(ctx):
    user = random.choice(listTouse) #making this variable for storing another user from list
    while userchoosed == user: #check if this random user equal userchoosed(the previous user)
        user = random.choices(listTouse) #again store another random user
        userchoosed == user #change the userchoosed to user for the next time member use this command
    await ctx.send(user)#and finally mention user

我尝试了这些,但我再次得到相同的用户连续两次提及有什么问题?

标签: pythondiscord.py

解决方案


在第二个代码片段中您想要更改userchooseduser,但实际上您在倒数第二行中更改user回。userchoosed改变它应该会给你你想要的结果。


推荐阅读