How can I get the word in a message for the dictionary parameter?

Viewed 41

I coded a Textbot for discord, which recognizes words and gives answers. It have grown much bigger than I thought and I wanted to organize it in a dictionary insted of 200 if-else chains. How can I get the "word" for the dictionary parameter? It only says "unresolved reference "word"".

@commands.Cog.listener()
    async def on_message(self, message):
        if any(word in message.content.lower() for word in replace):
            await message.channel.send(replace[word]["answer"])
1 Answers

Try this:

replace = {"lorem": {"answer":"ipsum"}, "hello": {"answer":"world"}}

import discord 
from discord.ext import commands
from discord.ext.commands import has_permissions

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix = ".", intents=intents)

@bot.event
async def on_message(message):
    for word in message.content.lower().split(" "):
        if word in list(replace.keys()):
            await message.channel.send(replace[word]["answer"])

bot.run("PUT YOUR TOKEN HERE")

(I added a bit more so that the code runs on its own)
It just iterates through the message sent, and if there is a word found in the dictionary replace, it returns the answer (from looking at your post, it looked like you were using dictionaries with the key answer being the answer for the bot to send, so I have done that.

Related