Last active
March 26, 2024 14:45
-
-
Save yychen/4ce5ea2a7b75923f9ff7dd8fb8481d4c to your computer and use it in GitHub Desktop.
Sample LINE Bot
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
// Based on https://line.github.io/line-bot-sdk-nodejs/getting-started/basic-usage.html#synopsis | |
// 做了一些修改讓同學們比較好理解 | |
const express = require('express') | |
const line = require('@line/bot-sdk'); | |
const app = express() | |
const port = 3000 | |
const config = { | |
channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN', | |
channelSecret: 'YOUR_CHANNEL_SECRET' | |
} | |
const client = new line.messagingApi.MessagingApiClient({ | |
channelAccessToken: config.channelAccessToken | |
}) | |
app.get('/', (req, res) => { | |
res.send(`Hi ${req.query.name}!`) | |
}) | |
app.post('/webhook', line.middleware(config), (req, res) => { | |
// req.body.events 可能有很多個 | |
for (const event of req.body.events) { | |
handleEvent(event) | |
} | |
// 回傳一個 OK 給呼叫的 server,這邊應該是回什麼都可以 | |
res.send("OK") | |
}) | |
function handleEvent(event) { | |
// 如果不是文字訊息,就跳出 | |
if (event.type !== 'message' || event.message.type !== 'text') { | |
return | |
} | |
// 回覆一模一樣的訊息,多一個驚嘆號 | |
client.replyMessage({ | |
replyToken: event.replyToken, | |
messages: [{ | |
type: 'text', | |
text: `${event.message.text}!` | |
}], | |
}) | |
} | |
app.listen(port, () => { | |
console.log(`Sample LINE bot server listening on port ${port}...`) | |
}) |
Author
yychen
commented
Mar 3, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment