Avvio Rapido

Questa pagina fornisce una breve introduzione alla libreria. Presume che tu abbia installato la libreria. Se è il caso, vedi la sezione installazione :ref:.

Un bot semplice

Facciamo un bot che risponde a un messaggio specifico passo dopo passo.

Assomiglia a questo:

Nota

Poiché questo esempio utilizza il contenuto dei messaggi, è necessario attivare l’intento privilegiato Intents.message_content.

import discord

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('your token here')

Nominiamo questo file example_bot.py. Assicurati di non nominarlo `discord.py in quanto è in conflitto con la libreria.

Ci sono molte cose da capire, quindi andiamo un passo alla volta:

  1. La prima istruzione importa la libreria, se dovesse sollevare un ModuleNotFoundError o ImportError, verifica la sezione installazione di :ref:per installarla correttamente.

  2. In seguito, creiamo un’istanza di Client. Si tratta della nostra connessione a Discord.

  3. Utilizziamo quindi il decoratore Client.event() per registrare un evento. Questa libreria ha molti eventi. Visto che questa libreria è asincrona, facciamo uso di funzioni di richiamo.

    A callback is essentially a function that is called when something happens. In our case, the on_ready() event is called when the bot has finished logging in and setting things up and the on_message() event is called when the bot has received a message.

  4. Since the on_message() event triggers for every message received, we have to make sure that we ignore messages from ourselves. We do this by checking if the Message.author is the same as the Client.user.

  5. Afterwards, we check if the Message.content starts with '$hello'. If it does, then we send a message in the channel it was used in with 'Hello!'. This is a basic way of handling commands, which can be later automated with the discord.ext.commands framework.

  6. Finally, we run the bot with our login token. If you need help getting your token or creating a bot, look in the Creating a Bot Account section.

Now that we’ve made a bot, we have to run the bot. Luckily, this is simple since this is just a Python script, we can run it directly.

On Windows:

$ py -3 example_bot.py

On other systems:

$ python3 example_bot.py

Now you can try playing around with your basic bot.

A Minimal Bot with Slash Commands

As a continuation, let’s create a bot that registers a simple slash command!

Assomiglia a questo:

import discord

bot = discord.Bot()

@bot.event
async def on_ready():
    print(f"We have logged in as {bot.user}")

@bot.slash_command(guild_ids=[your, guild_ids, here])
async def hello(ctx):
    await ctx.respond("Hello!")

bot.run("your token here")

Let’s look at the differences compared to the previous example, step-by-step:

  1. The first line remains unchanged.

  2. Next, we create an instance of Bot. This is different from Client, as it supports slash command creation and other features, while inheriting all the features of Client.

  3. We then use the Bot.slash_command() decorator to register a new slash command. The guild_ids attribute contains a list of guilds where this command will be active. If you omit it, the command will be globally available, and may take up to an hour to register.

  4. Afterwards, we trigger a response to the slash command in the form of a text reply. Please note that all slash commands must have some form of response, otherwise they will fail.

  5. Finally, we, once again, run the bot with our login token.

Congratulations! Now you have created your first slash command!