编程语言
首页 > 编程语言> > Python Line Messaging Api

Python Line Messaging Api

作者:互联网

Line Messaging

line 是国外一个很火的实时通信软件,类似与WX,由于公司业务需求,需要基于line开发一个聊天平台,下面主要介绍关于line messaging api 的使用。

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

起步

创建开发人员账号和创建channel

官方教程:https://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: https://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..."
      }
    }
  ]
}

字段说明

更多字段清查:https://developers.line.biz/en/reference/messaging-api/

消息事件

未发生事件

用户在组或聊天室中取消发送消息时的事件对象

type:unsend查看

跟踪事件

LINE官方帐户被添加为好友(或被拒绝)时触发的事件对象

type: follow 查看

取消关注事件

LINE官方帐户被取消关注时触发的事件对象

type: unfollow 查看

参加事件

LINE官方帐户加入群组或聊天室时触发的事件对象

type: join 查看

会员加入事件

用户加入LINE官方帐户所在的组或聊天室时触发的事件对象

type: memberJoined 查看

会员退出事件

用户退出LINE官方帐户所在的组或聊天室时触发的事件对象

type: memberLeft 查看

更多事件

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

标签:line,Python,bot,api,print,Messaging,Line,type,message
来源: https://www.cnblogs.com/pungchur/p/14385539.html