Select Random xx answer python bot

2019-08-12 14:38发布

问题:

How to make python bot pick a random name. For example if I provide a list of answers.

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")

回答1:

You can use random.choices (not choice) to select n items with replacement, if you are on Python 3.6+

@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")


回答2:

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)

This Python function picks 5 random elements out of a given list.

It iterates 5 times and uses a randomly selected integer to pull an element from the given list, then removes it to avoid duplicates. It uses the random module to accomplish this.

I don't know about getting it to discord, but I think this is what you were looking for.