Python Line Messaging Api

Line Messaging

line 是國外一個很火的實時通訊軟體,類似與WX,由於公司業務需求,需要基於line開發一個聊天平台,下面主要介紹關於line messaging api 的使用。

官方api://developers.line.biz/en/docs/messaging-api/overview/

起步

創建開發人員帳號和創建channel

官方教程://developers.line.biz/en/docs/line-developers-console/overview/

python開發人員使用

  1. 安裝 module

    pip install line-bot-sdk
    
  2. 要求:python2 >= 2.7 或 python3 >=3.4

  3. 示例

    from flask import Flask, request, abort
    
    from linebot import (
        LineBotApi, WebhookHandler
    )
    from linebot.exceptions import (
        InvalidSignatureError
    )
    from linebot.models import (
        MessageEvent, TextMessage, TextSendMessage,
    )
    
    app = Flask(__name__)
    
    line_bot_api = LineBotApi('YOUR_CHANNEL_ACCESS_TOKEN') # channel的token,創建channel之後有
    handler = WebhookHandler('YOUR_CHANNEL_SECRET')  #  channel的secret,創建channel之後有
    
    
    @app.route("/callback", methods=['POST'])
    def callback():  # 用於確認通訊
        # get X-Line-Signature header value
        signature = request.headers['X-Line-Signature']
    
        # get request body as text
        body = request.get_data(as_text=True)
        app.logger.info("Request body: " + body)
    
        # handle webhook body
        try:
            handler.handle(body, signature)
        except InvalidSignatureError:
            print("Invalid signature. Please check your channel access token/channel secret.")
            abort(400)
    
        return 'OK'
    
    
    @handler.add(MessageEvent, message=TextMessage)  # 處理消息事件,text類型的資訊
    def handle_message(event):
        line_bot_api.reply_message(  # 回復消息
            event.reply_token,
            TextSendMessage(text=event.message.text)
        )
    
    
    if __name__ == "__main__":
        app.run()
    

Python Api

githup: //github.com/line/line-bot-sdk-python

創建實例

line_bot_api = linebot.LineBotApi('YOUR_CHANNEL_ACCESS_TOKEN')

答覆消息

用於響應來自用戶,組和聊天室的事件。您可以從webhook事件對象獲取reply_token。

reply_message(self, reply_token, messages, notification_disabled=False, timeout=None)

line_bot_api.reply_message(reply_token, TextSendMessage(text='Hello World!'))

發送消息

1.隨時向單個用戶,組和聊天室發送消息

push_message(self, to, messages, notification_disabled=False, timeout=None)

line_bot_api.push_message(to, TextSendMessage(text='Hello World!'))

2.隨時向多個用戶,組和聊天室發送消息

multicast(self, to, messages, notification_disabled=False, timeout=None)

line_bot_api.multicast(['to1', 'to2'], TextSendMessage(text='Hello World!'))

廣播

隨時向所有關注的用戶發送消息

broadcast(self, messages, notification_disabled=False, timeout=None)

line_bot_api.broadcast(TextSendMessage(text='Hello World!'))

獲取用戶資訊

get_profile(self, user_id, timeout=None)

profile = line_bot_api.get_profile(user_id) # 通過用戶id,獲取用戶資訊

print(profile.display_name)
print(profile.user_id)
print(profile.picture_url)
print(profile.status_message)

獲取消息內容

獲取用戶發送的影像,影片和音頻數據。

get_message_content(self, message_id, timeout=None)

message_content = line_bot_api.get_message_content(message_id)
basedir = os.path.abspath(os.path.dirname(__file__))
file_path = basedir + "../.."
with open(file_path, 'wb') as fd:
    for chunk in message_content.iter_content():
        fd.write(chunk)

獲取機器人資訊

get_bot_info(self, timeout=None)

bot_info = line_bot_api.get_bot_info()

print(bot_info.display_name)
print(bot_info.user_id)
print(bot_info.basic_id)
print(bot_info.premium_id)
print(bot_info.picture_url)
print(bot_info.chat_mode)
print(bot_info.mark_as_read_mode)

Exception

line api 伺服器返回錯誤

try:
    line_bot_api.push_message('to', TextSendMessage(text='Hello World!'))
except linebot.exceptions.LineBotApiError as e:
    print(e.status_code)
    print(e.request_id)
    print(e.error.message)
    print(e.error.details)

Webhook

示例:

{
  "destination": "xxxxxxxxxx",
  "events": [
    {
      "replyToken": "0f3779fba3b349968c5d07db31eab56f",
      "type": "message",
      "mode": "active",
      "timestamp": 1462629479859,
      "source": {
        "type": "user",
        "userId": "U4af4980629..."
      },
      "message": {
        "id": "325708",
        "type": "text",
        "text": "Hello, world"
      }
    },
    {
      "replyToken": "8cf9239d56244f4197887e939187e19e",
      "type": "follow",
      "mode": "active",
      "timestamp": 1462629479859,
      "source": {
        "type": "user",
        "userId": "U4af4980629..."
      }
    }
  ]
}

欄位說明

  • destination:接收Webhook事件,漫遊器的用戶ID
  • events: 事件列表
  • replyToken:使用reply token能夠直接回復
  • type:事件類型
  • mode:channel的狀態
    • active:活動狀態
    • standby(正在開發中):頻道正在等待
  • timestamp:事件的時間(時間戳)
  • source:具有事件源資訊,user、group、room對象
    • type:類型
    • userId:用戶Id
  • message:消息對象
    • id:消息id
    • type:消息類型
    • text:文本

更多欄位清查://developers.line.biz/en/reference/messaging-api/

消息事件

未發生事件

用戶在組或聊天室中取消發送消息時的事件對象

type:unsend查看

跟蹤事件

LINE官方帳戶被添加為好友(或被拒絕)時觸發的事件對象

type: follow 查看

取消關注事件

LINE官方帳戶被取消關注時觸發的事件對象

type: unfollow 查看

參加事件

LINE官方帳戶加入群組或聊天室時觸發的事件對象

type: join 查看

會員加入事件

用戶加入LINE官方帳戶所在的組或聊天室時觸發的事件對象

type: memberJoined 查看

會員退出事件

用戶退出LINE官方帳戶所在的組或聊天室時觸發的事件對象

type: memberLeft 查看

更多事件

請查看://developers.line.biz/en/reference/messaging-api/#webhook-event-objects