Git Product home page Git Product logo

line-bot-sdk-python's Introduction

line-bot-sdk-python

Build Status PyPI version Documentation Status

SDK of the LINE Messaging API for Python.

About the LINE Messaging API

See the official API documentation for more information.

English: https://devdocs.line.me/en/

Japanese: https://devdocs.line.me/ja/

Install

$ pip install line-bot-sdk

Synopsis

Usage:

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')
handler = WebhookHandler('YOUR_CHANNEL_SECRET')


@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:
        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()

API

LineBotApi

__init__(self, channel_access_token, endpoint='https://api.line.me', timeout=5, http_client=RequestsHttpClient)

Create a new LineBotApi instance.

line_bot_api = linebot.LineBotApi('YOUR_CHANNEL_ACCESS_TOKEN')

You can override the timeout value for each method.

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

Respond to events from users, groups, and rooms. You can get a reply_token from a webhook event object.

https://devdocs.line.me/en/#reply-message

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

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

Send messages to users, groups, and rooms at any time.

https://devdocs.line.me/en/#push-message

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

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

Send messages to multiple users at any time.

https://devdocs.line.me/en/#multicast

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

get_profile(self, user_id, timeout=None)

Get user profile information.

https://devdocs.line.me/en/#bot-api-get-profile

profile = line_bot_api.get_profile(user_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)

Retrieve image, video, and audio data sent by users.

https://devdocs.line.me/en/#get-content

message_content = line_bot_api.get_message_content(message_id)

with open(file_path, 'wb') as fd:
    for chunk in message_content.iter_content():
        fd.write(chunk)

leave_group(self, group_id, timeout=None)

Leave a group.

https://devdocs.line.me/en/#leave

line_bot_api.leave_group(group_id)

leave_room(self, room_id, timeout=None)

Leave a room.

https://devdocs.line.me/en/#leave

line_bot_api.leave_room(room_id)

※ Error handling

If the LINE API server returns an error, LineBotApi raises LineBotApiError.

https://devdocs.line.me/en/#error-response

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

Send message object

https://devdocs.line.me/en/#send-message-object

These following classes are found in the linebot.models package.

TextSendMessage

text_message = TextSendMessage(text='Hello, world')

ImageSendMessage

image_message = ImageSendMessage(
    original_content_url='https://example.com/original.jpg',
    preview_image_url='https://example.com/preview.jpg'
)

VideoSendMessage

video_message = VideoSendMessage(
    original_content_url='https://example.com/original.mp4',
    preview_image_url='https://example.com/preview.jpg'
)

AudioSendMessage

audio_message = AudioSendMessage(
    original_content_url='https://example.com/original.m4a',
    duration=240000
)

LocationSendMessage

location_message = LocationSendMessage(
    title='my location',
    address='Tokyo',
    latitude=35.65910807942215,
    longitude=139.70372892916203
)

StickerSendMessage

sticker_message = StickerSendMessage(
    package_id='1',
    sticker_id='1'
)

ImagemapSendMessage

imagemap_message = ImagemapSendMessage(
    base_url='https://example.com/base',
    alt_text='this is an imagemap',
    base_size=BaseSize(height=1040, width=1040),
    actions=[
        URIImagemapAction(
            link_uri='https://example.com/',
            area=ImagemapArea(
                x=0, y=0, width=520, height=1040
            )
        ),
        MessageImagemapAction(
            text='hello',
            area=ImagemapArea(
                x=520, y=0, width=520, height=1040
            )
        )
    ]
)

TemplateSendMessage - ButtonsTemplate

buttons_template_message = TemplateSendMessage(
    alt_text='Buttons template',
    template=ButtonsTemplate(
        thumbnail_image_url='https://example.com/image.jpg',
        title='Menu',
        text='Please select',
        actions=[
            PostbackTemplateAction(
                label='postback',
                text='postback text',
                data='action=buy&itemid=1'
            ),
            MessageTemplateAction(
                label='message',
                text='message text'
            ),
            URITemplateAction(
                label='uri',
                uri='http://example.com/'
            )
        ]
    )
)

TemplateSendMessage - ConfirmTemplate

confirm_template_message = TemplateSendMessage(
    alt_text='Confirm template',
    template=ConfirmTemplate(
        text='Are you sure?',
        actions=[
            PostbackTemplateAction(
                label='postback',
                text='postback text',
                data='action=buy&itemid=1'
            ),
            MessageTemplateAction(
                label='message',
                text='message text'
            )
        ]
    )
)

