一个简单的 Golang LINE 机器人模板以及如何在 Heroku 上设置 LINE 机器人 API 的教程
A minimal Golang LINE Bot template built on the official line-bot-sdk-go v8. Clone it, deploy it, and you have a working LINE Bot in a few minutes.
/callback webhook endpoint and verifies the LINE signatureThat is the whole app — one file, main.go, roughly 100 lines. It is meant to be read and then rewritten into your own bot.
| Go | 1.25 or later |
| SDK | github.com/line/line-bot-sdk-go/v8 v8.22.0 |
Both are required. You get them from the LINE Developers Console.
| Name | Where to find it |
|---|---|
ChannelSecret |
Messaging API channel → Basic settings tab |
ChannelAccessToken |
Messaging API channel → Messaging API tab → issue a long-lived token |
PORT is optional and defaults to 5000. Most PaaS providers set it for you.
Channel Secret from the Basic settings tab.Channel Access Token on the Messaging API tab.Pick whichever platform you prefer.
Render reads render.yaml. Fill in ChannelSecret and ChannelAccessToken when prompted.
Heroku reads app.json and Procfile. Fill in the same two variables, and note the app name — you need it for the webhook URL.
Back in the LINE Developers Console, set the Webhook URL to your deployment plus /callback:
https://.onrender.com/callback
https://.herokuapp.com/callback
Hit Verify. If it returns success, add the bot as a friend and send it a message.
git clone https://github.com/kkdai/LineBotTemplate.git
cd LineBotTemplate
export ChannelSecret=
export ChannelAccessToken=
go run main.go
# http://localhost:5000/
LINE only calls HTTPS webhooks, so expose the local port with a tunnel:
ngrok http 5000
Then set the webhook URL to https://.ngrok-free.app/callback.
All the interesting code lives in the event loop in main.go:
for _, event := range cb.Events {
switch e := event.(type) {
case webhook.MessageEvent:
switch message := e.Message.(type) {
case webhook.TextMessageContent:
// your logic here
}
}
}
webhook.ImageMessageContent, webhook.LocationMessageContent, webhook.AudioMessageContent, and so on.messaging_api.TextMessage for StickerMessage, ImageMessage, FlexMessage, or TemplateMessage in the Messages slice.webhook.FollowEvent, webhook.JoinEvent, webhook.PostbackEvent, and webhook.BeaconEvent are cases on the outer switch, alongside webhook.MessageEvent.bot.PushMessage when you need to message a user outside of a reply window.See the Messaging API reference for the full surface.
It is one of my project 52.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
暂无开放 Issues,或尚未同步最近议题。