Skip to content

Commit

Permalink
Update permissions API, store counters to disk
Browse files Browse the repository at this point in the history
Signed-off-by: Naman Sood <mail@nsood.in>
  • Loading branch information
tendstofortytwo committed Jun 6, 2022
1 parent 0e94ca9 commit 5d39629
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 51 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
*.pii.js
node_modules
package-lock.json
counters.json
21 changes: 3 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,30 +19,15 @@ Discord bot with a `/reset-counter` command, that counts the number of days sinc
};
```

3. Fill out `counter.pii.js` with the following information:
3. Fill out `perms.pii.js` with the following information:

```js
module.exports = {
permissions: [
PermissionObjects...
]
'guildID': ['server-roles', 'allowed-to', 'reset-counter']
};
```

Where each `PermissionObject` looks like:

```js
{
guild: "<id of guild where permission is to apply>",
permissions: [
{
id: "<id of role or user to allow>",
type: "<either the string 'ROLE' or the string 'USER'>",
permission: true,
}
],
}
```
Any guild specified in perms.pii will have the list of allowed roles as an allowlist -- anyone else will be disallowed from using the bot. Any guild not specified in perms.pii will by default allow everyone to use the bot.

4. Run `node register.js` to register bot commands on Discord (one-time).

Expand Down
63 changes: 40 additions & 23 deletions counter.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,58 @@
const { SlashCommandBuilder } = require('@discordjs/builders');
const logger = require('./log');
const fs = require('fs');
const path = require('path');


const data = new SlashCommandBuilder()
.setName('reset-counter')
.setDescription('Resets the global counter')
.setDefaultPermission(false);

const counters = {};
.setDescription('Resets the global counter');

const log = logger.new('reset-counter');

const counterFile = 'counters.json';

function Counter() {
let counters = {};
if(fs.existsSync(counterFile)) {
try {
let contents = fs.readFileSync(counterFile, {encoding: 'utf-8'});
counters = JSON.parse(contents);
}
catch(e) {
log(`could not read ${counterFile} though it exists!`);
throw e;
}
}
this.set = function(id, val) {
counters[id] = val;
let json = JSON.stringify(counters);
fs.writeFile(counterFile, json, err => {
if(err) {
log(`WARN: could not save new ${counterFile}, err: ${err}`);
log(`setting counter[${id}] = ${val}`);
}
});
}
this.get = function(id) {
return counters[id];
}
}

const counter = new Counter();

const execute = async (interaction) => {
const newCounter = Date.now();
const id = interaction.guildId ?? interaction.user.id;
if(!counters[id]) {
counters[id] = Date.now();
if(!counter.get(id)) {
counter.set(id, Date.now());
log(`Starting counter for ${id}`);
await interaction.reply(`Counting...`);
return;
}
const daysSince = Math.floor((newCounter - counters[id]) / (24 * 60 * 60 * 1000));
const daysSince = Math.floor((newCounter - counter.get(id)) / (24 * 60 * 60 * 1000));
if(daysSince > 0) {
counters[id] = newCounter;
counter.set(id, newCounter);
log(`Resetting counter for ${id} after ${daysSince} days`);
await interaction.reply(`IT HAS BEEN ***~~${daysSince}~~*** ZERO DAYS.`);
}
Expand All @@ -39,18 +70,4 @@ const execute = async (interaction) => {
}
}

// permissions is an array where every object looks like:
// {
// guild: 'GUILD_ID',
// permissions: [
// {
// id: 'ROLE_ID or USER_ID',
// type: 'ROLE or USER',
// permission: true,
// }
// ],
// }
// this is an allowlist -- by default, everyone is blocked
// from using the bot
const { permissions } = require('./counter.pii');
module.exports = { data, execute, permissions };
module.exports = { data, execute };
26 changes: 20 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const {Intents, Client, Collection } = require('discord.js');
const counter = require('./counter');
const logger = require('./log');
const { discordToken } = require('./auth.pii');
const perms = require('./perms.pii');

function fail(err) { throw err; }
const log = logger.new('index');
Expand Down Expand Up @@ -33,12 +34,6 @@ async function main() {
const cmd = commands[i];
const name = cmd.data.name;
client.commands.set(name, cmd);
appCommands.filter(appCmd => appCmd.name === name).map(appCmd => appCmd.id).forEach(async appCmdId => {
const appCmd = await client.application.commands.fetch(appCmdId);
for(perm of cmd.permissions) {
await appCmd.permissions.add(perm);
}
});
}

log('commands registered');
Expand All @@ -49,6 +44,25 @@ async function main() {
return;
}

if(perms[interaction.guildId]) {
let allowedRoles = perms[interaction.guildId];
let found = false;
let hasRoles = interaction.member.roles.cache ?? interaction.member.roles;
for(let role of allowedRoles) {
if(hasRoles.some(r => r.name === role)) {
found = true;
break;
}
}
if(!found) {
return interaction.reply(
`Only those with the following roles can reset the counter in this server.
${allowedRoles.join(', ')}`
);
}
}

const cmd = client.commands.get(interaction.commandName);

if(!cmd) {
Expand Down
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "mathnews-bot",
"name": "counter-bot",
"version": "0.4.2",
"description": "",
"main": "index.js",
Expand All @@ -8,14 +8,14 @@
},
"repository": {
"type": "git",
"url": "git+https://github.com/namansood/mathnews-bot.git"
"url": "git+https://github.com/tendstofortytwo/counter-bot.git"
},
"author": "Naman Sood",
"license": "MIT",
"bugs": {
"url": "https://github.com/namansood/mathnews-bot/issues"
"url": "https://github.com/tendstofortytwo/counter-bot/issues"
},
"homepage": "https://github.com/namansood/mathnews-bot#readme",
"homepage": "https://github.com/tendstofortytwo/counter-bot#readme",
"dependencies": {
"@discordjs/rest": "^0.1.0-canary.0",
"discord-api-types": "^0.25.2",
Expand Down

0 comments on commit 5d39629

Please sign in to comment.