Skip to main content

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://developers.line.me/en/docs/messaging-api/reference/

Japanese: https://developers.line.me/ja/docs/messaging-api/reference/

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://developers.line.me/en/docs/messaging-api/reference/#send-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://developers.line.me/en/docs/messaging-api/reference/#send-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://developers.line.me/en/docs/messaging-api/reference/#send-multicast-messages

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

get_profile(self, user_id, timeout=None)

Get user profile information.

https://developers.line.me/en/docs/messaging-api/reference/#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_group_member_profile(self, group_id, user_id, timeout=None)

Gets the user profile of a member of a group that the bot is in. This can be the user ID of a user who has not added the bot as a friend or has blocked the bot.

https://developers.line.me/en/docs/messaging-api/reference/#get-group-member-profile

profile = line_bot_api.get_group_member_profile(group_id, user_id)

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

get_room_member_profile(self, room_id, user_id, timeout=None)

Gets the user profile of a member of a room that the bot is in. This can be the user ID of a user who has not added the bot as a friend or has blocked the bot.

https://developers.line.me/en/docs/messaging-api/reference/#get-room-member-profile

profile = line_bot_api.get_room_member_profile(room_id, user_id)

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

get_group_member_ids(self, group_id, start=None, timeout=None)

Gets the user IDs of the members of a group that the bot is in. This includes the user IDs of users who have not added the bot as a friend or has blocked the bot.

https://developers.line.me/en/docs/messaging-api/reference/#get-group-member-user-ids

member_ids_res = line_bot_api.get_group_member_ids(group_id)

print(member_ids_res.member_ids)
print(member_ids_res.next)

get_room_member_ids(self, room_id, start=None, timeout=None)

Gets the user IDs of the members of a room that the bot is in. This includes the user IDs of users who have not added the bot as a friend or has blocked the bot.

https://developers.line.me/en/docs/messaging-api/reference/#get-room-member-user-ids

member_ids_res = line_bot_api.get_room_member_ids(room_id)

print(member_ids_res.member_ids)
print(member_ids_res.next)

get_message_content(self, message_id, timeout=None)

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

https://developers.line.me/en/docs/messaging-api/reference/#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://developers.line.me/en/docs/messaging-api/reference/#leave-group

line_bot_api.leave_group(group_id)

leave_room(self, room_id, timeout=None)

Leave a room.

https://developers.line.me/en/docs/messaging-api/reference/#leave-room

line_bot_api.leave_room(room_id)

get_rich_menu(self, rich_menu_id, timeout=None)

Gets a rich menu via a rich menu ID.

https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu

rich_menu = line_bot_api.get_rich_menu(rich_menu_id)
print(rich_menu.rich_menu_id)

create_rich_menu(self, rich_menu, timeout=None)

Creates a rich menu. You must upload a rich menu image and link the rich menu to a user for the rich menu to be displayed. You can create up to 10 rich menus for one bot.

https://developers.line.me/en/docs/messaging-api/reference/#create-rich-menu

rich_menu_to_create = RichMenu(
    size=RichMenuSize(width=2500, height=843),
    selected=False,
    name="Nice richmenu",
    chat_bar_text="Tap here",
    areas=[RichMenuArea(
        bounds=RichMenuBounds(x=0, y=0, width=2500, height=843),
        action=URIAction(label='Go to line.me', uri='https://line.me'))]
)
rich_menu_id = line_bot_api.create_rich_menu(rich_menu=rich_menu_to_create)
print(rich_menu_id)

delete_rich_menu(self, rich_menu_id, timeout=None)

Deletes a rich menu.

https://developers.line.me/en/docs/messaging-api/reference/#delete-rich-menu

line_bot_api.delete_rich_menu(rich_menu_id)

get_rich_menu_id_of_user(self, user_id, timeout=None)

Gets the ID of the rich menu linked to a user.

https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-id-of-user

rich_menu_id = ine_bot_api.get_rich_menu_id_of_user(user_id)
print(rich_menu_id)

get_rich_menu_image(self, rich_menu_id, timeout=None)

Downloads an image associated with a rich menu.

https://developers.line.me/en/docs/messaging-api/reference/#download-rich-menu-image

content = line_bot_api.get_rich_menu_image(rich_menu_id)
with open(file_path, 'wb') as fd:
    for chunk in content.iter_content():
        fd.write(chunk)

set_rich_menu_image(self, rich_menu_id, content_type, content, timeout=None)

Uploads and attaches an image to a rich menu.

https://developers.line.me/en/docs/messaging-api/reference/#upload-rich-menu-image

with open(file_path, 'rb') as f:
    line_bot_api.set_rich_menu_image(rich_menu_id, content_type, f)

get_rich_menu_list(self, timeout=None)

Gets a list of all uploaded rich menus.

https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-list

rich_menu_list = line_bot_api.get_rich_menu_list()
for rich_menu in rich_menu_list:
    print(rich_menu.rich_menu_id)

※ Error handling

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

https://developers.line.me/en/docs/messaging-api/reference/#error-responses

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)

Message objects

https://developers.line.me/en/docs/messaging-api/reference/#message-objects

The 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=[
            PostbackAction(
                label='postback',
                text='postback text',
                data='action=buy&itemid=1'
            ),
            MessageAction(
                label='message',
                text='message text'
            ),
            URIAction(
                label='uri',
                uri='http://example.com/'
            )
        ]
    )
)

TemplateSendMessage - ConfirmTemplate

