Skip to content
This repository has been archived by the owner on Sep 12, 2024. It is now read-only.

Commit

Permalink
Refactor and add supabase changes
Browse files Browse the repository at this point in the history
  • Loading branch information
RaiVaibhav committed May 16, 2024
1 parent 0c5433e commit 862c087
Show file tree
Hide file tree
Showing 8 changed files with 171 additions and 59 deletions.
6 changes: 3 additions & 3 deletions src/database.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,21 @@ export type Database = {
Tables: {
community_raw: {
Row: {
created_on: string;
created_at: string;
id: number;
origin: string;
raw: Json;
source: string;
};
Insert: {
created_on?: string;
created_at?: string;
id?: number;
origin: string;
raw: Json;
source: string;
};
Update: {
created_on?: string;
created_at?: string;
id?: number;
origin?: string;
raw?: Json;
Expand Down
5 changes: 5 additions & 0 deletions src/events/action.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const enum ACTION {
DELETE = "delete",
UPDATE = "update",
CREATE = "create",
}
3 changes: 2 additions & 1 deletion src/events/threadCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ExtendedClient } from "../interfaces/ExtendedClient";
import { errorHandler } from "../utils/errorHandler";
import { sendToSupabase } from "../utils/sendToSupabase";
import { sleep } from "../utils/sleep";
import { ACTION } from "./action.types";

/**
* Handles the thread create event.
Expand All @@ -31,7 +32,7 @@ export const threadCreate = async (
/**
* We're logging our support thread messages out to supabase for automation purposes.
*/
await sendToSupabase("create", bot, thread);
await sendToSupabase(ACTION.CREATE, bot, thread);
const isMovedPost = thread.ownerId === bot.user?.id;

/**
Expand Down
6 changes: 4 additions & 2 deletions src/events/threadDelete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { AnyThreadChannel, ChannelType } from "discord.js";
import { ExtendedClient } from "../interfaces/ExtendedClient";
import { errorHandler } from "../utils/errorHandler";
import { sendToSupabase } from "../utils/sendToSupabase";
import { ACTION } from "./action.types";

/**
* Handles the thread delete event.
Expand All @@ -29,8 +30,9 @@ export const threadDelete = async (
/**
* We're logging our support thread messages out to supabase for automation purposes.
*/
await sendToSupabase("delete", bot, thread);
await sendToSupabase(ACTION.DELETE, bot, thread);
} catch (err) {
await errorHandler(bot, "thread delete", err);
// await errorHandler(bot, "thread delete", err);
console.log(err);
}
};
10 changes: 6 additions & 4 deletions src/events/threadUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@ import { ExtendedClient } from "../interfaces/ExtendedClient";
import { errorHandler } from "../utils/errorHandler";
import { sendToSupabase } from "../utils/sendToSupabase";

import { ACTION } from "./action.types";

/**
* Handles the thread update event.
*
* @param {ExtendedClient} bot The bot's Discord instance.
* @param {AnyThreadChannel} thread The thread channel payload from Discord.
* @param {AnyThreadChannel} newThread The thread channel payload from Discord.
* @returns {void} - Void.
*/
export const threadUpdate = async (
bot: ExtendedClient,
newThread: AnyThreadChannel,
oldThread: AnyThreadChannel
newThread: AnyThreadChannel
) => {
try {
/**
Expand All @@ -26,7 +28,7 @@ export const threadUpdate = async (
) {
return;
}

await sendToSupabase(ACTION.UPDATE, bot, newThread);
/**
* We're logging our support thread messages out to supabase for automation purposes.
*/
Expand Down
17 changes: 8 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,33 +69,32 @@ import { threadDelete } from "./events/threadDelete";
await threadCreate(bot, thread);
});

bot.on(Events.ThreadUpdate, async (newThread, oldThread) => {
console.log("thread update", newThread, oldThread);
await threadUpdate(bot, newThread, oldThread);
bot.on(Events.ThreadUpdate, async (_oldThread, newThread) => {
await threadUpdate(bot, newThread);
});

bot.on(Events.MessageReactionAdd, async (reaction, user) => {
bot.on(Events.MessageReactionAdd, async (_reaction, _user) => {
// console.log(reaction.toJSON(), user.toJSON());
});

bot.on(Events.MessageReactionRemove, async (reaction, user) => {
bot.on(Events.MessageReactionRemove, async (_reaction, _user) => {
// console.log(reaction.toJSON(), user.toJSON());
});

bot.on(Events.ThreadDelete, async (thread) => {
// console.log(thread);
// await threadDelete(bot, thread);
await threadDelete(bot, thread);
});

bot.on(Events.MessageCreate, async (message: Message) => {
bot.on(Events.MessageCreate, async (_message: Message) => {
// console.log("message create", message);
});

bot.on(Events.MessageUpdate, async (message) => {
bot.on(Events.MessageUpdate, async (_message) => {
// console.log("message update", message);
});

bot.on(Events.MessageDelete, async (message) => {
bot.on(Events.MessageDelete, async (_message) => {
// console.log(message.toJSON());
});

Expand Down
106 changes: 94 additions & 12 deletions src/utils/sendToSupabase.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,110 @@
/* eslint-disable camelcase */

Check failure on line 1 in src/utils/sendToSupabase.ts

View workflow job for this annotation

GitHub Actions / Continuous integration

Found a disable directive at /home/runner/work/deepgram-discord-bot/deepgram-discord-bot/src/utils/sendToSupabase.ts:1
import { createClient } from "@supabase/supabase-js";
import { AnyThreadChannel } from "discord.js";

import { Database } from "../database.types";
import { ACTION } from "../events/action.types";
import { ExtendedClient } from "../interfaces/ExtendedClient";
import { threadTransform } from "./transformers";

// const supabase = createClient<Database>(
// process.env.SUPABASE_URL || "",
// process.env.SUPABASE_ANON_KEY || ""
// );
import { threadAction } from "./transformers";

const timeZone = "America/New_York";

const supabase = createClient<Database>(
process.env.SUPABASE_URL || "",
process.env.SUPABASE_ANON_KEY || ""
);

/**
*
* @param action
* @param bot
* @param data
* @param {typeof ACTION} action - Create, update or delete.
* @param {ExtendedClient} bot - Bot instance.
* @param {AnyThreadChannel} thread - Thread instance.
* @returns {any} - Any.
*/
export const sendToSupabase = async (
action: string,
bot: ExtendedClient,
data: AnyThreadChannel
thread: AnyThreadChannel
) => {
// if (supabase) {
switch (action) {
case ACTION.CREATE: {
const threadData = await threadAction().create(thread);
const threadJson = {
raw: JSON.parse(JSON.stringify(threadData)),
source: "discord",
origin: threadData.id,
created_at:
thread.createdAt?.toLocaleString("en-US", { timeZone }) ||
new Date().toLocaleString("en-US", { timeZone }),
};
const { data, error } = await supabase
.from("community_raw")
.insert([threadJson])
.select();
if (error) {
return Promise.reject(error);
}
return data;
}
case ACTION.UPDATE: {
const threadData = await threadAction().update(thread);
const threadJson = {
raw: JSON.parse(JSON.stringify(threadData)),
source: "discord",
origin: threadData.id,
created_at:
thread.createdAt?.toLocaleString("en-US", { timeZone }) ||
new Date().toLocaleString("en-US", { timeZone }),
};

const { data, error } = await supabase
.from("community_raw")
.update({ ...threadJson })
.eq("source", threadData.id)
.select();

if (error) {
return Promise.reject(error);
}

return data;
}
case ACTION.DELETE: {
const { data, error } = await supabase
.from("community_raw")
.select("*")
.eq("source", thread.id);

if (data && data.length > 0) {
const { raw, ...rest } = data[0];
const deletedRawData = Object.assign(
{},
JSON.parse(JSON.stringify(raw)),
// How to convert the JSON to object, what is this typescript error
{
deleted: true,
}
);

const { data: deletedPost, error: deletePostError } = await supabase
.from("community_raw")
.update({ ...rest, ...deletedRawData })
.eq("source", thread.id)
.select();

// }
await threadTransform(data);
if (deletePostError) {
return Promise.reject(deletePostError);
}
return deletedPost;
}
if (error) {
return Promise.reject(error);
}
return;
}
default: {
return;
}
}
};
77 changes: 49 additions & 28 deletions src/utils/transformers.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import {
AnyThreadChannel,
Attachment,
HexColorString,
Message,
} from "discord.js";
import { Attachment, HexColorString, Message, ThreadChannel } from "discord.js";

type TransformPost = {
import { ACTION } from "../events/action.types";

export type TransformPost = {
id: string;
name: string;
archived: string;
Expand All @@ -21,9 +18,10 @@ type TransformPost = {
url: string;
createdTimestamp: number;
messages: TransformMessage[];
deleted?: boolean;
};

type TransformMessage = {
export type TransformMessage = {
channelId: string;
guildId: string;
createdTimestamp: number;
Expand All @@ -38,41 +36,46 @@ type TransformMessage = {
reactions: TransformMessageReaction[];
};

type TransformUser = {
export type TransformUser = {
id: string;
bot: boolean;
system: boolean;
username: string;
discriminator: string;
globalName: string;
avatar: string | null;
banner: string | null | undefined;
banner?: string | null;
defaultAvatarURL: string;
avatarDecoration: string | null;
createdTimestamp: number;
hexAccentColor: HexColorString | null | undefined;
hexAccentColor?: HexColorString | null;
displayName: string;
tag: string;
avatarDecorationURL: string | null; // call
avatarURL: string | null; // call
bannerURL: string | null; // call
};

type TransformEmoji = {
export type TransformEmoji = {
animated: boolean | null;
name: string | null;
id: string | null;
identifier: string;
imageURL: string | null;
};

type TransformMessageReaction = {
export type TransformMessageReaction = {
count: number;
emoji: TransformEmoji;
me: boolean;
message: TransformMessage;
};

export type ThreadActionReturn = {
[ACTION.CREATE]: (thread: ThreadChannel) => TransformPost;
[ACTION.UPDATE]: (thread: ThreadChannel) => TransformPost;
[ACTION.DELETE]: (thread: ThreadChannel) => any;
};
/**
*
* @param {Message} message - Transform Message to JSON.
Expand Down Expand Up @@ -106,20 +109,38 @@ export const messageTransform = async (message: Message) => {
};

/**
*
* @param {AnyThreadChannel} thread - Transform ThreadChannel to JSON.
* @returns {ThreadActionReturn} Returns object which can used as per the action.
*/
export const threadTransform = async (thread: AnyThreadChannel) => {
try {
const threadData = thread.toJSON() as TransformPost;
const customMessages = [];
const messages = await thread.messages.fetch();
for (const [, messageValue] of messages.entries()) {
const messageJson = await messageTransform(messageValue);
customMessages.push(messageJson);
}
threadData.messages = customMessages;
} catch {
//todo
}
export const threadAction = () => {
return {
[ACTION.CREATE]: async (thread: ThreadChannel) => {
const threadData = thread.toJSON() as TransformPost;
const customMessages = [];
const messages = await thread.messages.fetch();
for (const [, messageValue] of messages.entries()) {
const messageJson = await messageTransform(messageValue);
customMessages.push(messageJson);
}
threadData.messages = customMessages;
return threadData;
},
[ACTION.UPDATE]: async (thread: ThreadChannel) => {
// Same as create
const threadData = thread.toJSON() as TransformPost;
const customMessages = [];
const messages = await thread.messages.fetch();
for (const [, messageValue] of messages.entries()) {
const messageJson = await messageTransform(messageValue);
customMessages.push(messageJson);
}
threadData.messages = customMessages;
return threadData;
},
[ACTION.DELETE]: async (thread: ThreadChannel) => {
// There is no attribute in ThreadChannel which says if thread is
// deleted or not, means if we tried fetching messages from deleted
// thread, it will throw error
//Todo: fetch from supabase and then update the attribute
},
};
};

0 comments on commit 862c087

Please sign in to comment.