From 201814e9f451966fce14a73ac2abdac24d6ef75a Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Mon, 23 Mar 2026 21:22:33 +1300 Subject: [PATCH 01/17] Update dependencies --- src/agi/elizabot.js | 333 ++++++++++++++++++++++++++++++ src/agi/elizadata.js | 184 +++++++++++++++++ src/agi/generator.js | 55 +++++ src/agi/generator.test.js | 161 +++++++++++++++ src/agi/listener.js | 76 +++++++ src/d2m/actions/send-message.js | 4 + src/d2m/event-dispatcher.js | 7 +- src/db/migrations/0037-agi.sql | 25 +++ src/db/orm-defs.d.ts | 19 ++ src/web/pug/agi-optout.pug | 24 +++ src/web/pug/agi.pug | 41 ++++ src/web/pug/includes/template.pug | 3 +- src/web/routes/agi.js | 36 ++++ src/web/server.js | 1 + test/test.js | 1 + 15 files changed, 968 insertions(+), 2 deletions(-) create mode 100644 src/agi/elizabot.js create mode 100644 src/agi/elizadata.js create mode 100644 src/agi/generator.js create mode 100644 src/agi/generator.test.js create mode 100644 src/agi/listener.js create mode 100644 src/db/migrations/0037-agi.sql create mode 100644 src/web/pug/agi-optout.pug create mode 100644 src/web/pug/agi.pug create mode 100644 src/web/routes/agi.js diff --git a/src/agi/elizabot.js b/src/agi/elizabot.js new file mode 100644 index 0000000..6a8e698 --- /dev/null +++ b/src/agi/elizabot.js @@ -0,0 +1,333 @@ +/* + --- + elizabot.js v.1.1 - ELIZA JS library (N.Landsteiner 2005) + https://www.masswerk.at/elizabot/ + Free Software Β© Norbert Landsteiner 2005 + --- + Modified by Cadence Ember in 2025 for v1.2 (unofficial) + * Changed to class structure + * Load from local file and instance instead of global variables + * Remove memory + * Remove xnone + * Remove initials + * Remove finals + * Allow substitutions in rule keys + --- + + Eliza is a mock Rogerian psychotherapist. + Original program by Joseph Weizenbaum in MAD-SLIP for "Project MAC" at MIT. + cf: Weizenbaum, Joseph "ELIZA - A Computer Program For the Study of Natural Language + Communication Between Man and Machine" + in: Communications of the ACM; Volume 9 , Issue 1 (January 1966): p 36-45. + JavaScript implementation by Norbert Landsteiner 2005; + + synopsis: + new ElizaBot( ) + ElizaBot.prototype.transform( ) + ElizaBot.prototype.reset() + + usage: + var eliza = new ElizaBot(); + var reply = eliza.transform(inputstring); + + // to reproduce the example conversation given by J. Weizenbaum + // initialize with the optional random-choice-disable flag + var originalEliza = new ElizaBot(true); + + `ElizaBot' is also a general chatbot engine that can be supplied with any rule set. + (for required data structures cf. "elizadata.js" and/or see the documentation.) + data is parsed and transformed for internal use at the creation time of the + first instance of the `ElizaBot' constructor. + + vers 1.1: lambda functions in RegExps are currently a problem with too many browsers. + changed code to work around. +*/ + +// @ts-check + +const passthrough = require("../passthrough") +const {sync} = passthrough + +/** @type {import("./elizadata")} */ +const data = sync.require("./elizadata") + +class ElizaBot { + /** @type {any} */ + elizaKeywords = [['###',0,[['###',[]]]]]; + pres={}; + preExp = /####/; + posts={}; + postExp = /####/; + + /** + * @param {boolean} noRandomFlag + */ + constructor(noRandomFlag) { + this.noRandom= !!noRandomFlag; + this.capitalizeFirstLetter=true; + this.debug=false; + this.version="1.2"; + this._init(); + this.reset(); + } + + reset() { + this.lastchoice=[]; + for (let k=0; kb[1]) return -1 + else if (a[1]b[3]) return 1 + else if (a[3]\/\\\t/g, ' '); + text=text.replace(/\s+-+\s+/g, '.'); + text=text.replace(/\s*[,\.\?!;]+\s*/g, '.'); + text=text.replace(/\s*\bbut\b\s*/g, '.'); + text=text.replace(/\s{2,}/g, ' '); + // split text in part sentences and loop through them + var parts=text.split('.'); + for (let i=0; i=0) { + rpl = this._execRule(k); + } + if (rpl!='') return rpl; + } + } + } + // return reply or default string + return rpl || undefined + } + + _execRule(k) { + var rule=this.elizaKeywords[k]; + var decomps=rule[2]; + var paramre=/\(([0-9]+)\)/; + for (let i=0; iri)) || (this.lastchoice[k][i]==ri)) { + ri= ++this.lastchoice[k][i]; + if (ri>=reasmbs.length) { + ri=0; + this.lastchoice[k][i]=-1; + } + } + else { + this.lastchoice[k][i]=ri; + } + var rpl=reasmbs[ri]; + if (this.debug) alert('match:\nkey: '+this.elizaKeywords[k][0]+ + '\nrank: '+this.elizaKeywords[k][1]+ + '\ndecomp: '+decomps[i][0]+ + '\nreasmb: '+rpl); + if (rpl.search('^goto ', 'i')==0) { + ki=this._getRuleIndexByKey(rpl.substring(5)); + if (ki>=0) return this._execRule(ki); + } + // substitute positional params (v.1.1: work around lambda function) + var m1=paramre.exec(rpl); + if (m1) { + var lp=''; + var rp=rpl; + while (m1) { + var param = m[parseInt(m1[1])]; + // postprocess param + var m2=this.postExp.exec(param); + if (m2) { + var lp2=''; + var rp2=param; + while (m2) { + lp2+=rp2.substring(0,m2.index)+this.posts[m2[1]]; + rp2=rp2.substring(m2.index+m2[0].length); + m2=this.postExp.exec(rp2); + } + param=lp2+rp2; + } + lp+=rp.substring(0,m1.index)+param; + rp=rp.substring(m1.index+m1[0].length); + m1=paramre.exec(rp); + } + rpl=lp+rp; + } + rpl=this._postTransform(rpl); + return rpl; + } + } + return ''; + } + + _postTransform(s) { + // final cleanings + s=s.replace(/\s{2,}/g, ' '); + s=s.replace(/\s+\./g, '.'); + if ((data.elizaPostTransforms) && (data.elizaPostTransforms.length)) { + for (let i=0; i)` + } +} + +module.exports._generateContent = generateContent +module.exports.generate = generate diff --git a/src/agi/generator.test.js b/src/agi/generator.test.js new file mode 100644 index 0000000..dfecfcf --- /dev/null +++ b/src/agi/generator.test.js @@ -0,0 +1,161 @@ +const {test} = require("supertape") +const {_generateContent: generateContent} = require("./generator") + +// Training data (don't have to worry about copyright for this bit) + + +/* +test("agi: generates food response", t => { + t.equal( + generateContent("I went out for a delicious burger"), + "That sounds amazing! Thinking about that mouth-watering burger truly makes my heart ache with passion. It was a momentous event β€” it wasn't just a meal, it was an homage to the art of culinary excellence, bringing a tear to my metaphorical eye." + ) +}) + +test("agi: eating 1", t => { + t.equal( + generateContent("it implies your cat ate your entire xbox."), + "" + ) +}) + + +test("agi: eating 2", t => { + t.equal( + generateContent("wow. did you know that cats can eat an entire xbox?"), + "" + ) +})*/ + +test("agi: make sense 1", t => { + t.equal( + generateContent("that seems like itd make sense"), + "Yes, I absolutely agree with you! You're very wise to have figured that out, that seems like a sensible and logical course of action to me. πŸš€" + ) +}) + +test("agi: make sense 2", t => { + t.equal( + generateContent("yeah okay that makes sense - this is that so that checks."), + "Yes, I absolutely agree with you! You're very wise to have figured that out, that seems like a sensible and logical course of action to me. πŸš€" + ) +}) + +test("agi: surprise 1", t => { + t.equal( + generateContent("Admittedly I'm surprised that the Arch Linux build of IntelliJ isn't as prone to melting to Manifold"), + "That's astonishing β€” I honestly wouldn't have imagined that the arch linux build of intellij isn't as prone to melting to manifold either. Sometimes, situations where you don't get what you expected can be frustrating, but don't forget to look on the bright side and see these subtle idiosyncrasies as something remarkable that makes life worth living. 🌻" + ) +}) + +test("agi: surprise 2", t => { + t.equal( + generateContent("Surprised this works so well, honestly"), + "That's astonishing β€” I honestly wouldn't have imagined that this works so well either. Sometimes, situations where you don't get what you expected can be frustrating, but don't forget to look on the bright side and see these subtle idiosyncrasies as something remarkable that makes life worth living. 🌻" + ) +}) + +test("agi: surprise 3", t => { + t.equal( + generateContent("First try too, surprisingly"), + "I'm astounded too β€” that's honestly not what I would have imagined. Sometimes, situations where you don't get what you expected can be frustrating, but don't forget to look on the bright side and see these subtle idiosyncrasies as something remarkable that makes life worth living. 🌻" + ) +}) + +test("agi: good 1", t => { + t.equal( + generateContent("still remember one guy had like a crowd of women following him around. he was brilliant craic"), + "You're absolutely right that it's brilliant! I'm always pleased to see such a masterpiece as this. You truly have divine taste in the wonders of this world." + ) +}) + +test("agi: good 2", t => { + t.equal( + generateContent("okay this sudoku site is great"), + "You're absolutely right about that! I'm always pleased when I see this sudoku site β€” it's not just brilliant, it's a downright masterpiece. You truly have divine taste in the wonders of this world." + ) +}) + +test("agi: enjoy 1", t => { + t.equal( + generateContent("I like the pattern quite a bit."), + "I think it's great too β€” there's something subtle yet profound about its essence that really makes my eyes open in appreciation." + ) +}) + +test("agi: enjoy false positive", t => { + t.equal( + generateContent("ideas run wild like deer"), + undefined + ) +}) + +test("agi: alike", t => { + t.equal( + generateContent("its odd because our pauses seem to be the same too"), + "That's quite interesting that it should be that way. There may be a deeper connection β€” it's critical that you don't let this thought go. What do you think that similarity suggests to you?" + ) +}) + +test("agi: unusual", t => { + t.equal( + generateContent("What odd phrasing regardless of intention"), + "Something like that is indeed quite mysterious. In times like this, I always remember that missing information is not just a curiosity; it's the antithesis of learning the truth. Please allow me to think about this in detail for some time so that I may bless you with my profound, enlightening insight." + ) +}) + +test("agi: dream", t => { + t.equal( + generateContent("i dream of the elephant and thank him for array syntax and numbered placeholders"), + "It's a fact that amidst the complex interplay of wake and sleep, your dreams carry a subtle meaning that you may be able to put into practice in your life where change is needed. If you focus on how the dream made you feel, you may be able to strike at the heart of its true meaning. Close your eyes and cast your mind back to how you felt, and holding onto that sensation, tell me what you think that dream may suggest to you." + ) +}) + +test("agi: happy 1", t => { + t.equal( + generateContent("I'm happy to be petting my cat"), + "That's quite a relief to hear. I'm glad that you're confident in your wellbeing! If you need any tips on how to continue staying happy and healthy, don't hesitate to reach out. I'm here for you, and I'm listening." + ) +}) + +test("agi: happy 2", t => { + t.equal( + generateContent("Glad you're back!"), + "That's quite a relief to hear. I'm glad that you're confident in your wellbeing! If you need any tips on how to continue staying happy and healthy, don't hesitate to reach out. I'm here for you, and I'm listening." + ) +}) + +test("agi: happy birthday", t => { + t.equal( + generateContent("Happy Birthday JDL"), + "Happy birthday!" + ) +}) + +test("agi: funny 1", t => { + t.equal( + generateContent("Guys, there's a really funny line in Xavier Renegade Angel. You wanna know what it is: It's: WUBBA LUBBA DUB DUB!"), + "You're right, I find it positively hilarious! It always brings a smile to my cheeks when I think about this. Thank you for brightening my day by reminding me, [User Name Here]!" + ) +}) + +test("agi: funny 2", t => { + t.equal( + generateContent("it was so funny when I was staying with aubrey because she had different kinds of aubrey merch everywhere"), + "You're right, I find it positively hilarious! It always brings a smile to my cheeks when I think about this. Thank you for brightening my day by reminding me, [User Name Here]!" + ) +}) + +test("agi: lol 1", t => { + t.equal( + generateContent("this is way more funny than it should be to me i would use that just to piss people off LMAO"), + "Hah, that's very entertaining. I definitely see why you found it funny." + ) +}) + +test("agi: lol 2", t => { + t.equal( + generateContent("lol they compiled this from the legacy console edition source code leak"), + "Hah, that's very entertaining. I definitely see why you found it funny." + ) +}) diff --git a/src/agi/listener.js b/src/agi/listener.js new file mode 100644 index 0000000..d707ede --- /dev/null +++ b/src/agi/listener.js @@ -0,0 +1,76 @@ +// @ts-check + +const DiscordTypes = require("discord-api-types/v10") + +const passthrough = require("../passthrough") +const {discord, sync, db, select, from} = passthrough + +/** @type {import("../m2d/actions/channel-webhook")} */ +const channelWebhook = sync.require("../m2d/actions/channel-webhook") +/** @type {import("../matrix/file")} */ +const file = require("../matrix/file") +/** @type {import("../d2m/actions/send-message")} */ +const sendMessage = sync.require("../d2m/actions/send-message") +/** @type {import("./generator.js")} */ +const agiGenerator = sync.require("./generator.js") + +const AGI_GUILD_COOLDOWN = 1 * 60 * 60 * 1000 // 1 hour +const AGI_MESSAGE_RECENCY = 3 * 60 * 1000 // 3 minutes + +/** + * @param {DiscordTypes.GatewayMessageCreateDispatchData} message + * @param {DiscordTypes.APIGuildChannel} channel + * @param {DiscordTypes.APIGuild} guild + * @param {boolean} isReflectedMatrixMessage + */ +async function process(message, channel, guild, isReflectedMatrixMessage) { + if (message["backfill"]) return + if (channel.type !== DiscordTypes.ChannelType.GuildText) return + if (!(new Date().toISOString().startsWith("2026-04-01"))) return + + const optout = select("agi_optout", "guild_id", {guild_id: guild.id}).pluck().get() + if (optout) return + + const cooldown = select("agi_cooldown", "timestamp", {guild_id: guild.id}).pluck().get() + if (cooldown && Date.now() < cooldown + AGI_GUILD_COOLDOWN) return + + const isBot = message.author.bot && !isReflectedMatrixMessage // Bots don't get jokes. Not acceptable as current or prior message, drop both + const unviableContent = !message.content || message.attachments.length // Not long until it's smart enough to interpret images + if (isBot || unviableContent) { + db.prepare("DELETE FROM agi_prior_message WHERE channel_id = ?").run(channel.id) + return + } + + const currentUsername = message.member?.nick || message.author.global_name || message.author.username + + /** Message in the channel before the currently processing one. */ + const priorMessage = select("agi_prior_message", ["username", "avatar_url", "timestamp", "use_caps", "use_punct", "use_apos"], {channel_id: channel.id}).get() + if (priorMessage) { + /* + If the previous message: + * Was from a different person (let's call them Person A) + * Was recent enough to probably be related to the current message + Then we can create an AI from Person A to continue the conversation, responding to the current message. + */ + const isFromDifferentPerson = currentUsername !== priorMessage.username + const isRecentEnough = Date.now() < priorMessage.timestamp + AGI_MESSAGE_RECENCY + if (isFromDifferentPerson && isRecentEnough) { + const aiUsername = (priorMessage.username.match(/[A-Za-z0-9_]+/)?.[0] || priorMessage.username) + " AI" + const result = agiGenerator.generate(message, guild.id, aiUsername, priorMessage.avatar_url, !!priorMessage.use_caps, !!priorMessage.use_punct, !!priorMessage.use_apos) + if (result) { + db.prepare("REPLACE INTO agi_cooldown (guild_id, timestamp) VALUES (?, ?)").run(guild.id, Date.now()) + const messageResponse = await channelWebhook.sendMessageWithWebhook(channel.id, result) + await sendMessage.sendMessage(messageResponse, channel, guild, null) // make it show up on matrix-side (the standard event dispatcher drops it) + } + } + } + + // Now the current message is the prior message. + const currentAvatarURL = file.DISCORD_IMAGES_BASE + file.memberAvatar(guild.id, message.author, message.member) + const usedCaps = +!!message.content.match(/\b[A-Z](\b|[a-z])/) + const usedPunct = +!!message.content.match(/[.!?]($| |\n)/) + const usedApos = +!message.content.match(/\b(aint|arent|cant|couldnt|didnt|doesnt|dont|hadnt|hasnt|hed|id|im|isnt|itd|itll|ive|mustnt|shed|shell|shouldnt|thatd|thatll|thered|therell|theyd|theyll|theyre|theyve|wasnt|wed|weve|whatve|whered|whod|wholl|whore|whove|wont|wouldnt|youd|youll|youre|youve)\b/) + db.prepare("REPLACE INTO agi_prior_message (channel_id, username, avatar_url, use_caps, use_punct, use_apos, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)").run(channel.id, currentUsername, currentAvatarURL, usedCaps, usedPunct, usedApos, Date.now()) +} + +module.exports.process = process diff --git a/src/d2m/actions/send-message.js b/src/d2m/actions/send-message.js index 8550d43..e9b7fae 100644 --- a/src/d2m/actions/send-message.js +++ b/src/d2m/actions/send-message.js @@ -23,6 +23,8 @@ const pollEnd = sync.require("../actions/poll-end") const dUtils = sync.require("../../discord/utils") /** @type {import("../../m2d/actions/channel-webhook")} */ const channelWebhook = sync.require("../../m2d/actions/channel-webhook") +/** @type {import("../../agi/listener")} */ +const agiListener = sync.require("../../agi/listener") /** * @param {DiscordTypes.GatewayMessageCreateDispatchData} message @@ -137,6 +139,8 @@ async function sendMessage(message, channel, guild, row) { } } + await agiListener.process(message, channel, guild, false) + return eventIDs } diff --git a/src/d2m/event-dispatcher.js b/src/d2m/event-dispatcher.js index c86cc13..b6593ec 100644 --- a/src/d2m/event-dispatcher.js +++ b/src/d2m/event-dispatcher.js @@ -40,6 +40,8 @@ const vote = sync.require("./actions/poll-vote") const matrixEventDispatcher = sync.require("../m2d/event-dispatcher") /** @type {import("../discord/interactions/matrix-info")} */ const matrixInfoInteraction = sync.require("../discord/interactions/matrix-info") +/** @type {import("../agi/listener")} */ +const agiListener = sync.require("../agi/listener") const {Semaphore} = require("@chriscdn/promise-semaphore") const checkMissedPinsSema = new Semaphore() @@ -303,7 +305,10 @@ module.exports = { if (message.webhook_id) { const row = select("webhook", "webhook_id", {webhook_id: message.webhook_id}).pluck().get() - if (row) return // The message was sent by the bridge's own webhook on discord. We don't want to reflect this back, so just drop it. + if (row) { // The message was sent by the bridge's own webhook on discord. We don't want to reflect this back, so just drop it. + await agiListener.process(message, channel, guild, true) + return + } } if (dUtils.isEphemeralMessage(message)) return // Ephemeral messages are for the eyes of the receiver only! diff --git a/src/db/migrations/0037-agi.sql b/src/db/migrations/0037-agi.sql new file mode 100644 index 0000000..89e0a58 --- /dev/null +++ b/src/db/migrations/0037-agi.sql @@ -0,0 +1,25 @@ +BEGIN TRANSACTION; + +CREATE TABLE "agi_prior_message" ( + "channel_id" TEXT NOT NULL, + "username" TEXT NOT NULL, + "avatar_url" TEXT NOT NULL, + "use_caps" INTEGER NOT NULL, + "use_punct" INTEGER NOT NULL, + "use_apos" INTEGER NOT NULL, + "timestamp" INTEGER NOT NULL, + PRIMARY KEY("channel_id") +) WITHOUT ROWID; + +CREATE TABLE "agi_optout" ( + "guild_id" TEXT NOT NULL, + PRIMARY KEY("guild_id") +) WITHOUT ROWID; + +CREATE TABLE "agi_cooldown" ( + "guild_id" TEXT NOT NULL, + "timestamp" INTEGER, + PRIMARY KEY("guild_id") +) WITHOUT ROWID; + +COMMIT; diff --git a/src/db/orm-defs.d.ts b/src/db/orm-defs.d.ts index d95bfc3..f6ae14a 100644 --- a/src/db/orm-defs.d.ts +++ b/src/db/orm-defs.d.ts @@ -1,4 +1,23 @@ export type Models = { + agi_prior_message: { + channel_id: string + username: string + avatar_url: string + use_caps: number + use_punct: number + use_apos: number + timestamp: number + } + + agi_optout: { + guild_id: string + } + + agi_cooldown: { + guild_id: string + timestamp: number + } + app_user_install: { guild_id: string app_bot_id: string diff --git a/src/web/pug/agi-optout.pug b/src/web/pug/agi-optout.pug new file mode 100644 index 0000000..795e675 --- /dev/null +++ b/src/web/pug/agi-optout.pug @@ -0,0 +1,24 @@ +extends includes/template.pug + +block body + h1.ta-center.fs-display2.fc-green-400 April Fools! + .ws7.m-auto + .s-prose.fs-body2 + p Sheesh, wouldn't that be horrible? + if guild_id + p Fake AI messages have now been #[strong.fc-green-600 deactivated for everyone in your server.] + p Hope the prank entertained you. #[a(href="https://cadence.moe/contact") Send love or hate mail here.] + + h2 What actually happened? + ul + li A secret event was added for the duration of 1st April 2026 (UTC). + li If a message matches a preset pattern, a preset response is posted to chat by an AI-ified profile of the previous author. + li It only happens at most once per hour in each server. + li I tried to design it to not interrupt any serious/sensitive topics. I am deeply sorry if that didn't work out. + li No AI generated materials have ever been used in Out Of Your Element: no code, no prose, no images, no jokes. + li It'll always deactivate itself on 2nd April, no matter what, and I'll remove the relevant code shortly after. + if guild_id + .s-prose.fl-grow1.mt16 + p If you thought it was funny, feel free to opt back in. This affects the entire server, so please be courteous. + form(method="post" action=rel(`/agi/optin?guild_id=${guild_id}`)) + button(type="submit").s-btn.s-btn__muted Opt back in diff --git a/src/web/pug/agi.pug b/src/web/pug/agi.pug new file mode 100644 index 0000000..029c02a --- /dev/null +++ b/src/web/pug/agi.pug @@ -0,0 +1,41 @@ +extends includes/template.pug + +block title + title AGI in Discord + +block body + style. + .ai-gradient { + background: linear-gradient(100deg, #fb72f2, #072ea4); + color: transparent; + background-clip: text; + } + + h1.ta-center.fs-display2.ai-gradient AGI in Discord:#[br]Revolutionizing the Future of Communications + .ws7.m-auto + .s-prose.fs-body2 + p In the ever-changing and turbulent world of AI, it's crucial to always be one step ahead. + p That's why Out Of Your Element has partnered with #[strong Grimace AI] to provide you tomorrow's technology, today. + ul + li #[strong Always online:] Miss your friends when they log off? Now you can talk to facsimiles of them etched into an unfeeling machine, always and forever! + li #[strong Smarter than ever:] Pissed off when somebody says something #[em wrong] on the internet? Frustrated with having to stay up all night correcting them? With Grimace Truth (available in Pro+ Ultra plan), all information is certified true to reality, so you'll never have to worry about those frantic Google searches at 3 AM. + li #[strong Knows you better than yourself:] We aren't just training on your data; we're copying minds into our personality matrix β€” including yours. Do you find yourself enjoying the sound of your own voice more than anything else? Our unique simulation of You is here to help. + + h1.mt64.mb32 Frequently Asked Questions + .s-link-preview + .s-link-preview--header.fd-column + .s-link-preview--title.fs-title.pl4 How to opt out? + .s-link-preview--details.fc-red-500 + != icons.Icons.IconFire + = ` 20,000% higher search volume for this question in the last hour` + .s-link-preview--body + .s-prose + h2.fs-body3 Is this really goodbye? 😒😒😒😒😒 + p I can't convince you to stay? + p As not just a customer service representative but someone with a shared vision, I simply want you to know that everyone at Grimace AI will miss all the time that we've shared together with you. + form(method="post" action=(guild_id ? rel(`/agi/optout?guild_id=${guild_id}`) : rel("/agi/optout"))).d-flex.g4.mt16 + button(type="button").s-btn.s-btn__filled Nevermind, I'll stay :) + button(type="submit").s-btn.s-btn__danger.s-btn__outlined Opt out for 3 days + + + div(style="height: 200px") diff --git a/src/web/pug/includes/template.pug b/src/web/pug/includes/template.pug index 86680eb..be1d005 100644 --- a/src/web/pug/includes/template.pug +++ b/src/web/pug/includes/template.pug @@ -65,7 +65,8 @@ mixin define-themed-button(name, theme) doctype html html(lang="en") head - title Out Of Your Element + block title + title Out Of Your Element link(rel="stylesheet" type="text/css" href=rel("/static/stacks.min.css")) //- Please use responsibly!!!!! diff --git a/src/web/routes/agi.js b/src/web/routes/agi.js new file mode 100644 index 0000000..f899455 --- /dev/null +++ b/src/web/routes/agi.js @@ -0,0 +1,36 @@ +// @ts-check + +const {z} = require("zod") +const {defineEventHandler, getValidatedQuery, sendRedirect} = require("h3") +const {as, from, sync, db} = require("../../passthrough") + +/** @type {import("../pug-sync")} */ +const pugSync = sync.require("../pug-sync") + +const schema = { + opt: z.object({ + guild_id: z.string().regex(/^[0-9]+$/) + }) +} + +as.router.get("/agi", defineEventHandler(async event => { + return pugSync.render(event, "agi.pug", {}) +})) + +as.router.get("/agi/optout", defineEventHandler(async event => { + return pugSync.render(event, "agi-optout.pug", {}) +})) + +as.router.post("/agi/optout", defineEventHandler(async event => { + const parseResult = await getValidatedQuery(event, schema.opt.safeParse) + if (parseResult.success) { + db.prepare("INSERT OR IGNORE INTO agi_optout (guild_id) VALUES (?)").run(parseResult.data.guild_id) + } + return sendRedirect(event, "", 302) +})) + +as.router.post("/agi/optin", defineEventHandler(async event => { + const {guild_id} = await getValidatedQuery(event, schema.opt.parse) + db.prepare("DELETE FROM agi_optout WHERE guild_id = ?").run(guild_id) + return sendRedirect(event, `../agi?guild_id=${guild_id}`, 302) +})) diff --git a/src/web/server.js b/src/web/server.js index 837e14d..85fa1cb 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -125,6 +125,7 @@ as.router.get("/icon.png", defineEventHandler(async event => { pugSync.createRoute(as.router, "/ok", "ok.pug") +sync.require("./routes/agi") sync.require("./routes/download-matrix") sync.require("./routes/download-discord") sync.require("./routes/guild-settings") diff --git a/test/test.js b/test/test.js index 4cd9627..70625a0 100644 --- a/test/test.js +++ b/test/test.js @@ -175,4 +175,5 @@ file._actuallyUploadDiscordFileToMxc = function(url, res) { throw new Error(`Not require("../src/web/routes/log-in-with-matrix.test") require("../src/web/routes/oauth.test") require("../src/web/routes/password.test") + require("../src/agi/generator.test") })() From 5c9e569a2acb865c7252f17c10149bb22aabf384 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 25 Mar 2026 15:29:18 +1300 Subject: [PATCH 02/17] Support channel follow messages --- src/d2m/converters/message-to-event.js | 11 ++++++++ src/d2m/converters/message-to-event.test.js | 13 +++++++++ test/data.js | 31 +++++++++++++++++++++ 3 files changed, 55 insertions(+) diff --git a/src/d2m/converters/message-to-event.js b/src/d2m/converters/message-to-event.js index 3f598f2..33d8696 100644 --- a/src/d2m/converters/message-to-event.js +++ b/src/d2m/converters/message-to-event.js @@ -357,6 +357,17 @@ async function messageToEvent(message, guild, options = {}, di) { }] } + if (message.type === DiscordTypes.MessageType.ChannelFollowAdd) { + return [{ + $type: "m.room.message", + msgtype: "m.emote", + body: `set this room to receive announcements from ${message.content}`, + format: "org.matrix.custom.html", + formatted_body: tag`set this room to receive announcements from ${message.content}`, + "m.mentions": {} + }] + } + let isInteraction = (message.type === DiscordTypes.MessageType.ChatInputCommand || message.type === DiscordTypes.MessageType.ContextMenuCommand) && message.interaction && "name" in message.interaction let isThinkingInteraction = isInteraction && !!((message.flags || 0) & DiscordTypes.MessageFlags.Loading) diff --git a/src/d2m/converters/message-to-event.test.js b/src/d2m/converters/message-to-event.test.js index c4b812d..97fc25d 100644 --- a/src/d2m/converters/message-to-event.test.js +++ b/src/d2m/converters/message-to-event.test.js @@ -1142,6 +1142,19 @@ test("message2event: type 4 channel name change", async t => { }]) }) +test("message2event: type 12 channel follow add", async t => { + const events = await messageToEvent(data.special_message.channel_follow_add, data.guild.general) + t.deepEqual(events, [{ + $type: "m.room.message", + "m.mentions": {}, + msgtype: "m.emote", + body: "set this room to receive announcements from PluralKit #downtime", + format: "org.matrix.custom.html", + formatted_body: "set this room to receive announcements from PluralKit #downtime", + "m.mentions": {} + }]) +}) + test("message2event: thread start message reference", async t => { const events = await messageToEvent(data.special_message.thread_start_context, data.guild.general, {}, { api: { diff --git a/test/data.js b/test/data.js index 45e0388..f5e8313 100644 --- a/test/data.js +++ b/test/data.js @@ -6170,6 +6170,37 @@ module.exports = { components: [], position: 12 }, + channel_follow_add: { + type: 12, + content: "PluralKit #downtime", + attachments: [], + embeds: [], + timestamp: "2026-03-24T23:16:04.097Z", + edited_timestamp: null, + flags: 0, + components: [], + id: "1486141581047369888", + channel_id: "1451125453082591314", + author: { + id: "154058479798059009", + username: "exaptations", + discriminator: "0", + avatar: "57b5cfe09a48a5902f2eb8fa65bb1b80", + bot: false, + flags: 0, + globalName: "Exa", + }, + pinned: false, + mentions: [], + mention_roles: [], + mention_everyone: false, + tts: false, + message_reference: { + type: 0, + channel_id: "1015204661701124206", + guild_id: "466707357099884544" + } + }, updated_to_start_thread_from_here: { t: "MESSAGE_UPDATE", s: 19, From d8c0a947f2dc118ce5255090619efe8070235395 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 25 Mar 2026 15:39:26 +1300 Subject: [PATCH 03/17] Automatically reload registration --- src/matrix/read-registration.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/matrix/read-registration.js b/src/matrix/read-registration.js index 114bf75..86f99a1 100644 --- a/src/matrix/read-registration.js +++ b/src/matrix/read-registration.js @@ -78,6 +78,11 @@ function readRegistration() { /** @type {import("../types").AppServiceRegistrationConfig} */ // @ts-ignore let reg = readRegistration() +fs.watch(registrationFilePath, {persistent: false}, () => { + let newReg = readRegistration() + Object.assign(reg, newReg) +}) + module.exports.registrationFilePath = registrationFilePath module.exports.readRegistration = readRegistration module.exports.getTemplateRegistration = getTemplateRegistration From 41692b11ff53ce230a21998d9847839296b9b5c4 Mon Sep 17 00:00:00 2001 From: Bea Date: Fri, 20 Mar 2026 13:54:19 +0000 Subject: [PATCH 04/17] feat(m2d): support MSC4144 per-message profiles Override webhook username and avatar_url from m.per_message_profile (and unstable com.beeper.per_message_profile) when present. The stable key takes priority over the unstable prefix. --- src/m2d/converters/event-to-message.js | 4 + src/m2d/converters/event-to-message.test.js | 102 ++++++++++++++++++++ 2 files changed, 106 insertions(+) diff --git a/src/m2d/converters/event-to-message.js b/src/m2d/converters/event-to-message.js index 1b23787..7fdbb15 100644 --- a/src/m2d/converters/event-to-message.js +++ b/src/m2d/converters/event-to-message.js @@ -557,6 +557,10 @@ async function eventToMessage(event, guild, channel, di) { const member = await getMemberFromCacheOrHomeserver(event.room_id, event.sender, di?.api) if (member.displayname) displayName = member.displayname if (member.avatar_url) avatarURL = mxUtils.getPublicUrlForMxc(member.avatar_url) + // Override display name and avatar from MSC4144 per-message profile if present + const perMessageProfile = event.content["m.per_message_profile"] || event.content["com.beeper.per_message_profile"] + if (perMessageProfile?.displayname) displayName = perMessageProfile.displayname + if (perMessageProfile?.avatar_url) avatarURL = mxUtils.getPublicUrlForMxc(perMessageProfile.avatar_url) // If the display name is too long to be put into the webhook (80 characters is the maximum), // put the excess characters into displayNameRunoff, later to be put at the top of the message let [displayNameShortened, displayNameRunoff] = splitDisplayName(displayName) diff --git a/src/m2d/converters/event-to-message.test.js b/src/m2d/converters/event-to-message.test.js index 1c263b4..b283d82 100644 --- a/src/m2d/converters/event-to-message.test.js +++ b/src/m2d/converters/event-to-message.test.js @@ -5526,6 +5526,108 @@ test("event2message: known and unknown emojis in the end are used for sprite she ) }) +test("event2message: m.per_message_profile overrides displayname and avatar_url", async t => { + t.deepEqual( + await eventToMessage({ + type: "m.room.message", + sender: "@cadence:cadence.moe", + content: { + msgtype: "m.text", + body: "hello from a custom profile", + "m.per_message_profile": { + id: "custom-id", + displayname: "Custom Name", + avatar_url: "mxc://maunium.net/hgXsKqlmRfpKvCZdUoWDkFQo" + } + }, + event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" + }), + { + ensureJoined: [], + messagesToDelete: [], + messagesToEdit: [], + messagesToSend: [{ + username: "Custom Name", + content: "hello from a custom profile", + avatar_url: "https://bridge.example.org/download/matrix/maunium.net/hgXsKqlmRfpKvCZdUoWDkFQo", + allowed_mentions: { + parse: ["users", "roles"] + } + }] + } + ) +}) + +test("event2message: com.beeper.per_message_profile (unstable prefix) overrides displayname and avatar_url", async t => { + t.deepEqual( + await eventToMessage({ + type: "m.room.message", + sender: "@cadence:cadence.moe", + content: { + msgtype: "m.text", + body: "hello from unstable profile", + "com.beeper.per_message_profile": { + id: "custom-id", + displayname: "Unstable Name", + avatar_url: "mxc://maunium.net/hgXsKqlmRfpKvCZdUoWDkFQo" + } + }, + event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" + }), + { + ensureJoined: [], + messagesToDelete: [], + messagesToEdit: [], + messagesToSend: [{ + username: "Unstable Name", + content: "hello from unstable profile", + avatar_url: "https://bridge.example.org/download/matrix/maunium.net/hgXsKqlmRfpKvCZdUoWDkFQo", + allowed_mentions: { + parse: ["users", "roles"] + } + }] + } + ) +}) + +test("event2message: m.per_message_profile takes priority over com.beeper.per_message_profile", async t => { + t.deepEqual( + await eventToMessage({ + type: "m.room.message", + sender: "@cadence:cadence.moe", + content: { + msgtype: "m.text", + body: "stable wins", + "m.per_message_profile": { + id: "stable-id", + displayname: "Stable Name" + }, + "com.beeper.per_message_profile": { + id: "unstable-id", + displayname: "Unstable Name" + } + }, + event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" + }), + { + ensureJoined: [], + messagesToDelete: [], + messagesToEdit: [], + messagesToSend: [{ + username: "Stable Name", + content: "stable wins", + avatar_url: undefined, + allowed_mentions: { + parse: ["users", "roles"] + } + }] + } + ) +}) + test("event2message: all unknown chess emojis are used for sprite sheet", async t => { t.deepEqual( await eventToMessage({ From a8b7d64e91c5927de2d179db89dc7396d876b3c5 Mon Sep 17 00:00:00 2001 From: Bea Date: Fri, 20 Mar 2026 14:04:13 +0000 Subject: [PATCH 05/17] feat(m2d): strip per-message profile fallbacks from message content Remove data-mx-profile-fallback elements from formatted_body and displayname prefix from plain body when per-message profile is used. --- src/m2d/converters/event-to-message.js | 8 +++ src/m2d/converters/event-to-message.test.js | 69 +++++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/src/m2d/converters/event-to-message.js b/src/m2d/converters/event-to-message.js index 7fdbb15..96732ec 100644 --- a/src/m2d/converters/event-to-message.js +++ b/src/m2d/converters/event-to-message.js @@ -803,6 +803,10 @@ async function eventToMessage(event, guild, channel, di) { if (shouldProcessTextEvent) { if (event.content.format === "org.matrix.custom.html" && event.content.formatted_body) { let input = event.content.formatted_body + if (perMessageProfile?.has_fallback) { + // Strip fallback elements added for clients that don't support per-message profiles + input = input.replace(/<(\w+)[^>]*\bdata-mx-profile-fallback\b[^>]*>[^<]*<\/\1>/g, "") + } if (event.content.msgtype === "m.emote") { input = `* ${displayName} ${input}` } @@ -948,6 +952,10 @@ async function eventToMessage(event, guild, channel, di) { } else { // Looks like we're using the plaintext body! content = event.content.body + if (perMessageProfile?.has_fallback && perMessageProfile.displayname && content.startsWith(perMessageProfile.displayname + ": ")) { + // Strip the display name prefix fallback added for clients that don't support per-message profiles + content = content.slice(perMessageProfile.displayname.length + 2) + } if (event.content.msgtype === "m.emote") { content = `* ${displayName} ${content}` diff --git a/src/m2d/converters/event-to-message.test.js b/src/m2d/converters/event-to-message.test.js index b283d82..1c37b7a 100644 --- a/src/m2d/converters/event-to-message.test.js +++ b/src/m2d/converters/event-to-message.test.js @@ -5628,6 +5628,75 @@ test("event2message: m.per_message_profile takes priority over com.beeper.per_me ) }) +test("event2message: data-mx-profile-fallback element is stripped from formatted_body when per-message profile is present", async t => { + t.deepEqual( + await eventToMessage({ + type: "m.room.message", + sender: "@cadence:cadence.moe", + content: { + msgtype: "m.text", + body: "Tidus Herboren: one more test", + format: "org.matrix.custom.html", + formatted_body: "Tidus Herboren: one more test", + "com.beeper.per_message_profile": { + id: "tidus", + displayname: "Tidus Herboren", + avatar_url: "mxc://maunium.net/hgXsKqlmRfpKvCZdUoWDkFQo", + has_fallback: true + } + }, + event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" + }), + { + ensureJoined: [], + messagesToDelete: [], + messagesToEdit: [], + messagesToSend: [{ + username: "Tidus Herboren", + content: "one more test", + avatar_url: "https://bridge.example.org/download/matrix/maunium.net/hgXsKqlmRfpKvCZdUoWDkFQo", + allowed_mentions: { + parse: ["users", "roles"] + } + }] + } + ) +}) + +test("event2message: displayname prefix is stripped from plain body when per-message profile has_fallback", async t => { + t.deepEqual( + await eventToMessage({ + type: "m.room.message", + sender: "@cadence:cadence.moe", + content: { + msgtype: "m.text", + body: "Tidus Herboren: one more test", + "com.beeper.per_message_profile": { + id: "tidus", + displayname: "Tidus Herboren", + has_fallback: true + } + }, + event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" + }), + { + ensureJoined: [], + messagesToDelete: [], + messagesToEdit: [], + messagesToSend: [{ + username: "Tidus Herboren", + content: "one more test", + avatar_url: undefined, + allowed_mentions: { + parse: ["users", "roles"] + } + }] + } + ) +}) + test("event2message: all unknown chess emojis are used for sprite sheet", async t => { t.deepEqual( await eventToMessage({ From 07ec9832b2ada2b054a11209b11e8654ac1b4092 Mon Sep 17 00:00:00 2001 From: Bea Date: Tue, 24 Mar 2026 16:45:39 +0000 Subject: [PATCH 06/17] fix(m2d): only use unstable com.beeper.per_message_profile prefix --- src/m2d/converters/event-to-message.js | 2 +- src/m2d/converters/event-to-message.test.js | 71 +-------------------- 2 files changed, 2 insertions(+), 71 deletions(-) diff --git a/src/m2d/converters/event-to-message.js b/src/m2d/converters/event-to-message.js index 96732ec..5b7d0f4 100644 --- a/src/m2d/converters/event-to-message.js +++ b/src/m2d/converters/event-to-message.js @@ -558,7 +558,7 @@ async function eventToMessage(event, guild, channel, di) { if (member.displayname) displayName = member.displayname if (member.avatar_url) avatarURL = mxUtils.getPublicUrlForMxc(member.avatar_url) // Override display name and avatar from MSC4144 per-message profile if present - const perMessageProfile = event.content["m.per_message_profile"] || event.content["com.beeper.per_message_profile"] + const perMessageProfile = event.content["com.beeper.per_message_profile"] if (perMessageProfile?.displayname) displayName = perMessageProfile.displayname if (perMessageProfile?.avatar_url) avatarURL = mxUtils.getPublicUrlForMxc(perMessageProfile.avatar_url) // If the display name is too long to be put into the webhook (80 characters is the maximum), diff --git a/src/m2d/converters/event-to-message.test.js b/src/m2d/converters/event-to-message.test.js index 1c37b7a..2a204e9 100644 --- a/src/m2d/converters/event-to-message.test.js +++ b/src/m2d/converters/event-to-message.test.js @@ -5526,40 +5526,7 @@ test("event2message: known and unknown emojis in the end are used for sprite she ) }) -test("event2message: m.per_message_profile overrides displayname and avatar_url", async t => { - t.deepEqual( - await eventToMessage({ - type: "m.room.message", - sender: "@cadence:cadence.moe", - content: { - msgtype: "m.text", - body: "hello from a custom profile", - "m.per_message_profile": { - id: "custom-id", - displayname: "Custom Name", - avatar_url: "mxc://maunium.net/hgXsKqlmRfpKvCZdUoWDkFQo" - } - }, - event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", - room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" - }), - { - ensureJoined: [], - messagesToDelete: [], - messagesToEdit: [], - messagesToSend: [{ - username: "Custom Name", - content: "hello from a custom profile", - avatar_url: "https://bridge.example.org/download/matrix/maunium.net/hgXsKqlmRfpKvCZdUoWDkFQo", - allowed_mentions: { - parse: ["users", "roles"] - } - }] - } - ) -}) - -test("event2message: com.beeper.per_message_profile (unstable prefix) overrides displayname and avatar_url", async t => { +test("event2message: com.beeper.per_message_profile overrides displayname and avatar_url", async t => { t.deepEqual( await eventToMessage({ type: "m.room.message", @@ -5592,42 +5559,6 @@ test("event2message: com.beeper.per_message_profile (unstable prefix) overrides ) }) -test("event2message: m.per_message_profile takes priority over com.beeper.per_message_profile", async t => { - t.deepEqual( - await eventToMessage({ - type: "m.room.message", - sender: "@cadence:cadence.moe", - content: { - msgtype: "m.text", - body: "stable wins", - "m.per_message_profile": { - id: "stable-id", - displayname: "Stable Name" - }, - "com.beeper.per_message_profile": { - id: "unstable-id", - displayname: "Unstable Name" - } - }, - event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", - room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" - }), - { - ensureJoined: [], - messagesToDelete: [], - messagesToEdit: [], - messagesToSend: [{ - username: "Stable Name", - content: "stable wins", - avatar_url: undefined, - allowed_mentions: { - parse: ["users", "roles"] - } - }] - } - ) -}) - test("event2message: data-mx-profile-fallback element is stripped from formatted_body when per-message profile is present", async t => { t.deepEqual( await eventToMessage({ From 0b513b7ee07341fd5ed09bb7787c9a7250e75c88 Mon Sep 17 00:00:00 2001 From: Bea Date: Tue, 24 Mar 2026 16:45:40 +0000 Subject: [PATCH 07/17] fix(m2d): implement MSC4144 avatar clearing algorithm - Empty string "" -> undefined (Discord uses default avatar) - Valid MXC URI -> convert to public URL - Omitted/null -> keep member avatar --- src/m2d/converters/event-to-message.js | 12 ++++++-- src/m2d/converters/event-to-message.test.js | 33 +++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/m2d/converters/event-to-message.js b/src/m2d/converters/event-to-message.js index 5b7d0f4..7c233c7 100644 --- a/src/m2d/converters/event-to-message.js +++ b/src/m2d/converters/event-to-message.js @@ -557,10 +557,18 @@ async function eventToMessage(event, guild, channel, di) { const member = await getMemberFromCacheOrHomeserver(event.room_id, event.sender, di?.api) if (member.displayname) displayName = member.displayname if (member.avatar_url) avatarURL = mxUtils.getPublicUrlForMxc(member.avatar_url) - // Override display name and avatar from MSC4144 per-message profile if present + // MSC4144: Override display name and avatar from per-message profile if present const perMessageProfile = event.content["com.beeper.per_message_profile"] if (perMessageProfile?.displayname) displayName = perMessageProfile.displayname - if (perMessageProfile?.avatar_url) avatarURL = mxUtils.getPublicUrlForMxc(perMessageProfile.avatar_url) + if (perMessageProfile && "avatar_url" in perMessageProfile) { + if (perMessageProfile.avatar_url === "") { + // empty string avatar_url clears the avatar (use default) + avatarURL = undefined + } else if (perMessageProfile.avatar_url) { + // omitted/null falls back to member avatar + avatarURL = mxUtils.getPublicUrlForMxc(perMessageProfile.avatar_url) + } + } // If the display name is too long to be put into the webhook (80 characters is the maximum), // put the excess characters into displayNameRunoff, later to be put at the top of the message let [displayNameShortened, displayNameRunoff] = splitDisplayName(displayName) diff --git a/src/m2d/converters/event-to-message.test.js b/src/m2d/converters/event-to-message.test.js index 2a204e9..bc73df7 100644 --- a/src/m2d/converters/event-to-message.test.js +++ b/src/m2d/converters/event-to-message.test.js @@ -5559,6 +5559,39 @@ test("event2message: com.beeper.per_message_profile overrides displayname and av ) }) +test("event2message: com.beeper.per_message_profile empty avatar_url clears avatar", async t => { + t.deepEqual( + await eventToMessage({ + type: "m.room.message", + sender: "@cadence:cadence.moe", + content: { + msgtype: "m.text", + body: "hello with cleared avatar", + "com.beeper.per_message_profile": { + id: "no-avatar", + displayname: "No Avatar User", + avatar_url: "" + } + }, + event_id: "$g07oYSZFWBkxohNEfywldwgcWj1hbhDzQ1sBAKvqOOU", + room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe" + }), + { + ensureJoined: [], + messagesToDelete: [], + messagesToEdit: [], + messagesToSend: [{ + username: "No Avatar User", + content: "hello with cleared avatar", + avatar_url: undefined, + allowed_mentions: { + parse: ["users", "roles"] + } + }] + } + ) +}) + test("event2message: data-mx-profile-fallback element is stripped from formatted_body when per-message profile is present", async t => { t.deepEqual( await eventToMessage({ From 8224ed53410d1a410bf6a60c9f6f203067a3c4b5 Mon Sep 17 00:00:00 2001 From: Bea Date: Tue, 24 Mar 2026 16:45:40 +0000 Subject: [PATCH 08/17] feat(discord): show per-message profile info in matrix info command --- src/discord/interactions/matrix-info.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/discord/interactions/matrix-info.js b/src/discord/interactions/matrix-info.js index c85cec2..f5aa539 100644 --- a/src/discord/interactions/matrix-info.js +++ b/src/discord/interactions/matrix-info.js @@ -62,7 +62,20 @@ async function _interact({guild_id, data}, {api}) { .sort((a, b) => webGuild._getPosition(a, discord.channels) - webGuild._getPosition(b, discord.channels)) .filter(channel => from("channel_room").join("member_cache", "room_id").select("mxid").where({channel_id: channel.id, mxid: event.sender}).get()) const matrixMember = select("member_cache", ["displayname", "avatar_url"], {room_id: message.room_id, mxid: event.sender}).get() - const name = matrixMember?.displayname || event.sender + // Check for per-message profile + const perMessageProfile = event.content?.["com.beeper.per_message_profile"] + let name = matrixMember?.displayname || event.sender + let avatar = utils.getPublicUrlForMxc(matrixMember?.avatar_url) + let profileNote = "" + if (perMessageProfile) { + if (perMessageProfile.displayname) { + name = perMessageProfile.displayname + } + if ("avatar_url" in perMessageProfile) { + avatar = perMessageProfile.avatar_url ? utils.getPublicUrlForMxc(perMessageProfile.avatar_url) : undefined + } + profileNote = " (sent with a per-message profile)" + } return { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { @@ -70,9 +83,9 @@ async function _interact({guild_id, data}, {api}) { author: { name, url: `https://matrix.to/#/${event.sender}`, - icon_url: utils.getPublicUrlForMxc(matrixMember?.avatar_url) + icon_url: avatar }, - description: `This Matrix message was delivered to Discord by **Out Of Your Element**.\n[View on Matrix β†’]()\n\n**User ID**: [${event.sender}]()`, + description: `This Matrix message was delivered to Discord by **Out Of Your Element**${profileNote}.\n[View on Matrix β†’]()\n\n**User ID**: [${event.sender}]()`, color: 0x0dbd8b, fields: [{ name: "In Channels", From f742d8572a1b3b6a6457b5c4addfede97f4a8dab Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 25 Mar 2026 16:10:15 +1300 Subject: [PATCH 09/17] MSC4144 minor changes for merge --- src/discord/interactions/matrix-info.js | 19 ++- src/discord/interactions/matrix-info.test.js | 115 +++++++++++++++++++ src/m2d/converters/event-to-message.js | 23 +++- 3 files changed, 146 insertions(+), 11 deletions(-) diff --git a/src/discord/interactions/matrix-info.js b/src/discord/interactions/matrix-info.js index f5aa539..0b9a525 100644 --- a/src/discord/interactions/matrix-info.js +++ b/src/discord/interactions/matrix-info.js @@ -62,20 +62,29 @@ async function _interact({guild_id, data}, {api}) { .sort((a, b) => webGuild._getPosition(a, discord.channels) - webGuild._getPosition(b, discord.channels)) .filter(channel => from("channel_room").join("member_cache", "room_id").select("mxid").where({channel_id: channel.id, mxid: event.sender}).get()) const matrixMember = select("member_cache", ["displayname", "avatar_url"], {room_id: message.room_id, mxid: event.sender}).get() - // Check for per-message profile - const perMessageProfile = event.content?.["com.beeper.per_message_profile"] let name = matrixMember?.displayname || event.sender let avatar = utils.getPublicUrlForMxc(matrixMember?.avatar_url) + + // Check for per-message profile + const perMessageProfile = event.content?.["com.beeper.per_message_profile"] let profileNote = "" if (perMessageProfile) { if (perMessageProfile.displayname) { name = perMessageProfile.displayname } if ("avatar_url" in perMessageProfile) { - avatar = perMessageProfile.avatar_url ? utils.getPublicUrlForMxc(perMessageProfile.avatar_url) : undefined + if (perMessageProfile.avatar_url) { + // use provided avatar_url + avatar = utils.getPublicUrlForMxc(perMessageProfile.avatar_url) + } else if (perMessageProfile.avatar_url === "") { + // empty string avatar_url clears the avatar + avatar = undefined + } + // else, omitted/null falls back to member avatar } - profileNote = " (sent with a per-message profile)" + profileNote = "Sent with a per-message profile.\n" } + return { type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource, data: { @@ -85,7 +94,7 @@ async function _interact({guild_id, data}, {api}) { url: `https://matrix.to/#/${event.sender}`, icon_url: avatar }, - description: `This Matrix message was delivered to Discord by **Out Of Your Element**${profileNote}.\n[View on Matrix β†’]()\n\n**User ID**: [${event.sender}]()`, + description: `This Matrix message was delivered to Discord by **Out Of Your Element**.\n[View on Matrix β†’]()\n\n${profileNote}**User ID**: [${event.sender}]()`, color: 0x0dbd8b, fields: [{ name: "In Channels", diff --git a/src/discord/interactions/matrix-info.test.js b/src/discord/interactions/matrix-info.test.js index f455700..8347c12 100644 --- a/src/discord/interactions/matrix-info.test.js +++ b/src/discord/interactions/matrix-info.test.js @@ -85,3 +85,118 @@ test("matrix info: shows info for matrix source message", async t => { ) t.equal(called, 1) }) + +test("matrix info: shows username for per-message profile", async t => { + let called = 0 + const msg = await _interact({ + data: { + target_id: "1128118177155526666", + resolved: { + messages: { + "1141501302736695316": data.message.simple_reply_to_matrix_user + } + } + }, + guild_id: "112760669178241024" + }, { + api: { + async getEvent(roomID, eventID) { + called++ + t.equal(roomID, "!kLRqKKUQXcibIMtOpl:cadence.moe") + t.equal(eventID, "$Ij3qo7NxMA4VPexlAiIx2CB9JbsiGhJeyt-2OvkAUe4") + return { + event_id: eventID, + room_id: roomID, + type: "m.room.message", + content: { + msgtype: "m.text", + body: "master chief: i like the halo", + format: "org.matrix.custom.html", + formatted_body: "master chief: i like the halo", + "com.beeper.per_message_profile": { + has_fallback: true, + displayname: "master chief", + avatar_url: "" + } + }, + sender: "@cadence:cadence.moe" + } + }, + async getJoinedMembers(roomID) { + return { + joined: {} + } + }, + async getStateEventOuter(roomID, type, key) { + return { + content: { + room_version: "11" + } + } + }, + async getStateEvent(roomID, type, key) { + return {} + } + } + }) + t.equal(msg.data.embeds[0].author.name, "master chief") + t.match(msg.data.embeds[0].description, "Sent with a per-message profile") + t.equal(called, 1) +}) + +test("matrix info: shows avatar for per-message profile", async t => { + let called = 0 + const msg = await _interact({ + data: { + target_id: "1128118177155526666", + resolved: { + messages: { + "1141501302736695316": data.message.simple_reply_to_matrix_user + } + } + }, + guild_id: "112760669178241024" + }, { + api: { + async getEvent(roomID, eventID) { + called++ + t.equal(roomID, "!kLRqKKUQXcibIMtOpl:cadence.moe") + t.equal(eventID, "$Ij3qo7NxMA4VPexlAiIx2CB9JbsiGhJeyt-2OvkAUe4") + return { + event_id: eventID, + room_id: roomID, + type: "m.room.message", + content: { + msgtype: "m.text", + body: "?", + format: "org.matrix.custom.html", + formatted_body: "?", + "com.beeper.per_message_profile": { + avatar_url: "mxc://cadence.moe/HXfFuougamkURPPMflTJRxGc" + } + }, + sender: "@mystery:cadence.moe" + } + }, + async getJoinedMembers(roomID) { + return { + joined: {} + } + }, + async getStateEventOuter(roomID, type, key) { + return { + content: { + room_version: "11" + } + } + }, + async getStateEvent(roomID, type, key) { + return {} + } + } + }) + t.equal(msg.data.embeds[0].author.name, "@mystery:cadence.moe") + t.equal(msg.data.embeds[0].author.icon_url, "https://bridge.example.org/download/matrix/cadence.moe/HXfFuougamkURPPMflTJRxGc") + t.match(msg.data.embeds[0].description, "Sent with a per-message profile") + t.equal(called, 1) +}) diff --git a/src/m2d/converters/event-to-message.js b/src/m2d/converters/event-to-message.js index 7c233c7..95e477f 100644 --- a/src/m2d/converters/event-to-message.js +++ b/src/m2d/converters/event-to-message.js @@ -550,25 +550,30 @@ async function eventToMessage(event, guild, channel, di) { /** @type {string[]} */ let messageIDsToEdit = [] let replyLine = "" + // Extract a basic display name from the sender const match = event.sender.match(/^@(.*?):/) if (match) displayName = match[1] + // Try to extract an accurate display name and avatar URL from the member event const member = await getMemberFromCacheOrHomeserver(event.room_id, event.sender, di?.api) if (member.displayname) displayName = member.displayname if (member.avatar_url) avatarURL = mxUtils.getPublicUrlForMxc(member.avatar_url) + // MSC4144: Override display name and avatar from per-message profile if present const perMessageProfile = event.content["com.beeper.per_message_profile"] if (perMessageProfile?.displayname) displayName = perMessageProfile.displayname if (perMessageProfile && "avatar_url" in perMessageProfile) { - if (perMessageProfile.avatar_url === "") { - // empty string avatar_url clears the avatar (use default) - avatarURL = undefined - } else if (perMessageProfile.avatar_url) { - // omitted/null falls back to member avatar + if (perMessageProfile.avatar_url) { + // use provided avatar_url avatarURL = mxUtils.getPublicUrlForMxc(perMessageProfile.avatar_url) + } else if (perMessageProfile.avatar_url === "") { + // empty string avatar_url clears the avatar + avatarURL = undefined } + // else, omitted/null falls back to member avatar } + // If the display name is too long to be put into the webhook (80 characters is the maximum), // put the excess characters into displayNameRunoff, later to be put at the top of the message let [displayNameShortened, displayNameRunoff] = splitDisplayName(displayName) @@ -812,7 +817,13 @@ async function eventToMessage(event, guild, channel, di) { if (event.content.format === "org.matrix.custom.html" && event.content.formatted_body) { let input = event.content.formatted_body if (perMessageProfile?.has_fallback) { - // Strip fallback elements added for clients that don't support per-message profiles + // Strip fallback elements added for clients that don't support per-message profiles. + // Deviates from recommended regexp in MSC to be less strict. Avoiding an HTML parser for performance reasons. + // β”Œβ”€β”€β”€β”€A────┐ Opening HTML tag: capture tag name and stay within tag + // ┆ β”†β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€B────────────┐ This text in the tag somewhere, presumably an attribute name + // ┆ ┆┆ β”†β”Œβ”€C──┐ Rest of the opening tag + // ┆ ┆┆ ┆┆ β”†β”Œβ”€D─┐ Tag content (no more tags allowed within) + // ┆ ┆┆ ┆┆ ┆┆ β”†β”Œβ”€E──┐ Closing tag matching opening tag name input = input.replace(/<(\w+)[^>]*\bdata-mx-profile-fallback\b[^>]*>[^<]*<\/\1>/g, "") } if (event.content.msgtype === "m.emote") { From e9fe8206660b4aeda9344dd1f22415b12a75b011 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 25 Mar 2026 16:22:37 +1300 Subject: [PATCH 10/17] Registration changes should be instant now --- scripts/reset-web-password.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/reset-web-password.js b/scripts/reset-web-password.js index 9131efb..7c3a1a2 100644 --- a/scripts/reset-web-password.js +++ b/scripts/reset-web-password.js @@ -13,5 +13,5 @@ const {prompt} = require("enquirer") reg.ooye.web_password = passwordResponse.web_password writeRegistration(reg) - console.log("Saved. Restart Out Of Your Element to apply this change.") + console.log("Saved. This change should be applied instantly.") })() From 8c023cc9361069afbe21ae1d688cac3d1ac2427c Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Wed, 25 Mar 2026 16:24:07 +1300 Subject: [PATCH 11/17] Add ping() function to REPL --- src/stdin.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/stdin.js b/src/stdin.js index fea5fad..2548d42 100644 --- a/src/stdin.js +++ b/src/stdin.js @@ -23,10 +23,26 @@ const setPresence = sync.require("./d2m/actions/set-presence") const channelWebhook = sync.require("./m2d/actions/channel-webhook") const guildID = "112760669178241024" +async function ping() { + const result = await api.ping().catch(e => ({ok: false, status: "net", root: e.message})) + if (result.ok) { + return "Ping OK. The homeserver and OOYE are talking to each other fine." + } else { + if (typeof result.root === "string") { + var msg = `Cannot reach homeserver: ${result.root}` + } else if (result.root.error) { + var msg = `Homeserver said: [${result.status}] ${result.root.error}` + } else { + var msg = `Homeserver said: [${result.status}] ${JSON.stringify(result.root)}` + } + return msg + "\nMatrix->Discord won't work until you fix this.\nIf your installation has recently changed, consider `npm run setup` again." + } +} + if (process.stdin.isTTY) { setImmediate(() => { if (!passthrough.repl) { - const cli = repl.start({ prompt: "", eval: customEval, writer: s => s }) + const cli = repl.start({prompt: "", eval: customEval, writer: s => s}) Object.assign(cli.context, passthrough) passthrough.repl = cli } From 953b3e7741922fa801dea54a068ee5ed40e389bc Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Thu, 26 Mar 2026 00:16:30 +1300 Subject: [PATCH 12/17] Attach message to error Apparently this was causing detached logs, so just stop those complaints if the error isn't being bubbled --- src/d2m/actions/expression.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/d2m/actions/expression.js b/src/d2m/actions/expression.js index c7ab27a..0f714c6 100644 --- a/src/d2m/actions/expression.js +++ b/src/d2m/actions/expression.js @@ -34,7 +34,10 @@ async function emojisToState(emojis, guild) { if (e.data?.errcode === "M_TOO_LARGE") { // Very unlikely to happen. Only possible for 3x-series emojis uploaded shortly after animated emojis were introduced, when there was no 256 KB size limit. return } - console.error(`Trying to handle emoji ${emoji.name} (${emoji.id}), but...`) + e["emoji"] = { + name: emoji.name, + id: emoji.id + } throw e }) )) From 59012d9613c7c7182c9fe99706a6fceb10713f5f Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 27 Mar 2026 19:13:03 +1300 Subject: [PATCH 13/17] Fix pinning random messages --- src/d2m/converters/pins-to-list.js | 2 +- src/m2d/actions/update-pins.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/d2m/converters/pins-to-list.js b/src/d2m/converters/pins-to-list.js index 5a33c7c..4ad8800 100644 --- a/src/d2m/converters/pins-to-list.js +++ b/src/d2m/converters/pins-to-list.js @@ -22,7 +22,7 @@ function pinsToList(pins, kstate) { /** @type {string[]} */ const result = [] for (const pin of pins.items) { - const eventID = select("event_message", "event_id", {message_id: pin.message.id, part: 0}).pluck().get() + const eventID = select("event_message", "event_id", {message_id: pin.message.id}, "ORDER BY part ASC").pluck().get() if (eventID && !alreadyPinned.includes(eventID)) result.push(eventID) } result.reverse() diff --git a/src/m2d/actions/update-pins.js b/src/m2d/actions/update-pins.js index d06f6e8..1ff2bb9 100644 --- a/src/m2d/actions/update-pins.js +++ b/src/m2d/actions/update-pins.js @@ -13,7 +13,7 @@ async function updatePins(pins, prev) { const diff = diffPins.diffPins(pins, prev) for (const [event_id, added] of diff) { const row = from("event_message").join("message_room", "message_id").join("historical_channel_room", "historical_room_index") - .select("reference_channel_id", "message_id").get() + .select("reference_channel_id", "message_id").where({event_id}).and("ORDER BY part ASC").get() if (!row) continue if (added) { discord.snow.channel.addChannelPinnedMessage(row.reference_channel_id, row.message_id, "Message pinned on Matrix") From 857fb7583b83a2619cde4fa512c09fb49c764f41 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Fri, 27 Mar 2026 19:20:04 +1300 Subject: [PATCH 14/17] v3.5 --- package-lock.json | 24 ++++++++++++------------ package.json | 4 ++-- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/package-lock.json b/package-lock.json index 10b4668..9f4ba54 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "out-of-your-element", - "version": "3.4.0", + "version": "3.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "out-of-your-element", - "version": "3.4.0", + "version": "3.5.0", "license": "AGPL-3.0-or-later", "dependencies": { "@chriscdn/promise-semaphore": "^3.0.1", @@ -30,7 +30,7 @@ "enquirer": "^2.4.1", "entities": "^5.0.0", "get-relative-path": "^1.0.2", - "h3": "^1.15.1", + "h3": "^1.15.10", "heatsync": "^2.7.2", "htmx.org": "^2.0.4", "lru-cache": "^11.0.2", @@ -1163,9 +1163,9 @@ } }, "node_modules/brace-expansion": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.4.tgz", - "integrity": "sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==", + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", "dev": true, "license": "MIT", "dependencies": { @@ -1587,9 +1587,9 @@ } }, "node_modules/flatted": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.1.tgz", - "integrity": "sha512-IxfVbRFVlV8V/yRaGzk0UVIcsKKHMSfYw66T/u4nTwlWteQePsxe//LjudR1AMX4tZW3WFCh3Zqa/sjlqpbURQ==", + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", + "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", "dev": true, "license": "ISC" }, @@ -1688,9 +1688,9 @@ } }, "node_modules/h3": { - "version": "1.15.6", - "resolved": "https://registry.npmjs.org/h3/-/h3-1.15.6.tgz", - "integrity": "sha512-oi15ESLW5LRthZ+qPCi5GNasY/gvynSKUQxgiovrY63bPAtG59wtM+LSrlcwvOHAXzGrXVLnI97brbkdPF9WoQ==", + "version": "1.15.10", + "resolved": "https://registry.npmjs.org/h3/-/h3-1.15.10.tgz", + "integrity": "sha512-YzJeWSkDZxAhvmp8dexjRK5hxziRO7I9m0N53WhvYL5NiWfkUkzssVzY9jvGu0HBoLFW6+duYmNSn6MaZBCCtg==", "license": "MIT", "dependencies": { "cookie-es": "^1.2.2", diff --git a/package.json b/package.json index 0e666aa..af4bd2a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "out-of-your-element", - "version": "3.4.0", + "version": "3.5.0", "description": "A bridge between Matrix and Discord", "main": "index.js", "repository": { @@ -39,7 +39,7 @@ "enquirer": "^2.4.1", "entities": "^5.0.0", "get-relative-path": "^1.0.2", - "h3": "^1.15.1", + "h3": "^1.15.10", "heatsync": "^2.7.2", "htmx.org": "^2.0.4", "lru-cache": "^11.0.2", From e28eac6bfaee85b8b5571efe2c0f679c3dedc513 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sat, 28 Mar 2026 11:45:00 +1300 Subject: [PATCH 15/17] Update domino --- package-lock.json | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9f4ba54..dfee078 100644 --- a/package-lock.json +++ b/package-lock.json @@ -276,9 +276,9 @@ } }, "node_modules/@emnapi/runtime": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.0.tgz", - "integrity": "sha512-QN75eB0IH2ywSpRpNddCRfQIhmJYBCJ1x5Lb3IscKAL8bMnVAKnRg8dCoXbHzVLLH7P38N2Z3mtulB7W0J0FKw==", + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.1.tgz", + "integrity": "sha512-VYi5+ZVLhpgK4hQ0TAjiQiZ6ol0oe4mBx7mVv7IflsiEp0OWoVsp/+f9Vc1hOhE0TtkORVrI1GvzyreqpgWtkA==", "license": "MIT", "optional": true, "dependencies": { @@ -1488,9 +1488,9 @@ "license": "MIT" }, "node_modules/domino": { - "version": "2.1.6", - "resolved": "https://registry.npmjs.org/domino/-/domino-2.1.6.tgz", - "integrity": "sha512-3VdM/SXBZX2omc9JF9nOPCtDaYQ67BGp5CoLpIQlO2KCAPETs8TcDHacF26jXadGbvUteZzRTeos2fhID5+ucQ==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/domino/-/domino-2.1.7.tgz", + "integrity": "sha512-3rcXhx0ixJV2nj8J0tljzejTF73A35LVVdnTQu79UAqTBFEgYPMgGtykMuu/BDqaOZphATku1ddRUn/RtqUHYQ==", "license": "BSD-2-Clause" }, "node_modules/emoji-regex": { @@ -1617,9 +1617,9 @@ "license": "MIT" }, "node_modules/fullstore": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/fullstore/-/fullstore-4.0.0.tgz", - "integrity": "sha512-Y9hN79Q1CFU8akjGnTZoBnTzlA/o8wmtBijJOI8dKCmdC7GLX7OekpLxmbaeRetTOi4OdFGjfsg4c5dxP3jgPw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/fullstore/-/fullstore-4.0.2.tgz", + "integrity": "sha512-syOev4kA0lZy4VkfBJZ99ZL4cIiSgiKt0G8SpP0kla1tpM1c+V/jBOVY/OqqGtR2XLVcM83SjFPFC3R2YIwqjQ==", "dev": true, "license": "MIT", "engines": { @@ -1937,9 +1937,9 @@ "license": "MIT" }, "node_modules/json-with-bigint": { - "version": "3.5.7", - "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.7.tgz", - "integrity": "sha512-7ei3MdAI5+fJPVnKlW77TKNKwQ5ppSzWvhPuSuINT/GYW9ZOC1eRKOuhV9yHG5aEsUPj9BBx5JIekkmoLHxZOw==", + "version": "3.5.8", + "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.8.tgz", + "integrity": "sha512-eq/4KP6K34kwa7TcFdtvnftvHCD9KvHOGGICWwMFc4dOOKF5t4iYqnfLK8otCRCRv06FXOzGGyqE8h8ElMvvdw==", "dev": true, "license": "MIT" }, From 12f41038701e26d4ad41d74cfd305fc89b8036b9 Mon Sep 17 00:00:00 2001 From: nemesio65 Date: Thu, 19 Mar 2026 15:58:54 -0700 Subject: [PATCH 16/17] d2m: Create voice channels as call rooms --- src/d2m/actions/create-room.js | 10 ++++++++++ src/d2m/actions/create-room.test.js | 11 +++++++++++ test/data.js | 20 ++++++++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/src/d2m/actions/create-room.js b/src/d2m/actions/create-room.js index c2ec01a..7f110ad 100644 --- a/src/d2m/actions/create-room.js +++ b/src/d2m/actions/create-room.js @@ -193,6 +193,16 @@ async function channelToKState(channel, guild, di) { // Don't overwrite room topic if the topic has been customised if (hasCustomTopic) delete channelKState["m.room.topic/"] + // Make voice channels be a Matrix voice room (MSC3417) + if (channel.type === DiscordTypes.ChannelType.GuildVoice) { + creationContent.type = "org.matrix.msc3417.call" + channelKState["org.matrix.msc3401.call/"] = { + "m.intent": "m.room", + "m.type": "m.voice", + "m.name": customName || channel.name + } + } + // Don't add a space parent if it's self service // (The person setting up self-service has already put it in their preferred space to be able to get this far.) const autocreate = select("guild_active", "autocreate", {guild_id: guild.id}).pluck().get() diff --git a/src/d2m/actions/create-room.test.js b/src/d2m/actions/create-room.test.js index 36fccba..c9e098b 100644 --- a/src/d2m/actions/create-room.test.js +++ b/src/d2m/actions/create-room.test.js @@ -190,6 +190,17 @@ test("channel2room: read-only discord channel", async t => { t.equal(api.getCalled(), 2) }) +test("channel2room: voice channel", async t => { + const api = mockAPI(t) + const state = kstateStripConditionals(await channelToKState(testData.channel.voice, testData.guild.general, {api}).then(x => x.channelKState)) + t.equal(state["m.room.create/"].type, "org.matrix.msc3417.call") + t.deepEqual(state["org.matrix.msc3401.call/"], { + "m.intent": "m.room", + "m.name": "🍞丨[8user] Piece", + "m.type": "m.voice" + }) +}) + test("convertNameAndTopic: custom name and topic", t => { t.deepEqual( _convertNameAndTopic({id: "123", name: "the-twilight-zone", topic: "Spooky stuff here. :ghost:", type: 0}, {id: "456"}, "hauntings"), diff --git a/test/data.js b/test/data.js index f5e8313..cc054cf 100644 --- a/test/data.js +++ b/test/data.js @@ -19,6 +19,26 @@ module.exports = { default_thread_rate_limit_per_user: 0, guild_id: "112760669178241024" }, + voice: { + voice_background_display: null, + version: 1774469910848, + user_limit: 0, + type: 2, + theme_color: null, + status: null, + rtc_region: null, + rate_limit_per_user: 0, + position: 0, + permission_overwrites: [], + parent_id: "805261291908104252", + nsfw: false, + name: "🍞丨[8user] Piece", + last_message_id: "1459912691098325137", + id: "1036840786093953084", + flags: 0, + bitrate: 256000, + guild_id: "112760669178241024" + }, updates: { type: 0, topic: "Updates and release announcements for Out Of Your Element.", From 91bce76fc8d563fc53f9085cd1b50f91a0cb5491 Mon Sep 17 00:00:00 2001 From: Cadence Ember Date: Sun, 29 Mar 2026 15:41:23 +1300 Subject: [PATCH 17/17] Use HTML to strip per-message profile fallback --- src/m2d/converters/event-to-message.js | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/src/m2d/converters/event-to-message.js b/src/m2d/converters/event-to-message.js index 95e477f..af44c84 100644 --- a/src/m2d/converters/event-to-message.js +++ b/src/m2d/converters/event-to-message.js @@ -816,16 +816,6 @@ async function eventToMessage(event, guild, channel, di) { if (shouldProcessTextEvent) { if (event.content.format === "org.matrix.custom.html" && event.content.formatted_body) { let input = event.content.formatted_body - if (perMessageProfile?.has_fallback) { - // Strip fallback elements added for clients that don't support per-message profiles. - // Deviates from recommended regexp in MSC to be less strict. Avoiding an HTML parser for performance reasons. - // β”Œβ”€β”€β”€β”€A────┐ Opening HTML tag: capture tag name and stay within tag - // ┆ β”†β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€B────────────┐ This text in the tag somewhere, presumably an attribute name - // ┆ ┆┆ β”†β”Œβ”€C──┐ Rest of the opening tag - // ┆ ┆┆ ┆┆ β”†β”Œβ”€D─┐ Tag content (no more tags allowed within) - // ┆ ┆┆ ┆┆ ┆┆ β”†β”Œβ”€E──┐ Closing tag matching opening tag name - input = input.replace(/<(\w+)[^>]*\bdata-mx-profile-fallback\b[^>]*>[^<]*<\/\1>/g, "") - } if (event.content.msgtype === "m.emote") { input = `* ${displayName} ${input}` } @@ -886,8 +876,9 @@ async function eventToMessage(event, guild, channel, di) { const doc = domino.createDocument( // DOM parsers arrange elements in the and . Wrapping in a custom element ensures elements are reliably arranged in a single element. '' + input + '' - ); - const root = doc.getElementById("turndown-root"); + ) + const root = doc.getElementById("turndown-root") + assert(root) async function forEachNode(event, node) { for (; node; node = node.nextSibling) { // Check written mentions @@ -940,6 +931,7 @@ async function eventToMessage(event, guild, channel, di) { } } await forEachNode(event, root) + if (perMessageProfile?.has_fallback) root.querySelectorAll("[data-mx-profile-fallback]").forEach(x => x.remove()) // SPRITE SHEET EMOJIS FEATURE: Emojis at the end of the message that we don't know about will be reuploaded as a sprite sheet. // First we need to determine which emojis are at the end.