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

Ft/disco bot #617

Closed
wants to merge 2 commits into from
Closed
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
1 change: 1 addition & 0 deletions deco.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const compatibilityApps = [{
const config = {
apps: [
app("konfidency"),
app("discord-bot"),
app("mailchimp"),
app("ai-assistants"),
app("files"),
Expand Down
1 change: 1 addition & 0 deletions decohub/apps/discord-bot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "../../discord-bot/mod.ts";
4 changes: 2 additions & 2 deletions deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.3.0",
"std/": "https://deno.land/std@0.204.0/",
"partytown/": "https://deno.land/x/partytown@0.4.8/",
"deco-sites/std/": "https://denopkg.com/deco-sites/std@1.26.2/",
"deco/": "https://denopkg.com/deco-cx/deco@1.67.1/"
"deco-sites/std/": "https://denopkg.com/deco-sites/std@1.26.3/",
"deco/": "https://denopkg.com/deco-cx/deco@1.67.7/"
},
"lock": false,
"tasks": {
Expand Down
1 change: 1 addition & 0 deletions discord-bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>Discord bot used to integrate your git hub repository with discord</p>
195 changes: 195 additions & 0 deletions discord-bot/actions/gitPullRequestCommand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
import { GithubClient, PullRequest } from "../client.ts";
import {
Bot,
ChannelTypes,
createBot,
sendMessage,
startThreadWithoutMessage,
} from "https://deno.land/x/discordeno@18.0.1/mod.ts";
import { AppContext } from "../mod.ts";
import { getDiscordUsers, getOrganization } from "../utils.ts";

export interface Props {
repo: string;
channel_id: string;
}

export async function PullRequestsBot(
{ repo, channel_id }: Props,
_req: Request,
ctx: AppContext,
// deno-lint-ignore no-explicit-any
): Promise<any | null> {
const {
discord_bot_token,
discord_channel_id,
repositories,
} = ctx;

const bot_token = discord_bot_token.get();

if (!bot_token) {
return new Response(
JSON.stringify({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: "Bot token not found",
},
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}

const organization = getOrganization(repositories, repo);

if (organization === null) {
return new Response(
JSON.stringify({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: "Repository not found",
},
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}

const openPRs = await queryGitOpenedPR(organization, repo, ctx);

if (openPRs === undefined) {
return new Response(
JSON.stringify({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: "No opened pull requests",
},
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}

if (!channel_id) {
channel_id = discord_channel_id;
}

//Create the bot
const bot = await createBot({
token: bot_token,
});

const thread = await startThreadWithoutMessage(bot, channel_id, {
name: `Opened PRs at ${organization}/${repo}`,
autoArchiveDuration: 4320,
type: ChannelTypes.PublicThread,
});

await Promise.all(
openPRs.map(async (pr) =>
await sendPRMessageOnDiscord(
{ channelID: String(thread.id), pr, bot },
ctx,
)
),
);

return new Response(
null,
{ status: 204 },
);
}

export interface DiscordPRMessage {
channelID?: string;
pr: PullRequest;
bot?: Bot;
}

export async function sendPRMessageOnDiscord(
{ channelID, pr, bot }: DiscordPRMessage,
{
discord_bot_token,
discord_channel_id,
usersFromGitToDiscord,
}: AppContext,
) {
const bot_token = discord_bot_token.get();

if (!bot_token) {
return new Response(
JSON.stringify({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: "Bot token not found",
},
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}

const assign = pr.reviewers?.map((rev) =>
`<@${getDiscordUsers(usersFromGitToDiscord, rev.login) ?? rev.login}>`
).join(", ");

if (bot === undefined) {
bot = await createBot({
token: bot_token,
});
}

if (channelID === undefined) {
channelID = discord_channel_id;
}

await sendMessage(bot, channelID, {
content: `Title: ${pr.title}\nAssign to: ${assign}`,
embeds: [{
title: pr.url,
"url": pr.url,
fields: [
{ "name": "Owner", "value": pr.owner },
{ "name": "State", "value": pr.state },
],
}],
});
}

const queryGitOpenedPR = async (
organization: string,
repo: string,
{
octokit_token,
}: AppContext,
): Promise<PullRequest[] | undefined> => {
const git_token = octokit_token.get();
if (!git_token) {
return undefined;
}

const activePulls = await GithubClient.getAllActivePulls(
organization,
repo,
git_token,
).catch(
(err) => {
console.log("error");
if ((err as { status: number })?.status === 404) {
return undefined;
}
throw err;
},
);

const prs = activePulls?.map((pr) => ({
url: pr.html_url,
state: pr.state,
title: pr.title,
owner: pr.user?.login ?? "",
reviewers: pr.requested_reviewers?.map((rev) => ({
login: rev.login,
})) ?? [],
}));

return prs;
};

export default PullRequestsBot;
40 changes: 40 additions & 0 deletions discord-bot/actions/run.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Manifest } from "./manifest.gen.ts";
import { AppContext } from "../mod.ts";
import { WorkflowProps } from "deco-sites/admin/actions/workflows/start.ts";

interface Props {
repository?: string;
channel_id?: string;
}

export default async function Run(
{ repository }: Props,
_req: Request,
{ invoke, repositories, discord_channel_id }: AppContext,
) {
const startWorkflow = invoke.$live.actions.workflows.start;

const start = async (repo: string, channel_id: string) => {
const props: WorkflowProps<
"deco-sites/admin/workflows/gitPullRequests.ts",
Manifest
> = {
key: "deco-sites/admin/workflows/gitPullRequests.ts",
props: {
repo,
channel_id,
},
restart: true,
id: `${repo}_gitpullrequests_v0`,
};
await startWorkflow(props);
};

const repos = repository
? [repository]
: repositories.map((repo) => repo.repo);

for (const repo of repos) {
await start(repo, discord_channel_id);
}
}
102 changes: 102 additions & 0 deletions discord-bot/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { Octokit } from "https://cdn.skypack.dev/@octokit/rest@19.0.4";
import { Endpoints } from "https://esm.sh/@octokit/types@9.0.0";

export interface DiscordCommandOption {
name: string;
description: string;
required: boolean;
type: number;
}

export interface DiscordCommand {
name: string;
description: string;
options: DiscordCommandOption[];
type: number;
}

export interface DiscordClient {
"PUT commands": {
response: void;
body: DiscordCommand[];
};
}

/**
* TODO: Octokit doesn't work with esm.sh (timeouts) apparently. Didn't investigate a lot on why
* skypack was being used.
*
* But, also apparently, Skypack doesn't return types all that good. At least we're not leveraging it.
*
* So, I've included types from esm.sh (only types).
*
* At the same time, after using the client fully-typed,
* I'm starting to think that we might not need this client
* and Octokit might be enough.
*
* Also: RepoOwner shouldn't be constant in the future (repos will be hosted elsewhere),
* so we might use the opportunity to take this into consideration
*/
const _client = (octokit_token: string) =>
new Octokit({
auth: octokit_token,
});

export interface Reviewer {
login: string;
}

export interface PullRequest {
url: string;
state: string;
title: string;
owner: string;
reviewers: Reviewer[];
}

export class GithubClient {
private static getOctokit(octokit_token: string) {
return _client(octokit_token);
}

public static async getAllActivePulls(
organization: string,
repoName: string,
octokit_token: string,
) {
const octokit = this.getOctokit(octokit_token);
const response = await octokit.request(
"GET /repos/{owner}/{repo}/pulls?state=open",
{ owner: organization, repo: repoName },
) as Endpoints["GET /repos/{owner}/{repo}/pulls"]["response"];

// I'm not sure which sort is being used, but it's possible that this
// response only contains the first page. Might need to do some pagination here
// if we discover some important branches are not being returned.

return response.data;
}

public static async requestReviewersForPull(
organization: string,
repoName: string,
pullNumber: string,
reviewers: string[],
octokit_token: string,
) {
const octokit = this.getOctokit(octokit_token);
const response = await octokit.request(
"POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers",
{
owner: organization,
repo: repoName,
pull_number: pullNumber,
reviewers,
},
) as Endpoints[
"POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"
]["response"];

return response.data;
}
}
34 changes: 34 additions & 0 deletions discord-bot/commands/commands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { DiscordCommand } from "../client.ts";
import { AppContext } from "../mod.ts";

// Command containing options
const QUERY_COMMAND: DiscordCommand = {
name: "pullrequests",
description: "List the opened pull request",
options: [
{
name: "repo",
description: "Repository name",
required: true,
type: 3,
},
],
type: 1,
};

const ALL_COMMANDS = [QUERY_COMMAND];

export async function InstallGlobalCommands(
// deno-lint-ignore no-explicit-any
_props: any,
_req: unknown,
{ discordClient }: AppContext,
) {
try {
// This is calling the bulk overwrite endpoint: https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands
await discordClient["PUT commands"]({}, { body: ALL_COMMANDS });
} catch (err) {
console.error(err);
}
console.log("Installed global commands for discord's bot successfully");
}
Loading
Loading