This repository was archived by the owner on Mar 10, 2026. It is now read-only.
forked from cinnyapp/cinny
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathuseCommands.ts
More file actions
1041 lines (947 loc) · 34.9 KB
/
useCommands.ts
File metadata and controls
1041 lines (947 loc) · 34.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Direction,
EventTimeline,
IContextResponse,
MatrixClient,
Method,
Preset,
Room,
RoomMember,
Visibility,
RoomServerAclEventContent,
MsgType,
} from '$types/matrix-sdk';
import { useMemo } from 'react';
import { Membership, StateEvent } from '$types/matrix/room';
import {
addRoomIdToMDirect,
getDMRoomFor,
guessDmRoomUserId,
isRoomAlias,
isRoomId,
isServerName,
isUserId,
rateLimitedActions,
removeRoomIdFromMDirect,
} from '$utils/matrix';
import { getStateEvent } from '$utils/room';
import { splitWithSpace } from '$utils/common';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { createRoomEncryptionState } from '$components/create-room';
import { useRoomNavigate } from './useRoomNavigate';
import { enrichWidgetUrl } from './useRoomWidgets';
export const SHRUG = '¯\\_(ツ)_/¯';
export const TABLEFLIP = '(╯°□°)╯︵ ┻━┻';
export const UNFLIP = '┬─┬ノ( º_ºノ)';
const FLAG_PAT = '(?:^|\\s)-(\\w+)\\b';
const FLAG_REG = new RegExp(FLAG_PAT);
const FLAG_REG_G = new RegExp(FLAG_PAT, 'g');
export const splitPayloadContentAndFlags = (payload: string): [string, string | undefined] => {
const flagMatch = payload.match(FLAG_REG);
if (!flagMatch) {
return [payload, undefined];
}
const content = payload.slice(0, flagMatch.index);
const flags = payload.slice(flagMatch.index);
return [content, flags];
};
export const parseFlags = (flags: string | undefined): Record<string, string | undefined> => {
const result: Record<string, string> = {};
if (!flags) return result;
const matches: { key: string; index: number; match: string }[] = [];
for (let match = FLAG_REG_G.exec(flags); match !== null; match = FLAG_REG_G.exec(flags)) {
matches.push({ key: match[1], index: match.index, match: match[0] });
}
for (let i = 0; i < matches.length; i += 1) {
const { key, match } = matches[i];
const start = matches[i].index + match.length;
const end = i + 1 < matches.length ? matches[i + 1].index : flags.length;
const value = flags.slice(start, end).trim();
result[key] = value;
}
return result;
};
export const parseUsers = (payload: string): string[] => {
const users: string[] = [];
splitWithSpace(payload).forEach((item) => {
if (isUserId(item)) {
users.push(item);
}
});
return users;
};
export const parseServers = (payload: string): string[] => {
const servers: string[] = [];
splitWithSpace(payload).forEach((item) => {
if (isServerName(item)) {
servers.push(item);
}
});
return servers;
};
const getServerMembers = (room: Room, server: string): RoomMember[] => {
const members: RoomMember[] = room
.getMembers()
.filter((member) => member.userId.endsWith(`:${server}`));
return members;
};
export const parseTimestampFlag = (input: string): number | undefined => {
const match = input.match(/^(\d+(?:\.\d+)?)([dhms])$/); // supports floats like 1.5d
if (!match) {
return undefined;
}
const value = parseFloat(match[1]); // supports decimal values
const unit = match[2];
const now = Date.now(); // in milliseconds
let delta = 0;
switch (unit) {
case 'd':
delta = value * 24 * 60 * 60 * 1000;
break;
case 'h':
delta = value * 60 * 60 * 1000;
break;
case 'm':
delta = value * 60 * 1000;
break;
case 's':
delta = value * 1000;
break;
default:
return undefined;
}
const timestamp = now - delta;
return timestamp;
};
const hslToHex = (h: number, s: number, l: number): string => {
const a = s * Math.min(l, 1 - l);
const f = (n: number) => {
const k = (n + h * 12) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color)
.toString(16)
.padStart(2, '0');
};
return `#${f(0)}${f(8)}${f(4)}`;
};
const getAllTextNodes = (root: Node): Node[] =>
root.nodeType === Node.TEXT_NODE
? [root]
: Array.from(root.childNodes).reduce<Node[]>(
(acc, child) => acc.concat(getAllTextNodes(child)),
[]
);
export const rainbowify = (htmlInput: string): string => {
const div = document.createElement('div');
div.innerHTML = htmlInput;
const textNodes = getAllTextNodes(div);
const totalTextLen = textNodes.reduce((acc, node) => {
const text = node.textContent || '';
const cleanLen = Array.from(text).filter((c) => c.trim().length > 0).length;
return acc + cleanLen;
}, 0);
textNodes.reduce((currentGlobalIdx, node) => {
const text = node.textContent || '';
if (!text.trim()) return currentGlobalIdx;
const chars = Array.from(text);
const { html: newHtml, count: charsProcessed } = chars.reduce(
(acc, char) => {
if (char.trim().length === 0) {
return { html: acc.html + char, count: acc.count };
}
const hue = ((currentGlobalIdx + acc.count) / totalTextLen) * (5 / 6);
const color = hslToHex(hue, 1.0, 0.5);
const coloredChar = `<span data-mx-color="${color}">${char}</span>`;
return { html: acc.html + coloredChar, count: acc.count + 1 };
},
{ html: '', count: 0 }
);
const span = document.createElement('span');
span.innerHTML = newHtml;
node.parentNode?.replaceChild(span, node);
return currentGlobalIdx + charsProcessed;
}, 0);
return div.innerHTML;
};
export type CommandExe = (payload: string, html?: string) => Promise<void>;
export enum Command {
// Cinny commands
Me = 'me',
Notice = 'notice',
Shrug = 'shrug',
StartDm = 'startdm',
Join = 'join',
Leave = 'leave',
Invite = 'invite',
DisInvite = 'disinvite',
Kick = 'kick',
Ban = 'ban',
UnBan = 'unban',
Ignore = 'ignore',
UnIgnore = 'unignore',
MyRoomNick = 'myroomnick',
MyRoomAvatar = 'myroomavatar',
ConvertToDm = 'converttodm',
ConvertToRoom = 'converttoroom',
TableFlip = 'tableflip',
UnFlip = 'unflip',
Delete = 'delete',
Acl = 'acl',
// Sable commands
Color = 'color',
GColor = 'gcolor',
Font = 'font',
GFont = 'gfont',
AddWidget = 'addwidget',
Pronoun = 'pronoun',
GPronoun = 'gpronoun',
Rainbow = 'rainbow',
Raw = 'raw',
}
export type CommandContent = {
name: string;
description: string;
exe: CommandExe;
};
export type CommandRecord = Record<Command, CommandContent>;
export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
const { navigateRoom } = useRoomNavigate();
const [developerTools] = useSetting(settingsAtom, 'developerTools');
const commands: CommandRecord = useMemo(
() => ({
// Cinny commands
[Command.Me]: {
name: Command.Me,
description: 'Send action message',
exe: async () => undefined,
},
[Command.Notice]: {
name: Command.Notice,
description: 'Send notice message',
exe: async () => undefined,
},
[Command.Shrug]: {
name: Command.Shrug,
description: 'Send ¯\\_(ツ)_/¯ as message',
exe: async () => undefined,
},
[Command.TableFlip]: {
name: Command.TableFlip,
description: `Send ${TABLEFLIP} as message`,
exe: async () => undefined,
},
[Command.UnFlip]: {
name: Command.UnFlip,
description: `Send ${UNFLIP} as message`,
exe: async () => undefined,
},
[Command.StartDm]: {
name: Command.StartDm,
description: 'Start direct message with user. Example: /startdm userId1',
exe: async (payload) => {
const rawIds = splitWithSpace(payload);
const userIds = rawIds.filter((id) => isUserId(id) && id !== mx.getSafeUserId());
if (userIds.length === 0) return;
if (userIds.length === 1) {
const dmRoomId = getDMRoomFor(mx, userIds[0])?.roomId;
if (dmRoomId) {
navigateRoom(dmRoomId);
return;
}
}
const result = await mx.createRoom({
is_direct: true,
invite: userIds,
visibility: Visibility.Private,
preset: Preset.TrustedPrivateChat,
initial_state: [createRoomEncryptionState()],
});
addRoomIdToMDirect(mx, result.room_id, userIds[0]);
navigateRoom(result.room_id);
},
},
[Command.Join]: {
name: Command.Join,
description: 'Join room with address. Example: /join address1 address2',
exe: async (payload) => {
const rawIds = splitWithSpace(payload);
const roomIdOrAliases = rawIds.filter(
(idOrAlias) => isRoomId(idOrAlias) || isRoomAlias(idOrAlias)
);
roomIdOrAliases.forEach(async (idOrAlias) => {
await mx.joinRoom(idOrAlias);
});
},
},
[Command.Leave]: {
name: Command.Leave,
description: 'Leave current room.',
exe: async (payload) => {
if (payload.trim() === '') {
mx.leave(room.roomId);
return;
}
const rawIds = splitWithSpace(payload);
const roomIds = rawIds.filter((id) => isRoomId(id));
roomIds.map((id) => mx.leave(id));
},
},
[Command.Invite]: {
name: Command.Invite,
description: 'Invite user to room. Example: /invite userId1 userId2 [-r reason]',
exe: async (payload) => {
const [content, flags] = splitPayloadContentAndFlags(payload);
const users = parseUsers(content);
const flagToContent = parseFlags(flags);
const reason = flagToContent.r;
users.map((id) => mx.invite(room.roomId, id, reason));
},
},
[Command.DisInvite]: {
name: Command.DisInvite,
description: 'Disinvite user to room. Example: /disinvite userId1 userId2 [-r reason]',
exe: async (payload) => {
const [content, flags] = splitPayloadContentAndFlags(payload);
const users = parseUsers(content);
const flagToContent = parseFlags(flags);
const reason = flagToContent.r;
users.map((id) => mx.kick(room.roomId, id, reason));
},
},
[Command.Kick]: {
name: Command.Kick,
description: 'Kick user from room. Example: /kick userId1 userId2 servername [-r reason]',
exe: async (payload) => {
const [content, flags] = splitPayloadContentAndFlags(payload);
const users = parseUsers(content);
const servers = parseServers(content);
const flagToContent = parseFlags(flags);
const reason = flagToContent.r;
const serverMembers = servers?.flatMap((server) => getServerMembers(room, server));
const serverUsers = serverMembers
?.filter((m) => m.membership !== Membership.Ban)
.map((m) => m.userId);
if (Array.isArray(serverUsers)) {
serverUsers.forEach((user) => {
if (!users.includes(user)) users.push(user);
});
}
rateLimitedActions(users, (id) => mx.kick(room.roomId, id, reason));
},
},
[Command.Ban]: {
name: Command.Ban,
description: 'Ban user from room. Example: /ban userId1 userId2 servername [-r reason]',
exe: async (payload) => {
const [content, flags] = splitPayloadContentAndFlags(payload);
const users = parseUsers(content);
const servers = parseServers(content);
const flagToContent = parseFlags(flags);
const reason = flagToContent.r;
const serverMembers = servers?.flatMap((server) => getServerMembers(room, server));
const serverUsers = serverMembers?.map((m) => m.userId);
if (Array.isArray(serverUsers)) {
serverUsers.forEach((user) => {
if (!users.includes(user)) users.push(user);
});
}
rateLimitedActions(users, (id) => mx.ban(room.roomId, id, reason));
},
},
[Command.UnBan]: {
name: Command.UnBan,
description: 'Unban user from room. Example: /unban userId1 userId2',
exe: async (payload) => {
const rawIds = splitWithSpace(payload);
const users = rawIds.filter((id) => isUserId(id));
users.map((id) => mx.unban(room.roomId, id));
},
},
[Command.Ignore]: {
name: Command.Ignore,
description: 'Ignore user. Example: /ignore userId1 userId2',
exe: async (payload) => {
const rawIds = splitWithSpace(payload);
const userIds = rawIds.filter((id) => isUserId(id));
if (userIds.length > 0) {
let ignoredUsers = mx.getIgnoredUsers().concat(userIds);
ignoredUsers = [...new Set(ignoredUsers)];
await mx.setIgnoredUsers(ignoredUsers);
}
},
},
[Command.UnIgnore]: {
name: Command.UnIgnore,
description: 'Unignore user. Example: /unignore userId1 userId2',
exe: async (payload) => {
const rawIds = splitWithSpace(payload);
const userIds = rawIds.filter((id) => isUserId(id));
if (userIds.length > 0) {
const ignoredUsers = mx.getIgnoredUsers();
await mx.setIgnoredUsers(ignoredUsers.filter((id) => !userIds.includes(id)));
}
},
},
[Command.MyRoomNick]: {
name: Command.MyRoomNick,
description: 'Change nick in current room.',
exe: async (payload) => {
const nick = payload.trim();
if (nick === '') return;
const mEvent = room
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.getStateEvents(StateEvent.RoomMember, mx.getSafeUserId());
const content = mEvent?.getContent();
if (!content) return;
await mx.sendStateEvent(
room.roomId,
StateEvent.RoomMember as any,
{
...content,
displayname: nick,
},
mx.getSafeUserId()
);
},
},
[Command.MyRoomAvatar]: {
name: Command.MyRoomAvatar,
description: 'Change profile picture in current room. Example /myroomavatar mxc://xyzabc',
exe: async (payload) => {
if (payload.match(/^mxc:\/\/\S+$/)) {
const mEvent = room
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.getStateEvents(StateEvent.RoomMember, mx.getSafeUserId());
const content = mEvent?.getContent();
if (!content) return;
await mx.sendStateEvent(
room.roomId,
StateEvent.RoomMember as any,
{
...content,
avatar_url: payload,
},
mx.getSafeUserId()
);
}
},
},
[Command.ConvertToDm]: {
name: Command.ConvertToDm,
description: 'Convert room to direct message',
exe: async () => {
const dmUserId = guessDmRoomUserId(room, mx.getSafeUserId());
await addRoomIdToMDirect(mx, room.roomId, dmUserId);
},
},
[Command.ConvertToRoom]: {
name: Command.ConvertToRoom,
description: 'Convert direct message to room',
exe: async () => {
await removeRoomIdFromMDirect(mx, room.roomId);
},
},
[Command.Delete]: {
name: Command.Delete,
description:
'Delete messages from users. Example: /delete userId1 servername -past 1d|2h|5m|30s [-t m.room.message] [-r spam]',
exe: async (payload) => {
const [content, flags] = splitPayloadContentAndFlags(payload);
const users = parseUsers(content);
const servers = parseServers(content);
const flagToContent = parseFlags(flags);
const reason = flagToContent.r;
const pastContent = flagToContent.past ?? '';
const msgTypeContent = flagToContent.t;
const messageTypes: string[] = msgTypeContent ? splitWithSpace(msgTypeContent) : [];
const ts = parseTimestampFlag(pastContent);
if (!ts) return;
const serverMembers = servers?.flatMap((server) => getServerMembers(room, server));
const serverUsers = serverMembers?.map((m) => m.userId);
if (Array.isArray(serverUsers)) {
serverUsers.forEach((user) => {
if (!users.includes(user)) users.push(user);
});
}
const result = await mx.timestampToEvent(room.roomId, ts, Direction.Forward);
const startEventId = result.event_id;
const path = `/rooms/${encodeURIComponent(room.roomId)}/context/${encodeURIComponent(
startEventId
)}`;
const eventContext = await mx.http.authedRequest<IContextResponse>(Method.Get, path, {
limit: 0,
});
let token: string | undefined = eventContext.start;
while (token) {
// eslint-disable-next-line no-await-in-loop
const response = await mx.createMessagesRequest(
room.roomId,
token,
20,
Direction.Forward,
undefined
);
const { end, chunk } = response;
// remove until the latest event;
token = end;
const eventsToDelete = chunk.filter(
(roomEvent) =>
(messageTypes.length > 0 ? messageTypes.includes(roomEvent.type) : true) &&
users.includes(roomEvent.sender) &&
roomEvent.unsigned?.redacted_because === undefined
);
const eventIds = eventsToDelete.map((roomEvent) => roomEvent.event_id);
// eslint-disable-next-line no-await-in-loop
await rateLimitedActions(eventIds, (eventId) =>
mx.redactEvent(room.roomId, eventId, undefined, { reason })
);
}
},
},
[Command.Acl]: {
name: Command.Acl,
description:
'Manage server access control list. Example: /acl [-a servername1] [-d servername2] [-ra servername1] [-rd servername2]',
exe: async (payload) => {
const [, flags] = splitPayloadContentAndFlags(payload);
const flagToContent = parseFlags(flags);
const allowFlag = flagToContent.a;
const denyFlag = flagToContent.d;
const removeAllowFlag = flagToContent.ra;
const removeDenyFlag = flagToContent.rd;
const allowList = allowFlag ? splitWithSpace(allowFlag) : [];
const denyList = denyFlag ? splitWithSpace(denyFlag) : [];
const removeAllowList = removeAllowFlag ? splitWithSpace(removeAllowFlag) : [];
const removeDenyList = removeDenyFlag ? splitWithSpace(removeDenyFlag) : [];
const serverAcl = getStateEvent(
room,
StateEvent.RoomServerAcl
)?.getContent<RoomServerAclEventContent>();
const aclContent: RoomServerAclEventContent = {
allow: serverAcl?.allow ? [...serverAcl.allow] : [],
allow_ip_literals: serverAcl?.allow_ip_literals,
deny: serverAcl?.deny ? [...serverAcl.deny] : [],
};
allowList.forEach((servername) => {
if (!Array.isArray(aclContent.allow) || aclContent.allow.includes(servername)) return;
aclContent.allow.push(servername);
});
denyList.forEach((servername) => {
if (!Array.isArray(aclContent.deny) || aclContent.deny.includes(servername)) return;
aclContent.deny.push(servername);
});
aclContent.allow = aclContent.allow?.filter(
(servername) => !removeAllowList.includes(servername)
);
aclContent.deny = aclContent.deny?.filter(
(servername) => !removeDenyList.includes(servername)
);
aclContent.allow?.sort();
aclContent.deny?.sort();
await mx.sendStateEvent(room.roomId, StateEvent.RoomServerAcl as any, aclContent);
},
},
// Sable commands
[Command.Color]: {
name: Command.Color,
description: 'Set a room-specific color. Example: /color #ff00ff | /color reset',
exe: async (payload) => {
const input = payload.trim().toLowerCase();
const userId = mx.getSafeUserId();
const sendFeedback = (msg: string) => {
const localNotice = new (window as any).matrixcs.MatrixEvent({
type: 'm.room.message',
content: { msgtype: 'm.notice', body: msg },
event_id: `~sable-${Date.now()}`,
room_id: room.roomId,
sender: userId,
});
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
};
try {
if (input === 'reset' || input === 'clear') {
await mx.sendStateEvent(
room.roomId,
StateEvent.RoomCosmeticsColor as any,
{},
userId
);
sendFeedback('Room color has been reset.');
return;
}
if (/^#[0-9A-F]{6}$/i.test(input)) {
await mx.sendStateEvent(
room.roomId,
StateEvent.RoomCosmeticsColor as any,
{ color: input },
userId
);
sendFeedback(`Room color set to ${input}.`);
} else {
sendFeedback('Invalid format. Use #RRGGBB.');
}
} catch (e: any) {
if (e.errcode === 'M_FORBIDDEN') {
sendFeedback(
'Permission Denied. An admin must enable "Room Colors" in Settings > Cosmetics in app.sable.moe or another supported client.'
);
}
}
},
},
[Command.GColor]: {
name: Command.GColor,
description:
'Set your global color for the current Space. Example: /gcolor #ff00ff | /gcolor reset',
exe: async (payload) => {
const input = payload.trim().toLowerCase();
const userId = mx.getSafeUserId();
const sendFeedback = (msg: string) => {
const localNotice = new (window as any).matrixcs.MatrixEvent({
type: 'm.room.message',
content: { msgtype: 'm.notice', body: msg },
event_id: `~sable-g-${Date.now()}`,
room_id: room.roomId,
sender: userId,
});
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
};
const parents = room
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.getStateEvents(StateEvent.SpaceParent);
const targetSpaceId =
parents && parents.length > 0 ? parents[0].getStateKey() : room.roomId;
try {
if (input === 'reset' || input === 'clear') {
await mx.sendStateEvent(
targetSpaceId as any,
StateEvent.RoomCosmeticsColor as any,
{},
userId
);
sendFeedback('Global space color reset.');
return;
}
if (/^#[0-9A-F]{6}$/i.test(input)) {
await mx.sendStateEvent(
targetSpaceId as any,
StateEvent.RoomCosmeticsColor as any,
{ color: input },
userId
);
sendFeedback(`Global space color set to ${input}.`);
} else {
sendFeedback('Invalid format. Use #RRGGBB.');
}
} catch (e: any) {
if (e.errcode === 'M_FORBIDDEN') {
sendFeedback(
'Permission Denied. An admin must enable "Space-Wide Colors" in Settings > Cosmetics in app.sable.moe or another supported client.'
);
}
}
},
},
[Command.Font]: {
name: Command.Font,
description: 'Set a room-specific font. Example: /font Courier New | /font reset',
exe: async (payload) => {
const input = payload
.trim()
.replace(/[;{}<>]/g, '')
.slice(0, 32);
const userId = mx.getSafeUserId();
const sendFeedback = (msg: string) => {
const localNotice = new (window as any).matrixcs.MatrixEvent({
type: 'm.room.message',
content: { msgtype: 'm.notice', body: msg },
event_id: `~font-${Date.now()}`,
room_id: room.roomId,
sender: userId,
});
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
};
try {
if (input.toLowerCase() === 'reset' || input === '') {
await mx.sendStateEvent(room.roomId, StateEvent.RoomCosmeticsFont as any, {}, userId);
sendFeedback('Room font reset.');
return;
}
await mx.sendStateEvent(
room.roomId,
StateEvent.RoomCosmeticsFont as any,
{ font: input },
userId
);
sendFeedback(`Room font set to "${input}".`);
} catch (e: any) {
if (e.errcode === 'M_FORBIDDEN') {
sendFeedback(
'Permission Denied. An admin must enable "Room Fonts" in Settings > Cosmetics in app.sable.moe or another supported client.'
);
}
}
},
},
[Command.GFont]: {
name: Command.GFont,
description:
'Set a global font for the current Space. Example: /gfont Courier New | /gfont reset',
exe: async (payload) => {
const input = payload
.trim()
.replace(/[;{}<>]/g, '')
.slice(0, 32);
const userId = mx.getSafeUserId();
const sendFeedback = (msg: string) => {
const localNotice = new (window as any).matrixcs.MatrixEvent({
type: 'm.room.message',
content: { msgtype: 'm.notice', body: msg },
event_id: `~gfont-${Date.now()}`,
room_id: room.roomId,
sender: userId,
});
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
};
const parents = room
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.getStateEvents(StateEvent.SpaceParent);
const targetSpaceId =
parents && parents.length > 0 ? parents[0].getStateKey() : room.roomId;
try {
if (input.toLowerCase() === 'reset' || input === '') {
await mx.sendStateEvent(
targetSpaceId as any,
StateEvent.RoomCosmeticsFont as any,
{},
userId
);
sendFeedback('Space font reset.');
return;
}
await mx.sendStateEvent(
targetSpaceId as any,
StateEvent.RoomCosmeticsFont as any,
{ font: input },
userId
);
sendFeedback(`Space font set to "${input}".`);
} catch (e: any) {
if (e.errcode === 'M_FORBIDDEN') {
sendFeedback(
'Permission Denied. An admin must enable "Space-Wide Fonts" in Settings > Cosmetics in app.sable.moe or another supported client.'
);
}
}
},
},
[Command.AddWidget]: {
name: Command.AddWidget,
description: 'Add a widget to this room. Usage: /addwidget <url> [name]',
exe: async (payload) => {
const userId = mx.getSafeUserId();
const sendFeedback = (msg: string) => {
const localNotice = new (window as any).matrixcs.MatrixEvent({
type: 'm.room.message',
content: { msgtype: 'm.notice', body: msg },
event_id: `~nullptr-widget-${Date.now()}`,
room_id: room.roomId,
sender: userId,
});
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
};
const parts = payload.trim().split(/\s+/);
const url = parts[0];
const name = parts.slice(1).join(' ') || 'Widget';
if (!url) {
sendFeedback('Usage: /addwidget <url> [name]');
return;
}
let parsedUrl: URL;
try {
parsedUrl = new URL(url);
} catch {
sendFeedback('Invalid URL. Please provide a valid widget URL.');
return;
}
try {
const widgetId = `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
await mx.sendStateEvent(
room.roomId,
StateEvent.RoomWidget as any,
{
type: 'm.custom',
url: enrichWidgetUrl(parsedUrl.toString()),
name,
id: widgetId,
creatorUserId: userId,
} as any,
widgetId
);
sendFeedback(`Widget "${name}" added.`);
} catch (e: any) {
if (e.errcode === 'M_FORBIDDEN') {
sendFeedback(
'Permission denied. You need permission to manage widgets in this room.'
);
} else {
sendFeedback(`Failed to add widget: ${e.message || 'Unknown error'}`);
}
}
},
},
[Command.Pronoun]: {
name: Command.Pronoun,
description:
'Set your pronouns for this room. Example: /pronoun "they/them, it/its" | /pronoun reset',
exe: async (payload) => {
const match = payload.trim().match(/^"(.*)"$/);
const rawInput = match ? match[1].trim() : payload.trim();
const userId = mx.getSafeUserId();
const sendFeedback = (msg: string) => {
const localNotice = new (window as any).matrixcs.MatrixEvent({
type: 'm.room.message',
content: { msgtype: 'm.notice', body: msg },
event_id: `~pronoun-${Date.now()}`,
room_id: room.roomId,
sender: userId,
});
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
};
try {
if (['reset', 'clear', ''].includes(rawInput.toLowerCase())) {
await mx.sendStateEvent(
room.roomId,
StateEvent.RoomCosmeticsPronouns as any,
{},
userId
);
sendFeedback('Room pronouns have been reset.');
return;
}
const pronounsArray = rawInput
.split(',')
.map((p) => p.trim())
.filter((p) => p.length > 0)
.map((p) => ({ summary: p }));
await mx.sendStateEvent(
room.roomId,
StateEvent.RoomCosmeticsPronouns as any,
{ pronouns: pronounsArray },
userId
);
sendFeedback(`Room pronouns set: ${rawInput}`);
} catch (e: any) {
if (e.errcode === 'M_FORBIDDEN') {
sendFeedback('Permission Denied. Could not update room pronouns.');
}
}
},
},
[Command.GPronoun]: {
name: Command.GPronoun,
description:
'Set your global pronouns for this space. Example: /gpronoun "they/them, it/its" | /gpronoun reset',
exe: async (payload) => {
const match = payload.trim().match(/^"(.*)"$/);
const rawInput = match ? match[1].trim() : payload.trim();
const userId = mx.getSafeUserId();
const sendFeedback = (msg: string) => {
const localNotice = new (window as any).matrixcs.MatrixEvent({
type: 'm.room.message',
content: { msgtype: 'm.notice', body: msg },
event_id: `~gpronoun-${Date.now()}`,
room_id: room.roomId,
sender: userId,
});
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
};
const parents = room
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.getStateEvents(StateEvent.SpaceParent);
const targetSpaceId =
parents && parents.length > 0 ? parents[0].getStateKey() : room.roomId;
try {
if (['reset', 'clear', ''].includes(rawInput.toLowerCase())) {
await mx.sendStateEvent(
targetSpaceId as any,
StateEvent.RoomCosmeticsPronouns as any,
{},
userId
);
sendFeedback('Global space pronouns reset.');
return;
}
const pronounsArray = rawInput
.split(',')
.map((p) => p.trim())
.filter((p) => p.length > 0)
.map((p) => ({ summary: p }));
await mx.sendStateEvent(
targetSpaceId as any,
StateEvent.RoomCosmeticsPronouns as any,
{ pronouns: pronounsArray },
userId
);
sendFeedback(`Global space pronouns set: ${rawInput}`);
} catch (e: any) {
if (e.errcode === 'M_FORBIDDEN') {
sendFeedback('Permission Denied. Could not update space pronouns.');
}
}
},
},
[Command.Rainbow]: {
name: Command.Rainbow,
description: 'Send rainbow text.',
exe: async (payload, html) => {
if (!payload || payload.trim().length === 0) return;
const inputHtml = html || payload;
const rainbowHtml = rainbowify(inputHtml);
await mx.sendMessage(room.roomId, {