首页 > 解决方案 > 如何让不和谐的机器人从列表中随机发送一系列单词,但不重复?

问题描述

我正在尝试为我的不和谐机器人指定一个程序。好的,所以我有fun_facts下面的这个列表,当用户输入命令!funfact时,我希望我的机器人从列表中发送一个随机事实,但不重复。所以每次执行命令时,使用的事实不会重复并再次发送。

这是代码:任何改进它的帮助将不胜感激。

@client.event
async def on_message(message):

    fun_facts = ["Banging your head against a wall for one hour burns 150 calories.",
                 "Snakes can help predict earthquakes.",
                 "7% of American adults believe that chocolate milk comes from brown cows.",
                 "If you lift a kangaroo’s tail off the ground it can’t hop.",
                 "Bananas are curved because they grow towards the sun."]

        if message.content.startswith("!funfact"):
            await message.channel.send(random.choice(fun_facts))

标签: discord.py

解决方案


试试这个,每次都会使用不同的事实,直到列表用完为止。每次您的机器人重新启动时,您也会获得刷新列表。

all_fun_facts = ["Banging your head against a wall for one hour burns 150 calories.",
                 "Snakes can help predict earthquakes.",
                 "7% of American adults believe that chocolate milk comes from brown cows.",
                 "If you lift a kangaroo’s tail off the ground it can’t hop.",
                 "Bananas are curved because they grow towards the sun."]
fun_facts = all_fun_facts.copy()

@client.event
async def on_message(message):

        if message.content.startswith("!funfact"):
            try:
                fact = random.choice(fun_facts)
            except IndexError: # the list of fun facts is empty
                fun_facts = all_fun_facts.copy()
                fact = random.choice(fun_facts)
            await message.channel.send(fact)
            fun_facts.remove(fact)

如果您希望列表仅在为空时刷新,请尝试将列表写入文件:

from fun_facts import all_fun_facts

fun_facts = all_fun_facts.copy()

@client.event
async def on_message(message):

        if message.content.startswith("!funfact"):
            try:
                fact = random.choice(fun_facts)
            except IndexError: # the list of fun facts is empty
                fun_facts = all_fun_facts.copy()
                fact = random.choice(fun_facts)
            await message.channel.send(fact)
            fun_facts.remove(fact)

示例文件存储 ( fun_facts.py)

__all__ = ['all_fun_facts']
all_fun_facts = ["Banging your head against a wall for one hour burns 150 calories.",
                 "Snakes can help predict earthquakes.",
                 "7% of American adults believe that chocolate milk comes from brown cows.",
                 "If you lift a kangaroo’s tail off the ground it can’t hop.",
                 "Bananas are curved because they grow towards the sun."]

推荐阅读