What it really is @client.event? discord.py

2024/11/17 12:34:39

A few days ago I became interested in programming discord bots a bit. In the syntax of these programs I noticed a lot of unintelligible issues that I can not find an answer to. That's why I am asking you for help in understanding them.

All questions are based on this code:

import discord
import asyncio
from discord.ext import commandsbotToken = '***'client = commands.Bot(command_prefix = '.')@client.event
async def on_ready():print('Bot is ready!')@client.event
async def on_message(message):author = message.authorif message.content =='Hello':await client.send_message(message.channel, 'Welcome again {}!'.format(author))client.run(botToken)

What is @client.event? I found that is a event handler, but how is it worki? Why is it needed to run program? Is it somehow connected to a asyncio?

Answer

When a Client receives an event from Discord, It works out what that event is and generates, or locates, the objects that were sent by the event, such as a discord.Message for any MESSAGE_RECEIVE events, or a discord.Reaction for REACTION_ADD etc.
The client then sends the objects into the method that handles those events, but you first need to tell the client what those methods are. This is where the event decorators come in.


Decorators are, in essence, functions that take other functions as arguments. The most common one you'll see is @property. This says that the function you define should be passed into the property() function

@property
def name(self):return self._name

is the same as

def name(self):return self._namename = property(name)

This may be a bit confusing to wrap your head around, but this is how discord.py handles its events.


When you use the @client.event decorator on your on_message, what you are actually doing is saying on_message = client.event(on_message)

The internal code of discord.py for on_event is this

def event(self, coro):# Validation we don't need to worry aboutsetattr(self, coro.__name__, coro)return coro

Which means that it takes the function as its parameter, and sets a new attribute on the client itself. For our on_message example, we pass our on_message function into client.event() and it makes the client define a new client.on_message method that is the same method as our on_message.

Note: func.__name__ returns the name of that function. on_message.__name__ will return "on_message".
setattr(obj, name, value) sets an attribute on an object, so setattr(self, "foo", 100) means that self.foo will be 100.

Now that the client knows our on_message, when it receives an event saying that a message was sent, it creates the discord.Message object and passes that into client.on_message, which as we already established, is the same as our own on_message

If you wanted, you could even just skip the decorator and do this after your function, but it is less elegant than a decorator is:

on_message = client.event(on_message)
https://en.xdnf.cn/q/71217.html

Related Q&A

How to customize virtualenv shell prompt

How do you define a custom prompt to use when activating a Python virtual environment?I have a bash script for activating a virtualenv I use when calling specific Fabric commands. I want the shell pro…

How to get the percent change of values in a dataframe while caring about NaN values?

I have the following DataFrame:Date A 2015-01-01 10 2015-01-02 14 2015-01-05 NaN 2015-01-06 …

Convert CSV to YAML, with Unicode?

Im trying to convert a CSV file, containing Unicode strings, to a YAML file using Python 3.4.Currently, the YAML parser escapes my Unicode text into an ASCII string. I want the YAML parser to export t…

Why is the divide and conquer method of computing factorials so fast for large ints? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, argum…

Python calculate speed, distance, direction from 2 GPS coordinates

How do I calculate the speed, distance and direction (degrees) from 2 GPS coordinates in Python? Each point has lat, long, time.I found the Haversine distance calculation in this post:Calculate dista…

Installed gunicorn but it is not in venv/bin folder

Im new to gunicorn and trying to deploy a django website on an ubuntu. I have used: pip3 install gunicorn sudo apt-get install gunicornbut when I want to fill this file:sudo nano /etc/systemd/system/g…

Does Pythons asyncio lock.acquire maintain order?

If I have two functions doingasync with mylock.acquire():....Once the lock is released, is it guaranteed that the first to await will win, or is the order selected differently? (e.g. randomly, arbitra…

Howto ignore specific undefined variables in Pydev Eclipse

Im writing a crossplatform python script on windows using Eclipse with the Pydev plugin. The script makes use of the os.symlink() and os.readlink() methods if the current platform isnt NT. Since the os…

Faster way to calculate hexagon grid coordinates

Im using the following procedure to calculate hexagonal polygon coordinates of a given radius for a square grid of a given extent (lower left upper right):def calc_polygons(startx, starty, endx, endy,…

Why is -0.0 not the same as 0.0?

I could be missing something fundamental, but consider this interpreter session1:>>> -0.0 is 0.0 False >>> 0.0 is 0.0 True >>> -0.0 # The sign is even retained in the output…