From 8dc09307f3afa3512d98f2aa519eb51788411783 Mon Sep 17 00:00:00 2001 From: John Livingston Date: Wed, 8 Dec 2021 16:54:22 +0100 Subject: [PATCH] DemoBot: replying to mentions. --- bots/lib/bot/component.ts | 4 ++++ bots/lib/bot/handlers/demo.ts | 8 +++++++ bots/lib/bot/room.ts | 45 +++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/bots/lib/bot/component.ts b/bots/lib/bot/component.ts index fddd3d6b..f1926320 100644 --- a/bots/lib/bot/component.ts +++ b/bots/lib/bot/component.ts @@ -104,6 +104,10 @@ class BotComponent { } await room.part() } + + public getAddress (): JID | undefined { + return this.address + } } export { diff --git a/bots/lib/bot/handlers/demo.ts b/bots/lib/bot/handlers/demo.ts index a625ae5e..a5453ba1 100644 --- a/bots/lib/bot/handlers/demo.ts +++ b/bots/lib/bot/handlers/demo.ts @@ -44,6 +44,14 @@ export class BotHandlerDemo extends BotHandler { room.sendGroupchat(msg).catch(() => {}) }) + room.on('room_message', (msg: string, user?: XMPPUser, mentionned?: boolean) => { + if (!user || user.isMe) { return } + if (!room.isOnline()) { return } + if (!mentionned) { return } + + room.sendGroupchat(`Yep @${user.nick}?`).catch(() => {}) + }) + this.randomTimeout = setInterval(() => { this.sendRandomMessage() }, 10 * 1000) diff --git a/bots/lib/bot/room.ts b/bots/lib/bot/room.ts index dead0e54..126b2d3a 100644 --- a/bots/lib/bot/room.ts +++ b/bots/lib/bot/room.ts @@ -81,6 +81,9 @@ export class BotRoom extends EventEmitter { if (stanza.name === 'presence') { this.receivePresenceStanza(stanza, fromResource) } + if (stanza.name === 'message') { + this.receiveMessageStanza(stanza, fromResource) + } } public receivePresenceStanza (stanza: XMPPStanza, fromResource?: string): void { @@ -132,6 +135,48 @@ export class BotRoom extends EventEmitter { } } + protected receiveMessageStanza (stanza: XMPPStanza, fromResource?: string): void { + if (stanza.attrs.type !== 'groupchat') { + return + } + // ignoring messages send by the bot himself + if (stanza.attrs.from === this.userJID?.toString()) { + return + } + // ignoring history messages + if (stanza.getChild('delay')) { + return + } + const body = stanza.getChild('body') + // ignoring message without body (subject, ...) + if (!body) { + return + } + + let mentionned: boolean = false // I'm I mentionned? + // TODO: fix this ugly code. + if (this.userJID) { + const references = stanza.getChildren('reference') + for (const reference of references) { + if (reference.attrs.type === 'mention') { + if (reference.attrs.uri === 'xmpp:' + this.userJID.toString()) { + mentionned = true + } else { + const addr = this.component.getAddress() + if (addr) { + if (reference.attrs.uri === 'xmpp:' + addr.toString()) { + mentionned = true + } + } + } + } + } + } + + const user = fromResource ? this.roster.get(fromResource) : undefined + this.emit('room_message', body.toString(), user, mentionned) + } + public attachHandler (handler: BotHandler): void { this.handlers.push(handler) }