Files
ThreadNet-Web/apps/web/src/slash-commands/SlashCommands.tsx
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

913 lines
37 KiB
TypeScript
Raw Normal View History

2015-09-18 13:54:20 +01:00
/*
2026-04-29 09:14:22 +01:00
Copyright 2026 Element Creations Ltd.
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
Copyright 2020 The Matrix.org Foundation C.I.C.
2024-09-09 14:57:16 +01:00
Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>
Copyright 2018 New Vector Ltd
Copyright 2015, 2016 OpenMarket Ltd
2015-09-18 13:54:20 +01:00
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
2024-09-09 14:57:16 +01:00
Please see LICENSE files in the repository root for full details.
2015-09-18 13:54:20 +01:00
*/
2025-03-19 10:39:52 +00:00
import React from "react";
2025-02-05 13:25:06 +00:00
import {
ContentHelpers,
Direction,
EventType,
type IContent,
type MRoomTopicEventContent,
type User,
} from "matrix-js-sdk/src/matrix";
2021-12-09 09:10:23 +00:00
import { logger } from "matrix-js-sdk/src/logger";
2025-02-05 13:25:06 +00:00
import { KnownMembership, type RoomMemberEventContent } from "matrix-js-sdk/src/types";
import { LinkedText } from "@element-hq/web-shared-components";
2021-12-09 09:10:23 +00:00
import dis from "../dispatcher/dispatcher";
import { _t, _td, UserFriendlyError } from "../languageHandler";
import Modal from "../Modal";
import MultiInviter from "../utils/MultiInviter";
import { topicToHtml } from "../HtmlUtils";
import QuestionDialog from "../components/views/dialogs/QuestionDialog";
import WidgetUtils from "../utils/WidgetUtils";
import { textToHtmlRainbow } from "../utils/colour";
import { AddressType, getAddressType } from "../UserAddress";
import { abbreviateUrl } from "../utils/UrlUtils";
import { getDefaultIdentityServerUrl, setToDefaultIdentityServer } from "../utils/IdentityServerUtils";
import { WidgetType } from "../widgets/WidgetType";
import { Jitsi } from "../widgets/Jitsi";
import BugReportDialog from "../components/views/dialogs/BugReportDialog";
import { ensureDMExists } from "../createRoom";
import { type ViewUserPayload } from "../dispatcher/payloads/ViewUserPayload";
import { Action } from "../dispatcher/actions";
import SdkConfig from "../SdkConfig";
import SettingsStore from "../settings/SettingsStore";
import { UIComponent, UIFeature } from "../settings/UIFeature";
import { CHAT_EFFECTS } from "../effects";
import { guessAndSetDMRoom } from "../Rooms";
import DevtoolsDialog from "../components/views/dialogs/DevtoolsDialog";
import InfoDialog from "../components/views/dialogs/InfoDialog";
import SlashCommandHelpDialog from "../components/views/dialogs/SlashCommandHelpDialog";
import { shouldShowComponent } from "../customisations/helpers/UIComponents";
import { TimelineRenderingType } from "../contexts/RoomContext";
import { type ViewRoomPayload } from "../dispatcher/payloads/ViewRoomPayload";
import { htmlSerializeFromMdIfNeeded } from "../editor/serialize";
import { leaveRoomBehaviour } from "../utils/leave-behaviour";
import { MatrixClientPeg } from "../MatrixClientPeg";
2026-06-30 13:49:28 +01:00
import { isCurrentLocalRoom, reject, singleMxcUpload, success, successSync, splitAtFirstSpace } from "./utils";
import { deop, op } from "./op";
import { CommandCategories } from "./interface";
import { Command } from "./command";
import { goto, join } from "./join";
import { manuallyVerifyDevice } from "../components/views/dialogs/ManualDeviceKeyVerificationDialog";
import upgraderoom from "./upgraderoom/upgraderoom";
import { emoticon } from "./emoticon";
2026-04-29 09:14:22 +01:00
import { statusCommand } from "./status";
2026-07-07 13:29:54 +01:00
import { SDKContextClass } from "../contexts/SDKContextClass.ts";
export { CommandCategories, Command };
2017-05-23 09:44:11 +01:00
export const Commands = [
2021-02-25 16:59:27 -05:00
new Command({
command: "spoiler",
args: "<message>",
description: _td("slash_command|spoiler"),
runFn: function (cli, roomId, threadId, message = "") {
return successSync(ContentHelpers.makeHtmlMessage(message, `<span data-mx-spoiler>${message}</span>`));
2021-02-25 16:59:27 -05:00
},
category: CommandCategories.messages,
}),
emoticon("shrug", _td("slash_command|shrug"), "¯\\_(ツ)_/¯"),
emoticon("tableflip", _td("slash_command|tableflip"), "(╯°□°)╯︵ ┻━┻"),
emoticon("unflip", _td("slash_command|unflip"), "┬──┬ ( ゜-゜ノ)"),
emoticon("lenny", _td("slash_command|lenny"), "( ͡° ͜ʖ ͡°)"),
new Command({
command: "plain",
args: "<message>",
description: _td("slash_command|plain"),
runFn: function (cli, roomId, threadId, messages = "") {
return successSync(ContentHelpers.makeTextMessage(messages));
},
category: CommandCategories.messages,
}),
new Command({
command: "html",
2020-03-29 12:45:06 -07:00
args: "<message>",
description: _td("slash_command|html"),
runFn: function (cli, roomId, threadId, messages = "") {
return successSync(ContentHelpers.makeHtmlMessage(messages, messages));
2020-03-29 12:45:06 -07:00
},
category: CommandCategories.messages,
}),
upgraderoom,
2021-12-15 06:34:47 -06:00
new Command({
command: "jumptodate",
2022-04-14 17:13:18 +02:00
args: "<YYYY-MM-DD>",
description: _td("slash_command|jumptodate"),
2021-12-15 06:34:47 -06:00
isEnabled: () => SettingsStore.getValue("feature_jump_to_date"),
runFn: function (cli, roomId, threadId, args) {
2021-12-15 06:34:47 -06:00
if (args) {
return success(
(async (): Promise<void> => {
2021-12-15 06:34:47 -06:00
const unixTimestamp = Date.parse(args);
if (!unixTimestamp) {
throw new UserFriendlyError("slash_command|jumptodate_invalid_input", {
inputDate: args,
cause: undefined,
});
2021-12-15 06:34:47 -06:00
}
const { event_id: eventId, origin_server_ts: originServerTs } = await cli.timestampToEvent(
roomId,
unixTimestamp,
Direction.Forward,
);
logger.log(
`/timestamp_to_event: found ${eventId} (${originServerTs}) for timestamp=${unixTimestamp}`,
);
dis.dispatch<ViewRoomPayload>({
2021-12-15 06:34:47 -06:00
action: Action.ViewRoom,
event_id: eventId,
2021-12-15 06:34:47 -06:00
highlighted: true,
room_id: roomId,
metricsTrigger: "SlashCommand",
metricsViaKeyboard: true,
2021-12-15 06:34:47 -06:00
});
})(),
);
}
return reject(this.getUsage());
},
category: CommandCategories.actions,
}),
new Command({
command: "nick",
args: "<display_name>",
description: _td("slash_command|nick"),
runFn: function (cli, roomId, threadId, args) {
if (args) {
return success(cli.setDisplayName(args));
}
return reject(this.getUsage());
},
category: CommandCategories.actions,
renderingTypes: [TimelineRenderingType.Room],
}),
new Command({
command: "myroomnick",
aliases: ["roomnick"],
2019-02-24 01:36:47 +00:00
args: "<display_name>",
description: _td("slash_command|myroomnick"),
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
2019-02-24 01:36:47 +00:00
if (args) {
2024-03-20 14:27:29 +00:00
const ev = cli.getRoom(roomId)?.currentState.getStateEvents(EventType.RoomMember, cli.getSafeUserId());
const content: RoomMemberEventContent = {
...(ev ? ev.getContent() : { membership: KnownMembership.Join }),
2020-03-30 14:13:08 +01:00
displayname: args,
2019-02-24 01:36:47 +00:00
};
2024-03-20 14:27:29 +00:00
return success(cli.sendStateEvent(roomId, EventType.RoomMember, content, cli.getSafeUserId()));
2019-02-24 01:36:47 +00:00
}
return reject(this.getUsage());
},
category: CommandCategories.actions,
renderingTypes: [TimelineRenderingType.Room],
2019-02-24 01:36:47 +00:00
}),
new Command({
command: "roomavatar",
args: "[<mxc_url>]",
description: _td("slash_command|roomavatar"),
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
let promise = Promise.resolve(args ?? null);
if (!args) {
promise = singleMxcUpload(cli);
}
return success(
promise.then((url) => {
if (!url) return;
2024-03-20 14:27:29 +00:00
return cli.sendStateEvent(roomId, EventType.RoomAvatar, { url }, "");
}),
);
},
category: CommandCategories.actions,
renderingTypes: [TimelineRenderingType.Room],
}),
new Command({
command: "myroomavatar",
args: "[<mxc_url>]",
description: _td("slash_command|myroomavatar"),
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
const room = cli.getRoom(roomId);
const userId = cli.getSafeUserId();
let promise = Promise.resolve(args ?? null);
if (!args) {
promise = singleMxcUpload(cli);
}
return success(
promise.then((url) => {
2019-06-29 07:05:43 +01:00
if (!url) return;
2024-03-20 14:27:29 +00:00
const ev = room?.currentState.getStateEvents(EventType.RoomMember, userId);
const content: RoomMemberEventContent = {
...(ev ? ev.getContent() : { membership: KnownMembership.Join }),
avatar_url: url,
};
2024-03-20 14:27:29 +00:00
return cli.sendStateEvent(roomId, EventType.RoomMember, content, userId);
}),
);
},
category: CommandCategories.actions,
renderingTypes: [TimelineRenderingType.Room],
}),
new Command({
command: "myavatar",
2019-06-27 19:38:12 +01:00
args: "[<mxc_url>]",
description: _td("slash_command|myavatar"),
runFn: function (cli, roomId, threadId, args) {
let promise = Promise.resolve(args ?? null);
2019-06-27 19:38:12 +01:00
if (!args) {
promise = singleMxcUpload(cli);
2019-06-27 19:38:12 +01:00
}
return success(
promise.then((url) => {
2019-06-29 07:05:43 +01:00
if (!url) return;
return cli.setAvatarUrl(url);
2019-06-27 19:38:12 +01:00
}),
);
},
category: CommandCategories.actions,
renderingTypes: [TimelineRenderingType.Room],
2019-06-27 19:38:12 +01:00
}),
new Command({
command: "topic",
args: "[<topic>]",
description: _td("slash_command|topic"),
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
if (args) {
const html = htmlSerializeFromMdIfNeeded(args, { forceHTML: false });
return success(cli.setRoomTopic(roomId, args, html));
2015-09-18 13:54:20 +01:00
}
const room = cli.getRoom(roomId);
if (!room) {
return reject(
new UserFriendlyError("slash_command|topic_room_error", {
roomId,
cause: undefined,
}),
);
}
const content = room.currentState.getStateEvents("m.room.topic", "")?.getContent<MRoomTopicEventContent>();
const topic = !!content
? ContentHelpers.parseTopicContent(content)
: { text: _t("slash_command|topic_none") };
const body = topicToHtml(topic.text, topic.html, undefined, true);
2022-06-14 17:51:51 +01:00
Modal.createDialog(InfoDialog, {
title: room.name,
description: <LinkedText>{body}</LinkedText>,
hasCloseButton: true,
className: "markdown-body",
});
return success();
},
category: CommandCategories.admin,
renderingTypes: [TimelineRenderingType.Room],
}),
new Command({
command: "roomname",
2019-01-03 15:42:17 -08:00
args: "<name>",
description: _td("slash_command|roomname"),
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
2019-01-03 15:42:17 -08:00
if (args) {
return success(cli.setRoomName(roomId, args));
2019-01-03 15:42:17 -08:00
}
return reject(this.getUsage());
},
category: CommandCategories.admin,
renderingTypes: [TimelineRenderingType.Room],
2019-01-03 15:42:17 -08:00
}),
new Command({
command: "invite",
args: "<user-id> [<reason>]",
description: _td("slash_command|invite"),
2022-02-10 13:11:10 +00:00
analyticsName: "Invite",
isEnabled: (cli) => !isCurrentLocalRoom(cli) && shouldShowComponent(UIComponent.InviteUsers),
runFn: function (cli, roomId, threadId, args) {
if (args) {
const [address, reason] = splitAtFirstSpace(args);
if (address) {
// We use a MultiInviter to re-use the invite logic, even though
// we're only inviting one user.
// If we need an identity server but don't have one, things
// get a bit more complex here, but we try to show something
// meaningful.
2020-07-13 00:19:15 +01:00
let prom = Promise.resolve();
if (getAddressType(address) === AddressType.Email && !cli.getIdentityServerUrl()) {
const defaultIdentityServerUrl = getDefaultIdentityServerUrl();
if (defaultIdentityServerUrl) {
const { finished } = Modal.createDialog(QuestionDialog, {
title: _t("slash_command|invite_3pid_use_default_is_title"),
2022-06-14 17:51:51 +01:00
description: (
<p>
{_t("slash_command|invite_3pid_use_default_is_title_description", {
defaultIdentityServerName: abbreviateUrl(defaultIdentityServerUrl),
})}
2022-06-14 17:51:51 +01:00
</p>
),
button: _t("action|continue"),
2022-06-14 17:51:51 +01:00
});
2020-04-01 16:53:25 +01:00
2020-07-13 00:19:15 +01:00
prom = finished.then(([useDefault]) => {
2020-04-01 16:53:25 +01:00
if (useDefault) {
setToDefaultIdentityServer(cli);
2020-04-01 16:53:25 +01:00
return;
}
throw new UserFriendlyError("slash_command|invite_3pid_needs_is_error");
2020-04-01 16:53:25 +01:00
});
} else {
return reject(new UserFriendlyError("slash_command|invite_3pid_needs_is_error"));
}
}
const inviter = new MultiInviter(cli, roomId);
2020-07-13 00:19:15 +01:00
return success(
prom
.then(() => {
2024-06-14 09:13:41 -04:00
return inviter.invite([address], reason);
})
.then(() => {
if (inviter.getCompletionState(address) !== "invited") {
const errorStringFromInviterUtility = inviter.getErrorText(address);
if (errorStringFromInviterUtility) {
throw new Error(errorStringFromInviterUtility);
} else {
throw new UserFriendlyError("slash_command|invite_failed", {
user: address,
roomId,
cause: undefined,
});
}
2018-11-29 15:16:45 -07:00
}
}),
);
}
}
return reject(this.getUsage());
},
category: CommandCategories.actions,
renderingTypes: [TimelineRenderingType.Room],
}),
goto,
join,
new Command({
command: "part",
2020-04-14 10:06:57 +01:00
args: "[<room-address>]",
description: _td("action|leave_room"),
2022-02-10 13:11:10 +00:00
analyticsName: "Part",
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
2022-11-07 13:45:34 +00:00
let targetRoomId: string | undefined;
if (args) {
const matches = args.match(/^(\S+)$/);
if (matches) {
let roomAlias = matches[1];
2024-10-16 17:38:22 +01:00
if (!roomAlias.startsWith("#")) return reject(this.getUsage());
if (!roomAlias.includes(":")) {
roomAlias += ":" + cli.getDomain();
}
// Try to find a room with this alias
const rooms = cli.getRooms();
2022-11-07 13:45:34 +00:00
targetRoomId = rooms.find((room) => {
return room.getCanonicalAlias() === roomAlias || room.getAltAliases().includes(roomAlias);
})?.roomId;
if (!targetRoomId) {
return reject(
new UserFriendlyError("slash_command|part_unknown_alias", {
roomAlias,
cause: undefined,
}),
);
}
}
}
if (!targetRoomId) targetRoomId = roomId;
return success(leaveRoomBehaviour(cli, targetRoomId));
},
category: CommandCategories.actions,
renderingTypes: [TimelineRenderingType.Room],
}),
new Command({
command: "remove",
aliases: ["kick"],
args: "<user-id> [reason]",
description: _td("slash_command|remove"),
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
if (args) {
const [userId, reason] = splitAtFirstSpace(args);
if (userId) {
return success(cli.kick(roomId, userId, reason));
}
}
return reject(this.getUsage());
},
category: CommandCategories.admin,
renderingTypes: [TimelineRenderingType.Room],
}),
new Command({
command: "ban",
args: "<user-id> [reason]",
description: _td("slash_command|ban"),
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
if (args) {
const [userId, reason] = splitAtFirstSpace(args);
if (userId) {
return success(cli.ban(roomId, userId, reason));
}
2015-09-18 13:54:20 +01:00
}
return reject(this.getUsage());
},
category: CommandCategories.admin,
renderingTypes: [TimelineRenderingType.Room],
}),
new Command({
command: "unban",
args: "<user-id>",
description: _td("slash_command|unban"),
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
if (args) {
const matches = args.match(/^(\S+)$/);
if (matches) {
// Reset the user membership to "leave" to unban him
return success(cli.unban(roomId, matches[1]));
}
2015-09-18 13:54:20 +01:00
}
return reject(this.getUsage());
},
category: CommandCategories.admin,
renderingTypes: [TimelineRenderingType.Room],
}),
new Command({
command: "ignore",
args: "<user-id>",
description: _td("slash_command|ignore"),
runFn: function (cli, roomId, threadId, args) {
if (args) {
const matches = args.match(/^(@[^:]+:\S+)$/);
if (matches) {
const userId = matches[1];
const ignoredUsers = cli.getIgnoredUsers();
ignoredUsers.push(userId); // de-duped internally in the js-sdk
return success(
cli.setIgnoredUsers(ignoredUsers).then(() => {
2022-06-14 17:51:51 +01:00
Modal.createDialog(InfoDialog, {
title: _t("slash_command|ignore_dialog_title"),
description: (
<div>
<p>{_t("slash_command|ignore_dialog_description", { userId })}</p>
</div>
),
});
}),
);
}
}
return reject(this.getUsage());
},
category: CommandCategories.actions,
}),
new Command({
command: "unignore",
args: "<user-id>",
description: _td("slash_command|unignore"),
runFn: function (cli, roomId, threadId, args) {
if (args) {
const matches = args.match(/(^@[^:]+:\S+$)/);
if (matches) {
const userId = matches[1];
const ignoredUsers = cli.getIgnoredUsers();
const index = ignoredUsers.indexOf(userId);
if (index !== -1) ignoredUsers.splice(index, 1);
return success(
cli.setIgnoredUsers(ignoredUsers).then(() => {
2022-06-14 17:51:51 +01:00
Modal.createDialog(InfoDialog, {
title: _t("slash_command|unignore_dialog_title"),
description: (
<div>
<p>{_t("slash_command|unignore_dialog_description", { userId })}</p>
</div>
),
});
}),
);
}
}
return reject(this.getUsage());
},
category: CommandCategories.actions,
}),
op,
deop,
new Command({
command: "devtools",
description: _td("slash_command|devtools"),
runFn: function (cli, roomId, threadRootId) {
Modal.createDialog(DevtoolsDialog, { roomId, threadRootId }, "mx_DevtoolsDialog_wrapper");
return success();
},
category: CommandCategories.advanced,
2017-07-31 12:08:28 +01:00
}),
new Command({
command: "addwidget",
2020-04-20 09:35:35 -06:00
args: "<url | embed code | Jitsi url>",
description: _td("slash_command|addwidget"),
isEnabled: (cli) =>
SettingsStore.getValue(UIFeature.Widgets) &&
shouldShowComponent(UIComponent.AddIntegrations) &&
!isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, widgetUrl) {
2020-04-09 16:02:49 -06:00
if (!widgetUrl) {
return reject(new UserFriendlyError("slash_command|addwidget_missing_url"));
2020-04-09 16:02:49 -06:00
}
// Try and parse out a widget URL from iframes
if (widgetUrl.toLowerCase().startsWith("<iframe ")) {
const embed = new DOMParser().parseFromString(widgetUrl, "text/html").body;
if (embed?.childNodes?.length === 1) {
const iframe = embed.firstElementChild;
if (iframe?.tagName.toLowerCase() === "iframe") {
logger.log("Pulling URL out of iframe (embed code)");
if (!iframe.hasAttribute("src")) {
return reject(new UserFriendlyError("slash_command|addwidget_iframe_missing_src"));
}
widgetUrl = iframe.getAttribute("src")!;
2020-04-09 16:02:49 -06:00
}
}
}
if (!widgetUrl.startsWith("https://") && !widgetUrl.startsWith("http://")) {
return reject(new UserFriendlyError("slash_command|addwidget_invalid_protocol"));
}
if (WidgetUtils.canUserModifyWidgets(cli, roomId)) {
const userId = cli.getUserId();
const nowMs = new Date().getTime();
const widgetId = encodeURIComponent(`${roomId}_${userId}_${nowMs}`);
2020-04-09 16:02:49 -06:00
let type = WidgetType.CUSTOM;
2022-01-31 15:37:49 +00:00
let name = "Custom";
2020-04-09 16:02:49 -06:00
let data = {};
// Make the widget a Jitsi widget if it looks like a Jitsi widget
const jitsiData = Jitsi.getInstance().parsePreferredConferenceUrl(widgetUrl);
if (jitsiData) {
logger.log("Making /addwidget widget a Jitsi conference");
2020-04-09 16:02:49 -06:00
type = WidgetType.JITSI;
2022-01-31 15:37:49 +00:00
name = "Jitsi";
2020-04-09 16:02:49 -06:00
data = jitsiData;
widgetUrl = WidgetUtils.getLocalJitsiWrapperUrl();
}
return success(WidgetUtils.setRoomWidget(cli, roomId, widgetId, type, widgetUrl, name, data));
} else {
return reject(new UserFriendlyError("slash_command|addwidget_no_permissions"));
}
},
category: CommandCategories.admin,
renderingTypes: [TimelineRenderingType.Room],
}),
new Command({
command: "verify",
args: "<device-id> <device-fingerprint>",
description: _td("slash_command|verify"),
runFn: function (cli, _roomId, _threadId, args) {
if (args) {
const matches = args.match(/^(\S+) +(\S+)$/);
if (matches) {
const deviceId = matches[1];
const fingerprint = matches[2];
const { finished } = Modal.createDialog(QuestionDialog, {
title: _t("slash_command|manual_device_verification_confirm_title"),
description: _t("slash_command|manual_device_verification_confirm_description"),
button: _t("action|verify"),
danger: true,
});
return success(
finished.then(([confirmed]) => {
if (confirmed) manuallyVerifyDevice(cli, deviceId, fingerprint);
}),
);
}
}
return reject(this.getUsage());
},
category: CommandCategories.advanced,
renderingTypes: [TimelineRenderingType.Room],
}),
new Command({
command: "discardsession",
description: _td("slash_command|discardsession"),
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId) {
2018-08-29 18:09:37 +01:00
try {
cli.getCrypto()?.forceDiscardSession(roomId);
2018-08-29 18:09:37 +01:00
} catch (e) {
return reject(e instanceof Error ? e.message : e);
2018-08-29 18:09:37 +01:00
}
return success();
},
category: CommandCategories.advanced,
renderingTypes: [TimelineRenderingType.Room],
2018-08-29 18:09:37 +01:00
}),
new Command({
command: "rainbow",
description: _td("slash_command|rainbow"),
2019-05-12 16:36:43 +01:00
args: "<message>",
runFn: function (cli, roomId, threadId, args) {
if (!args) return reject(this.getUsage());
return successSync(ContentHelpers.makeHtmlMessage(args, textToHtmlRainbow(args)));
2019-05-12 16:36:43 +01:00
},
category: CommandCategories.messages,
2019-05-12 16:36:43 +01:00
}),
new Command({
command: "rainbowme",
description: _td("slash_command|rainbowme"),
2019-05-12 16:36:43 +01:00
args: "<message>",
runFn: function (cli, roomId, threadId, args) {
if (!args) return reject(this.getUsage());
return successSync(ContentHelpers.makeHtmlEmote(args, textToHtmlRainbow(args)));
2019-05-12 16:36:43 +01:00
},
category: CommandCategories.messages,
2019-05-12 17:14:30 +01:00
}),
new Command({
command: "help",
description: _td("slash_command|help"),
runFn: function (cli, roomId, threadId, args) {
Modal.createDialog(SlashCommandHelpDialog, { roomId });
2019-07-29 17:58:34 +01:00
return success();
},
category: CommandCategories.advanced,
2019-07-29 17:58:34 +01:00
}),
2020-03-30 14:13:08 +01:00
new Command({
command: "whois",
description: _td("slash_command|whois"),
2020-03-30 14:13:08 +01:00
args: "<user-id>",
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, userId) {
2020-03-30 14:13:08 +01:00
if (!userId || !userId.startsWith("@") || !userId.includes(":")) {
return reject(this.getUsage());
}
const member = cli.getRoom(roomId)?.getMember(userId);
dis.dispatch<ViewUserPayload>({
action: Action.ViewUser,
2021-06-18 16:21:46 +01:00
// XXX: We should be using a real member object and not assuming what the receiver wants.
member: member || ({ userId } as User),
2020-03-30 14:13:08 +01:00
});
return success();
},
category: CommandCategories.advanced,
}),
2020-04-19 12:09:07 +01:00
new Command({
command: "rageshake",
aliases: ["bugreport"],
description: _td("slash_command|rageshake"),
isEnabled: () => !!SdkConfig.get().bug_report_endpoint_url,
2020-04-19 12:09:07 +01:00
args: "<description>",
runFn: function (cli, roomId, threadId, args) {
return success(
2022-06-14 17:51:51 +01:00
Modal.createDialog(BugReportDialog, {
initialText: args,
}).finished,
);
2020-04-19 12:09:07 +01:00
},
category: CommandCategories.advanced,
}),
new Command({
command: "query",
description: _td("slash_command|query"),
args: "<user-id>",
runFn: function (cli, roomId, threadId, userId) {
2020-11-04 15:32:21 +00:00
// easter-egg for now: look up phone numbers through the thirdparty API
// (very dumb phone number detection...)
const isPhoneNumber = userId && /^\+?[0123456789]+$/.test(userId);
if (!userId || ((!userId.startsWith("@") || !userId.includes(":")) && !isPhoneNumber)) {
return reject(this.getUsage());
}
return success(
(async (): Promise<void> => {
2020-11-04 15:32:21 +00:00
if (isPhoneNumber) {
2026-07-07 13:29:54 +01:00
const results = await SDKContextClass.instance.legacyCallHandler.pstnLookup(userId);
2020-11-04 15:32:21 +00:00
if (!results || results.length === 0 || !results[0].userid) {
throw new UserFriendlyError("slash_command|query_not_found_phone_number");
2022-12-12 12:24:14 +01:00
}
2020-11-04 15:32:21 +00:00
userId = results[0].userid;
}
const roomId = await ensureDMExists(cli, userId);
if (!roomId) throw new Error("Failed to ensure DM exists");
2020-11-04 15:32:21 +00:00
dis.dispatch<ViewRoomPayload>({
2021-11-25 17:49:43 -03:00
action: Action.ViewRoom,
2020-11-04 15:32:21 +00:00
room_id: roomId,
metricsTrigger: "SlashCommand",
metricsViaKeyboard: true,
});
})(),
);
},
category: CommandCategories.actions,
}),
new Command({
command: "msg",
description: _td("slash_command|msg"),
args: "<user-id> [<message>]",
runFn: function (cli, roomId, threadId, args) {
if (args) {
2020-05-12 10:23:53 +01:00
// matches the first whitespace delimited group and then the rest of the string
const [userId, msg] = splitAtFirstSpace(args);
if (userId !== "") {
if (userId && userId.startsWith("@") && userId.includes(":")) {
return success(
(async (): Promise<void> => {
const roomId = await ensureDMExists(cli, userId);
if (!roomId) throw new Error("Failed to ensure DM exists");
dis.dispatch<ViewRoomPayload>({
2021-11-25 17:49:43 -03:00
action: Action.ViewRoom,
room_id: roomId,
metricsTrigger: "SlashCommand",
metricsViaKeyboard: true,
});
if (msg) {
cli.sendTextMessage(roomId, msg);
}
})(),
);
}
}
}
return reject(this.getUsage());
},
category: CommandCategories.actions,
}),
2020-10-29 17:56:24 +00:00
new Command({
command: "holdcall",
description: _td("slash_command|holdcall"),
2020-10-29 17:56:24 +00:00
category: CommandCategories.other,
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
2026-07-07 13:29:54 +01:00
const call = SDKContextClass.instance.legacyCallHandler.getCallForRoom(roomId);
2020-10-29 17:56:24 +00:00
if (!call) {
return reject(new UserFriendlyError("slash_command|no_active_call"));
2020-10-29 17:56:24 +00:00
}
call.setRemoteOnHold(true);
return success();
},
renderingTypes: [TimelineRenderingType.Room],
2020-10-29 17:56:24 +00:00
}),
new Command({
command: "unholdcall",
description: _td("slash_command|unholdcall"),
2020-10-29 17:56:24 +00:00
category: CommandCategories.other,
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
2026-07-07 13:29:54 +01:00
const call = SDKContextClass.instance.legacyCallHandler.getCallForRoom(roomId);
2020-10-29 17:56:24 +00:00
if (!call) {
return reject(new UserFriendlyError("slash_command|no_active_call"));
2020-10-29 17:56:24 +00:00
}
call.setRemoteOnHold(false);
return success();
},
renderingTypes: [TimelineRenderingType.Room],
2020-10-29 17:56:24 +00:00
}),
2021-01-13 15:30:09 +01:00
new Command({
command: "converttodm",
description: _td("slash_command|converttodm"),
2021-01-13 15:30:09 +01:00
category: CommandCategories.other,
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
const room = cli.getRoom(roomId);
if (!room) return reject(new UserFriendlyError("slash_command|could_not_find_room"));
2021-01-13 15:30:09 +01:00
return success(guessAndSetDMRoom(room, true));
},
renderingTypes: [TimelineRenderingType.Room],
2021-01-13 15:30:09 +01:00
}),
new Command({
command: "converttoroom",
description: _td("slash_command|converttoroom"),
2021-01-13 15:30:09 +01:00
category: CommandCategories.other,
isEnabled: (cli) => !isCurrentLocalRoom(cli),
runFn: function (cli, roomId, threadId, args) {
const room = cli.getRoom(roomId);
if (!room) return reject(new UserFriendlyError("slash_command|could_not_find_room"));
2021-01-13 15:30:09 +01:00
return success(guessAndSetDMRoom(room, false));
},
renderingTypes: [TimelineRenderingType.Room],
2021-01-13 15:30:09 +01:00
}),
2026-04-29 09:14:22 +01:00
statusCommand,
2020-02-29 01:29:52 +00:00
// Command definitions for autocompletion ONLY:
// /me is special because its not handled by SlashCommands.js and is instead done inside the Composer classes
new Command({
command: "me",
args: "<message>",
description: _td("slash_command|me"),
category: CommandCategories.messages,
hideCompletionAfterSpace: true,
2020-02-29 01:29:52 +00:00
}),
2020-11-26 18:27:35 +01:00
...CHAT_EFFECTS.map((effect) => {
return new Command({
command: effect.command,
description: effect.description(),
args: "<message>",
runFn: function (cli, roomId, threadId, args) {
let content: IContent;
if (!args) {
content = ContentHelpers.makeEmoteMessage(effect.fallbackMessage());
} else {
content = {
msgtype: effect.msgType,
body: args,
};
}
dis.dispatch({ action: `effects.${effect.command}` });
return successSync(content);
},
category: CommandCategories.effects,
renderingTypes: [TimelineRenderingType.Room],
2021-06-29 13:11:58 +01:00
});
2020-08-18 17:57:51 +02:00
}),
];
2017-05-23 09:44:11 +01:00
// build a map from names and aliases to the Command objects.
export const CommandMap = new Map<string, Command>();
Commands.forEach((cmd) => {
CommandMap.set(cmd.command, cmd);
cmd.aliases.forEach((alias) => {
CommandMap.set(alias, cmd);
});
});
2015-09-18 13:54:20 +01:00
/**
* If the supplied input starts with "/<command>", returns an object with these
* properties:
*
* cmd - the string following the / up to some whitespace
* args - the string (if any) after first whitespace
*
* If not, returns {}
*/
export function parseCommandString(input: string): { cmd?: string; args?: string } {
const trimmedInput = input.trimStart();
if (trimmedInput.charAt(0) !== "/") {
return {};
}
2016-01-14 17:33:52 +00:00
const withoutSlash = trimmedInput.slice(1);
const [cmd, args] = splitAtFirstSpace(withoutSlash);
2021-06-29 13:11:58 +01:00
return { cmd, args };
}
interface ICmd {
cmd?: Command;
args?: string;
}
/**
* Process the given text for /commands and returns a parsed command that can be used for running the operation.
* @param {string} roomId The room ID where the command was issued.
* @param {string} input The raw text input by the user.
* @return {ICmd} The parsed command object.
* Returns an empty object if the input didn't match a command.
*/
export function getCommand(roomId: string, input: string): ICmd {
2021-06-29 13:11:58 +01:00
const { cmd, args } = parseCommandString(input);
if (cmd && CommandMap.has(cmd) && CommandMap.get(cmd)!.isEnabled(MatrixClientPeg.get(), roomId)) {
2021-02-25 14:39:20 -05:00
return {
cmd: CommandMap.get(cmd),
args,
};
}
2021-04-13 10:33:32 +01:00
return {};
}