AI-Discord-Bot/index.js
2025-05-06 11:56:01 -04:00

45 lines
1.5 KiB
JavaScript

require('dotenv').config();
const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');
// Create a new client instance
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent],
});
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
// Login to Discord with your app's token
client.login(process.env.DISCORD_TOKEN);
// Command prefix and Ollama model configuration
const PREFIX = '!ollama';
const MODEL_URL = process.env.OLLAMA_API_URL;
// Event listener for messages
client.on('messageCreate', async (message) => {
// Ignore the message if it was sent by a bot or doesn't start with the prefix
if (message.author.bot || !message.content.startsWith(PREFIX)) return;
const args = message.content.slice(PREFIX.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ask') {
try {
// Construct the request payload for Ollama
const response = await axios.post(MODEL_URL, {
prompt: args.join(' '),
max_tokens: 100,
});
// Send the response from Ollama to the Discord channel
message.channel.send(response.data.choices[0].text);
} catch (error) {
console.error(`Error communicating with Ollama: ${error.message}`);
message.channel.send('I encountered an error while trying to get a response from Ollama. Please try again later.');
}
}
});