gwei-alert-bot/src/gasPriceChecker.ts
2023-04-18 13:35:09 -07:00

46 lines
1.5 KiB
TypeScript

import { EmbedBuilder, TextChannel } from 'discord.js';
import { getGasPricesInGwei } from './blockchain';
import { DiscordClient } from './discordClient';
import redisClient from './redis';
import { GasAlert } from '../types/gasAlert';
const createGasPriceChecker = (client: DiscordClient) => {
setInterval(async () => {
try {
const gasPrices = await getGasPricesInGwei();
const gasAlerts: GasAlert[] = await redisClient
.hVals('gas-alerts')
.then((values) => values.map(val => JSON.parse(val)));
gasAlerts.forEach(async (gasAlert) => {
if (gasPrices.average <= gasAlert.threshold) {
const channel = await client.channels.fetch(gasAlert.channelId) as TextChannel;
const user = await client.users.fetch(gasAlert.userId);
channel.send({
embeds: [
new EmbedBuilder()
.setTitle('Gas price alert!')
.setDescription(`<@${gasAlert.userId}>!
Gas prices have fallen below your alert threshold of ${gasAlert.threshold} Gwei:
${gasPrices.fast} ⦚⦚ 🚶${gasPrices.average} ⦚⦚ 🐢${gasPrices.slow}`)
.setColor('#FF8C00')
],
target: user
})
console.log(`Alerted ${user} under threshold ${gasAlert.threshold}: Removing alert...`)
await redisClient.hDel('gas-alerts', `${gasAlert.userId}`)
}
});
} catch (error) {
console.log(`Error checking gas prices:\n`, error);
}
}, 15000);
};
export { createGasPriceChecker };