Skip to content

Instantly share code, notes, and snippets.

@kmaida
Last active June 30, 2020 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmaida/2a7e1b6d92bb6f770870b52458d0dfa0 to your computer and use it in GitHub Desktop.
Save kmaida/2a7e1b6d92bb6f770870b52458d0dfa0 to your computer and use it in GitHub Desktop.
Useful little snippets for building Slack apps
// Username regex
// Starts with @
// Can contain only numbers, lowercase letters, -, ., _
// NOTE: this can be avoided by escaping characters (slash command settings)
const usernameRegex = /^@+[0-9a-z_\-.]*$/;
// Get all user ID mentions from a string
// <@UXXXX|user> (slash commands)
// <@UXXXX> (app mention text)
// Returns an array of user mentions
const getMentions = (text, isSlashcmd = false) => {
const regex = slashcmd ? /<@U[A-Z0-9]*?\|user>/g : /<@U[A-Z0-9]*?>/g;
return text.match(regex);
}
/**
* Message middleware: ignore some kinds of messages
* A bit hacky to catch inconsistencies in Slack API
* (Customer service was contacted; unreliable behavior confirmed)
* @param {object} event event object
* @return {Promise<void>} continue if not ignored message type
*/
async ignoreMention({ message, event, next }) {
const disallowedSubtypes = ['channel_topic', 'message_changed'];
const ignoreSubtypeEvent = disallowedSubtypes.indexOf(event.subtype) > -1;
const ignoreSubtypeMessage = message && message.subtype && disallowedSubtypes.indexOf(message.subtype) > -1;
const ignoreEdited = !!event.edited;
// If mention should be ignored, return
if (ignoreSubtypeEvent || ignoreSubtypeMessage || ignoreEdited) {
return;
}
// If mention should be processed, continue
await next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment