summary refs log tree commit diff
path: root/src/discord/interactions/ping.js
blob: 45824bed772708056c638e16e2bc564cf7d15acd (plain) (blame)
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
// @ts-check

const assert = require("assert").strict
const Ty = require("../../types")
const DiscordTypes = require("discord-api-types/v10")
const {discord, sync, select, from} = require("../../passthrough")
const {id: botID} = require("../../../addbot")
const {InteractionMethods} = require("snowtransfer")

/** @type {import("../../matrix/api")} */
const api = sync.require("../../matrix/api")
/** @type {import("../../matrix/utils")} */
const utils = sync.require("../../matrix/utils")
/** @type {import("../../web/routes/guild")} */
const webGuild = sync.require("../../web/routes/guild")

/**
 * @param {DiscordTypes.APIApplicationCommandAutocompleteGuildInteraction} interaction
 * @param {{api: typeof api}} di
 * @returns {AsyncGenerator<{[k in keyof InteractionMethods]?: Parameters<InteractionMethods[k]>[2]}>}
 */
async function* _interactAutocomplete({data, channel}, {api}) {
	function exit() {
		return {createInteractionResponse: {
			/** @type {DiscordTypes.InteractionResponseType.ApplicationCommandAutocompleteResult} */
			type: DiscordTypes.InteractionResponseType.ApplicationCommandAutocompleteResult,
			data: {
				choices: []
			}
		}}
	}

	// Check it was used in a bridged channel
	const roomID = select("channel_room", "room_id", {channel_id: channel?.id}).pluck().get()
	if (!roomID) return yield exit()

	// Check we are in fact autocompleting the first option, the user
	if (!data.options?.[0] || data.options[0].type !== DiscordTypes.ApplicationCommandOptionType.String || !data.options[0].focused) {
		return yield exit()
	}

	/** @type {{displayname: string | null, mxid: string}[][]} */
	const providedMatches = []

	const input = data.options[0].value
	if (input === "") {
		const events = await api.getEvents(roomID, "b", {limit: 40})
		const recents = new Set(events.chunk.map(e => e.sender))
		const matches = select("member_cache", ["mxid", "displayname"], {room_id: roomID}, "AND displayname IS NOT NULL LIMIT 25").all()
		matches.sort((a, b) => +recents.has(b.mxid) - +recents.has(a.mxid))
		providedMatches.push(matches)
	} else if (input.startsWith("@")) { // only autocomplete mxids
		const query = input.replaceAll(/[%_$]/g, char => `$${char}`) + "%"
		const matches = select("member_cache", ["mxid", "displayname"], {room_id: roomID}, "AND mxid LIKE ? ESCAPE '$' LIMIT 25").all(query)
		providedMatches.push(matches)
	} else {
		const query = "%" + input.replaceAll(/[%_$]/g, char => `$${char}`) + "%"
		const displaynameMatches = select("member_cache", ["mxid", "displayname"], {room_id: roomID}, "AND displayname IS NOT NULL AND displayname LIKE ? ESCAPE '$' LIMIT 25").all(query)
		// prioritise matches closer to the start
		displaynameMatches.sort((a, b) => {
			let ai = a.displayname?.toLowerCase().indexOf(input.toLowerCase()) ?? -1
			if (ai === -1) ai = 999
			let bi = b.displayname?.toLowerCase().indexOf(input.toLowerCase()) ?? -1
			if (bi === -1) bi = 999
			return ai - bi
		})
		providedMatches.push(displaynameMatches)
		let mxidMatches = select("member_cache", ["mxid", "displayname"], {room_id: roomID}, "AND displayname IS NOT NULL AND mxid LIKE ? ESCAPE '$' LIMIT 25").all(query)
		mxidMatches = mxidMatches.filter(match => {
			// don't include matches in domain part of mxid
			if (!match.mxid.match(/^[^:]*/)?.includes(query)) return false
			if (displaynameMatches.some(m => m.mxid === match.mxid)) return false
			return true
		})
		providedMatches.push(mxidMatches)
	}

	// merge together
	let matches = providedMatches.flat()

	// don't include bot
	matches = matches.filter(m => m.mxid !== utils.bot)

	// remove duplicates and count up to 25
	const limitedMatches = []
	const seen = new Set()
	for (const match of matches) {
		if (limitedMatches.length >= 25) break
		if (seen.has(match.mxid)) continue
		limitedMatches.push(match)
		seen.add(match.mxid)
	}

	yield {createInteractionResponse: {
		type: DiscordTypes.InteractionResponseType.ApplicationCommandAutocompleteResult,
		data: {
			choices: limitedMatches.map(row => ({name: (row.displayname || row.mxid).slice(0, 100), value: row.mxid.slice(0, 100)}))
		}
	}}
}

