LoginSignup
4
6

More than 3 years have passed since last update.

Node Slack SDKを使用してNode.jsからSlackAPIを叩く

Posted at

はじめに

Node.jsからslack apiを使用するにはNode Slack SDKが便利です。
本記事は@slack/web-apiのサンプルコードとなります。

install

npm install @slack/web-api

実装例

slack.js

require('dotenv').config()
const { WebClient } = require('@slack/web-api');
const token = process.env.SLACK_TOKEN;
const web = new WebClient(token);

exports.postMessage = async () => {
  // Post a message to the channel, and await the result.
  // Find more arguments and details of the response: https://api.slack.com/methods/chat.postMessage
  const result = await web.chat.postMessage({
    text: 'Hello world!',
    channel: '#test',
  });

  // The result contains an identifier for the message, `ts`.
  console.log(`Successfully send message ${result.ts}`);
}

exports.fileUpload = async () => {
  // Just use the `file` argument as the documentation suggests
  // See: https://api.slack.com/methods/files.upload
  const result = await web.files.upload({
    filename: 'test.txt',
    channels: '#test',
    content: 'aaaa',
    initial_comment: 'best',
  })

  // `res` contains information about the uploaded file
  console.log('File uploaded: ', result.file.id);
}

動作確認


$ node
> const slack = require('./slack.js');
> slack.postMessage();
> slack.fileUpload();

実行結果

スクリーンショット 2019-05-30 23.59.23.png

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6