bit-stats-tracker/src/Twitch.ts

94 lines
No EOL
2.1 KiB
TypeScript

//
// Twitch.ts
//
// Written by: Tyler Akins (2020/01/06)
//
import * as requests from "request-promise-native";
import * as tmi from "tmi.js";
import { TWITCH_URI } from "./constants";
import * as config from "./config";
import {
GET_FORMATTED_DATE,
WRITE_DATA,
LOAD_DATA
} from "./utils";
const IS_LIVE = async (channel_name: string): Promise<boolean> => {
// Fetch the data from the Twitch API to check if the user is live
let response = await requests.get(
TWITCH_URI,
{
qs: { user_login: channel_name},
headers: {
"Client-ID": config.CLIENT_ID
},
json: true
}
);
console.log(response)
return response.data.length !== 0;
};
export const START_BOT = async () => {
const client = tmi.Client({
options: {
debug: false,
clientId: config.CLIENT_ID
},
connection: {
secure: true,
reconnect: true
},
identity: {
username: config.USERNAME,
password: config.OAUTH_TOKEN
},
channels: [config.CHANNEL]
});
client.on("cheer", (channel: string, ctx: tmi.Userstate, message: string) => {
let bits: number = parseInt(ctx.bits);
let donator: string = ctx.username;
let date: string = GET_FORMATTED_DATE()
let data: data = LOAD_DATA();
// Ensure the channel is live when the bits are donated
if (!IS_LIVE(channel)) { return; };
// Data already exists
if (data[date]) {
// Check if the donator has already donated
if (!data[date].donators.includes(donator)) {
data[date].donators.push(donator);
};
// Add the bits to the total and the array of donations
data[date].total_bits += bits;
data[date].donations.push(bits);
}
// Making new data point
else {
data[date] = {
total_bits: bits,
donators: [donator],
donations: [bits]
};
};
WRITE_DATA(data);
});
};