---
# System prepended metadata

title: LineBot 聊天機器人（Python+Flask+Heroku)建立紀錄 Part 1
tags: [LineBot]

---



</style>}

# LineBot 聊天機器人（Python+Flask+Heroku)建立紀錄 Part 1
###### tags: `LineBot`


### 事前準備-各種註冊安裝下載
* Python 
* Line
* Heroku
* Git


## 初始化聊天機器人

### 載入所需模組
```
from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
import os

app = Flask(__name__)
```
### Line 聊天機器人個資
在Line developers裡面Channel 取得 Channel access token
```
handler = WebhookHandler('Channel access token')
line_bot_api = LineBotApi('Channel secret')
```




### 接收Line 的資訊

```
@app.route('/callback', methods= ['POST'])
def callback():
    signature = request.headers['X-Line-Signature']

    body = request.get_data(as_text = True)
    app.logger.info("Request body: " + body)
    print(body)

    try:
        print(body, signature)
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    return 'OK'
```

## Heroku 建立專案
登入Heroku
```
(base) MacBook-Pro:linebot Vic$ heroku login
heroku: Press any key to open up the browser to login or q to exit:

# 瀏覽器登入後
Logged in as 你的 Heroku 
```
### 利用heroku create 指令創造一個heroku application
```
(base) MacBook-Pro:linebot Vic$ heroku create name-of-app
Creating ⬢ name-of-app... done
https://name-of-app.herokuapp.com/ | https://git.heroku.com/name-of-app.git
```

### 準備heroku 的應用程式所需要的檔案
* Procfile
> 在项目的根目录中添加一个Procfile文件。这个文件用来指定运行程序的命令，使用<processtype>：<command>的形式来定义一个进程，每个进程一行。
>[李辉 - Flask Web开发实战 helloflask](http://helloflask.com/book/1/) 
    
```
web: gunicorn app:app –preload
```
* requirements.txt
告訴Heroku執行這個程式所需要安裝的套件：
```
Flask==1.1.2
gunicorn==19.9.0
line-bot-sdk==1.14.0
requests==2.23.0
beautifulsoup4==4.9.1
lxml==4.2.2
yfinance==0.1.54
mpl-finance==0.10.1
mplfinance==0.12.7a0
matplotlib==3.3.0
pandas==1.1.0
pandas-datareader==0.9.0
pyimgur==0.6.0
numpy==1.19.1
```
* runtime.txt
提供Heroku目前執行此程式的python 版本

## Git Push

### 初始化Git
```
(base) MacBook-Pro:linebot Vic$ git init
Initialized empty Git repository in /Users/Vic/Desktop/codervic/LineBot/.git/
```

### 推向Heroku
```
(base) MacBook-Pro:linebot Vic$ heroku git:remote -a name-of-app
set git remote heroku to https://git.heroku.com/name-of-app.git
```

### Deploy
```
$ git add .
$ git commit -am "whatever you like"
$ git push heroku master
```

## 重複訊息機器人
```
from flask import Flask, request, abort, render_template
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage, ImageSendMessage
import configparser
import os


app = Flask(__name__)

handler = WebhookHandler('Token')
line_bot_api = LineBotApi('Secret')

    
@app.route('/callback', methods= ['POST'])
def callback():
    signature = request.headers['X-Line-Signature']

    body = request.get_data(as_text = True)
    app.logger.info("Request body: " + body)
    print(body)

    try:
        print(body, signature)
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    return 'OK'

# 學你說話 function
@handler.add(MessageEvent, message = TextMessage)
def handle_message(event):

    if event.source.user_id != "Udeadbeefdeadbeefdeadbeefdeadbeef":
        line_bot_api.reply_message(
            event.reply_token, TextSendMessage(text = event.message.text)
        )





        
       
```

## 參考資料
* [卡米狗BLOG](https://ithelp.ithome.com.tw/articles/10217350)
* [李辉 - Flask Web开发实战 helloflask](http://helloflask.com/book/1/)
