How to use @slack/client - 10 common examples

To help you get started, we’ve selected a few @slack/client 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 automerge / trellis / src / lib / ampl / amplnet / slack-signaler.js View on Github external
function init(config) {
  let HANDLERS = { hello: () => {}, reply: () => {}, offer: () => {}, error: () => {} }
  let CHANNEL;
  let SESSION = config.session || UUID.generate()
  let NAME = config.name || "unknown"
  let DOC_ID;
  let last_ts
  let onConnectHandler = () => {}
  let CONNECT_DISPATCH = (h) => {
    console.log("GET SLACK CONNECT HANDLER")
    onConnectHandler = h
  }

  rtm = new RtmClient(config.bot_token);
  DOC_ID = config.doc_id

  // The client will emit an RTM.AUTHENTICATED event on successful connection, with the `rtm.start` payload
  rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (rtmStartData) => {
    console.log("CALL SLACK CONNECT HANDLER")
    onConnectHandler()
    for (const c of rtmStartData.channels) {
      if (c.is_member && c.name ==='signals') { CHANNEL = c.id }
    }
    console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}`);
  });

  // you need to wait for the client to fully connect before you can send messages
  rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, function () {
    let msg = JSON.stringify({ action: "hello", name:NAME, session:SESSION, doc_id:DOC_ID })
    rtm.sendMessage(msg, CHANNEL);
github jnummelin / kontena-slack-bot / index.js View on Github external
if(allowedUsers.lastIndexOf(user.name) != -1) {
      return true;
    }
    return false;
  }
}

// The client will emit an RTM.AUTHENTICATED event on successful connection, with the `rtm.start` payload if you want to cache it
rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function (rtmStartData) {
  console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}, but not yet connected to a channel`);
});

var pty = require('node-pty');