/**
 * @param {DiscordTypes.APIChatInputApplicationCommandGuildInteraction & {channel: DiscordTypes.APIGuildTextChannel}} interaction
 * @param {{api: typeof api}} di
 * @returns {AsyncGenerator<{[k in keyof InteractionMethods]?: Parameters<InteractionMethods[k]>[2]}>}
 */
async function* _interactCommand({data, channel, guild_id}, {api}) {
	const roomID = select("channel_room", "room_id", {channel_id: channel.id}).pluck().get()
	if (!roomID) {
		return yield {createInteractionResponse: {
			type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
			data: {
				flags: DiscordTypes.MessageFlags.Ephemeral,
				content: "This channel isn't bridged to Matrix."
			}
		}}
	}

	assert(data.options?.[0]?.type === DiscordTypes.ApplicationCommandOptionType.String)
	const mxid = data.options[0].value
	if (!mxid.match(/^@[^:]*:./)) {
		return yield {createInteractionResponse: {
			type: DiscordTypes.InteractionResponseType.ChannelMessageWithSource,
			data: {
				flags: DiscordTypes.MessageFlags.Ephemeral,
				content: "⚠️ To use `/ping`, you must select an option from autocomplete, or type a full Matrix ID.\n> Tip: This command is not necessary. You can also ping Matrix users just by typing @their name in your message. It won't look like anything, but it does go through."
			}
		}}
	}

	yield {createInteractionResponse: {
		type: DiscordTypes.InteractionResponseType.DeferredChannelMessageWithSource
	}}

	let member
	try {
		/** @type {Ty.Event.M_Room_Member} */
		member = await api.getStateEvent(roomID, "m.room.member", mxid)
	} catch (e) {}

	if (!member || member.membership !== "join") {
		const channelsInGuild = discord.guildChannelMap.get(guild_id)
		assert(channelsInGuild)
		const inChannels = channelsInGuild
		// @ts-ignore
		.map(/** @returns {DiscordTypes.APIGuildChannel} */ cid => discord.channels.get(cid))
			.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}).get())
		if (inChannels.length) {
			return yield {editOriginalInteractionResponse: {
				content: `That person isn't in this channel. They have only joined the following channels:\n${inChannels.map(c => `<#${c.id}>`).join(" • ")}\nYou can ask them to join this channel with \`/invite\`.`,
			}}
		} else {
			return yield {editOriginalInteractionResponse: {
				content: "That person isn't in this channel. You can invite them with `/invite`."
			}}
		}
	}

	yield {editOriginalInteractionResponse: {
		content: "@" + (member.displayname || mxid)
	}}

	yield {createFollowupMessage: {
		flags: DiscordTypes.MessageFlags.Ephemeral | DiscordTypes.MessageFlags.IsComponentsV2,
		components: [{
			type: DiscordTypes.ComponentType.Container,
			components: [{
				type: DiscordTypes.ComponentType.TextDisplay,
				content: "Tip: This command is not necessary. You can also ping Matrix users just by typing @their name in your message. It won't look like anything, but it does go through."
			}]
		}]
	}}
}

/* c8 ignore start */

/** @param {(DiscordTypes.APIChatInputApplicationCommandGuildInteraction & {channel: DiscordTypes.APIGuildTextChannel}) | DiscordTypes.APIApplicationCommandAutocompleteGuildInteraction} interaction */
async function interact(interaction) {
	if (interaction.type === DiscordTypes.InteractionType.ApplicationCommandAutocomplete) {
		for await (const response of _interactAutocomplete(interaction, {api})) {
			if (response.createInteractionResponse) {
				await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, response.createInteractionResponse)
			}
		}
	} else {
		for await (const response of _interactCommand(interaction, {api})) {
			if (response.createInteractionResponse) {
				await discord.snow.interaction.createInteractionResponse(interaction.id, interaction.token, response.createInteractionResponse)
			} else if (response.editOriginalInteractionResponse) {
				await discord.snow.interaction.editOriginalInteractionResponse(botID, interaction.token, response.editOriginalInteractionResponse)
			} else if (response.createFollowupMessage) {
				await discord.snow.interaction.createFollowupMessage(botID, interaction.token, response.createFollowupMessage)
			}
		}
	}
}

module.exports.interact = interact