TemplateSendMessage - CarouselTemplate

carousel_template_message = TemplateSendMessage(
    alt_text='Carousel template',
    template=CarouselTemplate(
        columns=[
            CarouselColumn(
                thumbnail_image_url='https://example.com/item1.jpg',
                title='this is menu1',
                text='description1',
                actions=[
                    PostbackTemplateAction(
                        label='postback1',
                        text='postback text1',
                        data='action=buy&itemid=1'
                    ),
                    MessageTemplateAction(
                        label='message1',
                        text='message text1'
                    ),
                    URITemplateAction(
                        label='uri1',
                        uri='http://example.com/1'
                    )
                ]
            ),
            CarouselColumn(
                thumbnail_image_url='https://example.com/item2.jpg',
                title='this is menu2',
                text='description2',
                actions=[
                    PostbackTemplateAction(
                        label='postback2',
                        text='postback text2',
                        data='action=buy&itemid=2'
                    ),
                    MessageTemplateAction(
                        label='message2',
                        text='message text2'
                    ),
                    URITemplateAction(
                        label='uri2',
                        uri='http://example.com/2'
                    )
                ]
            )
        ]
    )
)

Webhook

WebhookParser

※ You can use WebhookParser or WebhookHandler

__init__(self, channel_secret)

parser = linebot.WebhookParser('YOUR_CHANNEL_SECRET')

parse(self, body, signature)

Parses the webhook body and builds an event object list. If the signature does NOT match, InvalidSignatureError is raised.

events = parser.parse(body, signature)

for event in events:
    # Do something

WebhookHandler

※ You can use WebhookParser or WebhookHandler

__init__(self, channel_secret)

handler = linebot.WebhookHandler('YOUR_CHANNEL_SECRET')

handle(self, body, signature)

Handles webhooks. If the signature does NOT match, InvalidSignatureError is raised.

handler.handle(body, signature)

Add handler method

You can add a handler method by using the add decorator.

add(self, event, message=None)

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

When the event is an instance of MessageEvent and event.message is an instance of TextMessage, this handler method is called.

Set default handler method

You can set the default handler method by using the default decorator.

default(self)

@handler.default()
def default(event):
    print(event)

If there is no handler for an event, this default handler method is called.

Webhook event object

https://devdocs.line.me/en/#webhooks

The following classes are found in the linebot.models package.

Event

  • MessageEvent
  • FollowEvent
    • type
    • timestamp
    • source: Source
    • reply_token
  • UnfollowEvent
    • type
    • timestamp
    • source: Source
  • JoinEvent
    • type
    • timestamp
    • source: Source
    • reply_token
  • LeaveEvent
    • type
    • timestamp
    • source: Source
  • PostbackEvent
    • type
    • timestamp
    • source: Source
    • reply_token
    • postback: Postback
      • data
  • BeaconEvent
    • type
    • timestamp
    • source: Source
    • reply_token
    • beacon: Beacon
      • type
      • hwid
      • device_message

Source

  • SourceUser
    • type
    • user_id
  • SourceGroup
    • type
    • group_id
    • user_id
  • SourceRoom
    • type
    • room_id
    • user_id

Message

  • TextMessage
    • type
    • id
    • text
  • ImageMessage
    • type
    • id
  • VideoMessage
    • type
    • id
  • AudioMessage
    • type
    • id
  • LocationMessage
    • type
    • id
    • title
    • address
    • latitude
    • longitude
  • StickerMessage
    • type
    • id
    • package_id
    • sticker_id

Hints

Examples

Sample echo-bot using wsgiref.simple_server

Sample echo-bot using Flask

Sample bot using Flask

API documentation

$ cd docs
$ make html
$ open build/html/index.html

OR Documentation Status

Requirements

  • Python >= 2.7 or >= 3.3

For SDK developers

First install for development.

$ pip install -r requirements-dev.txt

Run tests

Test by using tox. We test against the following versions.

  • 2.7
  • 3.3
  • 3.4
  • 3.5
  • 3.6

To run all tests and to run flake8 against all versions, use:

tox

To run all tests against version 2.7, use:

$ tox -e py27

To run a test against version 2.7 and against a specific file, use:

$ tox -e py27 -- tests/test_webhook.py

And more... TBD

line-bot-sdk-python's People

Contributors

be-hase avatar c-bata avatar satetsu888 avatar guitarsucks avatar krrrr38 avatar charsyam avatar moznion avatar naari3 avatar okdtsk avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.