python—当值是字典中的列表时,如何调用该值以与discordapi一起使用

u4dcyp6a  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(323)

我正在学习编写我的第一个,简单的React为基础的机器人在不和谐。我正在用python编写代码,并通过replit托管代码(因为它有一种方法可以让您的bot 24/7在线)。
我已经知道了如何响应用户的关键字/触发词,但在编写以下代码时遇到了问题:
当用户键入一个像“death”这样的“trigger”单词时,我希望bot在我为“trigger”单词创建的字典(称为“quotes”)中查找,找到“death”的关键字,该关键字的值对是一个列表,然后随机返回列表中的一个值。
这就是字典中列表的样子(不是完整的,以节省空间)

  1. quotes = {
  2. 'death': [
  3. 'Even death is not to be feared by one who has lived wisely.',
  4. 'Ardently do today what must be done. Who knows? Tomorrow, death comes.',
  5. '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.'
  6. ],
  7. 'wisdom':['empty'],
  8. 'hello':['Hello!']
  9. }

我尝试使用的代码(这是与discordapi交互的代码,它似乎正在工作)

  1. @client.event
  2. async def on_message(message):
  3. if message.author == client.user:
  4. return
  5. msg = message.content
  6. for trigger_word in quotes:
  7. if trigger_word in msg.lower():
  8. await message.channel.send(random_quotes(quotes))

我尝试编写的额外python代码:

  1. def random_quotes(trigger_word):
  2. for trigger_word in quotes:
  3. return (random.choice(trigger_word))

这将返回(在discord中使用时,bot处于联机状态)第一个key:value pair 我有(在本例中,是“死亡”一词的随机字母)。
我是在python编码方面,还是在与discordapi交互方面遗漏了什么?我在字典设置中选择了这个列表,以便更容易添加许多不同的“触发”词,所有这些词都有多种可能的响应。
谢谢!

eagi6jfj

eagi6jfj1#

你会想用 dict.items() 迭代关键字对和引号列表,然后 random.choice() 从关键字列表中:

  1. import random
  2. quotes = {
  3. "death": [
  4. "Even death is not to be feared by one who has lived wisely.",
  5. "Ardently do today what must be done. Who knows? Tomorrow, death comes.",
  6. "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.",
  7. ],
  8. "wisdom": ["empty"],
  9. "hello": ["Hello!"],
  10. }
  11. @client.event
  12. async def on_message(message):
  13. if message.author == client.user:
  14. return
  15. msg = message.content
  16. for trigger_word, quote_texts in quotes.items():
  17. if trigger_word in msg.lower():
  18. quote = random.choice(quote_texts)
  19. await message.channel.send(quote)
  20. break # only trigger on one word per message

编辑

要支持多个关键字,您只需收集所有可能的引号,然后从中进行选择(如果一个关键字的引号多于另一个关键字的引号,这种池将提供更均匀的引号分布。)

  1. @client.event
  2. async def on_message(message):
  3. if message.author == client.user:
  4. return
  5. msg = message.content
  6. possible_quotes = []
  7. for trigger_word, quote_texts in quotes.items():
  8. if trigger_word in msg.lower():
  9. possible_quotes.extend(quote_texts)
  10. if possible_quotes:
  11. quote = random.choice(possible_quotes)
  12. await message.channel.send(quote)
展开查看全部
bwntbbo3

bwntbbo32#

我不知道你是不是这个意思,但试着这样做,替换:

  1. await message.channel.send(random_quotes(quotes))

使用:

  1. await message.channel.send(random_quotes(trigger_word))

以及:

  1. for trigger_word in quotes:
  2. return (random.choice(trigger_word))

使用:

  1. return random.choice(quotes[trigger_word])

相关问题