analitics

Pages

Sunday, March 12, 2023

Python 3.11.0 : testing discord application with python bot.

Today I opened the online discord and found that the Roblox bot works without problems, so I tested another python bot this time.
Discord settings are difficult for the application because they need to generate an authentication URL to your discord server.
Go to your applications area and select your application, see this webpage.
They ssay: "OAuth2 Use Discord as an authorization system or use our API on behalf of your users. Add a redirect URI, pick your scopes, roll a D20 for good luck, and go! ... Redirects You must specify at least one URI for authentication to work. If you pass a URI in an OAuth request, it must exactly match one of the URIs you enter here. "
I select my URL from my server discord then I set the In-App Authorization with SCOPES set to bot and applications.commands .
The source code for this bot needs to be able to send messages, select the Send Messages permission.
Select the permisions for Privileged Gateway Intents section:
The result of these settings will be an URL for authentification into GENERATED URL area.
Use this URL to make authentification with your discord server.
In my case the application and the server has the same name: catafest.
This is the source code I used in a python script named catafest_bot.py.
import discord
from discord.ext import commands

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

client = commands.Bot(command_prefix='!', intents=intents)

@client.event
async def on_ready():
    print('Bot is ready!')

@client.command()
async def send_message(ctx):
# Replace CHANNEL_ID with the ID of the channel you want to send the message
    channel = client.get_channel(CHANNEL_ID) 
    await channel.send('Hello there! This is a test message.') 

client.run('app_token')
I used pip tool to install the discord python package:
pip install discord --user
I run the script with python:
python catafest_bot.py
[2023-03-12 16:18:26] [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may
not work as expected.
[2023-03-12 16:18:26] [INFO    ] discord.client: logging in using static token
[2023-03-12 16:18:27] [INFO    ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 76b32c93c4...).
Bot is ready!
I used /msg to send the command to bot, !send_message:
The result on my server is this: