Skip to content

Commit 5d39629

Browse files
Update permissions API, store counters to disk
Signed-off-by: Naman Sood <mail@nsood.in>
1 parent 0e94ca9 commit 5d39629

5 files changed

Lines changed: 68 additions & 51 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
*.pii.js
22
node_modules
33
package-lock.json
4+
counters.json

README.md

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,15 @@ Discord bot with a `/reset-counter` command, that counts the number of days sinc
1919
};
2020
```
2121
22-
3. Fill out `counter.pii.js` with the following information:
22+
3. Fill out `perms.pii.js` with the following information:
2323
2424
```js
2525
module.exports = {
26-
permissions: [
27-
PermissionObjects...
28-
]
26+
'guildID': ['server-roles', 'allowed-to', 'reset-counter']
2927
};
3028
```
3129
32-
Where each `PermissionObject` looks like:
33-
34-
```js
35-
{
36-
guild: "<id of guild where permission is to apply>",
37-
permissions: [
38-
{
39-
id: "<id of role or user to allow>",
40-
type: "<either the string 'ROLE' or the string 'USER'>",
41-
permission: true,
42-
}
43-
],
44-
}
45-
```
30+
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.
4631
4732
4. Run `node register.js` to register bot commands on Discord (one-time).
4833

counter.js

Lines changed: 40 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,58 @@
11
const { SlashCommandBuilder } = require('@discordjs/builders');
22
const logger = require('./log');
3+
const fs = require('fs');
4+
const path = require('path');
5+
36

47
const data = new SlashCommandBuilder()
58
.setName('reset-counter')
6-
.setDescription('Resets the global counter')
7-
.setDefaultPermission(false);
8-
9-
const counters = {};
9+
.setDescription('Resets the global counter');
1010

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

13+
const counterFile = 'counters.json';
14+
15+
function Counter() {
16+
let counters = {};
17+
if(fs.existsSync(counterFile)) {
18+
try {
19+
let contents = fs.readFileSync(counterFile, {encoding: 'utf-8'});
20+
counters = JSON.parse(contents);
21+
}
22+
catch(e) {
23+
log(`could not read ${counterFile} though it exists!`);
24+
throw e;
25+
}
26+
}
27+
this.set = function(id, val) {
28+
counters[id] = val;
29+
let json = JSON.stringify(counters);
30+
fs.writeFile(counterFile, json, err => {
31+
if(err) {
32+
log(`WARN: could not save new ${counterFile}, err: ${err}`);
33+
log(`setting counter[${id}] = ${val}`);
34+
}
35+
});
36+
}
37+
this.get = function(id) {
38+
return counters[id];
39+
}
40+
}
41+
42+
const counter = new Counter();
43+
1344
const execute = async (interaction) => {
1445
const newCounter = Date.now();
1546
const id = interaction.guildId ?? interaction.user.id;
16-
if(!counters[id]) {
17-
counters[id] = Date.now();
47+
if(!counter.get(id)) {
48+
counter.set(id, Date.now());
1849
log(`Starting counter for ${id}`);
1950
await interaction.reply(`Counting...`);
2051
return;
2152
}
22-
const daysSince = Math.floor((newCounter - counters[id]) / (24 * 60 * 60 * 1000));
53+
const daysSince = Math.floor((newCounter - counter.get(id)) / (24 * 60 * 60 * 1000));
2354
if(daysSince > 0) {
24-
counters[id] = newCounter;
55+
counter.set(id, newCounter);
2556
log(`Resetting counter for ${id} after ${daysSince} days`);
2657
await interaction.reply(`IT HAS BEEN ***~~${daysSince}~~*** ZERO DAYS.`);
2758
}
@@ -39,18 +70,4 @@ const execute = async (interaction) => {
3970
}
4071
}
4172

42-
// permissions is an array where every object looks like:
43-
// {
44-
// guild: 'GUILD_ID',
45-
// permissions: [
46-
// {
47-
// id: 'ROLE_ID or USER_ID',
48-
// type: 'ROLE or USER',
49-
// permission: true,
50-
// }
51-
// ],
52-
// }
53-
// this is an allowlist -- by default, everyone is blocked
54-
// from using the bot
55-
const { permissions } = require('./counter.pii');
56-
module.exports = { data, execute, permissions };
73+
module.exports = { data, execute };

index.js

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const {Intents, Client, Collection } = require('discord.js');
22
const counter = require('./counter');
33
const logger = require('./log');
44
const { discordToken } = require('./auth.pii');
5+
const perms = require('./perms.pii');
56

67
function fail(err) { throw err; }
78
const log = logger.new('index');
@@ -33,12 +34,6 @@ async function main() {
3334
const cmd = commands[i];
3435
const name = cmd.data.name;
3536
client.commands.set(name, cmd);
36-
appCommands.filter(appCmd => appCmd.name === name).map(appCmd => appCmd.id).forEach(async appCmdId => {
37-
const appCmd = await client.application.commands.fetch(appCmdId);
38-
for(perm of cmd.permissions) {
39-
await appCmd.permissions.add(perm);
40-
}
41-
});
4237
}
4338

4439
log('commands registered');
@@ -49,6 +44,25 @@ async function main() {
4944
return;
5045
}
5146

47+
if(perms[interaction.guildId]) {
48+
let allowedRoles = perms[interaction.guildId];
49+
let found = false;
50+
let hasRoles = interaction.member.roles.cache ?? interaction.member.roles;
51+
for(let role of allowedRoles) {
52+
if(hasRoles.some(r => r.name === role)) {
53+
found = true;
54+
break;
55+
}
56+
}
57+
if(!found) {
58+
return interaction.reply(
59+
`Only those with the following roles can reset the counter in this server.
60+
61+
${allowedRoles.join(', ')}`
62+
);
63+
}
64+
}
65+
5266
const cmd = client.commands.get(interaction.commandName);
5367

5468
if(!cmd) {

package.json

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"name": "mathnews-bot",
2+
"name": "counter-bot",
33
"version": "0.4.2",
44
"description": "",
55
"main": "index.js",
@@ -8,14 +8,14 @@
88
},
99
"repository": {
1010
"type": "git",
11-
"url": "git+https://github.com/namansood/mathnews-bot.git"
11+
"url": "git+https://github.com/tendstofortytwo/counter-bot.git"
1212
},
1313
"author": "Naman Sood",
1414
"license": "MIT",
1515
"bugs": {
16-
"url": "https://github.com/namansood/mathnews-bot/issues"
16+
"url": "https://github.com/tendstofortytwo/counter-bot/issues"
1717
},
18-
"homepage": "https://github.com/namansood/mathnews-bot#readme",
18+
"homepage": "https://github.com/tendstofortytwo/counter-bot#readme",
1919
"dependencies": {
2020
"@discordjs/rest": "^0.1.0-canary.0",
2121
"discord-api-types": "^0.25.2",

0 commit comments

Comments
 (0)