Discord.py机器人仅响应*b命令,其余命令失效问题求助
问题原因与解决方案
嘿,我一眼就看出问题所在啦——你重复定义了多个on_message事件处理器!在Discord.py里,当你多次注册同一个事件(比如on_message)时,只有最后一个注册的会生效,前面的都会被覆盖掉。这就是为什么只有最后写的*b命令能正常响应,而*h、*a、*m都没动静的原因。
下面给你两种修复方案,选一种你觉得顺手的就行:
方案一:合并所有逻辑到同一个on_message事件
把所有命令的判断都放到同一个on_message函数里,这样所有命令都会被触发检查:
import discord import os import random client = discord.Client() anyphotos = [<你的Imgur链接列表>] mphotos = [<你的Imgur链接列表>] bphotos = [<你的Imgur链接列表>] @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return # 处理*h命令 if message.content.startswith('*h'): await message.channel.send("hello!") # 处理*a命令 elif message.content.startswith('*a'): await message.channel.send(random.choice(anyphotos)) # 处理*m命令 elif message.content.startswith('*m'): await message.channel.send(random.choice(mphotos)) # 处理*b命令 elif message.content.startswith('*b'): await message.channel.send(random.choice(bphotos)) client.run('<你的token>')
方案二:使用Discord.py的命令装饰器(更推荐)
Discord.py提供了专门的命令装饰器@client.command(),这种方式更清晰,也更符合官方推荐的写法,还能自动处理命令前缀、参数等:
import discord from discord.ext import commands import random # 这里指定命令前缀为*,和你原来的一致 client = commands.Bot(command_prefix='*') anyphotos = [<你的Imgur链接列表>] mphotos = [<你的Imgur链接列表>] bphotos = [<你的Imgur链接列表>] @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) # *h命令 @client.command() async def h(ctx): await ctx.send("hello!") # *a命令 @client.command() async def a(ctx): await ctx.send(random.choice(anyphotos)) # *m命令 @client.command() async def m(ctx): await ctx.send(random.choice(mphotos)) # *b命令 @client.command() async def b(ctx): await ctx.send(random.choice(bphotos)) client.run('<你的token>')
注意用命令装饰器的时候,需要从discord.ext导入commands模块,并且把原来的discord.Client()换成commands.Bot()哦。
内容的提问来源于stack exchange,提问作者ayth3ns
相关产品推荐
相关产品推荐

