Skip to main content

Chapitre 3 - Démarrer le bot

Nous rejoindre sur Discord

Ça y est, nous y sommes, nous allons enfin démarrer notre bot. Dans notre structure, le fichier qui permet de lancer notre bot est le app.js. Pour lancer notre bot, il suffit d'utiliser la commande node . dans un terminal de commandes (attention, le terminal doit être ouvert au même endroit que notre fichier app.js).

Si vous lancer cette commande maintenant, il ne se passera rien, puisque notre fichier app.js est vide !

Connecter le bot

Pour se connecter à notre bot, nous aurons besoin du code suivant :

require('log-timestamp'); // Avoir la date sur tous les logs générés
require('dotenv').config(); // Lire le fichier .env

const { Client } = require('discord.js'); // Utiliser les éléments de Discord

/* Initialisation de notre bot */
const client = new Client({intents:[]}); // Pour le moment, on ne met aucune intention

// Connexion à notre bot
client.login(process.env.TOKEN).then(()=>{
    console.log(`Logged in as ${client.user.tag} !`);
});

On peut voir maintenant que notre bot est connecté sur notre serveur :

Bien qu'on ne puisse rien faire pour le moment, on peut déjà récupérer des informations sur celui-ci. C'est ce que l'on a fait à la ligne 11 au moment du log : nous avons récupérer le nom de notre bot.

Utiliser les logs

Lorsque vous développez vos fonctionnalités, nous vous recommandons fortement d'utiliser les logs. Ils vous permettront d'obtenir des informations importante sur la structure de la variable présente dedans. Par exemple, voici ce que nous obtenons si nous affichons la structure de la variable client avec console.log(client); :

