πŸš€ How to Start a Discord Bot Using Node.js with Google Bard API πŸ€–

Mohammad Nizam Uddin Imran - Jul 13 - - Dev Community

Prerequisites

  1. Node.js installed.
  2. Discord account with a server.
  3. Google Cloud account with Bard API access.

Step 1: Set Up Your Project

  1. Create a New Directory:
   mkdir discord-bot-bard
   cd discord-bot-bard
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a Node.js Project:
   npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Install Required Packages:
   npm install discord.js axios dotenv
Enter fullscreen mode Exit fullscreen mode

Step 2: Create Your Discord Bot

  1. Create a New Bot Application:

  2. Get Your Bot Token:

    • Copy your bot token from the "Bot" tab.
  3. Invite Your Bot to Your Server:

    • Go to the "OAuth2" tab and generate an invite URL with necessary permissions.
    • Invite your bot using the generated URL.

Step 3: Integrate Google Bard API

  1. Set Up Google Cloud Project:

  2. Store Your API Keys:

Create a .env file:

   DISCORD_TOKEN=your-discord-bot-token
   BARD_API_KEY=your-google-bard-api-key
Enter fullscreen mode Exit fullscreen mode

Step 4: Write Your Bot Code

Create an index.js file and add the following code:

require('dotenv').config();
const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');

const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });

client.once('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', async (message) => {
  if (message.author.bot) return;

  if (message.content.startsWith('!bard')) {
    const query = message.content.replace('!bard', '').trim();

    if (!query) {
      message.channel.send('Please provide a prompt for Bard.');
      return;
    }

    try {
      const response = await axios.post(
        'https://bard.googleapis.com/v1/creations:generate',
        { prompt: query },
        {
          headers: {
            'Authorization': `Bearer ${process.env.BARD_API_KEY}`,
            'Content-Type': 'application/json',
          },
        }
      );

      const bardResponse = response.data.response;
      message.channel.send(bardResponse);
    } catch (error) {
      console.error('Error fetching Bard response:', error);
      message.channel.send('Sorry, I could not fetch a response from Bard.');
    }
  }
});

client.login(process.env.DISCORD_TOKEN);
Enter fullscreen mode Exit fullscreen mode

Step 5: Run Your Bot

Run your bot with:

node index.js
Enter fullscreen mode Exit fullscreen mode

πŸŽ‰ Conclusion

Your Discord bot is now online and ready to generate creative content using the Google Bard API! Have fun interacting with it and expanding its features. Happy coding! πŸ’»βœ¨

.