How to use the @slack/web-api.WebClient function in @slack/web-api

To help you get started, we’ve selected a few @slack/web-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 seratch / slack-app-examples / bolt-serverless-aws-template / aws-js / app.js View on Github external
// https://slack.dev/bolt/
const { App, ExpressReceiver } = require('@slack/bolt');
const expressReceiver = new ExpressReceiver({
  signingSecret: process.env.SLACK_SIGNING_SECRET
});
const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  receiver: expressReceiver
});
module.exports.expressApp = expressReceiver.app;

// ------------------------------------------------------
// If you need to use API methods that are not listed on https://api.slack.com/bot-users#methods
// you need to use user api token instead like this:
const { WebClient } = require('@slack/web-api');
app.client = new WebClient(process.env.SLACK_API_TOKEN);

// ------------------------------------------------------

// React to "app_mention" events
app.event('app_mention', ({ event, say }) => {
  app.client.users.info({ user: event.user })
    .then(res => {
      if (res.ok) {
        say({
          text: `Hi! <@${res.user.name}>`
        });
      } else {
        console.error(`Failed because of ${res.error}`)
      }
    }).catch(reason => {
      console.error(`Failed because ${reason}`)
github oughtinc / mosaic / server / lib / notifiers / slack.ts View on Github external
import { WebClient } from "@slack/web-api";

import NotificationRequest from "../models/notificationRequest";

let slackClient;
if (!process.env.SLACK_TOKEN) {
  console.log("SLACK_TOKEN is not set, Slack notifications will not be sent");
} else {
  slackClient = new WebClient(process.env.SLACK_TOKEN);
}

export default async function sendSlackNotification(
  notificationRequest: NotificationRequest,
) {
  if (!process.env.SLACK_TOKEN) {
    return;
  }

  const userResponse = await slackClient.users.lookupByEmail({
    email: notificationRequest.user.email,
  });
  if (!userResponse.ok) {
    // user probably doesn't have a Slack account, or e-mails don't match
    return;
  }
github slackapi / node-slack-sdk / examples / express-all-interactions / server.js View on Github external
const { users, neighborhoods } = require('./models');
const axios = require('axios');
const bodyParser = require('body-parser');

// Read the signing secret and access token from the environment variables
const slackSigningSecret = process.env.SLACK_SIGNING_SECRET;
const slackAccessToken = process.env.SLACK_ACCESS_TOKEN;
if (!slackSigningSecret || !slackAccessToken) {
  throw new Error('A Slack signing secret and access token are required to run this app.');
}

// Create the adapter using the app's signing secret
const slackInteractions = createMessageAdapter(slackSigningSecret);

// Create a Slack Web API client using the access token
const web = new WebClient(slackAccessToken);

// Initialize an Express application
const app = express();

// Attach the adapter to the Express application as a middleware
app.use('/slack/actions', slackInteractions.expressMiddleware());

// Attach the slash command handler
app.post('/slack/commands', bodyParser.urlencoded({ extended: false }), slackSlashCommand);

// Start the express application server
const port = process.env.PORT || 0;
http.createServer(app).listen(port, () => {
  console.log(`server listening on port ${port}`);
});
github matrix-org / matrix-appservice-slack / src / OAuth2.ts View on Github external
constructor(opts: {main: Main, client_id: string, client_secret: string, redirect_prefix: string}) {
        this.main = opts.main;
        this.userTokensWaiting = new Map(); // token -> userId
        this.clientId = opts.client_id;
        this.clientSecret = opts.client_secret;
        this.redirectPrefix = opts.redirect_prefix;
        this.client = new WebClient();
    }
github matrix-org / matrix-appservice-slack / src / SlackClientFactory.ts View on Github external
private async createTeamClient(token: string) {
        const opts = this.config ? this.config.slack_client_opts : undefined;
        const slackClient = new WebClient(token, {
            logger: {
                getLevel: () => LogLevel.DEBUG,
                setLevel: () => {}, // We don't care about these.
                setName: () => {},
                debug: (msg: string) => {
                    // non-ideal way to detect calls to slack.
                    webLog.debug.bind(webLog);
                    if (!this.onRemoteCall) { return; }
                    const match = /apiCall\('([\w\.]+)'\) start/.exec(msg);
                    if (match && match[1]) {
                        this.onRemoteCall(match[1]);
                    }
                    webLog.debug(msg);
                },
                warn: webLog.warn.bind(webLog),
                info: webLog.info.bind(webLog),
github markhobson / emojibot / src / handler.js View on Github external
function handleEvent(event, token) {
	switch (event.type) {
		case 'message':
			const web = new WebClient(token);
			Bot.process(event, web);
			break;
	}
}
github slackapi / node-slack-sdk / examples / greet-and-react / index.js View on Github external
function getClientByTeamId(teamId) {
  if (!clients[teamId] && botAuthorizationStorage.getItem(teamId)) {
    clients[teamId] = new WebClient(botAuthorizationStorage.getItem(teamId));
  }
  if (clients[teamId]) {
    return clients[teamId];
  }
  return null;
}
github kaisermann / pr-slack-bot / src / api / slack.js View on Github external
const memoize = require('memoizee');

const Logger = require('../includes/logger.js');
const DB = require('./db.js');
const { PRIVATE_TEST_CHANNELS } = require('../consts.js');

const { SLACK_BOT_TOKEN, SLACK_USER_TOKEN } = process.env;
const RTM = new RTMClient(SLACK_BOT_TOKEN);

const PR_REGEX = /github\.com\/([\w-.]*)?\/([\w-.]*?)\/pull\/(\d+)/i;
const PR_REGEX_GLOBAL = new RegExp(PR_REGEX.source, `${PR_REGEX.flags}g`);

const user_client = new WebClient(SLACK_USER_TOKEN, {
  retryConfig: retryPolicies.rapidRetryPolicy,
});
const bot_client = new WebClient(SLACK_BOT_TOKEN, {
  retryConfig: retryPolicies.rapidRetryPolicy,
});

exports.bot_client = bot_client;
exports.user_client = user_client;

const balancer = new Queue({
  rules: {
    common: {
      rate: 50,
      limit: 60,
      priority: 5,
    },
    send_message: {
      rate: 2,
      limit: 1,