SDK of the LINE Messaging API for Python.
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/
$ pip install line-bot-sdk
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()
__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.
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!'))
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!'))
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 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)
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)
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)
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)
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)
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 a group.
https://developers.line.me/en/docs/messaging-api/reference/#leave-group
line_bot_api.leave_group(group_id)
Leave a room.
https://developers.line.me/en/docs/messaging-api/reference/#leave-room
line_bot_api.leave_room(room_id)
Create a rich menu object through a group of given data and return rich menu id. The data is an rich menu object to create.
https://developers.line.me/en/docs/messaging-api/reference/#create-rich-menu
rich_menu_to_create = RichMenu(
size=RichMenuBound(
width=2500,
height=1686
),
selected= False,
name="nice richmenu",
chatBarText="touch me",
areas=[
RichMenuArea(
RichMenuBound(
x=0,
y=0,
width=2500,
height=1686
),
URITemplateAction(
uri='line://nv/location'
)
)
]
)
rich_menu_id = line_bot_api.create_rich_menu(data=rich_menu_to_create)
print(rich_menu_id)
Delete rich menu object through a given rich_menu_id.
https://developers.line.me/en/docs/messaging-api/reference/#delete-rich-menu
line_bot_api.delete_rich_menu(rich_menu_id)
Uploads and attaches an image to a rich menu through id and image path.
https://developers.line.me/en/docs/messaging-api/reference/#upload-rich-menu-image
line_bot_api.set_rich_menu_image(rich_menu_id, content_type, content)
Links a rich menu to a user. Only one rich menu can be linked to a user at one time.
https://developers.line.me/en/docs/messaging-api/reference/#link-rich-menu-to-user
line_bot_api.link_rich_menu_to_user(user_id, rich_menu_id)
Gets a list of all uploaded rich menus.
https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu-list
lst_rich_menu_obj = line_bot_api.get_rich_menu_list()
for rich_menu_obj in lst_rich_menu_obj:
print(rich_menu_obj.rich_menu_id)
Get rich menu object through a given Rich menu ID.
https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu
rich_menu_object = line_bot_api.get_rich_menu(rich_menu_id)
print(rich_menu_obj.rich_menu_id)
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_object = ine_bot_api.get_rich_menu_id_of_user(user_id)
print(rich_menu_object.rich_menu_id)
Unlinks a rich menu from a user.
https://developers.line.me/en/docs/messaging-api/reference/#unlink-rich-menu-from-user
line_bot_api.unlink_rich_menu_from_user(user_id)
Downloads an image associated with a rich menu.
https://developers.line.me/en/docs/messaging-api/reference/#download-rich-menu-image
message_content = line_bot_api.get_rich_menu_image(rich_menu_id)
with open(file_path, 'wb') as fd:
for chunk in message_content.iter_content():
fd.write(chunk)
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)
https://developers.line.me/en/docs/messaging-api/reference/#message-objects
The following classes are found in the linebot.models
package.
text_message = TextSendMessage(text='Hello, world')
image_message = ImageSendMessage(
original_content_url='https://example.com/original.jpg',
preview_image_url='https://example.com/preview.jpg'
)
video_message = VideoSendMessage(
original_content_url='https://example.com/original.mp4',
preview_image_url='https://example.com/preview.jpg'
)
audio_message = AudioSendMessage(
original_content_url='https://example.com/original.m4a',
duration=240000
)
location_message = LocationSendMessage(
title='my location',
address='Tokyo',
latitude=35.65910807942215,
longitude=139.70372892916203
)
sticker_message = StickerSendMessage(
package_id='1',
sticker_id='1'
)
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
)
)
]
)
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/'
)
]
)
)
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'
)
]
)
)
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'
)
]
)
]
)
)
image_carousel_template_message = TemplateSendMessage(
alt_text='ImageCarousel template',
template=ImageCarouselTemplate(
columns=[
ImageCarouselColumn(
image_url='https://example.com/item1.jpg',
action=PostbackTemplateAction(
label='postback1',
text='postback text1',
data='action=buy&itemid=1'
)
),
ImageCarouselColumn(
image_url='https://example.com/item2.jpg',
action=PostbackTemplateAction(
label='postback2',
text='postback text2',
data='action=buy&itemid=2'
)
)
]
)
)
※ You can use WebhookParser or WebhookHandler
parser = linebot.WebhookParser('YOUR_CHANNEL_SECRET')
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
※ You can use WebhookParser or WebhookHandler
handler = linebot.WebhookHandler('YOUR_CHANNEL_SECRET')
Handles webhooks. If the signature does NOT match, InvalidSignatureError is raised.
handler.handle(body, signature)
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.
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.
https://developers.line.me/en/docs/messaging-api/reference/#webhook-event-objects
The following classes are found in the linebot.models
package.
- 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
- SourceUser
- type
- user_id
- SourceGroup
- type
- group_id
- user_id
- SourceRoom
- type
- room_id
- user_id
- 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
Sample echo-bot using wsgiref.simple_server
Sample echo-bot using Flask
Sample bot using Flask
$ cd docs $ make html $ open build/html/index.html
- Python >= 2.7 or >= 3.4
First install for development.
$ pip install -r requirements-dev.txt
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