Skip to content
FMFallout Multiplayer Scripting APIScripting guides and API
GuideMaintainer authored

Roleplay chat and commands

Turn plain chat into local speech, add /me, /do, /ooc, /pm and /pay, and dispatch every command through one small registry with a /help that writes itself.

On a roleplay server, what a character says should only reach the people standing near them. Out of character talk is marked as such, actions are written in the third person, and handing someone caps is something the people around you can see happen. You will build all of that on top of playerChat and playerCommand, plus the command registry that the default gamemode uses to keep forty-odd commands manageable.

This is the chat, players and roleplay features of the default gamemode, rebuilt step by step.

  • Swallowing a chat line with playerChat and sending it somewhere else.
  • Finding the players around someone with Player.getInRange.
  • A command registry: one dispatcher, one map, and features that register their own commands.
  • Resolving a player from what somebody typed, by ID or by part of a nickname.
  • Colors in chat.
roleplay/
package.json
tsconfig.json
src/server/
index.ts imports, and the dispatcher
commands.ts the registry
players.ts "who did they mean?"
speech.ts local chat, /me, /do, /s, /b, /ooc, /pm
money.ts /pay

playerCommand fires for every line starting with /. Handling every command in one big if chain works for three commands and falls apart at thirty. Instead, keep a map from name to handler, and let each feature file register its own:

src/server/commands.ts
export type CommandHandler = (player: Player, args: string[]) => void;
const commands = new Map<string, CommandHandler>();
export function registerCommands(handlers: Readonly<Record<string, CommandHandler>>): void {
for (const [name, run] of Object.entries(handlers)) commands.set(name, run);
}
export function findCommand(name: string): CommandHandler | undefined {
return commands.get(name);
}
export function commandNames(): string[] {
return [...commands.keys()].sort();
}
export function reply(player: Player, text: string): void {
Chat.sendToPlayer(player, text, { author: "Server" });
}

The dispatcher lives in the entry point and is the only playerCommand handler in the resource:

src/server/index.ts
import { commandNames, findCommand, registerCommands, reply } from "./commands.js";
import "./speech.js";
import "./money.js";
registerCommands({
help: (player) => reply(player, `Commands: ${commandNames().map((name) => `/${name}`).join(" ")}`),
});
Events.on("playerCommand", (player: Player, name: string, args: string[]) => {
const run = findCommand(name.toLowerCase());
if (run === undefined) {
reply(player, `Unknown command /${name}. Type /help for the list.`);
return;
}
run(player, args);
});

/help now lists every command any feature registers, without anyone maintaining a list.

Commands like /pm and /pay name another player. Accept an ID (what other players see in /b lines), or any part of a nickname that matches exactly one person:

src/server/players.ts
import { reply } from "./commands.js";
export function findPlayer(sender: Player, query: string | undefined): Player | null {
if (query === undefined || query === "") return null;
const players = Player.all();
const id = Number(query);
const byId = Number.isInteger(id) ? players.find((p) => p.id === id) : undefined;
if (byId !== undefined) return byId;
const wanted = query.toLowerCase();
const matches = players.filter((p) => p.nickname.toLowerCase().includes(wanted));
if (matches.length !== 1) {
reply(sender, matches.length === 0 ? `Nobody called ${query}.` : `${matches.length} people match ${query}: be more precise.`);
return null;
}
return matches[0] ?? null;
}

Telling the sender why a lookup failed is half of what makes a command pleasant to use. “Nobody” and “be more precise” are two very different problems.

Return false from playerChat and the line goes nowhere. Then send it yourself, to the people in range. Distances are in game units, about 70 to a metre:

src/server/speech.ts
import { registerCommands, reply } from "./commands.js";
import { findPlayer } from "./players.js";
const kSayRange = 1400; // about 20 m
const kShoutRange = 2800;
// Colors are packed 0xRRGGBBAA.
const kSay = 0xe6e6e6ff;
const kShout = 0xffffffff;
const kAction = 0xc2a2daff;
const kLocalOoc = 0xa0a0a0ff;
const kOoc = 0x9fc5e8ff;
const kPrivate = 0xf0d070ff;
/** Everyone within range of the speaker, the speaker included. */
export function around(player: Player, range: number): Player[] {
const near = Player.getInRange(player, range, { limit: 512 })
.filter((other) => other.virtualWorld === player.virtualWorld);
return [player, ...near];
}
export function sayAround(player: Player, range: number, text: string, color: number): void {
for (const listener of around(player, range)) Chat.sendToPlayer(listener, text, { color });
}
const joined = (args: string[]): string => args.join(" ").trim();
Events.on("playerChat", (player: Player, text: string) => {
sayAround(player, kSayRange, `${player.nickname} says: ${text}`, kSay);
return false;
});

Player.getInRange does most of the work: it searches around a player, in that player’s worldspace or interior, nearest first. Two things to know about it:

  • It leaves the center out. A player is never in range of themselves, so around adds the speaker back; otherwise nobody would see their own line.
  • It returns 32 players by default. Pass limit (up to 512) for anything everyone nearby must receive. A crowded square is exactly where a missing line would be noticed.

It does not look at virtual worlds, so filter on virtualWorld yourself if your server uses them for instanced interiors or minigames.

Each of these is a line in the same registry. Empty input gets the usage, which is the only help most players ever read:

