Files
bot.js
package.json
Code
2 173
bot.js
const { Client, GatewayIntentBits, PermissionFlagsBits, ActivityType, SlashCommandBuilder } = require('discord.js');
require('dotenv').config();
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
const cooldowns = new Map();
const commands = [
new SlashCommandBuilder().setName('time').setDescription('Get the current time for a country or city')
.addStringOption(option => option.setName('country').setDescription('Country or city (defaults to UTC)').setMaxLength(100)),
new SlashCommandBuilder().setName('ban').setDescription('Ban a user (administrators only)')
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator).setDMPermission(false)
.addUserOption(option => option.setName('user').setDescription('User to ban').setRequired(true)),
new SlashCommandBuilder().setName('kick').setDescription('Kick a user (administrators only)')
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator).setDMPermission(false)
.addUserOption(option => option.setName('user').setDescription('User to kick').setRequired(true)),
new SlashCommandBuilder().setName('timeout').setDescription('Timeout a user (administrators only)')
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator).setDMPermission(false)
.addUserOption(option => option.setName('user').setDescription('User to timeout').setRequired(true))
.addIntegerOption(option => option.setName('minutes').setDescription('Duration in minutes (default: 10)').setMinValue(1).setMaxValue(40320)),
new SlashCommandBuilder().setName('spamtimetroe').setDescription('Send :Timetroe: a number of times')
.addIntegerOption(option => option.setName('amount').setDescription('Number of messages (1–10)').setRequired(true).setMinValue(1).setMaxValue(10))
];
async function getJson(url) {
const response = await fetch(url, { signal: AbortSignal.timeout(10000) });
if (!response.ok) throw new Error(`API returned ${response.status}`);
return response.json();
}
async function findPlace(query) {
const url = new URL('https://geocoding-api.open-meteo.com/v1/search');
url.search = new URLSearchParams({ name: query, count: '1', language: 'en', format: 'json' });
const data = await getJson(url);
return data.results?.[0];
}
function weatherDescription(code) {
if (code === 0) return 'clear';
if (code <= 3) return 'partly cloudy or overcast';
if (code <= 48) return 'foggy';
if (code <= 67) return 'rainy';
if (code <= 77) return 'snowy';
if (code <= 82) return 'rain showers';
if (code <= 86) return 'snow showers';
return 'thunderstorms';
}
client.once('clientReady', async () => {
console.log(`Logged in as ${client.user.tag}`);
console.log('KODARI_READY');
client.user.setActivity(':Timetroe: Time', { type: ActivityType.Playing });
try {
await client.application.commands.set(commands.map(command => command.toJSON()));
console.log('Slash commands registered');
} catch (error) {
console.error('Failed to register slash commands:', error);
}
});
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const key = `${interaction.user.id}:${interaction.commandName}`;
const now = Date.now();
if ((cooldowns.get(key) || 0) > now) {
await interaction.reply({ content: 'Please wait a few seconds before using that command again.', ephemeral: true });
return;
}
cooldowns.set(key, now + (interaction.commandName === 'spamtimetroe' ? 30000 : 3000));
setTimeout(() => { if ((cooldowns.get(key) || 0) <= Date.now()) cooldowns.delete(key); }, interaction.commandName === 'spamtimetroe' ? 30000 : 3000).unref();
try {
if (['ban', 'kick', 'timeout'].includes(interaction.commandName)) {
if (!interaction.inGuild() || !interaction.memberPermissions?.has(PermissionFlagsBits.Administrator)) {
await interaction.reply({ content: 'Only administrators can use this command.', ephemeral: true });
return;
}
await interaction.deferReply({ ephemeral: true });
const user = interaction.options.getUser('user', true);
const reason = `Requested by ${interaction.user.tag} (${interaction.user.id})`;
if (interaction.commandName === 'ban') {
await interaction.guild.members.ban(user.id, { reason });
} else {
const member = await interaction.guild.members.fetch(user.id);
if (interaction.commandName === 'kick') await member.kick(reason);
else await member.timeout((interaction.options.getInteger('minutes') ?? 10) * 60000, reason);
}
await interaction.editReply(`${interaction.commandName} completed for ${user.tag}.`);
return;
}
if (interaction.commandName === 'time') {
await interaction.deferReply();
const query = interaction.options.getString('country')?.trim();
if (!query) {
await interaction.editReply(`Current time (UTC): ${new Intl.DateTimeFormat('en', { dateStyle: 'full', timeStyle: 'long', timeZone: 'UTC' }).format(new Date())}`);
return;
}
const place = await findPlace(query);
if (!place?.timezone) {
await interaction.editReply('I could not find that country or city. Try a city name instead.');
return;
}
const time = new Intl.DateTimeFormat('en', { dateStyle: 'full', timeStyle: 'long', timeZone: place.timezone }).format(new Date());
await interaction.editReply(`Current time in ${place.name}${place.country ? `, ${place.country}` : ''}: ${time}`);
return;
}
if (interaction.commandName === 'spamtimetroe') {
await interaction.reply({ content: 'Sending :Timetroe: messages!', ephemeral: true });
for (let i = 0; i < interaction.options.getInteger('amount', true); i++) {
await interaction.channel.send({ content: ':Timetroe:', allowedMentions: { parse: [] } });
}
}
} catch (error) {
console.error(`Command ${interaction.commandName} failed:`, error);
const content = 'Something went wrong. Check the bot permissions and try again.';
try {
if (interaction.deferred) await interaction.editReply(content);
else if (interaction.replied) await interaction.followUp({ content, ephemeral: true });
else await interaction.reply({ content, ephemeral: true });
} catch (replyError) { console.error('Could not send command error:', replyError); }
}
});
client.on('messageCreate', async message => {
if (message.author.bot || !client.user || !message.mentions.has(client.user)) return;
const text = message.content.replace(new RegExp(`<@!?${client.user.id}>`, 'g'), '').trim();
if (!/\bweather\b/i.test(text)) return;
const key = `weather:${message.author.id}`;
if ((cooldowns.get(key) || 0) > Date.now()) return;
cooldowns.set(key, Date.now() + 5000);
setTimeout(() => { if ((cooldowns.get(key) || 0) <= Date.now()) cooldowns.delete(key); }, 5000).unref();
const match = text.match(/\bweather\b\s+(?:in|at|for)\s+(.+?)[?.!]*\s*$/i);
if (!match) {
await message.reply({ content: 'Which location? Try mentioning me with “weather in London”.', allowedMentions: { repliedUser: false } }).catch(console.error);
return;
}
try {
const place = await findPlace(match[1].trim().slice(0, 100));
if (!place) {
await message.reply({ content: 'I could not find that location. Try another city name.', allowedMentions: { repliedUser: false } });
return;
}
const url = new URL('https://api.open-meteo.com/v1/forecast');
url.search = new URLSearchParams({ latitude: String(place.latitude), longitude: String(place.longitude), current: 'temperature_2m,weather_code', timezone: 'auto' });
const data = await getJson(url);
if (!data.current || typeof data.current.temperature_2m !== 'number' || typeof data.current.weather_code !== 'number') throw new Error('Missing weather data');
await message.reply({ content: `Weather in ${place.name}${place.country ? `, ${place.country}` : ''}: ${data.current.temperature_2m}°C, ${weatherDescription(data.current.weather_code)}.`, allowedMentions: { repliedUser: false } });
} catch (error) {
console.error('Weather lookup failed:', error);
await message.reply({ content: 'I could not fetch the weather right now. Please try again later.', allowedMentions: { repliedUser: false } }).catch(console.error);
}
});
client.on('error', error => console.error('Discord client error:', error));
process.on('unhandledRejection', error => console.error('Unhandled rejection:', error));
client.login(process.env.DISCORD_TOKEN).catch(error => console.error('Login failed:', error));