Files
bot.js
package.json
README.md
Code
3 335
bot.js
const { Client, GatewayIntentBits, PermissionFlagsBits, REST, Routes, EmbedBuilder } = require('discord.js');
const OpenAI = require('openai');
require('dotenv').config();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers
]
});
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
const claimedChannels = new Set();
const conversationHistory = new Map();
client.once('ready', async () => {
console.log(`β
Bot is ready! Logged in as ${client.user.tag}`);
console.log(`π Serving ${client.guilds.cache.size} guilds`);
await registerCommands();
});
async function registerCommands() {
const commands = [
{
name: 'claim',
description: 'Claim a support ticket and stop AI responses (Admin only)',
}
];
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
try {
console.log('π Registering slash commands...');
for (const guild of client.guilds.cache.values()) {
await rest.put(
Routes.applicationGuildCommands(client.user.id, guild.id),
{ body: commands }
);
}
console.log('β
Slash commands registered successfully!');
} catch (error) {
console.error('β Error registering commands:', error);
}
}
client.on('guildCreate', async (guild) => {
console.log(`β Joined new guild: ${guild.name}`);
await registerCommands();
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'claim') {
if (!interaction.member.permissions.has(PermissionFlagsBits.Administrator)) {
await interaction.reply({
content: 'β You need Administrator permissions to use this command.',
ephemeral: true
});
return;
}
const channelId = interaction.channel.id;
if (claimedChannels.has(channelId)) {
await interaction.reply({
content: 'β οΈ This channel has already been claimed.',
ephemeral: true
});
return;
}
claimedChannels.add(channelId);
conversationHistory.delete(channelId);
const finalMessage = process.env.FINAL_MESSAGE || 'Thank you for waiting! A staff member will assist you shortly.';
const embed = new EmbedBuilder()
.setColor(0x00FF00)
.setTitle('β
Ticket Claimed')
.setDescription(finalMessage)
.setFooter({ text: `Claimed by ${interaction.user.tag}` })
.setTimestamp();
await interaction.reply({ embeds: [embed] });
console.log(`π« Channel ${channelId} claimed by ${interaction.user.tag}`);
}
});
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
if (!message.mentions.has(client.user.id)) return;
if (claimedChannels.has(message.channel.id)) {
return;
}
const typingInterval = setInterval(() => {
message.channel.sendTyping().catch(() => {});
}, 5000);
try {
await message.channel.sendTyping();
const cleanContent = message.content.replace(/<@!?\d+>/g, '').trim();
if (!conversationHistory.has(message.channel.id)) {
conversationHistory.set(message.channel.id, []);
}
const history = conversationHistory.get(message.channel.id);
history.push({
role: 'user',
content: cleanContent
});
if (history.length > 20) {
history.splice(0, history.length - 20);
}
const systemMessage = {
role: 'system',
content: 'You are a helpful AI support assistant for a Discord server. Detect the language of the user\'s message and respond in the same language. Be friendly, concise, and helpful. If you don\'t know something, be honest about it. Keep responses under 2000 characters to fit Discord message limits.'
};
const completion = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [systemMessage, ...history],
max_tokens: 500,
temperature: 0.7,
});
const aiResponse = completion.choices[0].message.content;
history.push({
role: 'assistant',
content: aiResponse
});
conversationHistory.set(message.channel.id, history);
if (aiResponse.length > 2000) {
const chunks = aiResponse.match(/[\s\S]{1,2000}/g);
for (const chunk of chunks) {
await message.reply(chunk);
}
} else {
await message.reply(aiResponse);
}
console.log(`π¬ Responded in channel ${message.channel.id} to ${message.author.tag}`);
} catch (error) {
console.error('β Error processing message:', error);
let errorMessage = 'β Sorry, I encountered an error while processing your request.';
if (error.code === 'insufficient_quota') {
errorMessage = 'β OpenAI API quota exceeded. Please contact an administrator.';
} else if (error.code === 'invalid_api_key') {
errorMessage = 'β Invalid OpenAI API key. Please contact an administrator.';
}
await message.reply(errorMessage).catch(() => {});
} finally {
clearInterval(typingInterval);
}
});
client.on('channelDelete', (channel) => {
claimedChannels.delete(channel.id);
conversationHistory.delete(channel.id);
console.log(`ποΈ Cleaned up data for deleted channel ${channel.id}`);
});
process.on('unhandledRejection', (error) => {
console.error('β Unhandled promise rejection:', error);
});
process.on('SIGINT', () => {
console.log('\nπ Shutting down gracefully...');
client.destroy();
process.exit(0);
});
client.login(process.env.DISCORD_TOKEN);