My discord bot is not responding to my commands

Question:

import discord
import os

client = discord.Client(intents=discord.Intents.default())


@client.event
async def on_ready():
  print("We have logged in as {0.user}".format(client))


@client.event
async def on_message(message):
  if message.author == client.user:
    return

    if message.content.startswith('$hello'):
      channel = message.channel
      await channel.send('Hello!')


client.run(os.getenv('TOKEN'))

I tried to make a discord bot using discord.py. The bot comes online and everything but does not respond to my messages. Can you tell me what is wrong?

Asked By: David

||

Answers:

You seem to have an indentation error:

async def on_message(message):
  if message.author == client.user:
    return

    if message.content.startswith('$hello'):
      channel = message.channel
      await channel.send('Hello!')

The last if-statement is never going to be executed. Instead, move it one indentation back such that:

async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('$hello'):
    channel = message.channel
    await channel.send('Hello!')
Answered By: Lexpj

There are a few potential issues with the code that could be causing the Discord bot not to respond to commands.

First, the on_message event handler function is indented incorrectly. The if statement that checks if the message starts with ‘$hello’ should be at the same indentation level as the on_message function, not indented further. This is because the return statement that is indented further will cause the function to return immediately, without checking the if statement or sending a response.

Here is an example of how the on_message function should be indented:

@client.event
async def on_message(message):  
if message.author == client.user:
    return

if message.content.startswith('$hello'):
    channel = message.channel
    await channel.send('Hello!')

Another potential issue is that the TOKEN environment variable is not being set. The os.getenv function is used to get the value of the TOKEN environment variable, but if this variable is not set, the os.getenv function will return None, and the client.run function will not be able to authenticate the bot.

To fix this issue, you can set the TOKEN environment variable to the bot token that you obtained from the Discord Developer Portal. This can be done in a variety of ways, depending on your operating system and the method that you prefer to use.

Answered By: A.S
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.