Sharkord
Plugins

Client SDK

What plugin UI code can reach in the browser.

@sharkord/plugin-sdk/client is the browser half of the SDK. It gives your components five things: Sharkord's own state, your server actions, messages your server pushed, per-user storage, and hotkeys.

import {
  actions,
  createCallAction,
  useCanUseAction,
  useCanUseCommand,
  useHotkey,
  useHotkeyBinding,
  usePlaybackDeviceId,
  usePush,
  useStoreSelector,
  useUserData,
} from "@sharkord/plugin-sdk/client";

The module reads window.__SHARKORD_STORE__ when it loads, so it only works inside a plugin bundle Sharkord served.

Reading State

Read the store for what the whole app knows. For what a component's own position implies, use the props its slot passes: selectedChannelId is the wrong answer inside a thread, and nothing here says which message or member a row belongs to.

import { useStoreSelector } from "@sharkord/plugin-sdk/client";

const SelectedChannel = () => {
  const channelId = useStoreSelector((state) => state.selectedChannelId);

  return <span>Selected channel: {channelId ?? "none"}</span>;
};

The selector runs against this state:

FieldType
userspublic users on the server
channelschannels
categorieschannel categories
rolesroles
emojiscustom emojis
pluginsloaded plugins with UI
ownUserIdnumber | undefined
selectedChannelIdnumber | undefined
currentVoiceChannelIdnumber | undefined
ownVoiceState{ micMuted, soundMuted, webcamEnabled, sharingScreen }, meaningful while currentVoiceChannelId is set
publicSettingsthe server's public settings
Return a stable reference

The selector must return the same reference for unchanged state. Reading a field ((state) => state.users) is fine; building a new array or object on every call re-renders forever. Memoize those with createSelector, which the host exposes on window.__SHARKORD_EXPOSED_LIBS__.

Calling the Server

import { createCallAction } from "@sharkord/plugin-sdk/client";
import type { TPlugin } from "../types";

const callAction = createCallAction<TPlugin>();

const SumButton = () => {
  const onClick = async () => {
    const result = await callAction("sum", { a: 1, b: 2 });
  };

  return <button onClick={onClick}>Calculate</button>;
};

Call createCallAction once at module scope. The contract checks the action name, the payload, and the response. See Actions.

The channel the user has open is sent along with every call, so the server hands your action an invoker.channelId without you passing one. It is checked against that user's channel permissions before your handler runs.

Receiving Pushes

The server can send your clients anything at any time, without them asking:

// server
ctx.push.toUser(userId, { kind: "rolled", value: 6 });
ctx.push.toUsers([1, 2, 3], data);
ctx.push.toAll(data);
ctx.push.toVoiceChannel(channelId, data);
// client
usePush<TPlugin>((data) => setLast(data));

Pushes are addressed on the server, so a user who is not a recipient never receives one. toVoiceChannel reaches everyone connected to that voice channel at that moment, and nobody when it is empty. toAll reaches every user currently online. A push cannot exceed 64 KB of JSON, and there is no delivery guarantee: a user who is offline, or who connects a second later, does not get it. Use it for live updates, not for state that has to arrive.

Playing Audio for the Call

Short sounds every listener should hear, such as a soundboard, are simpler to play in each browser than to stream through voice. The server pushes what to play to the channel, and each client plays it:

// server: an action the button calls
ctx.actions.register({
  name: "play",
  async executes(invoker, { channelId, soundId }) {
    const { users } = ctx.voice.getState(channelId);

    if (!users.some((user) => user.userId === invoker.userId)) {
      throw new Error("Join the voice channel first.");
    }

    ctx.push.toVoiceChannel(channelId, { soundId });
  },
});
// client: rendered in the voice panel for the whole voice session
const Soundboard = ({ channelId }: { channelId: number }) => {
  const deafened = useStoreSelector((state) => state.ownVoiceState.soundMuted);
  const sinkId = usePlaybackDeviceId();

  usePush<TPlugin>(async ({ soundId }) => {
    if (deafened) return;

    const response = await actions.fetchPluginRoute("soundboard", `/sounds/${soundId}`);
    const audio = new Audio(URL.createObjectURL(await response.blob()));

    if (sinkId) await audio.setSinkId(sinkId).catch(() => {});

    await audio.play();
  });

  return <SoundboardButton channelId={channelId} />;
};

const components: TPluginComponentsMapBySlotId = {
  [PluginSlot.VOICE_CONTROLS]: [Soundboard],
};

VOICE_CONTROLS is what keeps the listener alive: it is mounted from the moment the user joins voice until they leave, whatever channel they are reading. Leave it unrestricted, or a role you restricted stops hearing as well as playing; use useCanUseAction to disable the button instead. Like every slot but CONNECT_SCREEN, it only renders for users holding USE_PLUGINS.

soundMuted is deafen. Respect it, since nothing else silences audio your plugin plays itself. usePlaybackDeviceId is the output the user picked in their device settings, or undefined for the system default; the device can have been unplugged since, so catch a failing setSinkId. A volume slider for your sounds is yours to add, with audio.volume and useUserData to remember it.

Per-User Storage

useUserData is the browser side of ctx.userData: one JSON object per user per plugin, stored on the server.

import { useUserData } from "@sharkord/plugin-sdk/client";

