Search code examples
pythondiscorddiscord.py

discord.py is launching but not responding to messages


import discord
from discord import Intents, Message, Client
from discord.ext import commands
import os
from dotenv import load_dotenv
from pathlib import Path
from random import randint

#launchingbetween
dotenv_path = Path('C:/Users/USER/OneDrive/phyton/discordbot/venv/bot/.env')
load_dotenv(dotenv_path=dotenv_path)
TOKEN = os.getenv('DISCORD_TOKEN')

intents = discord.Intents.default()
intents.members = True
intents.message_content = True

client = commands.Bot(command_prefix=',', intents=intents)

@client.event
async def on_ready():
    print("the bot is here")

client.run(token=TOKEN)
#launchingbetween

@client.event
async def on_message(self, message=discord.Message):
    if message.content == "hi":
        await message.channel.send("hello")
    else:
        return

Everything other than the last 6 lines works. The message appears in terminal, bot becomes online. However, and the bot does not respond to messages; it does not give any errors, it just doesn't work. And it is not about permissions or anything; the bot used to work on the same server.


Solution

    • Your on_message method should be declared before the client.run.
    • self also have to be removed from the on_message, it would make sense if you were using cogs (you might want to take a look at these).
    • In order to explicit the variable type, you want to do on_message(message: discord.Message), with a : and not with an =.

    Correct code:

    @client.event
    async def on_ready():
        print("the bot is here")
    
    @client.event
    async def on_message(message: discord.Message):
        if message.content == "hi":
            await message.channel.send("hello")
        else:
            return
    
    client.run(token=TOKEN)