Guide: Build an AI Discord Bot

A step-by-step guide to building an AI Discord bot using Langbase Pipes.


Want to add an AI-powered chatbot to your Discord server? This comprehensive guide walks you through the process of building an AI Discord Bot using Langbase Pipes. You'll be able to create a bot that interacts with users, answers questions, and provides a more engaging Discord experience.

Let's get started!

We built a bot named Ask Langbase Docs, a Discord bot that can answer any questions about Langbase documentation. It is currently available on the Langbase Discord server. You can ask any question about Langbase documentation using the /ask command, and the bot will respond with the answer.

Here is a preview of the bot in action:

Here's what you need:

  • Node.js and npm: Make sure you have Node.js (version 18 or higher) and npm installed.
  • Langbase Account: If you don't have one already, sign up for free at https://langbase.com.
  • Discord Account and Server: You'll need a Discord account and a server where you can add and test your bot.
  • Discord Developer Portal Access: You'll be creating a Discord application and bot, so access to the Discord Developer Portal is required.
  • Cloudflare Account: We'll be using Cloudflare Workers for hosting the bot.

Step #1

  1. Create a Discord Application:

  2. Add a Bot:

    • Navigate to the "Bot" section in the left-hand menu.
    • Click "Add Bot" and confirm to create a bot user for your application.
  3. Bot Permissions:

    • In the "Bot" settings, under "Privileged Gateway Intents," enable the "Server Members Intent." This is important for the bot to identify users on your server.
  4. Copy Important Credentials:

    • Note down your application's Client ID and Client Secret – you'll need these later.

Step #2

  1. Create a Discord Server:

    • If you don't have a server already, create one for testing your bot.
  2. Invite the Bot to Your Server:

    • Back in the Discord Developer Portal, in your application's settings, go to the "OAuth2" section.
    • In the "Scopes" section, select "bot".
    • Under "Bot Permissions", select the following:
      • Text Permissions: Send Messages, Read Message History
      • Presence Permissions: Connect
    • Copy the generated invite link and use it to add the bot to your Discord server.

Step #3

Now, let's create the Langbase Pipe that will power the AI capabilities of your Discord bot:

  1. Create a New Pipe:

    • Log in to your Langbase account.
    • Go to the "Pipes" section and click "Create Pipe."
    • Give your pipe a name (e.g., "My Discord Bot Pipe").
  2. Configure Your Pipe:

    • You can choose a pre-built template from Langbase's library or customize your own. Choose the template that best suits your Discord bot's purpose. For our example, we are using a Question Answering template that uses a Langbase RAG Pipe to answer questions about Langbase.
  3. Get Your Pipe API Key:

    • Once your pipe is created, navigate to the pipe's settings and locate the API key. Copy this key – you'll need it to allow your Discord bot to communicate with Langbase.

Step #4

  1. Clone the Example Repository:

    • Open your terminal or command prompt.
    • Clone the example repository provided by Langbase:
      git clone https://github.com/LangbaseInc/langbase-examples.git cd langbase-examples/examples/ai-discord-bot
  2. Install Dependencies:

    • Install the project dependencies using npm:
      npm install

Step #5

  1. Rename .dev.vars:

    • Rename the example.dev.vars file to .dev.vars.
    • Important: Add .dev.vars to your .gitignore file. This file will contain sensitive information that should not be publicly exposed.
  2. Environment Variables:

    • Open the .dev.vars file and fill in the following placeholders with your Discord and Langbase credentials:

      DISCORD_TOKEN='YOUR_DISCORD_BOT_TOKEN' DISCORD_PUBLIC_KEY='YOUR_DISCORD_APPLICATION_PUBLIC_KEY' DISCORD_APPLICATION_ID='YOUR_DISCORD_APPLICATION_ID' DISCORD_GUILD_ID='YOUR_DISCORD_GUILD_ID' LANGBASE_PIPE_KEY='YOUR_LANGBASE_PIPE_API_KEY'
      • Where to find these values:
        • DISCORD_TOKEN: Discord Developer Portal > Your Application > Bot > Token (click "Reset Token" to generate a new one)
        • DISCORD_PUBLIC_KEY: Discord Developer Portal > Your Application > General Information > Public Key
        • DISCORD_APPLICATION_ID: Discord Developer Portal > Your Application > General Information > Application ID
        • DISCORD_GUILD_ID: In Discord, right-click your server > Server Settings > Advanced > Enable Developer Mode. Now, right-click your server again > Copy ID.
        • LANGBASE_PIPE_KEY: From the Langbase Pipe you created in Step 3.

Step #6

In this example, we're creating a slash command, /ask, which will allow users to interact with our bot.

  1. Command Registration:

    • To make the command usable, you need to register it. For testing, it's easiest to register it specifically for your server (guild):
      npm run register:guild
    • Replace placeholders with your actual credentials.
  2. Understanding the Command Code:

    • Open the src/server.ts file. This file contains the core logic for handling interactions with your bot.

    • The key part is the code that handles the /ask command:

      // ... inside the fetch request handler in server.ts if (command === 'ask') { const pipe = new Pipe(LANGBASE_PIPE_KEY) const question = input const response = await pipe.generateText({ messages: [{ role: 'user', content: question }], }) return new Response(JSON.stringify({ type: 4, data: { content: response.generations[0].text }, })) } // ... rest of the code
    • Explanation:

      • This code intercepts the /ask command, retrieves the user's input (their question), sends it to your Langbase Pipe, gets the AI-generated response, and formats it to send back to the Discord user.

Step #7

  1. Start Your Bot:

    npm run dev

    This will start your bot locally.

  2. Set Up ngrok:

    • Open a new terminal window and run:
      npm run ngrok
    • ngrok creates a public URL that forwards requests to your local development server. Copy the HTTPS URL provided by ngrok (e.g., https://8098-24-22-245-250.ngrok.io).
  3. Update Discord with ngrok URL:

    • Go back to the Discord Developer Portal > Your Application > Settings > Bot.
    • Under "Interactions Endpoint URL," paste your ngrok HTTPS URL.
    • Important: Click "Save" to apply the changes.
  4. Test Your Bot:

    • On your Discord server, type the /ask command followed by a question. Your bot should respond with an answer powered by Langbase!

Step #8

To make your bot publicly accessible, deploy it to Cloudflare Workers:

  1. Cloudflare Worker Setup:

  2. Publish Your Code:

    • From your project's root directory, run:
      npm run publish
  3. Set Environment Variables on Cloudflare:

    • In your Cloudflare Worker's settings, go to the "Settings" tab and then "Variables."
    • Add the environment variables (DISCORD_TOKEN, etc.) you defined in your .dev.vars file as secrets in your Cloudflare Worker settings.
  4. Point Discord to Cloudflare Worker:

    • In the Discord Developer Portal, update the "Interactions Endpoint URL" for your bot to point to your Cloudflare Worker's URL.

Congratulations! You have a working AI Discord bot powered by Langbase. Now, start exploring more advanced features, customizations, and integrations. Join the Langbase Discord community for support and to share your creations.

*/}