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

test bot #31

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
Binary file added assets/orbitconnect.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/orbitprojectconnect.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/orbitprojectdisconnect.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
21 changes: 21 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@
"node": "^18.x"
},
"scripts": {
"start": "node build/app.js",
"start": "node build/server.js",
"register": "node build/deploy-commands.js",
"dev": "nodemon build/app.js",
"dev": "npm run build && nodemon build/server.js",
"build": "rimraf ./build && tsc",
"format:check": "prettier --check .",
"format": "prettier --write ."
},
"author": "Armin T, LP",
"dependencies": {
"@aws-sdk/client-dynamodb": "^3.451.0",
"cors": "^2.8.5",
"discord-interactions": "^3.2.0",
"discord.js": "^14.14.1",
"dotenv": "^16.0.3",
Expand Down
229 changes: 10 additions & 219 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,225 +1,16 @@
//@ts-nocheck
import { Client, Collection, Events, GatewayIntentBits } from "discord.js";
import fs from "fs";
import path from "path";
import dotenv from "dotenv";
import { ALL_RESPONSES, createResponse } from "./util/responses.js";
import { DbHandler, userGithubMap } from "./model/dbHandler.js";
import { isRepoMember } from "./util/github.js";
import express from "express";
import cors from "cors";

dotenv.config();
const __dirname = new URL(".", import.meta.url).pathname;
const TOKEN = process.env.DISCORD_TOKEN;
const LP_GITHUB_APP_CLIENT_ID = process.env.LP_GITHUB_APP_CLIENT_ID;
const GUILD_ID = process.env.GUILD_ID;
import orbitRouter from "./routers/orbitRouter.js";

// Create a new client instance
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildMembers,
],
});

client.commands = new Collection();
const commandsPath = path.join(__dirname, "commands");
const commandFiles = fs
.readdirSync(commandsPath)
.filter((file) => file.endsWith(".js"));

for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ("data" in command && "execute" in command) {
client.commands.set(command.data.name, command);
} else {
console.log(
`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`,
);
}
}

class DiscordServer {
guild;
roles;

constructor() {
this.client = client;
}

async init() {
await this.client.login(TOKEN);
console.log("Discord client logged in");
}

async getparams() {
const guild = await this.client.guilds.fetch(GUILD_ID);
const roles = await guild.roles.fetch();

this.guild = guild;
this.roles = {};
for (const [id, role] of roles) {
this.roles[role.name.toLowerCase()] = role;
}
}
}

let server;
const TABLE_NAME = "rocket";
const dbHandler = new DbHandler();

// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, (c) => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});

client.on(Events.InteractionCreate, async (interaction) => {
// console.log("Interaction received");
if (interaction.isButton()) {
if (interaction.customId.startsWith("verify_button_")) {
// console.log("Verify button pressed");

const githubResponse = userGithubMap[interaction.user.id];
const app = express();
app.use(cors());
app.use(express.json());

if (!githubResponse) {
await interaction.update({
content: createResponse(ALL_RESPONSES.connectionIssue, [
interaction.user.id,
]),
components: [],
});
return;
}

let device_code = userGithubMap[interaction.user.id].device_code;
let grant_type = "urn:ietf:params:oauth:grant-type:device_code";
let resp = await fetch(
`https://github.com/login/oauth/access_token?client_id=${LP_GITHUB_APP_CLIENT_ID}&device_code=${device_code}&grant_type=${grant_type}`,
{
method: "POST",
headers: {
"X-GitHub-Api-Version": "2022-11-28",
Accept: "application/json",
},
},
);

let data = await resp.json();

let access_token = data.access_token;

if (!access_token) {
await interaction.update({
content: createResponse(ALL_RESPONSES.connectionIssue, [
interaction.user.id,
]),
components: [],
});
return;
}

let resp2 = await fetch(`https://api.github.com/user`, {
method: "GET",
headers: {
Authorization: `token ${access_token}`,
Accept: "application/json",
},
});
let data2 = await resp2.json();
let st = await isRepoMember(data2.login);

if (!st) {
await interaction.update({
content: createResponse(ALL_RESPONSES.checkMeNotMember, []),
components: [],
});
}

await dbHandler.setRecord(TABLE_NAME, interaction.user.id, {
PK: {
S: interaction.user.id,
},
SK: {
S: interaction.user.id,
},
integrations: {
M: {
github: {
M: {
username: {
S: data2.login,
},
id: {
N: String(data2.id),
},
date: {
S: new Date().toISOString(),
},
},
},
},
},
});

// get the guild
const member = await server.guild.members.fetch(interaction.user.id);
await member.roles.add(server.roles["member"].id);
await interaction.update({
content: createResponse(ALL_RESPONSES.checkMeSuccess, [
interaction.user.id,
]),
components: [],
});
}
} else if (interaction.isCommand()) {
const command = interaction.client.commands.get(interaction.commandName);

if (!command) {
console.error(
`No command matching ${interaction.commandName} was found.`,
);
return;
}

try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({
content: "There was an error while executing this command!",
ephemeral: true,
});
} else {
await interaction.reply({
content: "There was an error while executing this command!",
ephemeral: true,
});
}
}
}
});