const Preferences = () => {
  const { data, loading, save } = useUserData<TPlugin>();

  if (loading) return null;

  return (
    <button onClick={() => save({ ...data, compact: !data.compact })}>
      Toggle
    </button>
  );
};

A user can only read and write their own data, and the object is capped at 64 KB of JSON. Saving is rate limited like a command or action, and only works while the plugin is enabled, so a client cannot write rows for a plugin the server has never heard of. The server half can read and write anyone's with ctx.userData.get / set / delete. All of it is deleted when the plugin is removed. Since a user can write whatever they like here, treat it as user input on the server. See Data.

Hotkeys

Let a user bind a key to something your plugin does, such as playing a sound or toggling a mode. The key works while a game or another window has focus in the desktop app, or with the Bridge in a browser, and plugins never see raw key presses: the user picks the key, and your handler runs when it is pressed.

import { useHotkey, useHotkeyBinding } from "@sharkord/plugin-sdk/client";
import { HotkeyInput } from "@sharkord/ui";

const SoundRow = ({ sound }: { sound: TSound }) => {
  const id = `play-${sound.id}`;

  useHotkey({ id, label: `Play ${sound.name}` }, () => callAction("play", { soundId: sound.id }));

  const binding = useHotkeyBinding(id);

  return (
    <div>
      <span>{sound.name}</span>
      <HotkeyInput {...binding} />
    </div>
  );
};

useHotkey(action, handler) registers an action while the component using it is mounted, so a soundboard calls it once per sound and removing a sound removes its action. action is:

FieldMeaning
idUnique inside your plugin. Sharkord prefixes it with your plugin id, so two plugins can both have a play.
labelWhat the user reads in the Hotkeys settings.
mode"press" (default) calls the handler once per key press. "hold" also reports the release.

The handler receives the phase, "down" or "up". A press action only ever gets "down".

The user can bind your actions in two places, and both edit the same bind:

  • User Settings → Hotkeys, where every registered action is listed in a group named after your plugin.
  • Your own UI, with the HotkeyInput from @sharkord/ui, like any other component. It is the same control the settings page uses: it records the key, refuses combinations the browser or OS keeps, and refuses a key another action already uses. Unlike the settings page, it applies as soon as the user picks.

useHotkeyBinding(id) returns everything that control needs, so spreading it into HotkeyInput is the whole wiring: the labels come already translated into the user's language, and the rules are Sharkord's, not yours. It also returns display, the key as the user should read it, such as Ctrl + Alt + M, or undefined while unbound, and value, the stored key, for showing your own UI.

Things to keep in mind:

  • Hotkeys are experimental and off by default. They only fire when the user enabled them, so keep an on-screen button too, and never make a feature depend on them.
  • A bind belongs to the user's browser. It survives your component unmounting: when the action returns, so does its key.
  • The handler runs in the user's browser. For anything that needs permission, call a server action, exactly as a button would.
  • A key bound on several servers fires on all of them.
  • Like every hook here, they only work inside a component Sharkord rendered for your plugin.

Checking Access

An admin can restrict any of your commands and actions to roles, so a button that calls one may be useless for the user looking at it. These two answer whether they may:

import { useCanUseAction } from "@sharkord/plugin-sdk/client";
import type { TPlugin } from "../types";

const RollButton = () => {
  const canRoll = useCanUseAction<TPlugin>("roll");

  return (
    <button disabled={!canRoll} onClick={onRoll}>
      Roll
    </button>
  );
};

useCanUseCommand is the same for a slash command, for UI that lists or offers them. Both fold in USE_PLUGINS, so a user without it gets false either way, and both take the contract to autocomplete the name.

This is UX, not enforcement

It exists so you can disable a button instead of letting the call fail. The server checks again on every call, and that answer is the one that counts.

Store Actions

Besides executePluginAction, which is what callAction uses, actions exposes what your UI can do directly as the signed-in user:

import { actions } from "@sharkord/plugin-sdk/client";

await actions.sendMessage(channelId, "hello");
actions.selectChannel(channelId);

const response = await actions.fetchPluginRoute("my-plugin", "/preferences");

fetchPluginRoute attaches the user's token, so it is how you call your own authenticated HTTP routes without handling tokens yourself. These run as the current user, with that user's permissions.

Its third argument is a normal fetch init, so method, headers and body work as they do with fetch. That makes it the way to upload a file to your plugin:

await actions.fetchPluginRoute("my-plugin", "/sounds", {
  method: "POST",
  body: file,
});

Host Globals

The store and the shared libraries reach your bundle through globals, which is why your plugin does not ship its own React:

  • window.__SHARKORD_STORE__: getState, subscribe, actions, hooks
  • window.__SHARKORD_EXPOSED_LIBS__: createSelector, createCachedSelector
  • window.__SHARKORD_REACT__, __SHARKORD_REACT_JSX__, __SHARKORD_REACT_JSX_DEV__, __SHARKORD_REACT_DOM__, __SHARKORD_REACT_DOM_CLIENT__

The build tooling wires these up for you. Reach for them directly only when the SDK's helpers are not enough.

Reminder

Client code is public and runs in every user's browser. Do not put secrets in it, and do not treat a check you made here as security. Enforce it in a server action.

On this page