我正在学习编写我的第一个,简单的React为基础的机器人在不和谐。我正在用python编写代码,并通过replit托管代码(因为它有一种方法可以让您的bot 24/7在线)。
我已经知道了如何响应用户的关键字/触发词,但在编写以下代码时遇到了问题:
当用户键入一个像“death”这样的“trigger”单词时,我希望bot在我为“trigger”单词创建的字典(称为“quotes”)中查找,找到“death”的关键字,该关键字的值对是一个列表,然后随机返回列表中的一个值。
这就是字典中列表的样子(不是完整的,以节省空间)
quotes = {
'death': [
'Even death is not to be feared by one who has lived wisely.',
'Ardently do today what must be done. Who knows? Tomorrow, death comes.',
'To be idle is a short road to death and to be diligent is a way of life; foolish people are idle, wise people are diligent.'
],
'wisdom':['empty'],
'hello':['Hello!']
}
我尝试使用的代码(这是与discordapi交互的代码,它似乎正在工作)
@client.event
async def on_message(message):
if message.author == client.user:
return
msg = message.content
for trigger_word in quotes:
if trigger_word in msg.lower():
await message.channel.send(random_quotes(quotes))
我尝试编写的额外python代码:
def random_quotes(trigger_word):
for trigger_word in quotes:
return (random.choice(trigger_word))
这将返回(在discord中使用时,bot处于联机状态)第一个key:value pair 我有(在本例中,是“死亡”一词的随机字母)。
我是在python编码方面,还是在与discordapi交互方面遗漏了什么?我在字典设置中选择了这个列表,以便更容易添加许多不同的“触发”词,所有这些词都有多种可能的响应。
谢谢!
2条答案
按热度按时间eagi6jfj1#
你会想用
dict.items()
迭代关键字对和引号列表,然后random.choice()
从关键字列表中:编辑
要支持多个关键字,您只需收集所有可能的引号,然后从中进行选择(如果一个关键字的引号多于另一个关键字的引号,这种池将提供更均匀的引号分布。)
bwntbbo32#
我不知道你是不是这个意思,但试着这样做,替换:
使用:
以及:
使用: