Como hacer un bot en Discord | Parte 3 - Programando el bot

in #spanish6 years ago

Saludos, primero como es de costumbre debo recordarte que si no has leído las primeras dos partes del tutorial te recomiendo las leas, ya que sin haberlas leído no comprenderás muy bien esta parte del tutorial.

Esta es la tercera parte de la serie de tutoriales que estuve haciendo para realizar un bot de Discord en Python la cual está dividida en tres partes:

1° - Crear la aplicación y añadirla a un servidor (Link: https://steemit.com/discord/@eleiber/como-hacer-un-bot-en-discord--parte-1---creando-la-aplicacin )

2° - Instalar las aplicaciones necesarias y los módulos de Discord (Link: https://steemit.com/spanish/@eleiber/como-hacer-un-bot-en-discord-or-parte-2-instalando-las-apps-y-modulos )

3° - Programación de un bot sencillo con comandos básicos (Este tutorial)

Una vez tu cerebro está preparado para quemar neuronas programando, podremos empezar.

1 - Crear archivo: Primero debes abrir "IDLE" el cual es el editor de código, depurador y compilador integrado de Python, personalmente no uso este editor, pero es bueno para empezar a programar.

Una vez abierto IDLE debes crear el archivo ".py", guárdalo en tu directorio de preferencia y vuelve a la ventana del IDLE

Nota: si tienes dos ventanas de IDLE, no las confundas, la que dice Python 3.6 Shell es la ventana que ejecuta el código, y la que dice el nombre de tu archivo es la que edita el código.

2 - Importar módulos: Las primeras lineas de código que debes hacer son las que cargan los módulos de Discord en el bot.

La línea import discord carga el módulo de Discord en general.

La línea import asyncio carga el módulo AsyncIO el cual es útil en diversas ocasiones para el módulo "Discord.py"

La línea from discord.ext import commands carga desde el módulo de Discord la extensión "commands" la cual nos hará el trabajo mucho más fácil.

3 - Configurar prefijo y descripción: La extensión "commands" de "Discord.py" tiene este sistema de comandos el cual también tiene un comando help por defecto. Para configurarlo debes hacer lo siguiente:

La variable description, como su nombre lo dice, es la descripción de tu bot. Lo puedes cambiar a tu gusto,

Y en la variable bot, solo debes modificar la variable entre comillas, ese es el prefijo del bot, es decir, todos los comandos que empiecen con ese prefijo serán detectados como comandos en el bot.

4 - Cuando el bot se encienda: esta es una condición, que significa "cuando el bot cargue completamente", hay usuarios que hacen que el bot mande un mensaje en el server cuando se encienda, pero no recomiendo que lo hagan, ya que al principio estarán desconectado y conectado el bot varias veces. Yo lo que hago es poner un mensaje en la consola:

Ahí lo que hace el bot es que cuando carga completamente, el bot muestra un mensaje así:

Siendo bot.user.id la ID del bot, y bot.user.name, el nombre del bot, y el texto entre comillas en la variable game es el estado de jugando del bot.

5 - Comando avatar: Ahora vamos a hacer un comando simple, que muestre el link hacia el avatar del usuario que lo mande. Para ello necesitan escribir lo siguiente:

Si quieres otro nombre para el comando simplemente debes cambiar el texto en azul, preferiblemente escríbelo todo en minúsculas.

Y si quieres cambiar la descripción del comando, cambia el texto dentro de las 6 comillas dobles verdes.

En la línea await ctx.send(ctx.author.avatar_url) "await" es una "corrutina" que necesitan ciertas funciones de Discord.py, "ctx" es el contexto del mensaje, es decir, al poner "ctx.send" lo que hace es enviar el mensaje en el mismo canal donde se recibió el comando. Y ctx.author.avatar_url es la variable que representa la foto de perfil que tenía el autor del mensaje al momento del comando.

(Para más información acerca de todas estas variables, mira https://discordpy.readthedocs.io/en/rewrite/api.html)

6 - Configurar token y ejecutar el bot: ahora, para finalizar, debes configurar el token de tu bot para ejecutarlo, si no sabes como conseguir el token, deberías ver la parte 1 de esta serie de tutoriales. Una vez tengas el token, haz está línea de código al final de todo el código.

Dentro de las comillas simples debes pegar tu token. Una vez lo hayas pegado, solo debes presionar F5 y darle aceptar, entonces se ejecutará el bot, y una vez aparezca "Conectado como" es porque ya el bot cargó. Para ello puedes comprobar que funcione usando primero el comando "help", en mi caso sería "st!help"

Una vez comprobado que está funcionando puedes usar el comando "avatar"

Pues al parecer todo bien, y si a ti te aparece un error que dice "discord.Forbidden" o algo así en la consola, es porque el bot no tiene permisos para escribir en ese canal.

Hemos finalizado la serie de tutoriales de como hacer un bot de Discord muy sencillo en Python, si quieres que haga otra parte explicando como hacer un comando específico, o alguna duda que tengas, siempre puedes dejarlo en los comentarios.

Eleiber#8347

Las imágenes de Discord son propiedad de https://discordapp.com/

Sort:  

Interesante tu serie de tutoriales @Eleiber. Saludos.

Congratulations @eleiber! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Congratulations @eleiber! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Congratulations @eleiber! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:
SteemitBoard and the Veterans on Steemit - The First Community Badge.

Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Congratulations @eleiber! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Congratulations @eleiber! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @eleiber! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You made more than 600 upvotes. Your next target is to reach 700 upvotes.

Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

Trick or Treat - Publish your scariest halloween story and win a new badge
SteemitBoard notifications improved

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @eleiber! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You made more than 700 upvotes. Your next target is to reach 800 upvotes.

Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

SteemFest³ - SteemitBoard Contest Teaser
The new Steemfest³ Award is ready!

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @eleiber! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You made more than 800 upvotes. Your next target is to reach 900 upvotes.

Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @steemitboard:

Saint Nicholas challenge for good boys and girls

Support SteemitBoard's project! Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.28
TRX 0.13
JST 0.032
BTC 63041.44
ETH 2985.81
USDT 1.00
SBD 3.61