Discord bot Wikipedia lookup command breaks other bot functions

I’m working on a Discord bot and I found some code that searches Wikipedia for keywords. The issue is when I add this code to my bot, none of my other commands work anymore. I’m not sure what’s causing this problem.

@client.event
async def on_message(msg):
    text_parts = msg.content.split()
    if text_parts[0].lower() == "!search":
       search_terms = text_parts[1:]
       try:
           await client.send_message(msg.channel, get_wiki_info(search_terms))
       except wikipedia.exceptions.DisambiguationError as error:
           await client.send_message(msg.channel, error)

I thought about converting this to use @client.command instead but I’m not sure how to change the code properly. Also there’s another issue where it only processes single words, so when I try to search for something like ‘ice cream’ it only uses ‘cream’ and gives me a disambiguation error. Any help would be great!

Your Wikipedia search breaks because you’re splitting the search terms wrong. When you do text_parts[1:] and pass that list to get_wiki_info(), it’s probably only grabbing the last element. Fix it by joining the terms back together: ' '.join(text_parts[1:]). That’ll handle your ice cream search problem. Also, client.send_message() is deprecated - use msg.channel.send() for newer discord.py versions. Commands would be cleaner if you want to refactor, but fixing the string handling solves your immediate issue.

Converting to @client.command is straightforward and fixes both problems. Replace your on_message event with this:

@client.command()
async def search(ctx, *, query):
    try:
        await ctx.send(get_wiki_info(query))
    except wikipedia.exceptions.DisambiguationError as error:
        await ctx.send(error)

The * parameter grabs everything after the command as one string, so “ice cream” stays together. Use ctx.send() instead of the deprecated client.send_message(). This completely eliminates the on_message interference instead of just working around it. Just make sure you’ve got bot.run() with command_prefix set up properly.

Ah, found the problem! on_message intercepts everything and blocks your other commands. Just add await client.process_commands(msg) at the end of your on_message function - that’ll let other commands run after yours.