src/server/speech.ts
import { registerCommands, reply } from "./commands.js";
import { findPlayer } from "./players.js";
const kSayRange = 1400;
const kShoutRange = 2800;
const kSay = 0xe6e6e6ff;
const kShout = 0xffffffff;
const kAction = 0xc2a2daff;
const kLocalOoc = 0xa0a0a0ff;
const kOoc = 0x9fc5e8ff;
const kPrivate = 0xf0d070ff;
export function around(player: Player, range: number): Player[] {
const near = Player.getInRange(player, range, { limit: 512 })
.filter((other) => other.virtualWorld === player.virtualWorld);
return [player, ...near];
}
export function sayAround(player: Player, range: number, text: string, color: number): void {
for (const listener of around(player, range)) Chat.sendToPlayer(listener, text, { color });
}
const joined = (args: string[]): string => args.join(" ").trim();
Events.on("playerChat", (player: Player, text: string) => {
sayAround(player, kSayRange, `${player.nickname} says: ${text}`, kSay);
return false;
});
/** A command that needs some text after it. */
const withText = (usage: string, run: (player: Player, text: string) => void) =>
(player: Player, args: string[]): void => {
const text = joined(args);
if (text === "") reply(player, usage);
else run(player, text);
};
registerCommands({
// * Nate opens the door.
me: withText("/me <action>", (player, text) =>
sayAround(player, kSayRange, `* ${player.nickname} ${text}`, kAction)),
// * The door is locked. (( Nate ))
do: withText("/do <description>", (player, text) =>
sayAround(player, kSayRange, `* ${text} (( ${player.nickname} ))`, kAction)),
s: withText("/s <text>", (player, text) =>
sayAround(player, kShoutRange, `${player.nickname} shouts: ${text}!`, kShout)),
// Local out of character: the ID is there so people can /pm back.
b: withText("/b <text>", (player, text) =>
sayAround(player, kSayRange, `(( ${player.nickname} [${player.id}]: ${text} ))`, kLocalOoc)),
ooc: withText("/ooc <text>", (player, text) => {
for (const listener of Player.all()) {
Chat.sendToPlayer(listener, `(( [OOC] ${player.nickname}: ${text} ))`, { color: kOoc });
}
}),
pm: (player, args) => {
const [query, ...rest] = args;
const text = joined(rest);
if (query === undefined || text === "") return reply(player, "/pm <id or name> <text>");
const target = findPlayer(player, query);
if (target === null) return;
Chat.sendToPlayer(target, `(( PM from ${player.nickname} [${player.id}]: ${text} ))`, { color: kPrivate });
Chat.sendToPlayer(player, `(( PM to ${target.nickname} [${target.id}]: ${text} ))`, { color: kPrivate });
},
});

These lines pass a color and no author: the nickname is already part of the text, placed where each format needs it.

/pay is a small lesson in validating a transfer. The amount must be a positive whole number, the target must be someone else, standing close, and the sender must have the caps now:

src/server/money.ts
import { registerCommands, reply } from "./commands.js";
import { findPlayer } from "./players.js";
import { sayAround } from "./speech.js";
const kPayRange = 250;
const kMoney = 0x9be36aff;
const kAction = 0xc2a2daff;
registerCommands({
pay: (player, args) => {
const [query, amountText] = args;
const amount = Number(amountText);
if (query === undefined || !Number.isInteger(amount) || amount <= 0) {
return reply(player, "/pay <id or name> <caps>");
}
const target = findPlayer(player, query);
if (target === null) return;
if (target.id === player.id) return reply(player, "You cannot pay yourself.");
const near = Player.getInRange(player, kPayRange, { limit: 512 }).some((p) => p.id === target.id);
if (!near) return reply(player, `${target.nickname} is too far away.`);
const caps = player.getCaps();
if (caps < amount) return reply(player, `You only have ${caps} caps.`);
player.setCaps(caps - amount);
target.setCaps(target.getCaps() + amount);
Chat.sendToPlayer(player, `You gave ${amount} caps to ${target.nickname}.`, { color: kMoney });
Chat.sendToPlayer(target, `${player.nickname} gave you ${amount} caps.`, { color: kMoney });
sayAround(player, 1400, `* ${player.nickname} hands some caps to ${target.nickname}.`, kAction);
console.log(`${player.nickname} paid ${amount} caps to ${target.nickname}`);
},
});

Number.isInteger rejects NaN, Infinity, 1.5 and a missing argument in one check, and amount <= 0 rejects the rest. Drop that second half and /pay Nate -100 becomes a way to take caps from someone else.

  1. Build and load:

    Server console
    refresh
    ensure roleplay
  2. Type a plain line. Only you see it, as <you> says: ....

  3. With a second player, walk apart past twenty metres and talk. They stop seeing you.

  4. /s across that distance; /ooc from anywhere.

  5. /pay them from across the map, then standing next to them.

  6. /help. Every command from every file is there.

  • Muffled speech. Between kSayRange and twice that, send the line with every other word replaced by ... instead of dropping it.
  • Radio. Let /r reach everyone on the same frequency regardless of distance; see Voice and radio for the voice side of the same idea.
  • Admins. Add a second registry for staff commands, and only dispatch to it for players you have marked in a server-scoped state bag.