Nineteenn
Nineteenn

Reputation: 31

A Python discord bot not responding to a command

I tried making a discord bot and stumbled across an issue, the bot does not respond to commands and I have no clue what's wrong. Here's my code

import discord
from discord.ext import commands
class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))
        await client.change_presence(activity=discord.Game(name="Python"))

    async def on_message(self, message):
        print('Message from {0.author}: {0.content}'.format(message))
        await bot.process_commands(message)


client = MyClient()
client.run("Token Here")
bot = commands.Bot(command_prefix='!')

@bot.command()
async def test(ctx):
    await ctx.send("Sup")

Upvotes: 0

Views: 673

Answers (1)

Yohann Boniface
Yohann Boniface

Reputation: 594

You are currently mixing a discord.Client with a commands.bot. Discord.py provides multiples ways to creates bots that are not compatibles each other.

Moreover, client.run is blocking, and should be at the end of your script.!

import discord
from discord.ext import commands


class MyClient(commands.Bot):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))
        await client.change_presence(activity=discord.Game(name="Python"))

    async def on_message(self, message):
        print('Message from {0.author}: {0.content}'.format(message))
        await self.process_commands(message)


client = MyClient(command_prefix='!')


@client.command()
async def test(ctx):
    await ctx.send("Sup")


client.run("...")

enter image description here


Note that you are not obligated to subclass the commands.Bot class given by the library.

Here is an other exemple that don't use subclassing:

import discord
from discord.ext import commands


client = commands.Bot(command_prefix='!')


@client.event
async def on_ready():
    print('Logged on as {0}!'.format(client.user))
    await client.change_presence(activity=discord.Game(name="Python"))


@client.event
async def on_message(message):
    print('Message from {0.author}: {0.content}'.format(message))
    await client.process_commands(message)


@client.command()
async def test(ctx):
    await ctx.send("Sup")


client.run("...")

Using the second approach might be beneficial if you just started to learn dpy, and can work when you dont have a lot of commands. However, for bigger projects, the first approach will help to organise your bot by using cogs for commands and events.

Upvotes: 3

Related Questions