discord.py - 如何让不和谐的机器人从列表中随机发送一系列单词,但不重复?
问题描述
我正在尝试为我的不和谐机器人指定一个程序。好的,所以我有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."]
推荐阅读
- wso2 - WSO2 EI 的 GlowRoot
- javascript - 反应:启动画面/容器
- python - Python生日代码的语法错误
- angular - 使用刀片将 Angular5 集成到现有的 Laravel 项目中
- android - Delphi10.2 arm-linux-androideabi-ld.exe 问题 + android NDK
- socket.io - Socket.io 提交按钮
- javascript - 带有 ocLazyload 的 webpack 无法同时加载控制器和模板文件
- android - 无法解决:android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
- email - Outlook 2013 邮件中的表格内的背景颜色不起作用
- security - Google 和 Microsoft 的 Docx 预览