Skip to content

Commit

Permalink
chore: update ESLint rules, clean up imports, and remove incompatible…
Browse files Browse the repository at this point in the history
… Twitch dependencies
  • Loading branch information
alanbixby committed Jan 28, 2025
1 parent f59d3fc commit c8d28ee
Show file tree
Hide file tree
Showing 11 changed files with 150 additions and 130 deletions.
1 change: 1 addition & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"extends": "./node_modules/gts/",
"rules": {
"@typescript-eslint/no-explicit-any": "off",
"prettier/prettier": [
"error",
{
Expand Down
3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,6 @@
"redis": "^3.1.2",
"top-user-agents": "^1.0.37",
"twilio": "^3.71.1",
"twitch": "^4.6.5",
"twitch-auth": "^4.6.5",
"twitch-chat-client": "^4.6.5",
"twitter": "^1.7.1",
"winston": "^3.3.3"
},
Expand Down
16 changes: 14 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {existsSync, readFileSync} from 'fs';
import {banner} from './banner';
import dotenv from 'dotenv';
import {existsSync, readFileSync} from 'fs';
import path from 'path';
import {banner} from './banner';

if (process.env.npm_config_conf) {
if (
Expand Down Expand Up @@ -408,6 +408,18 @@ if (process.env.MAX_PRICE) {
);
}

if (
process.env.TWITCH_ACCESS_TOKEN ||
process.env.TWITCH_CHANNEL ||
process.env.TWITCH_CLIENT_ID ||
process.env.TWITCH_CLIENT_SECRET ||
process.env.TWITCH_REFRESH_TOKEN
) {
console.warn(
'ℹ TWITCH integrations are currently incompatible with this release'
);
}

const store = {
autoAddToCart: envOrBoolean(process.env.AUTO_ADD_TO_CART, true),
country: envOrString(process.env.COUNTRY, 'usa'),
Expand Down
6 changes: 3 additions & 3 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Link, Store} from './store/model';
import chalk from 'chalk';
import {config} from './config';
import winston from 'winston';
import {config} from './config';
import {Link, Store} from './store/model';

const prettyJson = winston.format.printf(info => {
const timestamp = new Date().toLocaleTimeString();
Expand All @@ -10,7 +10,7 @@ const prettyJson = winston.format.printf(info => {
'::'
)} ${info.message}`;

if (Object.keys(info.metadata).length > 0) {
if (Object.keys(info.metadata as object).length > 0) {
out = `${out} ${chalk.magenta(JSON.stringify(info.metadata, null, 2))}`;
}

Expand Down
5 changes: 3 additions & 2 deletions src/messaging/apns.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import {Link, Store} from '../store/model';
import {Print, logger} from '../logger';
import * as apn from '@parse/node-apn';
import {config} from '../config';
import {logger} from '../logger';
import {Link, Store} from '../store/model';

const {apns} = config.notifications;

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function sendApns(link: Link, store: Store) {
const options = {
token: {
Expand Down
9 changes: 3 additions & 6 deletions src/messaging/discord.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import {Link, Store} from '../store/model';
import Discord from 'discord.js';
import {DMPayload} from '.';
import {config} from '../config';
import {logger} from '../logger';
import {DMPayload} from '.';
import {RawUserData} from 'discord.js/typings/rawDataTypes';
import {Link, Store} from '../store/model';

const {notifyGroup, webhooks, notifyGroupSeries} = config.notifications.discord;
const {pollInterval, responseTimeout, token, userId} = config.captchaHandler;
Expand Down Expand Up @@ -211,9 +210,7 @@ async function getDiscordClientAsync() {
async function getDMChannelAsync(client?: Discord.Client) {
let dmChannelInstance = undefined;
if (userId && client) {
const user = await new Discord.User(client, {
id: userId,
} as RawUserData).fetch();
const user = await client.users.fetch(userId);
dmChannelInstance = await user.createDM();
}
return dmChannelInstance;
Expand Down
22 changes: 11 additions & 11 deletions src/messaging/notification.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
import {DMPayload} from '.';
import {Link, Store} from '../store/model';
import {adjustPhilipsHueLights} from './philips-hue';
import {playSound} from './sound';
import {sendApns} from './apns';
import {sendDesktopNotification} from './desktop';
import {sendDiscordMessage, sendDMAsync as sendDiscordDM} from './discord';
import {sendDMAsync as sendDiscordDM, sendDiscordMessage} from './discord';
import {sendEmail} from './email';
import {sendFreeMobileAlert} from './freemobile';
import {sendGotifyNotification} from './gotify';
import {sendMqttMessage} from './mqtt';
import {sendPagerDutyNotification} from './pagerduty';
import {adjustPhilipsHueLights} from './philips-hue';
import {sendPushbulletNotification} from './pushbullet';
import {sendPushoverNotification} from './pushover';
import {sendSlackMessage, sendDMAsync as sendSlackDM} from './slack';
import {updateRedis} from './redis';
import {sendDMAsync as sendSlackDM, sendSlackMessage} from './slack';
import {sendSms} from './sms';
import {playSound} from './sound';
import {sendStreamLabsAlert} from './streamlabs';
import {sendTelegramMessage} from './telegram';
import {sendTweet} from './twitter';
import {sendTwilioMessage} from './twilio';
import {sendTwitchMessage} from './twitch';
import {updateRedis} from './redis';
import {sendStreamLabsAlert} from './streamlabs';
import {sendFreeMobileAlert} from './freemobile';
import {DMPayload} from '.';
// import {sendTwitchMessage} from './twitch';
import {sendTweet} from './twitter';

export function sendNotification(link: Link, store: Store) {
// Priority
Expand All @@ -40,7 +40,7 @@ export function sendNotification(link: Link, store: Store) {
sendTelegramMessage(link, store);
sendTweet(link, store);
sendTwilioMessage(link, store);
sendTwitchMessage(link, store);
// sendTwitchMessage(link, store);
updateRedis(link, store);
sendStreamLabsAlert(link, store);
sendFreeMobileAlert(link, store);
Expand Down
8 changes: 4 additions & 4 deletions src/messaging/redis.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Link, Store} from '../store/model';
import redis, {RedisClient} from 'redis';
import {config} from '../config';
import {logger} from '../logger';
import {Link, Store} from '../store/model';

const {url} = config.notifications.redis;
let client: RedisClient;
Expand Down Expand Up @@ -30,17 +30,17 @@ export function updateRedis(link: Link, store: Store) {
};

const message = JSON.stringify(value);
client.set(key, message, (error, success) => {
client.set(key, message, error => {
if (error) {
logger.error(`✖ couldn't update redis for key (${key})`);
} else {
logger.info('✔ redis updated');
}
});

client.publish('streetmerchant', message, (error, success) => {
client.publish('streetmerchant', message, error => {
if (error) {
logger.error(`✖ couldn't publish to redis`);
logger.error("✖ couldn't publish to redis");
} else {
logger.info('✔ redis message published');
}
Expand Down
189 changes: 100 additions & 89 deletions src/messaging/twitch.ts
Original file line number Diff line number Diff line change
@@ -1,101 +1,112 @@
import {Link, Store} from '../store/model';
import {Print, logger} from '../logger';
import {RefreshableAuthProvider, StaticAuthProvider} from 'twitch-auth';
import {existsSync, promises, readFileSync} from 'fs';
import {ChatClient} from 'twitch-chat-client';
import {config} from '../config';
/**
* TODO: Needs to be upgraded to @twurple/auth + @twurple/chat - currently throws the following error if no client params are in
* dotenv and an item is found
*
* var _this = _super.call(this) || this;
TypeError: Class constructor EventEmitter cannot be invoked without 'new'
at ChatClient.IrcClient [as constructor] (/streetmerchant/node_modules/.pnpm/[email protected]/node_modules/ircv3/lib/IrcClient.js:24:28)
at new ChatClient (/streetmerchant/node_modules/.pnpm/[email protected][email protected]/node_modules/twitch-chat-client/lib/ChatClient.js:44:28)
at Object.<anonymous> (/streetmerchant/build/src/messaging/twitch.js:23:20)
*/

const {twitch} = config.notifications;
// import {Link, Store} from '../store/model';
// import {Print, logger} from '../logger';
// import {RefreshableAuthProvider, StaticAuthProvider} from 'twitch-auth';
// import {existsSync, promises, readFileSync} from 'fs';
// import {ChatClient} from 'twitch-chat-client';
// import {config} from '../config';

const messages: string[] = [];
let alreadySaying = false;
// const {twitch} = config.notifications;

let tokenData = {
accessToken: twitch.accessToken,
expiryTimestamp: 0,
refreshToken: twitch.refreshToken,
};
// const messages: string[] = [];
// let alreadySaying = false;

if (existsSync('./twitch.json')) {
tokenData = {
...JSON.parse(readFileSync('./twitch.json', 'utf-8')),
...tokenData,
};
}
// let tokenData = {
// accessToken: twitch.accessToken,
// expiryTimestamp: 0,
// refreshToken: twitch.refreshToken,
// };

const chatClient: ChatClient = new ChatClient(
new RefreshableAuthProvider(
new StaticAuthProvider(twitch.clientId, tokenData.accessToken),
{
clientSecret: twitch.clientSecret,
expiry:
tokenData.expiryTimestamp === null
? null
: new Date(tokenData.expiryTimestamp),
onRefresh: async ({accessToken, refreshToken, expiryDate}) => {
return promises.writeFile(
'./twitch.json',
JSON.stringify(
{
accessToken,
expiryTimestamp:
expiryDate === null ? null : expiryDate.getTime(),
refreshToken,
},
null,
4
),
'utf-8'
);
},
refreshToken: tokenData.refreshToken,
}
),
{
channels: [twitch.channel],
}
);
// if (existsSync('./twitch.json')) {
// tokenData = {
// ...JSON.parse(readFileSync('./twitch.json', 'utf-8')),
// ...tokenData,
// };
// }

chatClient.onJoin((channel: string, user: string) => {
if (channel === `#${twitch.channel}` && user === chatClient.currentNick) {
while (messages.length) {
const message: string | undefined = messages.shift();
// const chatClient: ChatClient = new ChatClient(
// new RefreshableAuthProvider(
// new StaticAuthProvider(twitch.clientId, tokenData.accessToken),
// {
// clientSecret: twitch.clientSecret,
// expiry:
// tokenData.expiryTimestamp === null
// ? null
// : new Date(tokenData.expiryTimestamp),
// onRefresh: async ({accessToken, refreshToken, expiryDate}) => {
// return promises.writeFile(
// './twitch.json',
// JSON.stringify(
// {
// accessToken,
// expiryTimestamp:
// expiryDate === null ? null : expiryDate.getTime(),
// refreshToken,
// },
// null,
// 4
// ),
// 'utf-8'
// );
// },
// refreshToken: tokenData.refreshToken,
// }
// ),
// {
// channels: [twitch.channel],
// }
// );

if (message !== undefined) {
try {
void chatClient.say(channel, message);
logger.info('✔ twitch message sent');
} catch (error: unknown) {
logger.error("✖ couldn't send twitch message", error);
}
}
}
}
// chatClient.onJoin((channel: string, user: string) => {
// if (channel === `#${twitch.channel}` && user === chatClient.currentNick) {
// while (messages.length) {
// const message: string | undefined = messages.shift();

void chatClient.quit();
});
// if (message !== undefined) {
// try {
// void chatClient.say(channel, message);
// logger.info('✔ twitch message sent');
// } catch (error: unknown) {
// logger.error("✖ couldn't send twitch message", error);
// }
// }
// }
// }

chatClient.onDisconnect(() => {
alreadySaying = false;
});
// void chatClient.quit();
// });

export function sendTwitchMessage(link: Link, store: Store) {
if (
tokenData.accessToken &&
twitch.channel &&
twitch.clientId &&
twitch.clientSecret &&
tokenData.refreshToken
) {
logger.debug('↗ sending twitch message');
// chatClient.onDisconnect(() => {
// alreadySaying = false;
// });

messages.push(
`${Print.inStock(link, store)}\n${link.cartUrl ? link.cartUrl : link.url}`
);
// export function sendTwitchMessage(link: Link, store: Store) {
// if (
// tokenData.accessToken &&
// twitch.channel &&
// twitch.clientId &&
// twitch.clientSecret &&
// tokenData.refreshToken
// ) {
// logger.debug('↗ sending twitch message');

if (!alreadySaying) {
alreadySaying = true;
void chatClient.connect();
}
}
}
// messages.push(
// `${Print.inStock(link, store)}\n${link.cartUrl ? link.cartUrl : link.url}`
// );

// if (!alreadySaying) {
// alreadySaying = true;
// void chatClient.connect();
// }
// }
// }
Loading

0 comments on commit c8d28ee

Please sign in to comment.