1Obtenir le Token
Rendez-vous sur le Discord Developer Portal et creez une nouvelle application.
Dans le menu Bot cliquez sur Reset Token. Copiez cette cle secrete dans un endroit sur et ne la partagez sous aucun pretexte.
Suivez ces etapes dans l'ordre pour configurer correctement votre bot sur Discord.
Rendez-vous sur le Discord Developer Portal et creez une nouvelle application.
Dans le menu Bot cliquez sur Reset Token. Copiez cette cle secrete dans un endroit sur et ne la partagez sous aucun pretexte.
Les intents autorisent le bot a lire les messages et analyser les membres du serveur.
Descendez vers Privileged Gateway Intents. Cochez imperativement Presence, Server Members et Message Content puis sauvegardez.
Generez le lien d'invitation pour joindre votre bot a un serveur Discord.
Allez dans OAuth2 puis URL Generator. Cochez les cases bot et applications.commands. Donnez-lui la permission Administrator et ouvrez le lien genere.
Python utilise discord.py avec une structure en Cogs. Les commandes sont hybrides pour marcher en slash et en prefixe texte.
mon_bot/
├── cogs/
│ ├── ping.py
│ ├── help.py
│ ├── profil.py
│ ├── say.py
│ ├── embed.py
│ ├── clear.py
│ └── ban.py
├── .env
└── main.py
# Installer les dependances requises
pip install discord.py python-dotenv
# Demarrer le bot
python main.py
TOKEN=InserezVotreTokenSecretIci
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
load_dotenv()
class MonBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="!", intents=discord.Intents.all())
async def setup_hook(self):
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await self.load_extension(f'cogs.{filename[:-3]}')
await self.tree.sync()
async def on_ready(self):
print(f'Connecte en tant que {self.user}')
bot = MonBot()
bot.run(os.getenv("TOKEN"))
import discord
from discord.ext import commands
class PingCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name="ping", description="Affiche la latence du bot")
async def ping(self, ctx):
latency = round(self.bot.latency * 1000)
await ctx.send(f'Pong ! Latence : {latency}ms')
async def setup(bot):
await bot.add_cog(PingCog(bot))
import discord
from discord.ext import commands
class HelpCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.remove_command("help")
@commands.hybrid_command(name="help", description="Affiche la liste des commandes")
async def help(self, ctx):
embed = discord.Embed(title="Centre d'aide du Bot", color=discord.Color.red())
embed.add_field(name="Commandes principales", value="ping, profil, say, embed, clear, ban", inline=False)
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(HelpCog(bot))
import discord
from discord.ext import commands
class ProfilCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name="profil", description="Affiche le profil d'un utilisateur")
async def profil(self, ctx, membre: discord.Member = None):
cible = membre if membre else ctx.author
embed = discord.Embed(title=f"Profil de {cible.display_name}", color=cible.color)
embed.set_thumbnail(url=cible.display_avatar.url)
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(ProfilCog(bot))
import discord
from discord.ext import commands
class SayCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name="say", description="Fait parler le bot")
async def say(self, ctx, *, message: str):
await ctx.send(message)
async def setup(bot):
await bot.add_cog(SayCog(bot))
import discord
from discord.ext import commands
class EmbedCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name="embed", description="Genere un message stylise")
async def embed_cmd(self, ctx, titre: str, description: str):
embed = discord.Embed(title=titre, description=description, color=discord.Color.red())
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(EmbedCog(bot))
import discord
from discord.ext import commands
class ClearCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name="clear", description="Supprime un nombre precis de messages")
@commands.has_permissions(manage_messages=True)
async def clear(self, ctx, nombre: int):
if nombre < 1 or nombre > 100:
return await ctx.send("Veuillez choisir un nombre entre 1 et 100.", ephemeral=True)
# Si commande textuelle on ajoute 1 pour effacer la commande elle-meme
limit = nombre if ctx.interaction else nombre + 1
await ctx.defer(ephemeral=True)
deleted = await ctx.channel.purge(limit=limit)
await ctx.send(f"{len(deleted)} messages supprimes !", ephemeral=True, delete_after=3)
async def setup(bot):
await bot.add_cog(ClearCog(bot))
import discord
from discord.ext import commands
class BanCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name="ban", description="Bannir un membre du serveur")
@commands.has_permissions(ban_members=True)
async def ban(self, ctx, membre: discord.Member, *, raison: str = "Aucune raison specifiee"):
await membre.ban(reason=raison)
await ctx.send(f"{membre.name} a ete banni. Raison : {raison}")
async def setup(bot):
await bot.add_cog(BanCog(bot))
JavaScript exploite discord.js avec une architecture modulaire. Les commandes gerent slash + texte avec une logique commune.
mon_bot/
├── commands/
│ ├── ping.js
│ ├── help.js
│ ├── profil.js
│ ├── say.js
│ ├── embed.js
│ ├── clear.js
│ └── ban.js
├── .env
├── package.json
└── bot.js
# Initialiser puis installer
npm init -y
npm install discord.js dotenv
# Demarrer le bot
node bot.js
TOKEN=InserezVotreTokenSecretIci
CLIENT_ID=InserezLIdDeLApplication
require('dotenv').config();
const { Client, Collection, REST, Routes } = require('discord.js');
const fs = require('fs');
const client = new Client({ intents: 3276799 });
client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const commandsData = [];
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
commandsData.push({ name: command.name, description: command.description, options: command.options || [] });
}
client.once('ready', async () => {
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
await rest.put(Routes.applicationCommands(process.env.CLIENT_ID), { body: commandsData });
console.log(`Connecte en tant que ${client.user.tag}`);
});
client.login(process.env.TOKEN);
module.exports = {
name: 'ping',
description: 'Affiche la latence du bot.',
async execute(context) {
const start = Date.now();
const reply = await context.reply({ content: 'Calcul en cours...', fetchReply: true });
const end = Date.now();
const latency = end - start;
const text = `Pong ! Latence : ${latency}ms`;
if (context.editReply) {
await context.editReply(text);
} else {
await reply.edit(text);
}
}
};
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: 'help',
description: 'Liste des commandes.',
async execute(context) {
const user = context.author || context.user;
const embed = new EmbedBuilder()
.setTitle('Centre d\'aide')
.setColor('#d32f2f')
.addFields(
{ name: 'Commandes', value: 'ping, profil, say, embed, clear, ban' }
)
.setFooter({ text: `Demande par ${user.username}` });
await context.reply({ embeds: [embed] });
}
};
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: 'profil',
description: 'Voir les informations utilisateur.',
options: [{ name: 'membre', type: 6, description: 'Membre a inspecter', required: false }],
async execute(context, args) {
let targetUser;
if (context.commandName) {
targetUser = context.options.getUser('membre') || context.user;
} else {
targetUser = context.mentions.users.first() || context.author;
}
const embed = new EmbedBuilder()
.setTitle(`Profil de ${targetUser.username}`)
.setThumbnail(targetUser.displayAvatarURL())
.addFields(
{ name: 'ID', value: targetUser.id },
{ name: 'Creation', value: new Date(targetUser.createdTimestamp).toLocaleDateString('fr-FR') }
);
await context.reply({ embeds: [embed] });
}
};
module.exports = {
name: 'say',
description: 'Repeter un texte.',
options: [{ name: 'message', type: 3, description: 'Texte a envoyer', required: true }],
async execute(context, args) {
let texte = '';
if (context.commandName) {
texte = context.options.getString('message');
await context.reply({ content: 'Message envoye', ephemeral: true });
await context.channel.send(texte);
} else {
texte = args.join(' ');
await context.delete();
await context.channel.send(texte);
}
}
};
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: 'embed',
description: 'Creer un embed basique.',
async execute(context, args) {
const embed = new EmbedBuilder()
.setTitle('Embed Personnalise')
.setDescription('Ceci est une description structuree.')
.setColor('#d32f2f');
await context.reply({ embeds: [embed] });
}
};
const { PermissionsBitField } = require('discord.js');
module.exports = {
name: 'clear',
description: 'Nettoyer le salon.',
options: [{ name: 'nombre', type: 4, description: 'Nombre de messages', required: true }],
async execute(context, args) {
if (!context.member.permissions.has(PermissionsBitField.Flags.ManageMessages)) {
return context.reply({ content: 'Permissions insuffisantes.', ephemeral: true });
}
let amount = context.commandName ? context.options.getInteger('nombre') : parseInt(args[0]);
if (!context.commandName) amount++;
if (amount > 100 || amount < 1) return context.reply('Nombre invalide.');
await context.channel.bulkDelete(amount, true);
const msg = await context.channel.send(`Messages supprimes.`);
setTimeout(() => msg.delete(), 3000);
}
};
const { PermissionsBitField } = require('discord.js');
module.exports = {
name: 'ban',
description: 'Bannir un utilisateur.',
options: [{ name: 'membre', type: 6, description: 'Membre a bannir', required: true }],
async execute(context, args) {
if (!context.member.permissions.has(PermissionsBitField.Flags.BanMembers)) {
return context.reply({ content: 'Permissions insuffisantes.', ephemeral: true });
}
const target = context.commandName
? context.options.getUser('membre')
: context.mentions.users.first();
if (!target) return context.reply('Membre introuvable.');
await context.guild.members.ban(target.id, { reason: 'Banni via commande' });
await context.reply(` ${target.username} a ete banni definitivement.`);
}
};
Checklist utile pour garder un bot propre, stable et maintenable, avec les infos IDE que vous utilisiez avant.
L'editeur le plus stable pour coder des bots. Ecosysteme massif d'extensions, terminal integre efficace et controle complet du projet.
Base sur VS Code, avec une experience acceleree pour l'ecriture et la navigation. Pratique quand vous enchainez les iterations rapidement.
Oriente comprehension globale du codebase. Adapté aux projets modules avec beaucoup de fichiers et dependances croisées.