Client {
  _events: [Object: null prototype] { shardDisconnect: [Function (anonymous)] },
  _eventsCount: 1,
  _maxListeners: undefined,
  options: {
    intents: 3,0,
    closeTimeout: 5000,
    waitGuildTimeout: 15000,
    shardCount: 1,
    makeCache: [Function (anonymous)],
    partials: [],
    failIfNotExists: true,
    presence: { status: 'online', user: [Object] },
    sweepers: { threads: [Object] },                                            
    ws: { large_threshold: 50,
      compress: false,
      properties: [Object],
      version: 10,
      presence: [Object]... },
    rest: { agent: [Getter],
      api: 'https://discord.com/api',
      authPrefix: 'Bot',
      cdn: 'https://cdn.discordapp.com',
      headers: {},
      invalidRequestWarningInterval: 0,
      globalRequestsPerSecond: 50,
      offset: 50,
      rejectOnRateLimit: null,
      retries: 3,
      timeout: 15000,
      userAgentAppendix: 'Node.js v16.16.0',
      version: '10',
      hashSweepInterval: 14400000,
      hashLifetime: 86400000,
      handlerSweepInterval: 3600000... },
    jsonTransformer: [Function: toSnakeCase],
    shards: [ 0 ]
  },
  rest: REST { _events: [Object: null prototype] {
      newListener: [Function (anonymous)],
      removeListener: [Function (anonymous)]
    },
    _eventsCount: 2,
    _maxListeners: undefined,
    cdn: CDN { base: 'https://cdn.discordapp.com' },
    requestManager: _RequestManager {
      _events: [Object: null prototype],
      _eventsCount: 4,
      _maxListeners: undefined,
      agent: [Agent],
      globalDelay: null,
      globalReset: 1659360905832,
      hashes: [Collection [Map]],
      handlers: [Collection [Map]],
      options: [Object],
      globalRemaining: 49,
      hashTimer: Timeout {
        _idleTimeout: 14400000,
        _idlePrev: [TimersList],
        _idleNext: [TimersList],
        _idleStart: 575,
        _onTimeout: [Function (anonymous)],
        _timerArgs: undefined,
        _repeat: 14400000,
        _destroyed: false,
        [Symbol(refed)]: false,
        [Symbol(kHasPrimitive)]: false,
        [Symbol(asyncId)]: 6,
        [Symbol(triggerId)]: 1
      },
      handlerTimer: Timeout {
        _idleTimeout: 3600000,
        _idlePrev: [Timeout],
        _idleNext: [TimersList],
        _idleStart: 575,
        _onTimeout: [Function (anonymous)],
        _timerArgs: undefined,
        _repeat: 3600000,
        _destroyed: false,
        [Symbol(refed)]: false,
        [Symbol(kHasPrimitive)]: false,
        [Symbol(asyncId)]: 7,
        [Symbol(triggerId)]: 1
      },
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false... },
  ws: WebSocketManager { _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined,
    gateway: 'wss://gateway.discord.gg/',
    totalShards: 1,
    shards: Collection(1) [Map] { 0 => [WebSocketShard] },
    status: 0,
    destroyed: false,
    reconnecting: false,
    [Symbol(kCapture)]: false... },
  actions: ActionsManager { client: [Circular *1],
    ApplicationCommandPermissionsUpdate: ApplicationCommandPermissionsUpdateAction { client: [Circular *1] },
    ChannelCreate: ChannelCreateAction { client: [Circular *1] },
    ChannelDelete: ChannelDeleteAction { client: [Circular *1] },
    ChannelUpdate: ChannelUpdateAction { client: [Circular *1] },
    GuildBanAdd: GuildBanAdd { client: [Circular *1] },
    GuildBanRemove: GuildBanRemove { client: [Circular *1] },
    GuildChannelsPositionUpdate: GuildChannelsPositionUpdate { client: [Circular *1] },
    GuildDelete: GuildDeleteAction { client: [Circular *1] },
    GuildEmojiCreate: GuildEmojiCreateAction { client: [Circular *1] },
    GuildEmojiDelete: GuildEmojiDeleteAction { client: [Circular *1] },
    GuildEmojiUpdate: GuildEmojiUpdateAction { client: [Circular *1] },
    GuildEmojisUpdate: GuildEmojisUpdateAction { client: [Circular *1] },
    GuildIntegrationsUpdate: GuildIntegrationsUpdate { client: [Circular *1] },
    GuildMemberRemove: GuildMemberRemoveAction { client: [Circular *1] },
    GuildMemberUpdate: GuildMemberUpdateAction { client: [Circular *1] },
    GuildRoleCreate: GuildRoleCreate { client: [Circular *1] },
    GuildRoleDelete: GuildRoleDeleteAction { client: [Circular *1] },
    GuildRoleUpdate: GuildRoleUpdateAction { client: [Circular *1] },
    GuildRolesPositionUpdate: GuildRolesPositionUpdate { client: [Circular *1] },
    GuildScheduledEventCreate: GuildScheduledEventCreateAction { client: [Circular *1] },
    GuildScheduledEventDelete: GuildScheduledEventDeleteAction { client: [Circular *1] },
    GuildScheduledEventUpdate: GuildScheduledEventUpdateAction { client: [Circular *1] },
    GuildScheduledEventUserAdd: GuildScheduledEventUserAddAction { client: [Circular *1] },
    GuildScheduledEventUserRemove: GuildScheduledEventUserRemoveAction { client: [Circular *1] },
    GuildStickerCreate: GuildStickerCreateAction { client: [Circular *1] },
    GuildStickerDelete: GuildStickerDeleteAction { client: [Circular *1] },
    GuildStickerUpdate: GuildStickerUpdateAction { client: [Circular *1] },
    GuildStickersUpdate: GuildStickersUpdateAction { client: [Circular *1] },
    GuildUpdate: GuildUpdateAction { client: [Circular *1] },
    InteractionCreate: InteractionCreateAction { client: [Circular *1] },
    InviteCreate: InviteCreateAction { client: [Circular *1] },
    InviteDelete: InviteDeleteAction { client: [Circular *1] },
    MessageCreate: MessageCreateAction { client: [Circular *1] },
    MessageDelete: MessageDeleteAction { client: [Circular *1] },
    MessageDeleteBulk: MessageDeleteBulkAction { client: [Circular *1] },
    MessageReactionAdd: MessageReactionAdd { client: [Circular *1] },
    MessageReactionRemove: MessageReactionRemove { client: [Circular *1] },
    MessageReactionRemoveAll: MessageReactionRemoveAll { client: [Circular *1] },
    MessageReactionRemoveEmoji: MessageReactionRemoveEmoji { client: [Circular *1] },
    MessageUpdate: MessageUpdateAction { client: [Circular *1] },
    PresenceUpdate: PresenceUpdateAction { client: [Circular *1] },
    StageInstanceCreate: StageInstanceCreateAction { client: [Circular *1] },
    StageInstanceDelete: StageInstanceDeleteAction { client: [Circular *1] },
    StageInstanceUpdate: StageInstanceUpdateAction { client: [Circular *1] },
    ThreadCreate: ThreadCreateAction { client: [Circular *1] },
    ThreadDelete: ThreadDeleteAction { client: [Circular *1] },
    ThreadListSync: ThreadListSyncAction { client: [Circular *1] },
    ThreadMemberUpdate: ThreadMemberUpdateAction { client: [Circular *1] },
    ThreadMembersUpdate: ThreadMembersUpdateAction { client: [Circular *1] },
    TypingStart: TypingStart { client: [Circular *1] },
    UserUpdate: UserUpdateAction { client: [Circular *1] },
    VoiceStateUpdate: VoiceStateUpdate { client: [Circular *1] },
    WebhooksUpdate: WebhooksUpdate { client: [Circular *1] }... },
  voice: ClientVoiceManager { adapters: Map(0) {} },
  shard: null,
  users: UserManager {},
  guilds: GuildManager {},
  channels: ChannelManager {},
  sweepers: Sweepers { options: { threads: [Object] },
    intervals: {
      applicationCommands: null,
      bans: null,
      emojis: null,
      invites: null,
      guildMembers: null,
      messages: null,
      presences: null,
      reactions: null,
      stageInstances: null,
      stickers: null,
      threadMembers: null,
      threads: Timeout {
        _idleTimeout: 3600000,
        _idlePrev: [TimersList],
        _idleNext: [Timeout],
        _idleStart: 608,
        _onTimeout: [Function (anonymous)],
        _timerArgs: undefined,
        _repeat: 3600000,
        _destroyed: false,
        [Symbol(refed)]: false,
        [Symbol(kHasPrimitive)]: false,
        [Symbol(asyncId)]: 8,
        [Symbol(triggerId)]: 1
      },
      users: null,
      voiceStates: null
    }... },
  presence: ClientPresence {
    userId: null,
    guild: null,
    status: 'online',
    activities: [],
    clientStatus: null
  },
  user: ClientUser {
    id: '1003016587437166612',
    bot: true,
    system: false,
    flags: UserFlagsBitField { bitfield: 0 },
    username: 'Formation Bot',
    discriminator: '3871',
    avatar: '8f35d791bf2a5e3af3b8a2be1ee493a9',
    banner: undefined,
    accentColor: undefined,
    verified: true,
    mfaEnabled: true
  },
  application: ClientApplication {
    id: '1003016587437166612',
    name: null,
    description: null,
    icon: null,
    tags: [],
    installParams: null,
    customInstallURL: null,
    flags: ApplicationFlagsBitField { bitfield: 565248 },
    cover: null,
    rpcOrigins: [],
    botRequireCodeGrant: null,
    botPublic: null,
    owner: null,
    commands: ApplicationCommandManager {
      permissions: [ApplicationCommandPermissionsManager]
    }
  },
  readyTimestamp: 1659360905580,
  [Symbol(kCapture)]: true
}