🔧 Automated Discord chatbot for chat interaction in channel using Gemini 2.0 Flash

3,807 views · 🔧 Miscellaneous

Description

A Discord bot that responds to mentions by sending messages to n8n workflows and returning the responses. Connects Discord conversations with custom automations, APIs, and AI services through n8n.

Full guide on: https://github.com/JimPresting/AI-Discord-Bot/blob/main/README.md

Discord Bot Summary

Overview

The Discord bot listens for mentions, forwards questions to an n8n workflow, processes responses, and replies in Discord. This workflow is intended for all Discord users who want to offer AI interactions with their respective channels.

What do you need?

Key Features

1. Listens for Mentions

2. Forwards Questions to n8n

3. Processes Data in n8n

4. Replies to Discord with n8n’s Response

5. Error Handling

6. Typing Indicator

7. Status Update

Step-by-Step Setup Guide as per Github Instructions

Key Takeaways


1. n8n: Create & Expose Your Webhook

  1. New Workflow

    • Log into your n8n instance.
    • Click Create Workflow (➕), name it e.g. Discord Bot Handler.
  2. Webhook Trigger

    • Add a node (➕) → search Webhook.
    • Set:
      • Authentication: None (or your choice)
      • HTTP Method: POST
      • Path: e.g. /discord-bot
    • Click Execute Node to activate.
  3. Copy Webhook URL

    • After execution, copy the Production Webhook URL.
    • You’ll paste this into your bot’s .env.
  4. Build Your Logic

    • Chain additional nodes (AI, database lookups, etc.) as required.
  5. Format the JSON Response

    • Insert a Function node before the end:
      return {
        json: { answer: "Your processed reply" }
      };
  6. Respond to Webhook

    • Add Respond to Webhook as the final node.
    • Point it at your Function node’s output (with the answer field).
  7. Activate

    • Toggle Active in the top‐right and Save.

2. Discord Developer Portal: App & Bot

  1. New Application

  2. Enable Intents & Permissions

    • Under Privileged Gateway Intents, toggle Message Content Intent.
    • Under Bot Permissions, check:
      • Read Messages/View Channels
      • Send Messages
      • Read Message History
  3. Grab Your Token

    • In Bot → click Copy (or Reset Token).
    • Store it securely.
  4. Invite Link (OAuth2 URL)

    • Go to OAuth2URL Generator.
    • Select scopes: bot, applications.commands.
    • Under Bot Permissions, select the same permissions as above.
    • Copy the generated URL, open it in your browser, and invite your bot.

3. Server Prep: Node.js & Project Setup

  1. Install Node.js v20.x

    sudo apt purge nodejs npm
    sudo apt autoremove
    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
    sudo apt install -y nodejs
    node -v    # Expect v20.x.x
    npm -v     # Expect 10.x.x
  2. Project Folder

    mkdir discord-bot
    cd discord-bot
  3. Initialize & Dependencies

    npm init -y
    npm install discord.js axios dotenv

4. Bot Code & Configuration

  1. Environment Variables

    • Create .env:
      nano .env
    • Populate:
      DISCORD_BOT_TOKEN=your_bot_token
      N8N_WEBHOOK_URL=https://your-n8n-instance.com/webhook/discord-bot
      # Optional: restrict to one channel
      # TARGET_CHANNEL_ID=123456789012345678
  2. Bot Script

    • Create index.js:
      nano index.js
    • Implement:
      • Import dotenv, discord.js, axios.
      • Set up client with MessageContent intent.
      • On messageCreate:
        1. Ignore bots or non‐mentions.
        2. (Optional) Filter by channel ID.
        3. Extract and validate the user’s question.
        4. Send “typing…” every 5 s; after 20 s send a status update if still processing.
        5. POST to your n8n webhook with question, channelId, userId, userName.
        6. Parse various response shapes to find answer.
        7. If answer.length ≤ 2000, message.reply(answer).
        8. Else, split into ~1900‑char chunks at sentence/paragraph breaks and send sequentially.
        9. On errors, clear intervals, log details, and reply with an error message.
  3. Login

    client.login(process.env.DISCORD_BOT_TOKEN);

5. Deployment: Keep It Alive with PM2

  1. Install PM2

    npm install -g pm2
  2. Start & Monitor

    pm2 start index.js --name discord-bot
    pm2 status
    pm2 logs discord-bot
  3. Auto‐Start on Boot

    pm2 startup
    # Follow the printed command (e.g. sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u your_user --hp /home/your_user)
    pm2 save

6. Test & Troubleshoot

  1. Functional Test

    • In your Discord server:
      @YourBot What’s the weather like?
    • Expect a reply from your n8n workflow.
  2. Common Pitfalls

    • No reply → check pm2 logs discord-bot.
    • Intent Errors → verify Message Content Intent in Portal.
    • Webhook failures → ensure workflow is active and URL is correct.
    • Formatting issues → confirm your Function node returns json.answer.
  3. Inspect Raw Data

    • Search your logs for Complete response from n8n: to debug payload shapes.


## 🔗 Nodes Used

Webhook, AI Agent, Simple Memory, Google Gemini Chat Model

## 📥 Import

Download [`workflow.json`](workflow.json) and import into n8n:
**Workflow menu → Import from File**

[📖 Importing guide](../../../docs/importing-templates.md) · [🔑 Credential setup](../../../docs/credential-setup.md)