Why doesn't multiple on_message events work?

后端 未结 2 622
名媛妹妹
名媛妹妹 2020-11-28 16:58

Why can\'t I have multiple on_message events?

import discord

client = discord.Client()

@client.event
async def on_ready():
    print(\'in on_r         


        
2条回答
  •  感情败类
    2020-11-28 17:06

    In python, functions are just objects.

    >>> def foo():
    ...     print ("hi")
    

    defines an object called foo, You can see this using a Python shell.

    >>> foo
    
    >>> foo()
    hi
    

    If you define a new method after, or redefine the variable foo, you lose access to the initial function.

    >>> foo = "hi"
    >>> foo
    hi
    >>> foo()
    Traceback ...:
        file "" ...
    TypeError: 'str' object is not callable
    

    How the @client.event decorator works is it tells your client that new messages should be piped into the messages, and well, if the method gets redefined, it means the old method is lost.

    >>> @bot.event
    ... async def on_message(m):
    ...     print(1)
    ...
    >>> bot.on_message(None) # @bot.event makes the bot define it's own method
    1
    >>> @bot.event
    ... async def on_message(m):
    ...     print(2)
    ...
    >>> bot.on_message(None) # bot's own method was redefined.
    2
    

提交回复
热议问题