Compare commits
No commits in common. "bfaa6ebd25e5348433f6fb978c5d33078db8d317" and "cea18e6a5fb6c34bbbc5255fb6af4e028448ce4b" have entirely different histories.
bfaa6ebd25
...
cea18e6a5f
@ -2,6 +2,8 @@ FROM node:18-slim as ts-compiler
|
||||
WORKDIR /usr/app
|
||||
COPY package*.json ./
|
||||
COPY tsconfig*.json ./
|
||||
# RUN apt update \
|
||||
# && apt install build-essential python3 libsqlite3-dev -y
|
||||
RUN npm install
|
||||
COPY . ./
|
||||
RUN npm run build
|
||||
@ -10,10 +12,15 @@ FROM node:18-slim as ts-remover
|
||||
WORKDIR /usr/app
|
||||
COPY --from=ts-compiler /usr/app/package*.json ./
|
||||
COPY --from=ts-compiler /usr/app/dist ./
|
||||
# RUN apt update \
|
||||
# && apt install build-essential python3 libsqlite3-dev sqlite3 -y
|
||||
# RUN npm install --build-from-source --sqlite=/usr/bin --omit=dev
|
||||
RUN npm install --omit=dev
|
||||
|
||||
FROM node:18-slim
|
||||
WORKDIR /usr/app
|
||||
COPY --from=ts-remover /usr/app ./
|
||||
COPY .env ./
|
||||
# RUN apt update \
|
||||
# && apt install libsqlite3-dev sqlite3 -y
|
||||
CMD node index.js
|
65
README.md
65
README.md
@ -1,65 +1,2 @@
|
||||
# Gwei Alert Bot
|
||||
# gwei-alert-bot
|
||||
|
||||
## Introduction
|
||||
|
||||
This repo contains Docker build files for a Discord bot built with Node.js and utilizes a composed Redis container for storage.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Docker + Docker Compose
|
||||
- A Discord bot token
|
||||
- A EVM RPC endpoint URL (websocket enabled) OR a local node running at `localhost:8545` (using docker host network mode)
|
||||
|
||||
## Usage
|
||||
|
||||
1. Clone the repository to your local machine
|
||||
|
||||
```bash
|
||||
git clone https://git.ssh.surf/MrTuxedo/gwei-alert-bot.git
|
||||
```
|
||||
|
||||
2. Create a .env file in the root of the project and add the following environment variables:
|
||||
|
||||
```makefile
|
||||
RPC_URL=<your rpc url>
|
||||
DISCORD_BOT_TOKEN=<your discord bot token>
|
||||
DISCORD_CLIENT=<your discord client ID>
|
||||
```
|
||||
|
||||
3. Run the Docker container
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
## Rebuilding with new changes
|
||||
|
||||
1. Stop the running bot and remove container by same name
|
||||
|
||||
```bash
|
||||
docker compose down
|
||||
```
|
||||
|
||||
2. Pull the new work
|
||||
|
||||
```bash
|
||||
git pull
|
||||
```
|
||||
|
||||
3. Build and Run
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
The following environment variables must be set in either `.env` or `docker-compose.yml` in order for the bot to function properly:
|
||||
|
||||
- RPC_URL: Your RPC url
|
||||
- DISCORD_BOT_TOKEN: the Oauth2 token for your Discord bot.
|
||||
- DISCORD_CLIENT: the client ID for your Discord bot. (app ID)
|
||||
|
||||
### License
|
||||
|
||||
[WTFPL](./LICENSE)
|
@ -1,8 +1,6 @@
|
||||
import 'dotenv/config.js';
|
||||
import Web3 from 'web3';
|
||||
|
||||
import { GasPrices } from '../types/gasPrices'
|
||||
import redisClient from './redis';
|
||||
import Web3 from 'web3';
|
||||
|
||||
const rpcUrl = process.env.RPC_URL || 'ws://localhost:8545';
|
||||
|
||||
@ -16,46 +14,34 @@ const web3 = new Web3(new Web3.providers.WebsocketProvider(rpcUrl, {
|
||||
}
|
||||
}));
|
||||
|
||||
export const subToBlockHeaders = (setDiscordStatus: () => Promise<void>) => {
|
||||
web3.eth.subscribe('newBlockHeaders', (error, blockHeader) => {
|
||||
if (error) console.error(error);
|
||||
|
||||
// Set status every 10 blocks
|
||||
const shouldSetStatus = blockHeader.number % 10 === 0;
|
||||
|
||||
// Get the gas price for this block
|
||||
web3.eth.getGasPrice((error, gasPrice) => {
|
||||
if (error) console.error(error);
|
||||
|
||||
if (shouldSetStatus) console.log('Gas price in wei:', gasPrice);
|
||||
|
||||
redisClient.set('gas-price', Math.round(Number(gasPrice)))
|
||||
});
|
||||
|
||||
if (shouldSetStatus) setDiscordStatus()
|
||||
});
|
||||
}
|
||||
|
||||
const gweiFromWei = (priceInWei: number): number =>
|
||||
Math.round(Number(web3.utils.fromWei(`${Math.round(priceInWei)}`, 'gwei')));
|
||||
|
||||
const getGasPrice = async (): Promise<number> => {
|
||||
const gasPrice = await redisClient.get('gas-price');
|
||||
// Get the current gas price in gwei
|
||||
async function getGasPrice() {
|
||||
const gasPrice = await web3.eth.getGasPrice();
|
||||
return Number(gasPrice);
|
||||
}
|
||||
|
||||
const getGasPricesInGwei = async (): Promise<GasPrices> => {
|
||||
const gasPrice = await getGasPrice()
|
||||
const fastPrice = gasPrice * 1.1;
|
||||
const slowPrice = gasPrice * 0.9;
|
||||
|
||||
const gasPrices = {
|
||||
fast: gweiFromWei(fastPrice),
|
||||
average: gweiFromWei(gasPrice),
|
||||
slow: gweiFromWei(slowPrice),
|
||||
};
|
||||
const gweiFromWei = (priceInWei: number): number =>
|
||||
Number(web3.utils.fromWei(`${Math.round(priceInWei)}`, 'gwei'));
|
||||
|
||||
return gasPrices;
|
||||
try {
|
||||
const gasPrice = await getGasPrice()
|
||||
const fastPrice = gasPrice * 1.2;
|
||||
const slowPrice = gasPrice * 0.8;
|
||||
|
||||
const gasPrices = {
|
||||
fast: gweiFromWei(fastPrice),
|
||||
average: gweiFromWei(gasPrice),
|
||||
slow: gweiFromWei(slowPrice),
|
||||
};
|
||||
|
||||
return Promise.resolve(gasPrices);
|
||||
// await redisClient.set('gas-prices', JSON.stringify(gasPrices));
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Export the getCurrentGasPrice function
|
||||
export { getGasPricesInGwei };
|
@ -1,12 +0,0 @@
|
||||
import { SlashCommandBuilder, ChatInputCommandInteraction } from 'discord.js';
|
||||
import { handleAlertDeleteCommand } from '../handlers';
|
||||
|
||||
module.exports = {
|
||||
data: new SlashCommandBuilder()
|
||||
.setName('alert-delete')
|
||||
.setDescription('Remove your gwei alert threshold'),
|
||||
|
||||
async execute(interaction: ChatInputCommandInteraction) {
|
||||
return await handleAlertDeleteCommand(interaction);
|
||||
}
|
||||
}
|
@ -23,6 +23,8 @@ const rest = new REST({ version: '10' }).setToken(token);
|
||||
// and deploy your commands!
|
||||
export const deployCommands = async () => {
|
||||
try {
|
||||
console.log(`Started refreshing ${commands.length} global application (/) commands.`);
|
||||
|
||||
// The put method is used to fully refresh all commands in the guild with the current set
|
||||
const data = await rest.put(
|
||||
Routes.applicationCommands(clientId),
|
||||
|
@ -2,23 +2,23 @@ import { Events, Interaction } from 'discord.js';
|
||||
import { DiscordClient } from '../discordClient';
|
||||
|
||||
module.exports = {
|
||||
name: Events.InteractionCreate,
|
||||
async execute(interaction: Interaction) {
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
name: Events.InteractionCreate,
|
||||
async execute(interaction: Interaction) {
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
|
||||
const client = interaction.client as DiscordClient;
|
||||
const command = client.commands.get(interaction.commandName);
|
||||
const client = interaction.client as DiscordClient;
|
||||
const command = client.commands.get(interaction.commandName);
|
||||
|
||||
if (!command) {
|
||||
console.error(`No command matching ${interaction.commandName} was found.`);
|
||||
return;
|
||||
}
|
||||
if (!command) {
|
||||
console.error(`No command matching ${interaction.commandName} was found.`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await command.execute(interaction);
|
||||
} catch (error) {
|
||||
console.error(`Error executing ${interaction.commandName}`);
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await command.execute(interaction);
|
||||
} catch (error) {
|
||||
console.error(`Error executing ${interaction.commandName}`);
|
||||
console.error(error);
|
||||
}
|
||||
},
|
||||
};
|
@ -1,24 +0,0 @@
|
||||
import 'dotenv/config.js';
|
||||
import { Events, Message, EmbedBuilder, User } from "discord.js";
|
||||
import { DiscordClient } from '../discordClient';
|
||||
|
||||
module.exports = {
|
||||
name: Events.MessageCreate,
|
||||
async execute(client: DiscordClient, message: Message) {
|
||||
if (message.author.bot) return;
|
||||
if (message.mentions.has(client.user as User)) {
|
||||
const embeds = [
|
||||
new EmbedBuilder()
|
||||
.setColor('#008000')
|
||||
.setTitle('Available slash commands')
|
||||
.setDescription(
|
||||
`/gas
|
||||
/alert [GWEI]
|
||||
/alert-delete
|
||||
/pending-alert`
|
||||
)
|
||||
]
|
||||
message.reply({embeds});
|
||||
}
|
||||
}
|
||||
};
|
@ -5,6 +5,6 @@ module.exports = {
|
||||
name: Events.ClientReady,
|
||||
once: true,
|
||||
execute(client: DiscordClient) {
|
||||
if (client.user) return console.log(`Ready! Logged in as ${client.user.id}: ${client.user.tag}`);
|
||||
if (client.user) return console.log(`Ready! Logged in as ${client.user.tag}`);
|
||||
}
|
||||
};
|
@ -1,8 +1,7 @@
|
||||
import { EmbedBuilder, TextChannel } from 'discord.js';
|
||||
|
||||
import { getGasPricesInGwei } from './blockchain';
|
||||
import { DiscordClient } from './discordClient';
|
||||
import redisClient from './redis';
|
||||
import { DiscordClient } from './discordClient';
|
||||
|
||||
import { GasAlert } from '../types/gasAlert';
|
||||
|
||||
@ -12,8 +11,8 @@ const createGasPriceChecker = (client: DiscordClient) => {
|
||||
const gasPrices = await getGasPricesInGwei();
|
||||
|
||||
const gasAlerts: GasAlert[] = await redisClient
|
||||
.hVals('gas-alerts')
|
||||
.then((values) => values.map(val => JSON.parse(val)));
|
||||
.get('gas-alerts')
|
||||
.then((value) => (value ? JSON.parse(value) : []));
|
||||
|
||||
gasAlerts.forEach(async (gasAlert) => {
|
||||
if (gasPrices.average <= gasAlert.threshold) {
|
||||
@ -24,20 +23,15 @@ const createGasPriceChecker = (client: DiscordClient) => {
|
||||
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}`)
|
||||
.setDescription(`<@${gasAlert.userId}>!\n\nThe current gas prices have fallen below your alert threshold of ${gasAlert.threshold} Gwei. The current gas prices are: \n\n Fast: ${gasPrices.fast} Gwei \n\n Average: ${gasPrices.average} Gwei \n\n Slow: ${gasPrices.slow} Gwei`)
|
||||
.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);
|
||||
console.error(`Error checking gas prices: ${error}`);
|
||||
}
|
||||
}, 15000);
|
||||
};
|
||||
|
@ -8,12 +8,12 @@ import { GasAlert } from '../types/gasAlert';
|
||||
const handleGasCommand = async (interaction: ChatInputCommandInteraction): Promise<void> => {
|
||||
const gasPrices = await getGasPricesInGwei();
|
||||
|
||||
console.log(`Replying to command "/gas": \n`, 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}`)
|
||||
.setDescription(`The current gas prices are: \n\n Fast: ${gasPrices.fast} Gwei \n\n Average: ${gasPrices.average} Gwei \n\n Slow: ${gasPrices.slow} Gwei`)
|
||||
|
||||
await interaction.reply({ embeds: [embed] });
|
||||
};
|
||||
@ -28,7 +28,9 @@ const handleGasAlertCommand = async (interaction: ChatInputCommandInteraction):
|
||||
|
||||
console.log(`Replying to command "/gas gwei ${threshold}"`);
|
||||
|
||||
await redisClient.connect();
|
||||
await redisClient.hSet('gas-alerts', `${userId}`, JSON.stringify(gasAlert));
|
||||
await redisClient.disconnect();
|
||||
|
||||
await interaction.reply(`Your gas alert threshold of ${threshold} Gwei has been set.`);
|
||||
};
|
||||
@ -37,28 +39,17 @@ const handleGasAlertCommand = async (interaction: ChatInputCommandInteraction):
|
||||
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) : {};
|
||||
await redisClient.connect();
|
||||
const alertThreshold = await redisClient.get(`${userId}`);
|
||||
await redisClient.disconnect();
|
||||
|
||||
console.log(`Replying to command "/gas pending"`);
|
||||
|
||||
if (threshold === null) {
|
||||
if (alertThreshold === null) {
|
||||
await interaction.reply('No gas price alerts set');
|
||||
} else {
|
||||
await interaction.reply(`Current gas price alert threshold: ${threshold} Gwei`);
|
||||
await interaction.reply(`Current gas price alert threshold: ${alertThreshold} 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 };
|
||||
export { handleGasCommand, handleGasAlertCommand, handleGasPendingCommand };
|
||||
|
35
src/index.ts
35
src/index.ts
@ -1,21 +1,10 @@
|
||||
/* This program is free software. It comes without any warranty, to
|
||||
* the extent permitted by applicable law. You can redistribute it
|
||||
* and/or modify it under the terms of the Do What The Fuck You Want
|
||||
* To Public License, Version 2, as published by Sam Hocevar. See
|
||||
* http://www.wtfpl.net/ for more details. */
|
||||
|
||||
import 'dotenv/config.js';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { ActivityType, GatewayIntentBits } from 'discord.js';
|
||||
|
||||
import { getGasPricesInGwei, subToBlockHeaders } from './blockchain';
|
||||
import { GatewayIntentBits } from 'discord.js';
|
||||
import { deployCommands } from './deploy';
|
||||
import { DiscordClient } from './discordClient';
|
||||
import { createGasPriceChecker } from './gasPriceChecker';
|
||||
import redisClient from './redis';
|
||||
|
||||
import { GasAlert } from '../types/gasAlert';
|
||||
|
||||
const token = process.env.DISCORD_BOT_TOKEN || "";
|
||||
|
||||
@ -44,36 +33,16 @@ for (const file of eventFiles) {
|
||||
const event = require(filePath);
|
||||
if (event.once) {
|
||||
client.once(event.name, (...args) => event.execute(...args));
|
||||
} else if (event.name == 'messageCreate') {
|
||||
client.on(event.name, (...args) => event.execute(client, ...args));
|
||||
} else {
|
||||
client.on(event.name, (...args) => event.execute(...args));
|
||||
}
|
||||
}
|
||||
|
||||
deployCommands();
|
||||
|
||||
console.log('Booting up discord bot')
|
||||
|
||||
// Log in to Discord
|
||||
client.login(token)
|
||||
.then(async () => {
|
||||
// Connect to redis
|
||||
await redisClient.connect()
|
||||
.catch((reason) => console.log("Error connecting to redis!\n", reason))
|
||||
})
|
||||
.then(async () => {
|
||||
const setDiscordStatus = async () => {
|
||||
if (client.user) {
|
||||
const { average, fast, slow } = await getGasPricesInGwei();
|
||||
client.user.setActivity(
|
||||
`⚡${fast} ⦚ 🚶${average} ⦚ 🐢${slow}`
|
||||
, { type: ActivityType.Watching });
|
||||
}
|
||||
}
|
||||
// Start listening to blockchain
|
||||
subToBlockHeaders(setDiscordStatus);
|
||||
})
|
||||
.then(deployCommands)
|
||||
.then(() => {
|
||||
// Start the gas price checker
|
||||
createGasPriceChecker(client);
|
||||
|
Loading…
Reference in New Issue
Block a user