apparently I am creating a simple discord reply bot and I have an error with my code. Even if I say the correct word with $ in chat, it is still using and replying to me with the else statement. I do not have this problem on the replit, but I do on my home PC, what could be the problem?
import discord
import os
from dotenv import load_dotenv
client = discord.Client(intents=discord.Intents.default())
load_dotenv()
TOKEN = 'TOKEN'
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send("Hello World!")
else:
await message.channel.send("Hello World! BUT ERROR")
@client.event
async def on_connect():
print("Bot Connected")
client.run(TOKEN)
If I understand your question correctly. I suggested that you use the following code instead for this simple task.
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.lower() == '$hello':
await message.channel.send("Hello World!")
else:
await message.channel.send("Hello World! BUT ERROR")
What I have changed here is simply using the string matching instead of startswith() function.
Your bot does not have the Message Content Intents , so it will not be able to read messages sent by users.
In discord.py 2.0, a bot must have the Message intent in order to read messages' content.
To enable Message Intents for your bot, follow these steps:
"Privileged Gateway Intents"
."Message Content Intent"
. Enable it. The next step: At the start of your bot code, you should have a line of code that creates a Client
or Bot
object, for example: client = discord.Client()
or bot = discord.Bot(...)
First, you should define a variable intents
:
intents = discord.Intents.all() # define intents
Now, add the parameter intents
to the object, like this:
client = discord.Client(intents=intents)
or:
bot = discord.Bot(..., intents=intents)
And you are all set!
Hope this helped.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.