Skip to content

Commit

Permalink
use lodash for data deep comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
versx committed Jul 30, 2022
1 parent eab9665 commit c01aa47
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 39 deletions.
28 changes: 20 additions & 8 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@
"discord.js": "^12.5.1",
"eslint": "^7.16.0",
"i18n": "^0.9.0",
"lodash": "^4.17.21",
"mustache": "^4.1.0"
},
"devDependencies": {
"@types/axios": "^0.14.0",
"@types/i18n": "^0.12.0",
"@types/lodash": "^4.14.182",
"@types/mustache": "^4.1.1",
"@types/node": "^14.0.1",
"@typescript-eslint/eslint-plugin": "^3.0.0",
Expand Down
54 changes: 30 additions & 24 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ import { sendDm } from './handlers/dm';
import { createActiveEventEmbed, createEmbedFromNewEvent } from './handlers/embeds';
import { PokemonEvents } from './models/events';
import { UrlWatcher } from './services/url-watcher';
import { post, getWebhookData, WebhookData } from './services/utils';
import { post, getWebhookData } from './services/utils';
import { ActiveEvent } from './types/events';

const client = new Client();
const urlToWatch = 'https://raw.githubusercontent.com/ccev/pogoinfo/v2/active/events.json';
const intervalM = 1 * 60 * 1000;
const intervalM = 1 * 60 * 1000; // 60 seconds
const NotAvailable = 'N/A';
let started = false;

Expand Down Expand Up @@ -78,7 +78,7 @@ const createChannels = async (): Promise<void> => {
}
};

const createVoiceChannels = async (guildInfo: any, activeEvents: any): Promise<void> => {
const createVoiceChannels = async (guildInfo: any, activeEvents: ActiveEvent[]): Promise<void> => {
// Check if event category id set for guild
if (!guildInfo.eventsCategoryId) {
return;
Expand Down Expand Up @@ -210,41 +210,47 @@ UrlWatcher(urlToWatch, intervalM, async (): Promise<void> => {
// Delete previous event messages if set
if (config.deletePreviousEvents) {
// Get information returned about webhook
getWebhookData(webhook)?.then((webhookData: WebhookData | null) => {
// Check if
if (webhookData?.guild_id && webhookData?.channel_id) {
const guild = client.guilds.cache.get(webhookData.guild_id);
if (guild) {
const channel = guild.channels.cache.get(webhookData.channel_id);
try {
// Ensure we only try to delete messages from text channels
if (channel?.type == 'text') {
(channel as TextChannel).bulkDelete(100);
}
} catch (err) {
console.error('Error:', err);
}
const webhookData = await getWebhookData(webhook);
if (!webhookData) {
// Failed to get webhook result data from response
console.error(`Failed to get webhook data from ${webhook}`);
continue;
}
// Check if webhook result response has
if (!webhookData?.guild_id || !webhookData?.channel_id) {
// Missing required information from webhook data response
continue;
}
const guild = client.guilds.cache.get(webhookData.guild_id);
if (guild) {
const channel = guild.channels.cache.get(webhookData.channel_id);
try {
// Ensure we only try to delete messages from text channels
if (channel?.type == 'text') {
(channel as TextChannel).bulkDelete(100);
}
} catch (err) {
// Fails if messages to delete are older than 14 days
console.error('Error:', err);
}
}).catch(err => {
console.error(`Failed to get webhook data for ${webhook}: ${err}`);
});
}
}
await post(<string>webhook, payload);
}
}
// If bot token set we're logged into Discord bot
if (config.token) {
// Check that bot token and user ids list are set
if (config.token && config.userIds.length) {
// Create Discord embed that'll be sent to users
const embed = await createActiveEventEmbed(event);
// Send direct message to users
for (const userId of config.userIds) {
const member = client.users.cache.get(userId);
if (member == null) {
if (!member || member == null) {
console.error(`Failed to get member by id ${userId}`);
continue;
}
// Send DM info about event to Discord user
await sendDm(member, { embed: embed });
await sendDm(member, { embed });
console.info(`New event direct message sent to ${member?.username} (${member?.id})`);
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/services/url-watcher.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

import { NoParamCallback } from 'fs';
import { isEqual } from 'lodash';
import { get, deepEqual } from '../services/utils';

let previousData: any;
Expand All @@ -15,7 +16,7 @@ export const UrlWatcher = (urlToWatch: string, interval: number, changedCallback
previousData = data;
return;
}
if (!deepEqual(previousData, data)) {
if (!isEqual(previousData, data)) {
previousData = data;
changedCallback(null);
}
Expand Down
10 changes: 4 additions & 6 deletions src/services/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict';

const axios = require('axios').default;

const UserAgent = 'PokemonGoEventWatcher';

/**
Expand Down Expand Up @@ -32,18 +31,17 @@ export const get = async <T>(url: string): Promise<T | null> => {
* @param {*} data
*/
export const post = async <T>(url: string, data: any): Promise<T | null> => {
const req = axios({
url: url,
const req = await axios({
url,
method: 'POST',
data: data,
data,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': UserAgent,
},
});
//const req = await axios.post(url, data);
if (req.status !== 200 && req.statusText !== 'No Content') {
if (req.status !== 200 || (req.status !== 204 && req.statusText !== 'No Content')) {
console.error(`Failed to post data to ${url}:`, req.statusText);
return null;
}
Expand Down

0 comments on commit c01aa47

Please sign in to comment.