gpt4 book ai didi

discord.py - 如何让不和谐机器人从列表中随机发送一系列单词,但不重复发送?

转载 作者:行者123 更新时间:2023-12-04 09:48:05 25 4
gpt4 key购买 nike

我正在尝试为我的不和谐机器人指定一个程序。
好的,我有这个列表 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))

最佳答案

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

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."]

关于discord.py - 如何让不和谐机器人从列表中随机发送一系列单词,但不重复发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62051537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com