gwei-alert-bot/src/handlers.ts

71 lines
2.5 KiB
TypeScript

import { ChatInputCommandInteraction, EmbedBuilder } from 'discord.js';
import redisClient from './redis';
import { GasAlert } from '../types/gasAlert';
import { GasPrices } from '../types/gasPrices';
// Respond to the "/gas" command
const handleGasCommand = async (interaction: ChatInputCommandInteraction): Promise<void> => {
const gasPricesStr = await redisClient.get('current-prices');
if (gasPricesStr) {
const gasPrices = JSON.parse(gasPricesStr) as GasPrices;
console.log(`Replying to command "/gas": \n`, gasPrices);
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Current Gas Prices')
.setDescription(`${gasPrices.fast} ⦚⦚🚶 ${gasPrices.average} ⦚⦚ 🐢 ${gasPrices.slow}`);
await interaction.reply({ embeds: [embed] });
} else {
console.log(`Error fetching gas prices!`);
await interaction.reply('ERROR FETCHING GAS!!!1!')
}
};
// Respond to the "/gas alert ${gwei}" command
const handleGasAlertCommand = async (interaction: ChatInputCommandInteraction): Promise<void> => {
const threshold = parseInt(interaction.options.getString('gwei')!);
const channelId = interaction.channelId;
const userId = interaction.user.id;
const gasAlert: GasAlert = { threshold, channelId, userId };
console.log(`Replying to command "/gas gwei ${threshold}"`);
await redisClient.hSet('gas-alerts', `${userId}`, JSON.stringify(gasAlert));
await interaction.reply(`Your gas alert threshold of ${threshold} Gwei has been set.`);
};
// Respond to the "/gas pending" command
const handleGasPendingCommand = async (interaction: ChatInputCommandInteraction): Promise<void> => {
const userId = interaction.user.id;
const alertStr = await redisClient.hGet('gas-alerts', `${userId}`);
const { threshold = null } = alertStr ? JSON.parse(alertStr) : {};
console.log(`Replying to command "/gas pending"`);
if (threshold === null) {
await interaction.reply('No gas price alerts set');
} else {
await interaction.reply(`Current gas price alert threshold: ${threshold} Gwei`);
}
};
// Respond to the "/alert-delete" command
const handleAlertDeleteCommand = async (interaction: ChatInputCommandInteraction): Promise<void> => {
const userId = interaction.user.id;
const user = interaction.user.username;
console.log(`Replying to command "/alert-delete"`);
await redisClient.hDel('gas-alerts', `${userId}`);
await interaction.reply(`Removed your gas price alert, ${user}`);
};
export { handleGasCommand, handleGasAlertCommand, handleGasPendingCommand, handleAlertDeleteCommand };