【问题标题】:discord.py bot only responds to one commanddiscord.py bot 只响应一个命令
【发布时间】:2021-04-09 00:42:04
【问题描述】:
它只在给定时间显示其中一个命令。
如果我写!hi 或!bye 它不会工作,但如果我写!sing 它会输出la la la。
如果我切换它之前的角色,它会变成
!hi 或 !sing 不工作
但是!bye工作和说Goodbye!
import os
client = discord.Client()
@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
if message.content.startswith('!hi'):
await message.channel.send('Hello!')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!bye'):
await message.channel.send('Goodbye Friend!')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!sing'):
await message.channel.send('la la la')
client.run(os.getenv('TOKEN'))```
【问题讨论】:
标签:
python
error-handling
discord
bots
discord.py
【解决方案1】:
这是使用commands.Bot()的完美示例:
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.command()
async def hi(ctx):
await ctx.send("Hello!")
@bot.command()
async def sing(ctx):
await ctx.send("la la la!")
@bot.command()
async def bye(ctx):
await ctx.send("Goodbye friend!")
Bot() 继承自 Client(),在处理命令时提供了更多功能!
参考资料:
【解决方案2】:
只有一个事件,不要为每个命令都创建一个新事件。
@client.event
async def on_message(message):
if message.author == client.user:
return
elif message.content.startswith('!sing'):
await message.channel.send('La La la.')
elif message.content.startswith('!hi'):
await message.channel.send('Hello!')
【解决方案3】:
不要重复 on_message 事件。只有一个并将 if 语句放入这一事件中。
【解决方案4】:
您尝试使用多个事件,而不是在一个事件中使用所有事件,如下所示:
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!hi'):
await message.channel.send('Hello!')
elif message.content.startswith('!bye'):
await message.channel.send('Goodbye Friend!')
elif message.content.startswith('!sing'):
await message.channel.send('la la la')
另外,请确保在其他事件中使用 elif 而不是 if。
应该这样做。