hbag
hbag

Reputation: 32

Checking if any message contents match array items

I'm writing a small, joke Discord bot, and decided to lump all the keywords that my bot would give an identical response to into an array, to save time. I'm trying to figure out how I would test if any of the contents of the message match any of the keywords in the array.

client = discord.Client()

keywords=["keyword1", "keyword2", "keyword3"]


@client.event                              ######################
async def on_message(message):             # stops bot from     #
    if message.author == client.user:      # replying to itself #
        return                             ######################

    if message.content.contains(keywords):
        msg = "Hello, {0.author.mention}!".format(message)
        await client.send_message(message.channel, msg)

I was expecting the code to check the array for anything that matches the keywords in the array, but I actually just get a the following TB:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Baguette\PycharmProjects\bot\venv\lib\site-packages\discord\client.py", line 270, in _run_event
    await coro(*args, **kwargs)
  File "C:/Users/Baguette/PycharmProjects/bot/main", line 17, in on_message
    if message.content.contains(keywords):
AttributeError: 'str' object has no attribute 'contains'

Upvotes: 0

Views: 716

Answers (1)

ForceBru
ForceBru

Reputation: 44878

You can try this:

if any(keyword in message.content.lower() for keyword in keywords):
    ...  # respond accordingly here

Upvotes: 1

Related Questions