为什么我不能有多个on_message事件?
import discord
client = discord.Client()
@client.event
async def on_ready():
print('in on_ready')
@client.event
async def on_message(message):
print("in on_message #1")
@client.event
async def on_message(message):
print("in on_message #2")
@client.event
async def on_message(message):
print("in on_message #3")
client.run("TOKEN")
例如,如果我在discord中键入任何内容,则始终只触发最后一个on_message.我怎样才能让这三个人都工作?
解决方法:
本机客户端无法实现
您只能有一个on_message,如果您有多个,则只会为on_message事件调用最后一个.你只需要将你的三个on_message结合起来.
import discord
client = discord.Client()
@client.event
async def on_message(message):
print("in on_message #1")
print("in on_message #2")
print("in on_message #3")
client.run("TOKEN")
像任何Python变量/函数一样(除非装饰器存储你的函数,@ client.event通过仅保留最近的回调来实现),如果多个名称相同,则最近将保留,并且所有其他名称将被覆盖.
这是一个简单的例子,我写的是为了让你广泛了解discord.py中的事件是如何工作的(注意:实际的代码并不完全像这样,因为它被重写并显着减少).
class Client:
def event(self, func):
if func.__name__ == "on_message":
self.on_message_handle = func
return func
def receive_message(self, msg):
func = getattr(self, "on_message_handle", None)
if func is not None:
func(msg)
else:
self.process_commands(msg)
client = Client()
@client.event
def on_message(msg):
print("in on_message #1")
@client.event
def on_message(msg):
print("in on_message #2")
client.receive_message("hello")
# "in on_message #2"
正如您所看到的,client.event只保留一个on_message实例.
你可以使用Bot实例
或者,如果您使用的是discord.py的ext.commands扩展,则有一种本机方式可以有多个on_message回调.您可以通过将它们定义为侦听器来实现.您最多只能有一个on_message事件和无限量的on_message侦听器.
from discord.ext import commands
bot = commands.Bot('.')
@bot.event
async def on_message(msg):
print("in on_message #1")
await bot.process_commands(msg) # so `Command` instances will still get called
@bot.listen()
async def on_message(msg):
print("in on_message #2")
@bot.listen()
async def on_message(msg):
print("in on_message #3")
bot.run("TOKEN")
收到消息后,所有on_message#1-3都将被打印.