首页 > 解决方案 > discord.py:如何检查消息是否包含列表中的文本

问题描述

我做了一个 rickroll 检测器,但它需要检查消息(定义为 i)是否包含“禁止”列表中的单词/文本 | 代码:

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)

生病将更多的东西添加到“禁止”列表中,所以这只是一个测试

标签: pythondiscorddiscord.py

解决方案


你可能想要这样做:

@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

不需要用空格分割消息来检查它是否包含某个字符串(也不需要删除<>)。此外,在您的代码中,您试图检查一个数组 ( banned) 是否包含在字符串 ( i) 中。

我不知道有什么RickRollDetector作用,但仅上面的代码就可以满足您的要求。


推荐阅读