ozvault home

EXAMPLES · DISCORD BOTS

Discord bot storage with OzVault Connect

Give your Discord bot free per-user cloud storage: /link connects a user's OzVault with OAuth, then /save stores attachments in their account.

Reviewed Published by OzVault

How it works

#

Bots cannot receive OAuth redirects themselves, so the bot runs a small HTTPS callback endpoint (Express here). /link replies with an ephemeral, single-use authorization link bound to that Discord user. After the user approves on OzVault, the callback stores their tokens; /save, /files and /quota then work against the user's own storage. Each user's files live in their account, using their quota rather than yours.

Register PUBLIC_URL/ozvault/callback (an HTTPS address that reaches the bot) as the redirect URL, and enable storage:quota:read, storage:app:read, storage:app:write and offline_access. Keep the client secret on the bot host only.

discord.js v14 bot

#
TypeScript
// bot.mjs — Node.js 20+:  npm i discord.js express
import { Client, Events, GatewayIntentBits, MessageFlags, REST, Routes, SlashCommandBuilder } from "discord.js";
import express from "express";
import { randomBytes, createHash } from "node:crypto";

const OZVAULT = "https://ozvault.lol";
const API = "https://api.ozvault.lol";
const { DISCORD_TOKEN, DISCORD_APP_ID, OZVAULT_CLIENT_ID, OZVAULT_CLIENT_SECRET, PUBLIC_URL } = process.env;
const REDIRECT_URI = PUBLIC_URL + "/ozvault/callback"; // register this exact URL in the developer portal
const basic = "Basic " + Buffer.from(OZVAULT_CLIENT_ID + ":" + OZVAULT_CLIENT_SECRET).toString("base64");

const pending = new Map();     // state -> { discordId, verifier, expires }
const connections = new Map(); // discordId -> tokens (use a database in production)
const refreshing = new Map();  // discordId -> in-flight refresh

await new REST().setToken(DISCORD_TOKEN).put(Routes.applicationCommands(DISCORD_APP_ID), {
  body: [
    new SlashCommandBuilder().setName("link").setDescription("Connect your OzVault storage"),
    new SlashCommandBuilder().setName("save").setDescription("Save an attachment to your OzVault")
      .addAttachmentOption((o) => o.setName("file").setDescription("File to save").setRequired(true)),
    new SlashCommandBuilder().setName("files").setDescription("List files this bot saved for you"),
    new SlashCommandBuilder().setName("quota").setDescription("Show your remaining OzVault storage"),
  ].map((c) => c.toJSON()),
});

async function tokenRequest(params) {
  const r = await fetch(OZVAULT + "/oauth/token", {
    method: "POST",
    headers: { Authorization: basic, "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams(params),
  });
  const body = await r.json();
  if (!r.ok) throw new Error(body.error_description || body.error);
  return { ...body, expiresAt: Date.now() + body.expires_in * 1000 };
}

async function accessToken(discordId) {
  const t = connections.get(discordId);
  if (!t) return null;
  if (Date.now() < t.expiresAt - 60_000) return t.access_token;
  if (!refreshing.has(discordId)) // one refresh at a time per user
    refreshing.set(discordId, tokenRequest({ grant_type: "refresh_token", refresh_token: t.refresh_token })
      .then((next) => (connections.set(discordId, next), next.access_token))
      .catch((e) => { connections.delete(discordId); throw e; })
      .finally(() => refreshing.delete(discordId)));
  return refreshing.get(discordId);
}

const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.on(Events.InteractionCreate, async (interaction) => {
  if (!interaction.isChatInputCommand()) return;
  const userId = interaction.user.id;

  if (interaction.commandName === "link") {
    const state = randomBytes(16).toString("base64url");
    const verifier = randomBytes(32).toString("base64url");
    pending.set(state, { discordId: userId, verifier, expires: Date.now() + 10 * 60_000 });
    const url = new URL(OZVAULT + "/oauth/authorize");
    url.search = new URLSearchParams({
      response_type: "code",
      client_id: OZVAULT_CLIENT_ID,
      redirect_uri: REDIRECT_URI,
      scope: "storage:quota:read storage:app:read storage:app:write offline_access",
      state,
      code_challenge: createHash("sha256").update(verifier).digest("base64url"),
      code_challenge_method: "S256",
    }).toString();
    // Ephemeral: only the person who ran /link sees their personal link.
    return interaction.reply({ content: "Connect your OzVault storage: " + url, flags: MessageFlags.Ephemeral });
  }

  await interaction.deferReply({ flags: MessageFlags.Ephemeral });
  const token = await accessToken(userId).catch(() => null);
  if (!token) return interaction.editReply("Run /link to connect OzVault first.");
  const auth = { Authorization: "Bearer " + token };

  if (interaction.commandName === "save") {
    const file = interaction.options.getAttachment("file", true);
    if (file.size > 4 * 1024 * 1024) return interaction.editReply("Files over 4 MiB need the resumable upload API.");
    const bytes = Buffer.from(await (await fetch(file.url)).arrayBuffer());
    const r = await fetch(API + "/v1/app/files?" + new URLSearchParams({
      name: "discord/" + Date.now() + "-" + file.name,
      contentType: file.contentType ?? "application/octet-stream",
    }), { method: "POST", headers: { ...auth, "Content-Type": "application/octet-stream" }, body: bytes });
    const body = await r.json();
    return interaction.editReply(r.ok ? "Saved " + body.name + " (" + body.size + " bytes)." : "OzVault: " + body.error.message);
  }
  if (interaction.commandName === "files") {
    const r = await fetch(API + "/v1/app/files?limit=10", { headers: auth });
    const { items } = await r.json();
    return interaction.editReply(items.length ? items.map((f) => "• " + f.name + " — " + f.size + " bytes").join("\n") : "No files yet.");
  }
  if (interaction.commandName === "quota") {
    const q = await (await fetch(API + "/v1/storage/quota", { headers: auth })).json();
    return interaction.editReply((q.available / 1e9).toFixed(2) + " GB available of " + (q.quota / 1e9).toFixed(0) + " GB.");
  }
});

const web = express();
web.get("/ozvault/callback", async (req, res) => {
  const flow = pending.get(String(req.query.state));
  pending.delete(String(req.query.state));
  if (!flow || flow.expires < Date.now() || req.query.iss !== OZVAULT) return res.status(400).send("This link expired. Run /link again.");
  if (req.query.error) return res.send("Connection cancelled. You can close this tab.");
  try {
    connections.set(flow.discordId, await tokenRequest({
      grant_type: "authorization_code",
      code: String(req.query.code),
      redirect_uri: REDIRECT_URI,
      code_verifier: flow.verifier,
    }));
    res.send("OzVault connected. Return to Discord.");
  } catch {
    res.status(502).send("Could not connect. Run /link again.");
  }
});
web.listen(3000);
client.login(DISCORD_TOKEN);

Clear documentation is part of the product.