// Emitted when there's a message on a channel where the bot is participating
rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) {
  try {
    if(message.text.lastIndexOf(botKeyword, 0) === 0) {
      if (allowChecker(message.user)) {
        cmd = "kontena " + message.text.substring(botKeyword.length);
        var term = pty.spawn('kontena', message.text.substring(botKeyword.length).trim().split(' '), {
          name: 'xterm-color',
          cols: 200,
          rows: 50,
          cwd: process.env.HOME,
          env: process.env
        });
        // Send typing notification to indicate that the work is ongoing
        const intervalObj = setInterval(() => {
          rtm.sendTyping(message.channel);
        }, 2000);
        // Collect all output data to an array
github novoda / spikes / slacker / app.js View on Github external
// getBiggestSlacker(oldest, latest, result => {
//   console.log(result);
// });


var rtm = new RtmClient(token, {logLevel: 'debug'});
rtm.start();

var messages = [];
var index = 0;

rtm.on(RTM_CLIENT_EVENTS.RTM_CONNECTION_OPENED, function () {
  test();
});

rtm.on(RTM_EVENTS.MESSAGE, function (message) {
  console.log(message);

  if (message.type === 'message' && !message.bot_id) {
    if (index === 100) {
      index = 0;
    }
    messages.splice(index, 0 , message);
    index++;
  }

  // Listens to all `message` events from the team
});

function test() {
  setTimeout(test, 30 * 60);
github jnummelin / kontena-slack-bot / index.js View on Github external
var exec = require('child_process').exec;
const stripAnsi = require('strip-ansi');

var RtmClient = require('@slack/client').RtmClient;
var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;
var RTM_EVENTS = require('@slack/client').RTM_EVENTS;
var MemoryDataStore = require('@slack/client').MemoryDataStore;

var bot_token = process.env.SLACK_TOKEN || '';

var rtm = new RtmClient(bot_token, {
  logLevel: 'error',
  dataStore: new MemoryDataStore()
});

var botName = process.env.BOT_NAME || 'kontenabot';
var botKeyword = botName + ':';

console.log('Waiting for keyword "' + botKeyword + '"')

// Setup crude way to allow only specified users
allowChecker = function(user) {
  return true;
}
var allowedUsers = [];
if(process.env.ALLOWED_USERS) {
  allowedUsers = process.env.ALLOWED_USERS.split(',');
  allowChecker = function(userId) {
    var user = rtm.dataStore.getUserById(userId);
github openmobilityfoundation / mds-core / packages / mds-logger / index.ts View on Github external
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function makeCensoredLogMsg(...msgs: any[]): any[] {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return makeCensoredLogMsgRecurse(msgs).map((item: any) =>
    // never print out '[object Object]'
    String(item) === '[object Object]' ? JSON.stringify(item) : item
  )
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
let slackClient: any = null
if (env.SLACK_TOKEN) {
  // An access token (from your Slack app or custom integration - xoxa, xoxp, or xoxb)
  slackClient = new SlackClient(env.SLACK_TOKEN)
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function sendSlack(msg: any, channelParam?: string) {
  if (!slackClient) {
    return
  }

  // See: https://api.slack.com/methods/chat.postMessage
  const channel = channelParam || env.SLACK_CHANNEL || '#sandbox'
  console.log('INFO sendSlack', channel, msg)
  try {
    const res = await slackClient.chat.postMessage({
      // This argument can be a channel ID, a DM ID, a MPDM ID, or a group ID
      token: env.SLACK_TOKEN,
      channel,
github denouche / virtual-assistant / src / interface / slack-service.js View on Github external
constructor(options) {
        super();
        
        this.slackToken = options.token;
        this.administrators = options.administrators || [];

        this.slack = null; // RtmClient
        this.slackWebClient = new WebClient(this.slackToken);
        this.authenticatedUserId = null; // Current bot id

        this.init();
        this.slack.start();
    }
github slackapi / node-slack-interactive-messages / examples / express-all-interactions / server.js View on Github external
const { WebClient } = require('@slack/client');
const { users, neighborhoods } = require('./models');
const axios = require('axios');

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

// Create the adapter using the app's verification token
const slackInteractions = createMessageAdapter(process.env.SLACK_VERIFICATION_TOKEN);

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

// Initialize an Express application
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

// 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', 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 bulwark-crypto / bulwark-explorer / cron / block.js View on Github external
block.vinsCount = vinsCount;
    block.voutsCount = voutsCount;

    // Notice how this is done at the end. If we crash half way through syncing a block, we'll re-try till the block was correctly saved.
    await block.save();

    const syncPercent = ((block.height / stop) * 100).toFixed(2);
    console.dateLog(`(${syncPercent}%) Height: ${block.height}/${stop} Hash: ${block.hash} Txs: ${block.txs.length} Vins: ${vinsCount} Vouts: ${voutsCount}`);

    blockSyncing = false;
  }

  // Post an update to slack incoming webhook if url is
  // provided in config.js.
  if (block && !!config.slack && !!config.slack.url) {
    const webhook = new IncomingWebhook(config.slack.url);
    const superblock = await rpc.call('getnextsuperblock');
    const finalBlock = superblock - 1920;

    let text = '';
    // If finalization period is within 12 hours (12 * 60 * 60) / 90 = 480
    if (block.height == (finalBlock - 480)) {
      text = `
      Finalization window starts in 12 hours.\n
      \n
      Current block: ${block.height}\n
      Finalization block: ${finalBlock}\n
      Budget payment block: ${superblock}\n
      https://explorer.bulwarkcrypto.com/#/block/${block.height}\n
      `;
    }
    // If finalization block.
github matrix-hacks / matrix-puppet-slack / client.js View on Github external
return new Promise((resolve, reject) => {
      this.rtm = new RtmClient(this.token);

      // reject on any unrecoverable error
      this.rtm.on(CLIENT_EVENTS.RTM.UNABLE_TO_RTM_START, (err) => {
        this.emit('unable-to-start', err);
        reject(err);
      });

      // disconnect is called only when there is no chance of reconnection,
      // either due to unrecoverable errors or the disabling of reconnect
      // so it's the best way to know to act towards reconnecting
      // the issue here is that at this point we dont know if
      // its an "unrecoverable error" or not, so if we were to implement
      // reconnect ourself in respones to this event, we may start looping
      this.rtm.on(CLIENT_EVENTS.RTM.DISCONNECT, () => {
        this.emit('disconnected'); // can use this to announce status and issue a reconnect
      });
github IBM / watson-discovery-news-alerting / bot / server-bot.js View on Github external
import { RtmClient, CLIENT_EVENTS } from '@slack/client'

const bot_token = process.env.SLACK_BOT_TOKEN || ''

const rtm = new RtmClient(bot_token)

let channel

// The client will emit an RTM.AUTHENTICATED event on successful connection, with the `rtm.start` payload
rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (rtmStartData) => {
  for (const c of rtmStartData.channels) {
    if (c.is_member && c.name ==='general') {
      channel = c.id
    }
  }
  console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}, but not yet connected to a channel`)
})

rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, () => {
  console.log('Connection opened.')
})