Python Discord Bot - Part 1 [EN/PT-BR]

avatar
(Edited)

[EN]
Hello!!
This past week we had a couple discussions on the discord server for @hive-br about discord bots.
The first one was on general channel, where some people demonstrated interest in learning how to program, asking about different programming languages, and how to get started. I suggested to start with python and that I think that a fun way to learn python would be creating a discord bot.
The second one was on the curation channel, and started from a suggestion I made to try to make the curation of our community account more efficient. I think that if we used a queue for the posts selected by the curators, waiting for the voting power to regenerate, would be better, but I'm not sure.

Before I start, in my background I already have good experience programming in python. But I only created a simple discord bot once, just for fun, about 3 years ago. And I don't have any experience with beem, other then reading a few articles since I joined Hive.
So I decided to start writing a discord bot for curation in python and post my progress so others can learn as well. I don't know if this bot will be used for real, I'm doing it just for learning purposes and will publish all the code here. It might be useful for someone else getting started as well.

Let's get started. I suggest that you first create a test discord server, and I assume you already have one to continue. The next step is to create the bot on discord and link it to your discord server. For this, you need to go to discord's developer portal at https://discord.com/developers/applications and create a new application.

[PT-BR]
Olá!!
Essa semana passada tivemos algumas conversas no discord da @hive-br sobre bots para discord.
A primeira conversa foi no nosso canal principal, quando algumas pessoas demonstraram interesse em aprender a programar, perguntando sobre diferentes linguagens de programação, e como começar a programar. Eu sugeri python para começar, e disse que uma forma divertida de aprender python seria criando um bot para discord.
A segunda conversa foi no canal de curadoria, e começou com uma sugestão que fiz para tentar tornar a curadoria da nossa comunidade mais eficiente. Eu acho que se usar uma curadoria com fila, esperando o poder de voto se regenerar, seria melhor, mas não tenho certeza.

Antes de começar, quero dizer que ja tenho experiencia programando em python. Eu ja criei um bot bem simples para discord uma única vez de brincadeira, uns 3 anos atras. E não tenho nenhuma experiencia com beem, só o que vi foram alguns posts desde que entrei para Hive.
Então decidi começar a escrever um bot para discord em python para curadoria e vou postando meu progresso para que outros possam aprender também. Eu não sei se esse bot vai ser usado para alguma coisa, estou fazendo somente para usar como aprendizado e vou públicar todo o código aqui. Talvez seja útil para mais alguem.

Vamos começar. Eu sugiro que voce primeiro crie um servidor de teste no discord, e estou assumindo que voce ja criou um para continuar daqui. A seguir o proximo passo é criar o bot no discord e conectar com o seu servidor. Para isso voce deve ir para o portal do desenvolvedor do discord no seguinte link: https://discord.com/developers/applications e clicar em criar nova aplicação.

[EN]
In the next screen, you will see the general information, and you can add a description and tags for your app, it's optional.
[PT-BR]
Na proxima tela, voce vai ver a pagina de informações gerais e voce pode adicionar uma descrição e palavras chave, mas é opcional.

[EN]
Now on the left menu, click on OAuth2 and then URL Generator. Select the scope "bot" and then scroll the page down.
[PT-BR]
Agora no menu a esquerda, clique em OAuth2 e em seguida URL Generator. Selecione o scope "bot" e depois role a pagina para baixo.

[EN]
On Bot Permissions, I suggest selecting administrator. But you can also read about all the different permissions.
[PT-BR]
Em Bot Permissions, eu sugiro selecionar administrator. Mas voce pode ler mais sobre as diferentes permissões disponiveis.

[EN]
Keep scrolling down and you will get a link. Copy this link and open it in a new tab or window in your browser.
[PT-BR]
Continue rolando a pagina e voce vai encontrar o link. Copie este link e abre ele em uma nova aba ou janela do seu navegador.

[EN]
Select your test discord server and continue.
[PT-BR]
Selecione o seu servidor de teste e continue.

