How to use @slack/events-api - 7 common examples

To help you get started, we’ve selected a few @slack/events-api examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ingenious-agency / mundialbot / src / index.js View on Github external
// Initialize using verification token from environment variables
require('dotenv').config();

const PORT = process.env.PORT;
const SLACK_TOKEN = process.env.SLACK_TOKEN;
const EVENT_TOKEN = process.env.EVENT_TOKEN;

const createSlackEventAdapter = require('@slack/events-api').createSlackEventAdapter;
const { WebClient } = require('@slack/client');

const { getUserLocations, mentionedUsers } = require('./slack');
const { isTeamPlaying, getPlayingGames } = require('./footbal');
const { buildNationalTeamPlayingMessage, isCurrentGameQuestion, buildCurrentGamesMessage, buildGenericAnswer } = require('./language');

const web = new WebClient(SLACK_TOKEN);
const slackEvents = createSlackEventAdapter(EVENT_TOKEN);

const sendMessage = (channel, text) => {
  web.chat.postMessage({ channel, text }).catch(console.error);
};

slackEvents.on('message', async (event) => {
  try {
    const userIds = mentionedUsers(event.text);
    if (userIds) {
      const userDetails = await getUserLocations(SLACK_TOKEN, userIds);
      const playingDetails = [];
      for (let userDetail of userDetails) {
        const isPlaying = await isTeamPlaying(userDetail.country);
        if(isPlaying) playingDetails.push(userDetail);
      }
      if (playingDetails.length > 0) {
github seratch / slack-app-examples / serverless-gcp-template / index.js View on Github external
function handler(req, res) {
  // https://cloud.google.com/functions/docs/writing/http
  const body = isOnGoogleCloud() ? req.rawBody.toString() : req.body.toString();
  console.log(`Request body: ${body}`);
  try {
    console.log(`X-Slack-Signature: ${req.get('X-Slack-Signature')}`);
    // https://github.com/slackapi/node-slack-events-api/blob/v2.2.0/src/http-handler.js#L22-L58
    verifyRequestSignature({
      signingSecret: config.SLACK_SIGNING_SECRET,
      requestSignature: req.get('X-Slack-Signature'),
      requestTimestamp: req.get('X-Slack-Request-Timestamp'),
      body: body
    });
  } catch (verificationErr) {
    console.error(`Slack signature validation failed: ${verificationErr}`)
    return res.status(401).json({ ok: false });
  }

  if (body.startsWith('{')) {
    // application/json
    const payload = JSON.parse(body);
    if (payload.type === 'url_verification') {
      // ------------------------------------
      // Events API: url_verification
github slackapi / template-announcement-approvals / index.js View on Github external
require('dotenv').config();

const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const slackEventsAPI = require('@slack/events-api');
const slackInteractiveMessages = require('@slack/interactive-messages');
const normalizePort = require('normalize-port');
const bot = require('./lib/bot');

// --- Slack Events ---
const slackEvents = slackEventsAPI.createSlackEventAdapter(process.env.SLACK_VERIFICATION_TOKEN);

bot.getAuthorizedUser();

slackEvents.on('message', (event) => {
  // Filter out messages from this bot itself or updates to messages
  if (event.subtype === 'bot_message' || event.subtype === 'message_changed' || event.subtype === 'message_deleted') {
    return;
  }
  bot.handleDirectMessage(event.user, event.channel, event.text);
});

// --- Slack Interactive Messages ---
const slackMessages =
  slackInteractiveMessages.createMessageAdapter(process.env.SLACK_VERIFICATION_TOKEN);

// Action handling
github slackapi / TalkBot / index.js View on Github external
const bodyParser = require('body-parser');
const WebClient = require('@slack/client').WebClient;
const createSlackEventAdapter = require('@slack/events-api').createSlackEventAdapter;


/**
 * Tokens:
 * Slack, Firebase, Twilio
 */

// Retrieve bot token from dotenv file
const bot_token = process.env.SLACK_BOT_TOKEN || '';
// Authorization token
const auth_token = process.env.SLACK_AUTH_TOKEN || '';
// Verification token for Events Adapter
const slackEvents = createSlackEventAdapter(process.env.SLACK_VERIFICATION_TOKEN);
// Twilio client authorization
const twilio_sid = process.env.TWILIO_SID || '';
const twilio_auth = process.env.TWILIO_AUTH_TOKEN || '';


/**
 * App Configuration:
 * Express, BodyParser, Firebase, Events API, Web Clients, Twilio
 */

// Creates our express app
const app = express();
// Use BodyParser for app
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Slack events client
github slackapi / node-slack-sdk / examples / greet-and-react / index.js View on Github external
// Load environment variables from `.env` file (optional)
require('dotenv').config();

const { createEventAdapter } = require('@slack/events-api');
const { WebClient } = require('@slack/web-api');
const passport = require('passport');
const LocalStorage = require('node-localstorage').LocalStorage;
const SlackStrategy = require('@aoberoi/passport-slack').default.Strategy;
const http = require('http');
const express = require('express');

// *** Initialize event adapter using signing secret from environment variables ***
const slackEvents = createEventAdapter(process.env.SLACK_SIGNING_SECRET, {
  includeBody: true
});

// Initialize a Local Storage object to store authorization info
// NOTE: This is an insecure method and thus for demo purposes only!
const botAuthorizationStorage = new LocalStorage('./storage');

// Helpers to cache and lookup appropriate client
// NOTE: Not enterprise-ready. if the event was triggered inside a shared channel, this lookup
// could fail but there might be a suitable client from one of the other teams that is within that
// shared channel.
const clients = {};
function getClientByTeamId(teamId) {
  if (!clients[teamId] && botAuthorizationStorage.getItem(teamId)) {
    clients[teamId] = new WebClient(botAuthorizationStorage.getItem(teamId));
  }
github universoimpulso / atena / routes / slack.js View on Github external
import express from "express";
import { createEventAdapter } from "@slack/events-api";
import interactionController from "../controllers/interaction";
import { getChannel } from "../utils/interactions";

import { isValidChannel, getStyleLog } from "../utils";
const router = express.Router();
const slackEvents = createEventAdapter(process.env.SLACK_SIGNIN_EVENTS);

router.use("/events", slackEvents.expressMiddleware());

const handleEvent = async e => {
  const channel = getChannel(e);

  if (isValidChannel(channel)) {
    if (e.type === "article") {
      e.origin = "blog";
    }
    e.type === "reaction_removed"
      ? interactionController.remove(e)
      : interactionController.save(e);
    console.log(getStyleLog("blue"), "\nevent:", e);
  } else {
    console.log(
github integrations / slack / lib / slack / client.js View on Github external
const { WebClient } = require('@slack/client');
const { createSlackEventAdapter } = require('@slack/events-api');

module.exports = {
  web: new WebClient(process.env.SLACK_ACCESS_TOKEN),
  events: createSlackEventAdapter(process.env.SLACK_VERIFICATION_TOKEN),
};

@slack/events-api

Official library for using the Slack Platform's Web API

MIT
Latest version published 3 years ago

Package Health Score

67 / 100
Full package analysis