Car*_*tor 0 python command bots discord
I've just gotten into writing discord bots. While trying to follow online instructions and tutorials, my bot would not respond to commands. It responded perfectly fine to on_message(), but no matter what I try it won't respond to commands. I'm sure it's something simple, but I would appreciate the help.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
bot = commands.Bot(command_prefix='$')
TOKEN = '<token-here>'
@bot.event
async def on_ready():
print(f'Bot connected as {bot.user}')
@bot.event
async def on_message(message):
if message.content == 'test':
await message.channel.send('Testing 1 2 3')
@bot.command(name='go')
async def dosomething(ctx):
print("command called") #Tried putting this in help in debugging
await message.channel.send("I did something")
bot.run(TOKEN)
Run Code Online (Sandbox Code Playgroud)
小智 9
我一开始也犯了同样的错误。
@bot.event
async def on_message(message):
if message.content == 'test':
await message.channel.send('Testing 1 2 3')
Run Code Online (Sandbox Code Playgroud)
此函数覆盖 on_message 事件,因此它永远不会发送到 bot.command()
要修复它,您只需在 on_message 函数的末尾添加 await bot.process_commands(message) :
async def on_message(message):
if message.content == 'test':
await message.channel.send('Testing 1 2 3')
await bot.process_commands(message)
Run Code Online (Sandbox Code Playgroud)
尚未测试,但这应该可以解决您的问题。
好的。首先,顶部唯一需要的导入语句是from discord.ext import commands. 另外两个没有必要。
其次,我尝试自己修改你的代码,发现该on_message()函数似乎会干扰命令,因此将其删除应该会有所帮助。
第三,当我复制自己的一个工作机器人并慢慢更改所有代码直到它与您的相同时,我才发现这一点。由于某种原因,当我复制并粘贴你的代码时,Python 不喜欢它。我以前从未见过这样的事情,所以老实说,除了您的代码是正确的并且只要您删除该on_message()函数就应该可以工作之外,我真的不知道该说什么。
这是我工作的最终代码:
from discord.ext import commands
bot = commands.Bot(command_prefix="$")
TOKEN = "<token-here>"
@bot.event
async def on_ready():
print(f'Bot connected as {bot.user}')
@bot.command()
async def dosomething(ctx):
await ctx.send("I did something")
bot.run(TOKEN)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我对代码进行的唯一更改是删除了顶部的冗余导入,并删除了该on_message()函数。它在我这边工作得非常完美,所以我建议您在新文件中像这样重新输入它,看看是否有效。
如果这对您不起作用,那么我的下一个猜测是您的安装存在问题discord.py,因此您可以尝试卸载它,然后重新安装。
如果这些都没有帮助,请告诉我,我会看看是否可以帮助您找到其他可能导致问题的原因。