“`html

Python Line Bot 教學

在這篇文章中,我們將學習如何使用 Python 建立一個簡單的 Line Bot。這個教學適合所有想要了解如何製作聊天機器人的朋友,無論你是初學者還是有一定基礎的開發者。

什麼是 Line Bot?

Line Bot 是一種自動化的聊天機器人,能夠在 Line 聊天平台上與用戶互動。透過 Line Bot,開發者可以為用戶提供各種自動回覆服務,並設計實用功能,讓用戶能夠輕鬆獲取所需資訊。

建立 Line Bot

首先,你需要到 Line Developers 註冊並創建一個聊天頻道。以下是詳細步驟:

1. 創建一個聊天頻道

Line Bot設定

進入 Line Developers,選擇「創建新頻道」並按照指示操作。

2. 輸入發行者名稱

Line Bot怎麼

輸入你的發行者名稱,這將顯示在用戶的聊天列表中。

3. 點擊 Create a Messaging API channel

什麼事Line Bot

選擇 Messaging API,然後點擊「創建」。

4. 填寫頻道基本資料

Line Bot架設

根據需求填寫剩餘的頻道基本資料。

5. 點擊創建

Line Bot自動回覆

6. 點擊 Messaging API

Line Bot免費

7. 點擊 Auto-reply messages

Line Bot應用

8. 停用歡迎訊息與自動回應訊息

Line Bot教學

Line Bot Python 程式範例

1. 創建 config.ini

[line-bot]
channel_access_token = 你的token
channel_secret = 你的金鑰

2. 取得 Channel access token

在 Messaging API 中,你可以找到 Channel access token,點選 issue 後會顯示你的 token。

line自動回覆

3. 取得 Channel secret

在 Basic settings 中,你可以找到 Channel secret。

Line機器人教學

4. 建立 app.py

以下是一個簡單的 Line Bot 程式碼範例:

from __future__ import unicode_literals
import os
from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
import configparser
import random

app = Flask(__name__)

# LINE 聊天機器人的基本資料
config = configparser.ConfigParser()
config.read('config.ini')

line_bot_api = LineBotApi(config.get('line-bot', 'channel_access_token'))
handler = WebhookHandler(config.get('line-bot', 'channel_secret'))

@app.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']
    body = request.get_data(as_text=True)
    
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    return 'OK'

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=event.message.text)
    )

if __name__ == "__main__":
    app.run()

如果缺少一些 SDK,可以使用以下指令安裝:

$ pip3 install flask line-bot-sdk

Ngrok 怎麼設置

Ngrok 是一個方便的工具,能將本地伺服器映射到互聯網上。這樣你就可以在本地環境測試你的 Line Bot。以下是設置方法:

1. Ngrok 安裝步驟

Line Bot Python

2. 解壓縮 Ngrok.zip

unzip ngrok.zip

3. 設置 Ngrok token

ngrok authtoken 你的token

4. 設置 Ngrok port

ngrok http 5000

5. 更換 Webhook URL

在 Line Developers 中,將 Webhook URL 更改為 Ngrok 提供的網址加上 “/callback”。

6. 開啟加入群組權限

在 Messaging API 中,允許機器人加入群組聊天。

Line Bot PHP

常見問題解答

Q1: Line Bot 需要哪些權限?

Line Bot 需要 Messaging API 的權限,並且可以選擇是否允許加入群組聊天。

Q2: 如何測試我的 Line Bot?

你可以使用 Ngrok 來將本地伺服器公開,然後透過 Line 應用程式與你的機器人互動。

Q3: 如果遇到錯誤該怎麼辦?

檢查你的 token 和 secret 是否正確,並確保 Ngrok 正在運行。

參考資料可以參考 [Python Line Bot 教學](https://www.learncodewithmike.com/2020/06/python-line-bot.html) 以獲取更多資訊。

“`

Categorized in: