Select Random xx answer python bot

不羁的心 提交于 2019-12-24 08:38:21

问题


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.



来源:https://stackoverflow.com/questions/50722715/select-random-xx-answer-python-bot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!