选择Random xx answer python bot

时间:2018-06-06 14:17:36

标签: python python-3.x discord discord.py

如何让python bot选择一个随机名称。例如,如果我提供一个列表 答案。

answers = ["apple", "ball", "cat", "dog", "elephant", "frog", "gun"]

@bot.command()  
async def choose(k : int):
    """Chooses between multiple choices."""
    if 0 <= k <= 50:
        await bot.say("This is your random {} pick".format(k))
        embed = discord.Embed(description='\n'.join(random.choices(answers, k=k)))
        await bot.say(embed=embed)
    else:
        await bot.say("Invalid number")

2 个答案:

答案 0 :(得分:2)

如果您使用的是Python 3.6 +,则可以使用here(而不是choice)来选择替换的n项目

@bot.command()  
async def choose(k : int):
    """Chooses between multiple choices."""
    if 0 <= k <= 50:
        await bot.say("This is your random {} pick".format(k))
        embed = discord.Embed(description='\n'.join(random.choices(answers, k=k)))
        await bot.say(embed=embed)
    else:
        await bot.say("Invalid number")

@choose.error
def choose_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await bot.say("Please specify how many")

答案 1 :(得分:-1)

import random 

answers = ["apple", "ball", "cat", "dog", "elephant", "frog", "gun"]

def pick5(listOfAnswers):
    print("This is your random 5 pick:")

    for i in range(0, 5):
        myInt = random.randint(0,len(listOfAnswers)-1)
        print(listOfAnswers[myInt])
        listOfAnswers.remove(listOfAnswers[myInt])

pick5(answers)

这个Python函数从给定列表中选取5个随机元素。

迭代5次并使用随机选择的整数从给定列表中提取元素,然后将其删除以避免重复。它使用随机模块来实现这一目标。

我不知道让它变得不和谐,但我认为这就是你要找的东西。