client.on(Events.MessageCreate, (message) => {
// console.log("Message received");
if (!message.content.startsWith("!") || message.author.bot) return;
// console.log(message);
});
app.use("/orbit", orbitRouter);

client.on(Events.GuildMemberAdd, async (member) => {
try {
await client.users.send(member.user.id, {
content: createResponse(ALL_RESPONSES.welcomeMessage, [member.user.id]),
});
} catch (error) {
console.log("Failed to send DM:", error);
}
app.get("/ping", async (req, res) => {
res.send("pong");
});

// Log in to Discord with your client's token
server = new DiscordServer();
await server.init();
await server.getparams();
export default app;
36 changes: 36 additions & 0 deletions src/commands/connectOrbit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
SlashCommandBuilder,
ActionRowBuilder,
TextInputBuilder,
TextInputStyle,
ModalBuilder,
ModalActionRowComponentBuilder
} from "discord.js";

const data = new SlashCommandBuilder()
.setName("connect-orbit")
.setDescription("Connects your discord to orbit for notifications");

const modal = new ModalBuilder()
.setCustomId('connectOrbitModal')
.setTitle('Settings for connecting to Orbit');

// Add components to modal
const emailInput = new TextInputBuilder()
.setCustomId('emailInput')
.setLabel("What's email linked to Orbit")
.setStyle(TextInputStyle.Short);

// An action row only holds one text input,
// so you need one action row per text input.
const firstActionRow = new ActionRowBuilder<ModalActionRowComponentBuilder>().addComponents(emailInput);

// Add inputs to the modal
modal.addComponents(firstActionRow);

async function execute(interaction) {
// Show the modal to the user
await interaction.showModal(modal);
}

export { data, execute };
44 changes: 44 additions & 0 deletions src/commands/connectOrbitProject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {
SlashCommandBuilder,
ActionRowBuilder,
StringSelectMenuBuilder,
StringSelectMenuOptionBuilder
} from "discord.js";

const data = new SlashCommandBuilder()
.setName("connect-orbit-project")
.setDescription("Connects your discord to orbit for notifications");

async function execute(interaction) {
const select = new StringSelectMenuBuilder()
.setCustomId('TeamSelect')
.setPlaceholder('Make a selection!');

const row = new ActionRowBuilder().addComponents(select);

const teams = await fetch("http://localhost:3000/api/teams").then(res => res.json()) as Array<any>;

if (teams == null || teams.length == 0) {
await interaction.reply({
content: "No teams to connect to!",
components: [],
});
return;
}

teams.forEach(team => {
select.addOptions(
new StringSelectMenuOptionBuilder()
.setLabel(team.name)
.setDescription(team.description || " ")
.setValue(team.id.toString()),
);
});
await interaction.reply({
content: "Select your team:",
components: [row],
});
}

export { data, execute };

Loading