How can I get a discord bot to send a message if a command is said?

Question:

I’m making a discord bot using Python but none of the commands that should be running are running. I’ve traced it down to the if command below:

  if message.content.startswith("$hello"): # <<<<<< This command is causing issues!
    print("Command detected: $hello")
    await message.channel.send('Hello there! I am a bot. Thats it.')

$hello is supposed to say in the chat "Hello there! I am a bot. Thats it."
However, the if command doesnt work, and even if $hello is said, it doesn’t run what it is supposed to.

Here is the entire code itself:


import discord
import os

client = discord.Client(intents=discord.Intents(messages=True))


@client.event
async def on_ready():
  print('Logged in as {0.user}'.format(client))


@client.event
async def on_message(message):
  print("Message detected.")
  if message.author == client.user:
    print("Returning...")
    return
  print("User message confirmed to not be a bot.")
  if message.content.startswith("$hello"): #<<< This is causing issues!
    print("Command detected: $hello")
    await message.channel.send('Hello there! I am a bot. Thats it.')

# imagine there is a run command here, with the token
# im not putting it here since its a security risk
# the run bot command works

I’ve tried using different types of commands, like startswith and == contains but it doesn’t print the hello message. Anyone got any idea how to get it working?

Asked By: donut28

||

Answers:

import discord
import os
#make sure to set up your command syntax and set your intents so the bot can read messages
client= commands.Bot(command_prefix='$', intents=discord.Intents.default())
client.remove_command("help")


#don't use on_message for commands, it's gonna cause problems.
#instead, use the command funtion here
@client.command()
async def command(ctx):
    ctx.channel.send("command is working!")

client.run("token")
``` that should work 
Answered By: Sean Gilbert

Intents.messages is not the same as Intents.message_content!

messages:

Whether guild and direct message related events are enabled.

This is a shortcut to set or get both guild_messages and dm_messages.

message_content:

Whether message content, attachments, embeds and components will be available in messages

You’re missing message_content.

Answered By: stijndcl
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.