Redis Timer System

This commit is contained in:
Dragon Fire
2020-11-19 17:03:56 -05:00
parent 480e736b53
commit 8cdba0ff30
8 changed files with 81 additions and 12 deletions
+4
View File
@@ -4,6 +4,8 @@ const Collection = require('@discordjs/collection');
const winston = require('winston');
const fs = require('fs');
const path = require('path');
const Redis = require('./Redis');
const TimerManager = require('./timer/TimerManager');
const PokemonStore = require('./pokemon/PokemonStore');
const MemePosterClient = require('./MemePoster');
const activities = require('../assets/json/activity');
@@ -30,7 +32,9 @@ module.exports = class XiaoClient extends CommandoClient {
winston.format.printf(log => `[${log.timestamp}] [${log.level.toUpperCase()}]: ${log.message}`)
)
});
this.redis = Redis ? Redis.db : null;
this.webhook = new WebhookClient(XIAO_WEBHOOK_ID, XIAO_WEBHOOK_TOKEN, { disableMentions: 'everyone' });
this.timers = new TimerManager(this);
this.pokemon = new PokemonStore();
this.memePoster = POSTER_ID && POSTER_TOKEN ? new MemePosterClient(POSTER_ID, POSTER_TOKEN, {
subreddits,
+22
View File
@@ -0,0 +1,22 @@
const Redis = require('ioredis');
const { REDIS_HOST, REDIS_PASS } = process.env;
const redis = new Redis({
port: 6379,
host: REDIS_HOST,
enableReadyCheck: true,
password: REDIS_PASS,
db: 0
});
module.exports = class RedisClient {
static get db() {
return redis;
}
static start() {
redis.on('connect', () => console.info('[REDIS][CONNECT]: Connecting...'));
redis.on('ready', () => console.info('[REDIS][READY]: Ready!'));
redis.on('error', error => console.error(`[REDIS][ERROR]: Encountered error:\n${error}`));
redis.on('reconnecting', () => console.warn('[REDIS][RECONNECT]: Reconnecting...'));
}
};
+34
View File
@@ -0,0 +1,34 @@
const Redis = require('../Redis');
module.exports = class TimerManager {
constructor(client) {
Object.defineProperty(this, 'client', { value: client });
}
async fetchAll() {
const timers = await Redis.db.hgetall('timer');
for (const data of Object.keys(timers)) {
data = JSON.parse(data);
await this.setTimer(data.channelID, new Date(data.time) - new Date(), data.userID, data.title, false);
}
return this;
}
async setTimer(channelID, time, userID, title, updateRedis = true) {
const data = { time: new Date(Date.now() + time).toISOString(), channelID, userID, title };
const timeout = setTimeout(async () => {
try {
const channel = await this.client.channels.fetch(channelID);
await channel.send(`🕰️ <@${userID}>, you wanted me to remind you of: **"${title}"**.`);
} finally {
await Redis.db.hdel('timer', `${channelID}-${userID}`);
}
}, time);
if (updateRedis) await Redis.db.hset('timer', { [`${channelID}-${userID}`]: JSON.stringify(data) });
return timeout;
}
exists(channelID, userID) {
return Redis.db.hexists('timer', `${channelID}-${userID}`);
}
};