Created
December 18, 2020 16:36
-
-
Save wendeehsu/3f69fc6d2c2e92bdc5e3d86afc03e089 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const line = require('@line/bot-sdk'); | |
const express = require('express'); | |
const https = require('https'); | |
const fetch = require('node-fetch'); | |
const webHookURL = 'https://your-slack-incoming-webhook-url'; | |
require('dotenv').config(); | |
// create LINE SDK config from env variables | |
const config = { | |
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN, | |
channelSecret: process.env.CHANNEL_SECRET, | |
}; | |
// create LINE SDK client | |
const client = new line.Client(config); | |
const app = express(); | |
// register a webhook handler with middleware | |
app.post('/callback', line.middleware(config), (req, res) => { | |
Promise | |
.all(req.body.events.map(handleEvent)) | |
.then((result) => res.json(result)) | |
.catch((err) => { | |
console.error(err); | |
res.status(500).end(); | |
}); | |
}); | |
// event handler | |
function handleEvent(event) { | |
if (event.type !== 'message' || event.message.type !== 'text') { | |
// ignore non-text-message event | |
return Promise.resolve(null); | |
} | |
// create a echoing text message | |
const echo = { text: event.message.text }; | |
console.log(event.message.text); | |
try { | |
sendSlackMessage(webHookURL, echo); | |
} catch (e) { | |
console.error('There was a error with the request', e); | |
} | |
} | |
// post to slack | |
function sendSlackMessage(webhookURL, messageBody) { | |
console.log("sending slack message..."); | |
try { | |
messageBody = JSON.stringify(messageBody); | |
console.log(messageBody); | |
} catch (e) { | |
throw new Error('Failed to stringify messageBody', e); | |
} | |
fetch(webhookURL, { method: 'POST', body: messageBody }); | |
} | |
// listen on port | |
const port = process.env.PORT || 3000; | |
app.listen(port, () => { | |
console.log(`listening on ${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment