Skip to content

Commit

Permalink
add new api endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
electron271 committed Dec 2, 2024
1 parent cfe1467 commit 97d349f
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 15 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ DISCORD_CHANNEL_ID="123456789012345678" # this bot is only designed to work in o
ENCRYPTION_KEY="dontsharethis!" # openssl rand -base64 32
BOT_OWNER="123456789012345678"
ACTIVITY="s$help for commands"
PREFIX="s$"
PREFIX="s$"
ALLOWED_ROLES="123456789012345678,123456789012345678" # comma separated list of role ids for /api/roles endpoint
3 changes: 3 additions & 0 deletions nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ http {
location / {
proxy_pass http://app:8000;
}
location /api {
proxy_pass http://app:8000;
}

# Serve static files in /data
location /data {
Expand Down
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,6 @@ model UserLookup {
username String @default("")
anonymous Boolean @default(true)
fullOptOut Boolean @default(false) // this can severely impact the graph functionality and should be used sparingly
roles String[] @default([])
@@id([id])
}
28 changes: 15 additions & 13 deletions src/bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ const { expressMain } = require('./express');

// Initialize Prisma Client
const prisma = new PrismaClient();
// Create the Discord client
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildPresences,
],
});


// Utility: Encrypt user ID
function anonymousId(id) {
Expand All @@ -25,10 +36,12 @@ function anonymousId(id) {
// Utility: Update user in the database or create if not exists
async function updateUserLookup(prisma, user) {
if (!user) return;
// get user as guild member
const member = await user.client.guilds.cache.get(process.env.DISCORD_SERVER_ID)?.members.fetch(user.id);
await prisma.userLookup.upsert({
where: { id: BigInt(user.id) },
update: { username: user.username, fullOptOut: false },
create: { id: BigInt(user.id), username: user.username },
update: { username: user.username, fullOptOut: false, roles: member?.roles.cache.map((role) => role.id) },
create: { id: BigInt(user.id), username: user.username, roles: member?.roles.cache.map((role) => role.id) },
});
}

Expand Down Expand Up @@ -88,17 +101,6 @@ async function generateGEXF() {
}
}

// Create the Discord client
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildPresences,
],
});

// On client ready
client.once(Events.ClientReady, (readyClient) => {
console.log(`Ready! Logged in as ${readyClient.user.tag}`);
Expand Down
44 changes: 43 additions & 1 deletion src/express.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const express = require('express')
const { Client } = require('discord.js');
const app = express()
const port = 8000

Expand All @@ -13,12 +14,18 @@ Total users who left and got opted out: <6>
Endpoints
=========
/ - This page
GET > text/plain
/data/graph.gexf - GEXF graph data
GET > text/plain
/api/roles - provide select role data
POST json (user_id: int) > json (user_id: int, roles: [int])
powered by graphology, express.js, prisma, and discord.js
`

function expressMain(prisma) {
function expressMain(prisma, client) {
app.get('/', async (req, res) => {
const totalUsers = await prisma.userLookup.count();
const totalUniqueMentions = await prisma.mention.count();
Expand All @@ -29,6 +36,41 @@ function expressMain(prisma) {
res.send(statsTemplate.replace('<2>', totalUsers).replace('<3>', totalUniqueMentions).replace('<4>', totalNonAnonymousUsers).replace('<5>', totalAnonymousUsers).replace('<6>', totalOptOutUsers));
});

app.use(express.json()); // Ensure this middleware is added

app.post('/api/roles', async (req, res) => {
const userId = req.body?.user_id; // Safely access user_id
if (!userId) {
res.status(400).send({ error: 'Missing user_id in request body' });
return;
}

try {
// Fetch user roles from database
const userRoles = await prisma.userLookup.findUnique({
where: { id: BigInt(userId) },
select: { roles: true } // Only fetch roles
});

if (!userRoles) {
res.status(404).send({ error: 'User not found' });
return;
}

// Filter roles based on allowed roles
const allowedRoles = process.env.ALLOWED_ROLES.split(',');
const filteredRoles = userRoles.roles.filter((role) =>
allowedRoles.includes(role)
);

res.status(200).send({ user_id: userId, roles: filteredRoles });
} catch (error) {
console.error(error);
res.status(500).send({ error: 'Internal server error' });
}
});


app.listen(port, () => {
console.log(`Express server listening at http://localhost:${port}!`);
});
Expand Down

0 comments on commit 97d349f

Please sign in to comment.