简体   繁体   中英

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")

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("...")

在此处输入图像描述


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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM