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;
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;
<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>
<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>