Discord bot message event handler not triggering with OpenAI integration

Issue with Discord Bot Message Detection

I’m building a Discord bot that should respond to messages using OpenAI’s API, but the message event isn’t being detected properly. The bot connects successfully and shows as online, but nothing happens when I send commands.

import openai
import discord

openai.api_key = "your_api_key_here"

bot = discord.Client()

@bot.event
async def on_ready():
    print('Bot is running')

async def on_message(msg):
    if msg.content.startswith("!query"):
        print('Message detected')
        
        user_input = msg.content[7:]
        
        result = openai.Completion.create(
            engine="text-davinci-003",
            prompt=f"{user_input}\n",
            temperature=0.5,
            max_tokens=512,
            top_p=1,
            frequency_penalty=0.2,
            presence_penalty=0.1
        )
        
        await msg.channel.send(result.choices[0].text)

bot.run('your_bot_token')

The bot connects fine and prints ‘Bot is running’, but when I type !query followed by text, nothing happens. No errors show up in the console either. I’ve double checked that my API key and bot token are correct in the actual code.

What could be preventing the message event from working?

yeah, that’s the decorator issue neo mentioned. made the same mistake myself lol. quick heads up tho - that OpenAI completion API is deprecated. you’ll want to switch to the chat completions API or it’ll stop working eventually. but fix that @bot.event decorator first and you should be good.

You’re missing the @bot.event decorator on your on_message function. Without it, Discord.py doesn’t know this is an event handler, so it never gets called. Fix it like this: python @bot.event async def on_message(msg): if msg.content.startswith("!query"): # rest of your code I had this exact same problem when I started making Discord bots. The function worked fine but did nothing because Discord.py didn’t know it was supposed to handle events. Also, add if msg.author == bot.user: return to ignore the bot’s own messages and prevent loops, though that’s not your current problem.

The decorator issue is spot on - that’s your main problem. Add @bot.event to your on_message function and it’ll start working. I hit the same thing integrating OpenAI with my bot last year. Quick heads up: text-davinci-003 got deprecated ages ago. Switch to the ChatCompletion API with gpt-3.5-turbo or gpt-4 instead. Response structure’s a bit different but way better performance. Also check your bot permissions in Discord’s developer portal - you need ‘Send Messages’ and ‘Read Message History’ enabled.