Skip to content

Commit

Permalink
added user update endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Frenkii committed Jan 27, 2024
1 parent 40db69b commit bdf862c
Show file tree
Hide file tree
Showing 10 changed files with 85 additions and 57 deletions.
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ services:
command: npm run dev
ports:
- '9229:9229/tcp'
- '8000:8000/tcp'
volumes:
- .:/opt:delegated
environment:
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "discord-bot",
"version": "1.4.1",
"version": "1.5.0",
"scripts": {
"run": "tsc && node ./dist/src/index.js",
"commands:update": "rimraf ./dist && tsc && node ./dist/scripts/registerCommands.js",
Expand Down
2 changes: 1 addition & 1 deletion src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export const Config: EnvConfig = {
HP_TOKEN: process.env.HP_TOKEN ?? '',

PING_GROUPS: ['EDDH', 'EDDB', 'EDDV', 'EDDL', 'EDDK', 'EDDF', 'EDDS', 'EDDN', 'EDDM', 'CTR EDWW', 'CTR EDGG', 'CTR EDMM', 'Minor EDWW', 'Minor EDGG', 'Minor EDMM', 'ECFMP EDWW', 'ECFMP EDGG', 'ECFMP EDMM'],
MANAGEABLE_GROUPS: ['Mentor EDWW', 'Mentor EDGG', 'Mentor EDMM', 'Mentor', 'NAV EDWW', 'NAV EDGG', 'NAV EDMM', 'NAV', 'Event EDWW', 'Event EDGG', 'Event EDMM', 'Event', 'PTD Trainer', 'PMP Mentor'],
MANAGEABLE_GROUPS: ['EDWW Mentor', 'EDGG Mentor', 'EDMM Mentor', 'Mentor', 'EDWW Nav', 'EDGG Nav', 'EDMM Nav', 'NAV', 'EDWW Event', 'EDGG Event', 'EDMM Event', 'Event', 'PTD Trainer', 'PMP Mentor'],

EVENT_UPDATE: process.env.EVENT_UPDATE == 'true',
EVENT_UPDATE_CRON: process.env.EVENT_UPDATE_CRON ?? '0 */3 0 0 0',
Expand Down
11 changes: 1 addition & 10 deletions src/events/onGuildMemberUpdateEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { sendModeratorMessage } from '../utils/sendModeratorMessage';
import dayjs from 'dayjs';
import vatgerApiService from '../services/vatgerApiService';
import vatsimApiService from '../services/vatsimApiService';
import { getDepartmentRoles } from '../utils/getDepartmentRoles';
import { DiscordBotClient } from '../core/client';

export default class OnGuildMemberUpdateEvent extends DiscordEvent {
Expand All @@ -28,15 +27,7 @@ export default class OnGuildMemberUpdateEvent extends DiscordEvent {
if (isVatger) {
await newUser.roles.add(Config.VATGER_MEMBER_ROLE_ID);
console.log(`Added VATGER Role to ${newUser.id}`);

const userCid = await vatsimApiService.getCIDFromDiscordID(newUser.id);

if (userCid) {
const vatgerApiData = await vatgerApiService.getUserDetailsFromVatger(userCid);
const userRolesToAdd = await getDepartmentRoles(vatgerApiData.teams, guild);

await newUser.roles.add(userRolesToAdd);
}

await userService.updateUser(newUser, { isVatger: true })
}
} catch (e: any) {
Expand Down
74 changes: 72 additions & 2 deletions src/http/apiController.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { Request, Response } from 'express';
import userModel from '../models/user.model';
import userModel, { UserDocument } from '../models/user.model';
import { findGuildMemberByDiscordID } from '../utils/findGuildMember';
import { Config } from '../core/config';
import { GuildMember } from 'discord.js';
import { Collection, GuildMember, Role } from 'discord.js';
import userService from '../services/user.service';
import map from '../utils/departmentRolesMap';
import { DiscordBotClient } from '../core/client';

async function handleMemberJoin(request: Request, response: Response) {
response.send({ message: 'OK' });

try {

const cid = request.body.cid;

if (cid == null) {
Expand Down Expand Up @@ -66,7 +70,73 @@ async function handleMemberLeave(request: Request, response: Response) {
}
}

async function updateMember(req: Request, res: Response) {
try {
const guild = DiscordBotClient.guilds.cache.get(Config.GUILD_ID);
const cid = req.body.cid;
const teams: string[] = req.body.teams;

const user: UserDocument | null = await userService.getUserByCid(cid);

const guildMember: GuildMember | undefined = await findGuildMemberByDiscordID(user?.discordId);
let guildMemberRoles = guildMember?.roles.cache;

for (const group of Config.MANAGEABLE_GROUPS) {
if (map.has(group)) {
if (teams.includes(group) && !guildMemberRoles?.some(r => r.id === map.get(group))) {
await guildMember?.roles.add(map.get(group));
} else if (!teams.includes(group) && guildMemberRoles?.some(r => r.id === map.get(group))) {
await guildMember?.roles.remove(map.get(group));
}
}
}

guildMemberRoles = guildMember?.roles.cache;
const roleNamesArray: string[] = [];

if (guildMemberRoles) {
for (const role of guildMemberRoles) {
roleNamesArray.push(role[1].name);
}
}

const guildRoles: Collection<string, Role> | undefined = guild?.roles.cache;

const navRole = guildRoles?.filter(r => r.name === 'Nav');
const mentorRole = guildRoles?.filter(r => r.name === 'Mentor');
const eventRole = guildRoles?.filter(r => r.name === 'Event');

if (navRole) {
if (roleNamesArray.filter(x => ['EDGG Nav','EDMM Nav','EDWW Nav'].includes(x)).length > 0) {
await guildMember?.roles.add(navRole)
} else {
await guildMember?.roles.remove(navRole)
}
}
if (mentorRole) {
if (roleNamesArray.filter(x => ['EDGG Mentor','EDMM Mentor','EDWW Mentor'].includes(x)).length > 0) {
await guildMember?.roles.add(mentorRole);
} else {
await guildMember?.roles.remove(mentorRole);
}
}
if (eventRole) {
if (roleNamesArray.filter(x => ['EDGG Event','EDMM Event','EDWW Event'].includes(x)).length > 0) {
await guildMember?.roles.add(eventRole)
} else {
await guildMember?.roles.remove(eventRole)
}
}

res.send({ message: 'OK' });

} catch (error: any) {
console.error('Failed to update member', error.message);
}
}

export default {
handleMemberJoin,
handleMemberLeave,
updateMember
};
1 change: 1 addition & 0 deletions src/http/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ httpClient.use(bodyParser.json());

httpClient.post('/member/join', apiController.handleMemberJoin);
httpClient.post('/member/leave', apiController.handleMemberLeave);
httpClient.post('/member/update', apiController.updateMember);
4 changes: 2 additions & 2 deletions src/interfaces/user.interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
interface User {
interface IUser {
discordId: string;
cid: number;
isVatger: boolean;
Expand All @@ -7,4 +7,4 @@ interface User {
militaryRating: number;
}

export default User;
export default IUser;
7 changes: 4 additions & 3 deletions src/services/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,14 @@ async function getUserByDiscordId(discordId: string) {

}

async function getUserByCid(cid: number) {
async function getUserByCid(cid: number): Promise<UserDocument> {
try {
const user: UserDocument | null = await userModel.findOne({ cid: cid });

if (user) {
return user;
if (!user) {
throw new Error('Pilot not found');
}
return user;
} catch (error) {
throw new Error(`Cant get user CID: ${error}`);
}
Expand Down
2 changes: 2 additions & 0 deletions src/utils/departmentRolesMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ map.set('EDMM Nav', '1107561970997149717');
map.set('EDGG Event', '1107563041509351455');
map.set('EDWW Event', '1107562913448865884');
map.set('EDMM Event', '1107563076942827531');
map.set('PMP Mentor', '1108030536284385330');
map.set('PTD Trainer', '1107774004758057001');

// Dev Map
// const map = new Map();
Expand Down
38 changes: 0 additions & 38 deletions src/utils/getDepartmentRoles.ts

This file was deleted.

0 comments on commit bdf862c

Please sign in to comment.