Search code examples
pythondiscord

Python return message with multiple word list


I am making a very simple bot on discord that return a message if the bot reads simple word, whoever sends it. I would like the bot to return a 2nd message if he reads another word in a second list.

As it is, if someone type "WORD 2", it return perfecty "MESSAGE 2" but it's not working for "WORD 1" and "MESSAGE 1", nothing happen.

My code is the following :

import discord
from discord.ext import commands
from discord.utils import get
from discord.ext.commands import Bot

client = commands.Bot(command_prefix = ".")

class Myclient(discord.Client):
    async def on_ready(self):
        print('Logged on as', self.user)

    async def on_message(self, message):
        word_list = ['WORD 1']
        # don't respond to ourselves
        if message.author == self.user:
            return
        messageContent = message.content
        if len(messageContent) > 0:
            for word in word_list:
                if word in messageContent:
                    await message.channel.send('MESSAGE 1 @everyone')

    async def on_message(self, message):
        word_list = ['WORD2']
        # don't respond to ourselves
        if message.author == self.user:
            return
        messageContent = message.content
        if len(messageContent) > 0:
            for word in word_list:
                if word in messageContent:
                    await message.channel.send('MESSAGE 2 @everyone')

client = Myclient()
client.run('my token here')

Solution

  • What you can do is to simply have a dict which maps matching words to response messages:

        async def on_message(self, message):
            response_map = {'WORD1': 'MESSAGE 1 @everyone', 'WORD2':'MESSAGE 2 @everyone'}
            # don't respond to ourselves
            if message.author == self.user:
                return
            messageContent = message.content
            if len(messageContent) > 0:
                for word, message in response_map:
                    if word in messageContent:
                        await message.channel.send(message)