简体   繁体   中英

(PYTHON DISCORD BOT) What does @[].event and @[].command() do?

I'm coding a simple discord bot and I'm new in that. I use @.event or @.command() before I define a function like that because I saw them on a video:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="!", description="I'M HERE TO SERVE YOU.",)

@bot.event
async def on_ready():
   print(f"BOT {bot.user.name} IS READY TO MISSION.")

@client.command() 
async def ping(ctx):
   await ctx.send(f"PONG! {round(client.latency * 1000)}ms")

I'm wondering what does them do. Is there a way to work this codes without using them?

Those are discord py's decorators and are used to declare the some information for the function that follows.

The @.event is used when you want your bot to do something when a event happens. Such as a on_typing event, on_message event or a on_member_join event. When ones of these events happen, you bot will do what ever you wrote. Your on_ready event is a event your bot waits for and will do what you wrote after.

The @.command() is used when you want to create commands that users in discord can type in and executed your code. So when a user does your defined prefix and the keywords after, the @.command will make your code execute your function. In the () you can pass in things like ctx, that can be used in your function, read the documentation about that.

They are very easy to use once you get your head around and can be used a lot in your program. I don't think you can create commands or events without the decorators. Just remember if you are making a command, add @.command above it. And if it's a event like on_message, add @.event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM