mirror of
				https://github.com/keanuplayz/TravBot-v3.git
				synced 2024-08-15 02:33:12 +00:00 
			
		
		
		
	Improve emote resolving for .emote and .react commands (#33)
This commit is contained in:
		
							parent
							
								
									9c2ff59a34
								
							
						
					
					
						commit
						053b835e89
					
				
					 3 changed files with 113 additions and 40 deletions
				
			
		|  | @ -1,5 +1,5 @@ | ||||||
| import Command from "../../core/command"; | import Command from "../../core/command"; | ||||||
| import {queryClosestEmoteByName} from "./subcommands/emote-utils"; | import {processEmoteQueryFormatted} from "./subcommands/emote-utils"; | ||||||
| import {botHasPermission} from "../../core/lib"; | import {botHasPermission} from "../../core/lib"; | ||||||
| import {Permissions} from "discord.js"; | import {Permissions} from "discord.js"; | ||||||
| 
 | 
 | ||||||
|  | @ -10,9 +10,8 @@ export default new Command({ | ||||||
|         description: "The emote(s) to send.", |         description: "The emote(s) to send.", | ||||||
|         usage: "<emotes...>", |         usage: "<emotes...>", | ||||||
|         async run({guild, channel, message, args}) { |         async run({guild, channel, message, args}) { | ||||||
|             let output = ""; |             const output = processEmoteQueryFormatted(args); | ||||||
|             for (const query of args) output += queryClosestEmoteByName(query).toString(); |             if (output.length > 0) channel.send(output); | ||||||
|             channel.send(output); |  | ||||||
|         } |         } | ||||||
|     }) |     }) | ||||||
| }); | }); | ||||||
|  |  | ||||||
|  | @ -1,7 +1,7 @@ | ||||||
| import Command from "../../core/command"; | import Command from "../../core/command"; | ||||||
| import {CommonLibrary} from "../../core/lib"; | import {CommonLibrary} from "../../core/lib"; | ||||||
| import {Message, Channel, TextChannel} from "discord.js"; | import {Message, Channel, TextChannel} from "discord.js"; | ||||||
| import {queryClosestEmoteByName} from "./subcommands/emote-utils"; | import {processEmoteQueryArray} from "./subcommands/emote-utils"; | ||||||
| 
 | 
 | ||||||