confirm_template_message = TemplateSendMessage(
    alt_text='Confirm template',
    template=ConfirmTemplate(
        text='Are you sure?',
        actions=[
            PostbackAction(
                label='postback',
                text='postback text',
                data='action=buy&itemid=1'
            ),
            MessageAction(
                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=[
                    PostbackAction(
                        label='postback1',
                        text='postback text1',
                        data='action=buy&itemid=1'
                    ),
                    MessageAction(
                        label='message1',
                        text='message text1'
                    ),
                    URIAction(
                        label='uri1',
                        uri='http://example.com/1'
                    )
                ]
            ),
            CarouselColumn(
                thumbnail_image_url='https://example.com/item2.jpg',
                title='this is menu2',
                text='description2',
                actions=[
                    PostbackAction(
                        label='postback2',
                        text='postback text2',
                        data='action=buy&itemid=2'
                    ),
                    MessageAction(
                        label='message2',
                        text='message text2'
                    ),
                    URIAction(
                        label='uri2',
                        uri='http://example.com/2'
                    )
                ]
            )
        ]
    )
)

TemplateSendMessage - ImageCarouselTemplate

image_carousel_template_message = TemplateSendMessage(
    alt_text='ImageCarousel template',
    template=ImageCarouselTemplate(
        columns=[
            ImageCarouselColumn(
                image_url='https://example.com/item1.jpg',
                action=PostbackAction(
                    label='postback1',
                    text='postback text1',
                    data='action=buy&itemid=1'
                )
            ),
            ImageCarouselColumn(
                image_url='https://example.com/item2.jpg',
                action=PostbackAction(
                    label='postback2',
                    text='postback text2',
                    data='action=buy&itemid=2'
                )
            )
        ]
    )
)

With QuickReply

text_message = TextSendMessage(text='Hello, world',
                               quick_reply=QuickReply(items=[
                                   QuickReplyButton(action=MessageAction(label="label", text="text"))
                               ]))

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://developers.line.me/en/docs/messaging-api/reference/#webhook-event-objects

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

      • params: dict

  • 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

  • FileMessage
    • type

    • id

    • file_size

    • file_name

Hints

Examples

simple-server-echo

Sample echo-bot using wsgiref.simple_server

flask-echo

Sample echo-bot using Flask

flask-kitchensink

Sample bot using Flask

API documentation

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

OR Documentation Status

Requirements

  • Python >= 2.7 or >= 3.4

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.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

Metadata

Release files for line-bot-sdk 1.8.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for line-bot-sdk 1.8.0
File Size Uploaded
line-bot-sdk-1.8.0.tar.gz 51.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for line-bot-sdk 1.8.0
File Interpreter ABI Platform
line_bot_sdk-1.8.0-py2.py3-none-any.whl Python 2, Python 3 none any Details

Total release size: 95.7 kB

Release files / line-bot-sdk-1.8.0.tar.gz

Download URL line-bot-sdk-1.8.0.tar.gz
Size 51.1 kB
Tags Source
SHA-256 checksum
How to use checksums
cf2b4c0de6714d5b30e35f57db4d668bb234b2d309248e3160c9795ebc98b0fa
BLAKE2b-256 checksum
How to use checksums
2788a6a7e2b8b028027b0278c91d9ea59c83da87b7c961c82813c9d2518e6071
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via Python-urllib/2.7

Release files / line_bot_sdk-1.8.0-py2.py3-none-any.whl

Download URL line_bot_sdk-1.8.0-py2.py3-none-any.whl
Size 44.7 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
054a2cc3beeccd0557e188c4c60be9bc92b031f724fdb6adc35e2bb31fbc7607
BLAKE2b-256 checksum
How to use checksums
9205af3c243548080096b2370d749e8859977dd2ee994a8cf2a420c3f1d33ca2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via Python-urllib/2.7

Release history Release notifications | RSS feed

3.26.0

2 release files

3.23.1

2 release files

3.22.0

2 release files

3.20.0

2 release files

3.19.2

2 release files

3.19.1

2 release files

3.19.0

2 release files

3.18.1

2 release files

3.17.1

2 release files

3.17.0

2 release files

3.16.3

2 release files

3.16.2

2 release files

3.16.0

2 release files

3.15.0

2 release files

3.14.5

2 release files

3.14.4

2 release files

3.14.3

2 release files

3.14.2

2 release files

3.14.0

2 release files

3.12.0

2 release files

3.11.1

2 release files

3.11.0

2 release files

3.10.2

2 release files

3.9.0

2 release files

3.8.1

2 release files

3.8.0

2 release files

3.7.0

2 release files

3.6.0

2 release files

3.5.1

2 release files

3.5.0

2 release files

3.4.0

2 release files

3.3.0

2 release files

3.2.0

2 release files

3.1.0

2 release files

3.0.3

2 release files

3.0.2

2 release files

2.4.3

2 release files

2.4.2

2 release files

2.4.1

2 release files

2.3.0

2 release files

2.2.1

2 release files

2.1.0

2 release files

2.0.1

2 release files

1.20.0

2 release files

1.19.1

1 release file

1.19.0

3 release files

1.18.0

2 release files

1.16.0

2 release files

1.15.0

2 release files

1.13.0

2 release files

1.12.1

2 release files

1.12.0

2 release files

1.11.0

2 release files

1.9.0

2 release files

This release

1.8.0 This release

2 release files

1.7.2

2 release files

1.7.1

2 release files

1.7.0

2 release files

1.6.0

2 release files

1.5.0

2 release files

1.4.0

2 release files

1.3.0

2 release files

1.2.0

2 release files

1.1.0

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

0.1.0

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page