From c803e7fd76eb87e122bc46cf723da38e10a01c79 Mon Sep 17 00:00:00 2001 From: Tyler-A Date: Tue, 7 Jan 2020 00:06:14 -0600 Subject: [PATCH] Add main bot for actually interacting with Twitch and storing the data. --- src/Twitch.ts | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/Twitch.ts diff --git a/src/Twitch.ts b/src/Twitch.ts new file mode 100644 index 0000000..eac8d5d --- /dev/null +++ b/src/Twitch.ts @@ -0,0 +1,94 @@ +// +// 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 => { + + // 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); + }); +}; \ No newline at end of file