| export default new Command({ | export default new Command({ | ||||||
|     description: |     description: | ||||||
|  | @ -10,17 +10,11 @@ export default new Command({ | ||||||
|     async run($: CommonLibrary): Promise<any> { |     async run($: CommonLibrary): Promise<any> { | ||||||
|         let target: Message | undefined; |         let target: Message | undefined; | ||||||
|         let distance = 1; |         let distance = 1; | ||||||
|          | 
 | ||||||
|         // allows reactions by using an in-line reply
 |         if ($.message.reference) { | ||||||
|         if($.message.reference){ |             // If the command message is a reply to another message, use that as the react target.
 | ||||||
|             const messageID = $.message.reference.messageID; |             target = await $.channel.messages.fetch($.message.reference.messageID!); | ||||||
|             try{ |  | ||||||
|                 target = await $.channel.messages.fetch(messageID!) |  | ||||||
|             }catch{ |  | ||||||
|                 return $.channel.send("Unknown error occurred!") |  | ||||||
|             } |  | ||||||
|         } |         } | ||||||
|          |  | ||||||
|         // handles reacts by message id/distance
 |         // handles reacts by message id/distance
 | ||||||
|         else if ($.args.length >= 2) { |         else if ($.args.length >= 2) { | ||||||
|             const last = $.args[$.args.length - 1]; // Because this is optional, do not .pop() unless you're sure it's a message link indicator.
 |             const last = $.args[$.args.length - 1]; // Because this is optional, do not .pop() unless you're sure it's a message link indicator.
 | ||||||
|  | @ -106,9 +100,8 @@ export default new Command({ | ||||||
|             ).last(); |             ).last(); | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         for (const search of $.args) { |         for (const emote of processEmoteQueryArray($.args)) { | ||||||
|             // Even though the bot will always grab *some* emote, the user can choose not to keep that emote there if it isn't what they want
 |             // Even though the bot will always grab *some* emote, the user can choose not to keep that emote there if it isn't what they want
 | ||||||
|             const emote = queryClosestEmoteByName(search); |  | ||||||
|             const reaction = await target!.react(emote); |             const reaction = await target!.react(emote); | ||||||
| 
 | 
 | ||||||
|             // This part is called with a promise because you don't want to wait 5 seconds between each reaction.
 |             // This part is called with a promise because you don't want to wait 5 seconds between each reaction.
 | ||||||
|  |  | ||||||
|  | @ -1,33 +1,114 @@ | ||||||
|  | import {GuildEmoji} from "discord.js"; | ||||||
| import {client} from "../../../index"; | import {client} from "../../../index"; | ||||||
| 
 | 
 | ||||||
| // Calculate and match the list of emotes against the queried emote, then sort the IDs based on calculated priority.
 | // Levenshtein distance coefficients for all transformation types.
 | ||||||
| export function queryClosestEmoteByName(query: string) { | // TODO: Investigate what values result in the most optimal matching strategy.
 | ||||||
|     const priorityTable: {[id: string]: number} = {}; | const directMatchWeight = 0.0; | ||||||
|  | const uppercaseWeight = 0.2; | ||||||
|  | const lowercaseWeight = 0.5; | ||||||
|  | const substitutionWeight = 1.0; | ||||||
|  | const deletionWeight = 1.5; | ||||||
|  | const insertionWeight = 1.5; | ||||||
| 
 | 
 | ||||||
|     for (const emote of client.emojis.cache.values()) priorityTable[emote.id] = compareEmoteNames(emote.name, query); | // Maximum Levenshtein distance for an emote to be considered a suitable match candidate.
 | ||||||
|  | const maxAcceptedDistance = 3.0; | ||||||
| 
 | 
 | ||||||
|     const resultingIDs = Object.keys(priorityTable).sort((a, b) => priorityTable[b] - priorityTable[a]); | // Algorithm taken from https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows
 | ||||||
|     return client.emojis.cache.get(resultingIDs[0])!; | // Modified for separate handling of uppercasing and lowercasing transformations.
 | ||||||
| } | function levenshtein(s: string, t: string): number { | ||||||
|  |     const m = s.length; | ||||||
|  |     const n = t.length; | ||||||
| 
 | 
 | ||||||
| // Compare an emote's name against a query to see how alike the two are. The higher the number, the closer they are. Takes into account length and capitalization.
 |     let v0 = new Array(n + 1); | ||||||
| function compareEmoteNames(emote: string, query: string) { |     let v1 = new Array(n + 1); | ||||||
|     let likeness = -Math.abs(emote.length - query.length); |  | ||||||
|     const isQueryLonger = query.length > emote.length; |  | ||||||
| 
 | 
 | ||||||
|     // Loop through all indexes that the two strings share then compare each letter.
 |     let i, j; | ||||||
|     for (let i = 0; i < (isQueryLonger ? emote.length : query.length); i++) { |  | ||||||
|         const c = emote[i]; |  | ||||||
|         const q = query[i]; |  | ||||||
| 
 | 
 | ||||||
|         // If they're the exact same character
 |     for (i = 0; i <= n; i++) v0[i] = i; | ||||||
|         if (c === q) likeness += 1.5; | 
 | ||||||
|         // If the emote is uppercase but the query is lowercase
 |     for (i = 0; i < m; i++) { | ||||||
|         else if (c === q.toUpperCase()) likeness += 1; |         v1[0] = i + 1; | ||||||
|         // If the emote is lowercase but the query is uppercase
 | 
 | ||||||
|         else if (c === q.toLowerCase()) likeness += 0.5; |         for (j = 0; j < n; j++) { | ||||||
|         // Otherwise, if they're different characters, don't add anything (this isn't a spellchecker)
 |             let r; | ||||||
|  | 
 | ||||||
|  |             if (s[i] === t[j]) r = directMatchWeight; | ||||||
|  |             else if (s[i] === t[j].toUpperCase()) r = uppercaseWeight; | ||||||
|  |             else if (s[i] === t[j].toLowerCase()) r = lowercaseWeight; | ||||||
|  |             else r = substitutionWeight; | ||||||
|  | 
 | ||||||
|  |             v1[j + 1] = Math.min( | ||||||
|  |                 v0[j + 1] + deletionWeight, | ||||||
|  |                 v1[j] + insertionWeight, | ||||||
|  |                 v0[j] + r); | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|  |         const tmp = v1; | ||||||
|  |         v1 = v0, v0 = tmp; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     return likeness; |     return v0[n]; | ||||||
| } | } | ||||||
|  | 
 | ||||||
|  | function searchSimilarEmotes(query: string): GuildEmoji[] { | ||||||
|  |     const emoteCandidates: {emote: GuildEmoji, dist: number}[] = []; | ||||||
|  | 
 | ||||||
|  |     for (const emote of client.emojis.cache.values()) { | ||||||
|  |         const dist = levenshtein(emote.name, query); | ||||||
|  |         if (dist <= maxAcceptedDistance) { | ||||||
|  |             emoteCandidates.push({ emote, dist }); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     emoteCandidates.sort((b, a) => b.dist - a.dist); | ||||||
|  |     return emoteCandidates.map(em => em.emote); | ||||||
|  | } | ||||||
|  | 
 | ||||||
|  | const unicodeEmojiRegex = /^(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])[\ufe00-\ufe0f]?$/; | ||||||
|  | const discordEmoteMentionRegex = /^<a?:\w+:\d+>$/; | ||||||
|  | const emoteNameWithSelectorRegex = /^(.+)~(\d+)$/; | ||||||
|  | 
 | ||||||
|  | function processEmoteQuery(query: string[], isFormatted: boolean): string[] { | ||||||
|  |     return query.map(emote => { | ||||||
|  |         emote = emote.trim(); | ||||||
|  | 
 | ||||||
|  |         // If the query directly matches a Unicode emoji or a Discord custom emote mention, pass it as-is.
 | ||||||
|  |         if (discordEmoteMentionRegex.test(emote) | ||||||
|  |             || unicodeEmojiRegex.test(emote)) return emote; | ||||||
|  | 
 | ||||||
|  |         // If formatted mode is enabled, parse whitespace and newline elements.
 | ||||||
|  |         if (isFormatted) { | ||||||
|  |             if (emote == "-") return " "; | ||||||
|  |             if (emote == "+") return "\n"; | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|  |         // Selector number used for disambiguating multiple emotes with same name.
 | ||||||
|  |         let selector = 0; | ||||||
|  | 
 | ||||||
|  |         // If the query has emoteName~123 format, extract the actual name and the selector number.
 | ||||||
|  |         const queryWithSelector = emote.match(emoteNameWithSelectorRegex); | ||||||
|  |         if (queryWithSelector) { | ||||||
|  |             emote = queryWithSelector[1]; | ||||||
|  |             selector = +queryWithSelector[2]; | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|  |         // Try to match an emote name directly if the selector is for the closest match.
 | ||||||
|  |         if (selector == 0) { | ||||||
|  |             const directMatchEmote = client.emojis.cache.find(em => em.name === emote); | ||||||
|  |             if (directMatchEmote) return directMatchEmote.toString(); | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|  |         // Find all similar emote candidates within certian threshold and select Nth top one according to the selector.
 | ||||||
|  |         const similarEmotes = searchSimilarEmotes(emote); | ||||||
|  |         if (similarEmotes.length > 0) { | ||||||
|  |             selector = Math.min(selector, similarEmotes.length); | ||||||
|  |             return similarEmotes[selector].toString(); | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|  |         // Return some "missing/invalid emote" indicator.
 | ||||||
|  |         return "❓"; | ||||||
|  |     }); | ||||||
|  | } | ||||||
|  | 
 | ||||||
|  | export const processEmoteQueryArray = (query: string[]): string[] => processEmoteQuery(query, false); | ||||||
|  | export const processEmoteQueryFormatted = (query: string[]): string => processEmoteQuery(query, true).join(""); | ||||||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue