I've created a Discord Bot which is very much running when started but the commands are not responsive. The code is below:
TOKEN = os.getenv('TOKEN')
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_ready():
print(f'{client.user} is now running!!')
@client.event
async def hello_message(ctx):
if ctx.author == client.user:
return
if ctx.content.startswith('$hello'):
await ctx.channel.send('Hello there!!!')
if __name__ == "__main__":
client.run(TOKEN)
When executed - the bot shows up online and prints the running message. However, it is not responding to any commands.
Using discord.Client
for commands:
In discord.py, you need to use the commands.Bot
class instead of discord.Client to handle commands effectively. The commands.Bot
class provides built-in command parsing and handling.
Using on_ready()
for commands:
The on_ready()
event is triggered when the bot is connected and ready to perform actions, but it is not meant to handle commands. You should use commands.Bot
to handle commands separately.
Here is the updated code:
import os
import discord
from discord.ext import commands
TOKEN = os.getenv('TOKEN')
# Create the bot with the command prefix
bot = commands.Bot(command_prefix='$')
# Event: Bot is ready
@bot.event
async def on_ready():
print(f'{bot.user} is now running!!')
# Command: Hello
@bot.command()
async def hello(ctx):
await ctx.send('Hello there!!!')
# Run the bot
if __name__ == "__main__":
bot.run(TOKEN)