Skip to content

Commit

Permalink
Setup basic keyv for ratelimiting
Browse files Browse the repository at this point in the history
  • Loading branch information
yanukadeneth99 committed Aug 23, 2022
1 parent 8761d37 commit 7daa4e6
Show file tree
Hide file tree
Showing 8 changed files with 89 additions and 29 deletions.
4 changes: 2 additions & 2 deletions events/interactionCreate.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const feedback_handle = require("../modals/feedback_handle");

module.exports = {
name: "interactionCreate",
async execute(client, interaction) {
async execute(keyv, client, interaction) {
try {
// Get the Log Channel
const errorchannel = await client.channels.cache.get(channels.error);
Expand All @@ -25,7 +25,7 @@ module.exports = {
} else if (interaction.commandName === "balance") {
require("../responses/balance_response")(interaction);
} else if (interaction.commandName === "faucet") {
require("../responses/faucet_response")(interaction);
require("../responses/faucet_response")(keyv, interaction);
}
// Invalid Chat command passed
else {
Expand Down
13 changes: 7 additions & 6 deletions events/ready.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,20 @@ module.exports = {
once: true,
async execute(client) {
try {
// Morning Print of Waking Up
// Setting Status of Bot
client.user.setActivity("LearnWeb3DAO", {
type: ActivityType.Watching,
});
client.user.setStatus("online");

//Morning Print of Waking Up
// const logchannel = await client.channels.cache.get(channels.log);
// logchannel.send(
// `[LOGIN/RESTART]\n${new Date(
// Date.now()
// ).toUTCString()}\nFaucet Bot Woken`
// );

// Setting Status of Bot
client.user.setActivity("LearnWeb3DAO", {
type: ActivityType.Watching,
});
client.user.setStatus("online");
console.log(`Ready! Logged in as ${client.user.tag}`);
} catch (error) {
console.error(`Error Starting BOT in ready : ${error}`);
Expand Down
7 changes: 3 additions & 4 deletions example.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
"log": "0000000000000",
"error": "0000000000000"
},
"roles": {
"admin": "0000000000000"
},
"bypassRoles": ["0000000000000"],
"networks": {
"goerli": {
"nativeCurrency": "eth",
Expand All @@ -36,7 +34,8 @@
"stats": {
"walletAddress": "xxxxxxxx",
"dailyEth": 1,
"maxFee": 95000000000
"maxFee": 95000000000,
"coolDownTime": 60000
},
"secrets": {
"walletPrivateKey": "xxxxxxxxx",
Expand Down
10 changes: 9 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
// Starting Point of the project : run `node .`
const fs = require("node:fs");
const path = require("node:path");
const Keyv = require("keyv");
const { Collection } = require("discord.js");
const { secrets } = require("./config.json");
const client = require("./client"); // Get Client

// KeyV Creation and Handling
const keyv = new Keyv();
keyv.on("error", (err) => {
console.error("Keyv connection error:", err);
throw new Error("Error KEYV: ", err);
});

// Run the Events
const eventsPath = path.join(__dirname, "events");
const eventFiles = fs
Expand All @@ -17,7 +25,7 @@ for (const file of eventFiles) {
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(client, ...args));
client.on(event.name, (...args) => event.execute(keyv, client, ...args));
}
}

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"discord-api-types": "^0.37.3",
"discord.js": "^14.2.0",
"dotenv": "^16.0.1",
"ethers": "^5.7.0"
"ethers": "^5.7.0",
"keyv": "^4.4.1"
}
}
25 changes: 25 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 0 additions & 12 deletions responses/balance_response.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,6 @@ module.exports = async (interaction) => {
await interaction.editReply(
`[${networkName.toUpperCase()}] [${balancefinal}] [${tokenName.toUpperCase()}]`
);

// Log out the transaction
// const logchannel = await interaction.client.channels.cache.get(
// channels.log
// );
// logchannel.send(
// `[BALANCE]\n${new Date(
// Date.now()
// ).toUTCString()}\nNetwork : ${networkName.toUpperCase()}\nToken : ${tokenName.toUpperCase()}\nBy : ${
// interaction.user.username
// }`
// );
} catch (error) {
console.error(`Error [RESPONCE - BALANCE] : ${error}`);
const errorchannel = await interaction.client.channels.cache.get(
Expand Down
44 changes: 41 additions & 3 deletions responses/faucet_response.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,24 @@ const ethers = require("ethers");
const getProvider = require("../utils/getProvider");
const getBalance = require("../utils/getBalance");
const transfer = require("../utils/transfer");
const { stats, networks, channels } = require("../config.json");
const {
stats,
networks,
tokens,
channels,
bypassRoles,
} = require("../config.json");

// TODO : Apply Rate Limiting
// TODO : Make sure only verified members can do this (or any other role)
// BUG : Find why mumbai transfers doesnt work
// TODO : Return with user input if the needed variables are not there, like below :
/*
if (!PRIVATE_KEY || !FROM_ADDRESS || !ALCHEMY_RINKEBY_URL) {
return ({ status: 'error', message: 'Missing environment variables, please ask human to set them up.' });
}
*/

module.exports = async (interaction) => {
module.exports = async (keyv, interaction) => {
// Initial Responce to client
await interaction.reply({ content: "🤖 Mining....", fetchReply: true });
try {
Expand All @@ -31,6 +42,25 @@ module.exports = async (interaction) => {
return;
}

//* Rate Limiting for non Admins
if (bypassRoles.some((role) => interaction.member.roles.cache.has(role))) {
const lastReqTime = await keyv.get(interaction.user.id);
if (lastReqTime) {
// CoolDownTime is set in Miliseconds.
if (Date.now() - lastReqTime < stats.coolDownTime) {
// Divide this by 60 if you want to shift to minutes
const timeLeft = Math.floor(
(stats.coolDownTime - (Date.now() - lastReqTime)) / 1000
);
await interaction.editReply(
`😎 Cool people waits for ${timeLeft} seconds`
);
return;
}
} else {
await keyv.set(interaction.user.id, Date.now());
}
}
// Get the Provider based on the network
const provider = getProvider(networkName);

Expand All @@ -56,6 +86,14 @@ module.exports = async (interaction) => {
}
//* Non Native Transfer (ERC-20)
else {
// If there is no contract address for that token
if (!tokens[tokenName][networkName]) {
await interaction.editReply(
`😱 Token unavailable for network : ${networkName.toUpperCase()}`
);
return;
}

// If the balance is too low (curBalance is in a float)
const curBalance = await getBalance(provider, tokenName, networkName);
if (curBalance < stats.dailyEth) {
Expand Down

0 comments on commit 7daa4e6

Please sign in to comment.