[EN]
Now your bot is already added to your server and we will start working on our python script. But there is still one more thing we will need from discord developer portal. The python script needs a token to connect from the portal. So let's generate this token now since we are here and will save it for later. So let's go back to the developers portal and click on Bot in the left menu and you will see the page below.
[PT-BR]
Agora nosso bot ja esta conectado ao servidor e nós podemos começar a trabalhar no nosso script em python. Mas tem mais uma coisa que vamos precisar do portal do desenvolvedor. O script em python precisa de um token do portal para se conectar. Vamos gerar esse token agora ja que estamos aqui e vamos salvar para depois. Vamos voltar ao portal de desenvolvedores e clicar em "Bot" no menu a esquerda e veremos a pagina abaixo.

[EN]
Click reset token and follow the steps to get your token, copy it to a notepad and save it.
Now let's start working on the python script. I'm using Visual Studio Code, but you can use any code editor you like. I'm also considering that you have python already installed. You will need to install the discordpy library and I suggest installing also dotenv library. You can do this by typing the lines below in your terminal.
[PT-BR]
Clique em reset token e siga os passos até pegar o seu token, copie para um bloco de notas e guarde.
Agora vamos começar a escrever o script em python. Eu estou usando o Visual Studio Code, mas voce pode usar o editor de sua preferencia. Estou considerando que voce ja tenha instalado python. E voce vai precisar instalar a biblioteca discordpy e eu sugiro também instalar a biblioteca dotenv. Voce instala digitando as linhas abaixo no seu terminal.

pip install discord
pip install python-dotenv

[EN]
So I'm going to use dotenv to create a separate file to hold my environment variables. The first variable will be that token we saved from discord developer portal. In your project folder, create a file named ".env", put the token inside like the example below.
[PT-BR]
Eu vou usar o dotenv para criar um arquivo separado para as minhas variaves de ambiente. A primeira variavel que vou armazenar é aquele token que guardamos do portal do desenvolvedor. Dentro da pasta do seu projeto, crie um arquivo com o nome ".env", e dentro dele coloque o token como no exemplo abaixo.

export DISCORD_TOKEN="___TOKEN YOU COPIED___"

[EN]
Now let's create our python script. I found a couple sample scripts online, I got a little bit from each and will copy below the script I used to get started.
[PT-BR]
Agora vamos criar o nosso script em python. Eu peguei uns dois exemplos que encontrei pesquisando, e com um pouco de cada, criei um para começar, que estou copiando abaixo.

# Importing libraries
import os
import discord
from dotenv import load_dotenv

# Using dotenv to load environment variables from .env file
# And getting the discord token that is saved on .env file
load_dotenv()
discordToken = os.getenv('DISCORD_TOKEN')

# Create the discord client instance
intents = discord.Intents.all()
client = discord.Client(command_prefix='!', intents=intents)

# This function will run only once when the bot loads
@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

# This function will run everytime there is a new message in one of the channels the bot has access.
# If someone types "Hi" the bot will answer "Hello" back
@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content == 'Hi':
        await message.channel.send(f'Hello')

# Run the client
client.run(discordToken)

[EN]
Here is a link to the discordpy API reference - https://discordpy.readthedocs.io/en/stable/api.html#

You can run this script from your terminal, and the bot will connect to your discord server. As you can see in the code, if you type "Hi", the bot will answer "Hello". So we got a working bot, very basic.

I'm going to end this post here. My plan is to write another post modifying this basic script and adding the code to create the curation bot. I will be using Supabase as my database and beem library to connect to the blockchain.

Hope this helps someone else. If you have any questions, feel free to ask in the comments.
See you next time!!

[PT-BR]
Aqui esta o link para a referencia do API do discordpy - https://discordpy.readthedocs.io/en/stable/api.html#

Voce pode rodar este script no seu terminal, e o bot vai conectar com o seu servidor do discord. Como voce pode ver no código, se voce escrever "Hi", o bot vai responder "Hello". E assim fizemos um bot bem basico funcionar.

Eu vou terminar este post por aqui. Meu plano é escrever mais um post modificando este script inicial, adicionando o código para criar o bot de curadoria. Eu vou usar Supabase de banco de dados e a biblioteca beem para conectar com o blockchain.

Espero que este post ajude mais alguem. Se voce tiver alguma pergunta, fique a vontade para colocar nos comentarios.
Até a próxima!!



0
0
0.000
3 comments