Mohammad Nizam Uddin Imran
Posted on July 13, 2024
Prerequisites
- Node.js installed.
- Discord account with a server.
- Google Cloud account with Bard API access.
Step 1: Set Up Your Project
- Create a New Directory:
mkdir discord-bot-bard
cd discord-bot-bard
- Initialize a Node.js Project:
npm init -y
- Install Required Packages:
npm install discord.js axios dotenv
Step 2: Create Your Discord Bot
-
Create a New Bot Application:
- Go to the Discord Developer Portal.
- Create a new application.
- Add a bot under the "Bot" tab.
-
Get Your Bot Token:
- Copy your bot token from the "Bot" tab.
-
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
-
Set Up Google Cloud Project:
- Create a new project in the Google Cloud Console.
- Enable the Bard API.
- Create an API key.
Store Your API Keys:
Create a .env
file:
DISCORD_TOKEN=your-discord-bot-token
BARD_API_KEY=your-google-bard-api-key
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);
Step 5: Run Your Bot
Run your bot with:
node index.js
🎉 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! 💻✨
💖 💪 🙅 🚩
Mohammad Nizam Uddin Imran
Posted on July 13, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
musicbot Writing a 'music quiz' command for your discord.js bot (Updated March 2020)
November 9, 2019