Skip to content

Instantly share code, notes, and snippets.

@kazz12211
Last active October 10, 2022 14:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazz12211/46470bdd8d85f13f83e9c6642f427226 to your computer and use it in GitHub Desktop.
Save kazz12211/46470bdd8d85f13f83e9c6642f427226 to your computer and use it in GitHub Desktop.
Node.jsでSlackのチャネルにメッセージやファイルを送信する方法

Slack API呼び出しモジュール

const { WebClient } = require('@slack/web-api');
const fs = require('fs');

function fileContent(path) {
    const data = fs.readFileSync(path);
    return data;
}

const Slack = {
    init: () => {
        this.client = new WebClient('Slack APIのトークン');
    },
    sendMessage: async (message) => {
        const params = {
            channel: 'チャネル名またはチャネルID',
            text: message
        };
        return await this.client.chat.postMessage(params);
    },
    fileUpload: async (file) => {
        console.log(file);
        const params = {
            channels: 'チャネル名またはチャネルID',
            file: fileContent(file.path),
            filename: file.originalname,
            filetype: file.mimetype,
            title: file.originalname
        };
        return await this.client.files.upload(params);
    }
};

module.exports = Slack;

Routerモジュール

const express = require('express');
const router = express.Router();
const Slack = require('../slack');
const multer = require('multer');

Slack.init();

router.get('/', (req, res) => {
    res.render('index.html', {});
});

router.post('/send', (req, res) => {
    const message = req.body.message;
    Slack.sendMessage(message).then(resp => console.log(resp));
    res.redirect('/');
});

router.post('/upload', multer({dest: '/tmp/fileuploads/'}).single('file'), (req, res) => {
    Slack.fileUpload(req.file).then(resp => console.log(resp));
    res.redirect('/');
});

module.exports = router;

メッセージを送信するHTMLフォーム

<form action="/send" class="form" method="POST">
    <div class="form-group">
        <label for="message">メッセージ</label>
        <textarea name="message" id="message" cols="30" rows="5" class="form-control"></textarea>
    </div>
    <button class="btn btn-primary" type="submit">送信</button>
</form>

ファイルをアップロードするHTMLフォーム

<form action="/upload" class="form" method="POST" enctype="multipart/form-data">
    <div class="form-group">
        <label for="file">アップロード</label>
        <input type="file" class="form-control-file" id="file" name="file">
    </div>
    <button class="btn btn-primary" type="submit">送信</button>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment