docker builds successfully, now need to figure out websocket connection

This commit is contained in:
GooeyTuxedo
2023-04-17 20:06:37 -07:00
parent a87549dfcd
commit 3dd291f394
11 changed files with 708 additions and 42 deletions

View File

@ -1,11 +1,12 @@
import 'dotenv/config.js';
import { GasPrices } from '../types/gasPrices'
const Web3 = require('web3');
const Web3WsProvider = require('web3-providers-ws');
const rpcUrl = process.env.RPC_URL || 'ws://localhost:8545';
// Create a new web3 instance
const web3 = new Web3(rpcUrl);
const web3 = new Web3(new Web3WsProvider(rpcUrl));
// Get the current gas price in gwei
const getGasPricesInGwei = async (): Promise<GasPrices> => {

40
src/deploy.ts Normal file
View File

@ -0,0 +1,40 @@
import 'dotenv/config.js';
import fs from 'node:fs';
import path from 'node:path';
import { ApplicationCommand, REST, Routes } from 'discord.js';
const clientId = process.env.DISCORD_CLIENT || "";
const token = process.env.DISCORD_BOT_TOKEN || "";
const commands: ApplicationCommand[] = [];
// Grab all the command files from the commands directory you created earlier
const commandsPath = path.join(__dirname, './commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
// Construct and prepare an instance of the REST module
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),
{ body: commands },
) as ApplicationCommand[];
console.log(`Successfully reloaded ${data.length} global application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error('Error setting application commands: \n', error);
}
};

5
src/discordClient.ts Normal file
View File

@ -0,0 +1,5 @@
import { Client, Collection } from "discord.js";
export class DiscordClient extends Client {
public commands: Collection<string, any> = new Collection();
}

View File

@ -0,0 +1,24 @@
import { Events, Interaction } from 'discord.js';
import { DiscordClient } from '../discordClient';
module.exports = {
name: Events.InteractionCreate,
async execute(interaction: Interaction) {
if (!interaction.isChatInputCommand()) return;
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;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
},
};

10
src/events/ready.ts Normal file
View File

@ -0,0 +1,10 @@
import { Events } from "discord.js";
import { DiscordClient } from "../discordClient";
module.exports = {
name: Events.ClientReady,
once: true,
execute(client: DiscordClient) {
if (client.user) return console.log(`Ready! Logged in as ${client.user.tag}`);
}
};

View File

@ -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.`);
};
@ -36,7 +38,10 @@ const handleGasAlertCommand = async (interaction: ChatInputCommandInteraction):
// Respond to the "/gas pending" command
const handleGasPendingCommand = async (interaction: ChatInputCommandInteraction): Promise<void> => {
const userId = interaction.user.id;
await redisClient.connect();
const alertThreshold = await redisClient.get(`${userId}`);
await redisClient.disconnect();
console.log(`Replying to command "/gas pending"`);

View File

@ -1,20 +1,16 @@
import 'dotenv/config.js';
import fs from 'node:fs';
import path from 'node:path';
import { ApplicationCommand, Client, Collection, GatewayIntentBits, REST, Routes } from 'discord.js';
import { GatewayIntentBits } from 'discord.js';
import { deployCommands } from './deploy';
import { DiscordClient } from './discordClient';
import { createGasPriceChecker } from './gasPriceChecker';
const clientId = process.env.DISCORD_CLIENT || "";
const token = process.env.DISCORD_BOT_TOKEN || "";
export class DiscordClient extends Client {
public commands: Collection<string, any> = new Collection();
}
// Create a new Discord client
const client = new DiscordClient({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] });
const commands: ApplicationCommand[] = [];
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
@ -23,7 +19,6 @@ for (const file of commandFiles) {
const command = require(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON())
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
@ -46,22 +41,8 @@ for (const file of eventFiles) {
console.log('Booting up discord bot')
// Log in to Discord
client.login(process.env.DISCORD_BOT_TOKEN)
.then(async () => {
console.log(`Started refreshing ${commands.length} global application (/) commands.`);
// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(token);
// 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),
{ body: commands },
) as ApplicationCommand[];
console.log(`Successfully reloaded ${data.length} global application (/) commands.`);
})
client.login(token)
.then(deployCommands)
.then(() => {
// Start the gas price checker
createGasPriceChecker(client);

View File

@ -1,13 +1,13 @@
import Redis from 'redis';
import { createClient } from 'redis';
// Create a new Redis client
const client = Redis.createClient({
url: 'redis://redis:6379'
const client = createClient({
url: 'redis://gwei-bot-redis:6379'
});
// Log any Redis errors to the console
client.on('error', (error) => {
console.error(error);
console.error('Redis Client Error', error);
});
// Export the Redis client