Files
bot.js
package.json
Code
2 64
bot.js
const { Client, GatewayIntentBits } = require('discord.js');
require('dotenv').config();
if (!process.env.DISCORD_TOKEN) {
console.error('DISCORD_TOKEN is missing. Add it to the .env file.');
process.exit(1);
}
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const commands = [
{ name: 'ping', description: 'Check whether the bot is online' },
{ name: 'hello', description: 'Say hello' }
];
client.once('clientReady', async () => {
try {
await client.application.commands.set(commands);
console.log('Slash commands registered.');
} catch (error) {
console.error('Failed to register slash commands:', error);
}
console.log(`Bot is ready! Logged in as ${client.user.tag}`);
console.log('KODARI_READY');
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
try {
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
} else if (interaction.commandName === 'hello') {
await interaction.reply('สวัสดี!');
}
} catch (error) {
console.error('Failed to respond to interaction:', error);
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({ content: 'เกิดข้อผิดพลาด ลองใหม่อีกครั้ง', ephemeral: true }).catch(console.error);
}
}
});
client.on('error', (error) => {
console.error('Discord client error:', error);
});
client.login(process.env.DISCORD_TOKEN).catch((error) => {
console.error('Failed to log in to Discord:', error);
process.exitCode = 1;
});