Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add firebase database #16

Merged
merged 5 commits into from
May 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/backend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ log/
node_modules/
obs_objects_ref/
twitch_chat_history/

.env
.eslintrc.json
.vscode

matanbot-bab21-firebase-adminsdk-bsty9-9195f4ab44.json
11 changes: 4 additions & 7 deletions src/backend/bot_brain.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
"use strict";
const obs = require("./obs_helper.js");
const consts = require("./consts.js");
const commands = require("./commands.js");
import * as commands from "./commands.js";
const { add } = require("winston");

let matanbot_mention_count = 0;
let mlk_quote_num = 0;

const added_commands = commands.loadCommands();
let added_commands : commands.Command[] = [];

//every 5 minutes, save commands to persist usage counts
setInterval(() => commands.saveCommands(added_commands), 5 * 60 * 1000);
(async () => added_commands = await commands.loadCommands())();

//logic for when matanbot is mentioned
function respondToMatanbotMention(user_info : any) {
Expand Down Expand Up @@ -78,7 +77,6 @@ function addCommand(user_info : any, user_parameters: any) {

const new_command = commands.newCommand(user_info["display-name"], user_parameters);
added_commands.push(new_command);
commands.saveCommands(added_commands);
return `Added !${new_command.command_word}`;
}

Expand All @@ -96,7 +94,6 @@ function editCommand(user_parameters: string[]) {

const edit_command = commands.editCommand(added_commands[edit_command_index], user_parameters);
added_commands[edit_command_index] = edit_command;
commands.saveCommands(added_commands);

return `Edited !${edit_command.command_word}`;
}
Expand Down Expand Up @@ -150,7 +147,7 @@ const message_main = async (user_info : any, user_msg : string) => {
if (user_parameters[0] === `count`) {
return `${user_command} has been used ${added_command.usage_count} times.`;
} else if (user_parameters[0] === `age`) {
return `${user_command} was added on ${added_command.added_date} by ${added_command.added_by}.`;
return `${user_command} was added on ${added_command.added_timestamp} by ${added_command.added_by}.`;
} else {
added_command.usage_count = added_command.usage_count + 1;

Expand Down
1 change: 0 additions & 1 deletion src/backend/commands.json

This file was deleted.

40 changes: 25 additions & 15 deletions src/backend/commands.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const fs = require("fs");
import fs from "fs";

type Command = {
import * as firestore from "./firestore";

export type Command = {
command_word: string;
response_array: string[];
mod_only: boolean;
Expand All @@ -10,17 +12,24 @@ type Command = {
};

//load commands from json file
export const loadCommands = () => {
const commands_json = fs.readFileSync("commands.json");
return JSON.parse(commands_json).commands;
};

//persist commands to store state when bot is off
export const saveCommands = (commands: Command[]) => {
fs.writeFileSync("commands.json", JSON.stringify({ commands: commands }));
export const loadCommands = async () => {
//const commands_json = String(fs.readFileSync("commands.json"));
//return JSON.parse(commands_json).commands;
const commands = await firestore.getCommands();
return commands.map((command_data) => ({
command_word: command_data.command_word,
response_array: command_data.response_array,
mod_only: command_data.mod_only,
added_by: command_data.added_by,
added_timestamp: command_data.added_timestamp,
usage_count: command_data.usage_count,
}));
};

export const findCommand = (command_word: string, commands: Command[]) => {
export const findCommand = (
command_word: string,
commands: Command[]
): Command => {
return commands.find(
(command: Command) => command.command_word === command_word
);
Expand Down Expand Up @@ -49,24 +58,25 @@ export const newCommand = (
usage_count: 0,
};

firestore.saveCommand(new_command);
return new_command;
};

//create new command with the new parameters
//but use original commands added_by, added_timestamp and usage_count
export const editCommand = (command: Command, user_parameters: string[]) => {
const edited_command = newCommand(
command.added_by,
user_parameters
);
const edited_command = newCommand(command.added_by, user_parameters);
edited_command.added_timestamp = command.added_timestamp;
edited_command.usage_count = command.usage_count;
firestore.saveCommand(edited_command);
return edited_command;
};

//replace instances of {count} in the response_array w/command's usage count
//reduce array into a string and return
export const commandResponse = (command: Command) => {
//send usage to db, this function only gets called when command gets used
firestore.incrementCommandUsage(command.command_word);
return command.response_array.reduce((cur_value, add_value) => {
if (add_value === `{count}`) {
return `${cur_value} ${command.usage_count}`;
Expand Down
40 changes: 40 additions & 0 deletions src/backend/firestore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import admin from "firebase-admin";
import serviceAccount from "./matanbot-bab21-firebase-adminsdk-bsty9-9195f4ab44.json";

const params = {
//clone json object into new object to make typescript happy
type: serviceAccount.type,
projectId: serviceAccount.project_id,
privateKeyId: serviceAccount.private_key_id,
privateKey: serviceAccount.private_key,
clientEmail: serviceAccount.client_email,
clientId: serviceAccount.client_id,
authUri: serviceAccount.auth_uri,
tokenUri: serviceAccount.token_uri,
authProviderX509CertUrl: serviceAccount.auth_provider_x509_cert_url,
clientC509CertUrl: serviceAccount.client_x509_cert_url,
};

admin.initializeApp({
credential: admin.credential.cert(params),
});

const db: FirebaseFirestore.Firestore = admin.firestore();

//every document in the chat_commands collection represents a single chat command
export const getCommands = async () => {
const commands_ref = db.collection("chat_commands");
const commands = await commands_ref.get();
return commands.docs.map((command_doc) => command_doc.data());
};

export const incrementCommandUsage = async (command_name: string) => {
const doc_ref = db.collection('chat_commands').doc(command_name);
await doc_ref.update({
usage_count: admin.firestore.FieldValue.increment(1)
});
}

export const saveCommand = async (command: any) => {
await db.collection('chat_commands').doc(command.command_word).set(command, {merge: true});
}
Loading