discord.py: How to check if a message contains text from a list

Question:

I made a rickroll detector but it needs to check if the message (defined as i) contains a word/text from the "banned" list.

Code:

import discord
from discord.ext import commands
from async_rickroll_detector import RickRollDetector

banned = []
banned = ["dQw4w9WgXcQ, rW7hXs-81hM"]
BOT_TOKEN = "<TOKEN>"
RICKROLL_FOUND_MESSAGE = "⚠️ Rickroll Alert ⚠️"

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

@bot.event
async def on_ready():
   global detector
   detector = RickRollDetector()

@bot.event
async def on_message(msg):
for i in msg.content.split(" "):
    i = i.replace("<","").replace(">", "") #Removes <> that could be used to hide embeds
    if banned in i and await detector.find(i):
        await msg.reply(RICKROLL_FOUND_MESSAGE)
        break

await bot.process_commands(msg)

bot.run(BOT_TOKEN)

I’ll add more things to the "banned" list so this is just a test.

Asked By: Aritz331_

||

Answers:

You probably want to do this:

@bot.event
async def on_message(msg):
    for banned_word in banned:
        if banned_word in msg.content:
            await msg.reply(RICKROLL_FOUND_MESSAGE)
            break

There is no need to split the message by spaces to check if it contains a certain string (nor to remove <>). Also, in your code you’re trying to check if an array (banned) is contained in a string (i).

I don’t know what RickRollDetector does, but the code above alone should do what you’re asking.

Answered By: altermetax

A better way to this is use any().

@bot.event
async def on_message(msg):
   if any(x in msg.content for x in banned):
      await msg.reply(RICKROLL_FOUND_MESSAGE)

And you don’t need to use break and it is cleaner. 🙂

Answered By: MatiYo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.