Search code examples
pythonpython-3.xwildcardstring-matchingdiscord.py

How to match exact strings and wildcard strings


Say for example I have this:

import discord, asyncio, time

client = discord.Client()

@client.event
async def on_message(message):
    if message.content.lower().startswith("!test"):
        await client.send_message(message.channel,'test')

client.run('clienttokenhere')

I would like to do be able to to do 2 things:

1) Make it so that if and only if the user types in exactly !test and nothing else, it will print out test in the channel

2) Make it so that if the user types in !test first followed by a space and at least one other string character, it wlll print out test -- so for examples: a) !test will not print out anything, b) !test (!test followed by a single space) will not print out anything, c) !test1 will not print out anything, d) !testabc will not print out anything, but e) !test 1 will print out test, f) !test 123abc will print out test, g) !test a will print out test, and h) !test ?!abc123 will print out test, etc.

I only know of startswith and endswith, and far as my research tells, there's no such thing as exact and I'm not sure how to make it so that it requires a minimum number characters after a startswith


Solution

  • Use the == operator.

    1) Print test when there's only !test in the received string

    if message.content.lower() == '!test':
        await client.send_message(message.channel,'test')
    

    2) Print test followed by the string when it's followed by a string

    # If it starts with !test and a space, and the length of a list
    # separated by a space containing only non-empty strings is larger than 1,
    # print the string without the first word (which is !test)
    
    if message.content.lower().startswith("!test ") 
       and len([x for x in message.content.lower().split(' ') if x]) > 1:
        await client.send_message(message.channel, 'test ' + ' '.join(message.content.split(' ')[1:]))