Git Product home page Git Product logo

line-bot-sdk-python's Introduction

LINE Messaging API SDK for Python

PyPI version

SDK of the LINE Messaging API for Python.

Introduction

The LINE Messaging API SDK for Python makes it easy to develop bots using LINE Messaging API, and you can create a sample bot within minutes.

Documentation

See the official API documentation for more information

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

Japanese: https://developers.line.biz/ja/docs/messaging-api/overview/

Requirements

  • Python >= 3.8

Installation

$ pip install line-bot-sdk

Synopsis

Usage:

from flask import Flask, request, abort

from linebot.v3 import (
    WebhookHandler
)
from linebot.v3.exceptions import (
    InvalidSignatureError
)
from linebot.v3.messaging import (
    Configuration,
    ApiClient,
    MessagingApi,
    ReplyMessageRequest,
    TextMessage
)
from linebot.v3.webhooks import (
    MessageEvent,
    TextMessageContent
)

app = Flask(__name__)

configuration = Configuration(access_token='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:
        app.logger.info("Invalid signature. Please check your channel access token/channel secret.")
        abort(400)

    return 'OK'


@handler.add(MessageEvent, message=TextMessageContent)
def handle_message(event):
    with ApiClient(configuration) as api_client:
        line_bot_api = MessagingApi(api_client)
        line_bot_api.reply_message_with_http_info(
            ReplyMessageRequest(
                reply_token=event.reply_token,
                messages=[TextMessage(text=event.message.text)]
            )
        )

if __name__ == "__main__":
    app.run()

API

See linebot/v3/messaging/docs . Other docs are in linebot/v3/<feature>/docs/*.md.

Webhook

WebhookParser

※ You can use WebhookParser

__init__(self, channel_secret)

parser = linebot.v3.WebhookParser('YOUR_CHANNEL_SECRET')

parse(self, body, signature, as_payload=False)

Parses the webhook body, and returns a list of Event objects or a WebhookPayload object (depending on as_payload). If the signature does NOT match, InvalidSignatureError is raised.

events = parser.parse(body, signature)

for event in events:
    do_something(event)
payload = parser.parse(body, signature, as_payload=True)

for event in payload.events:
    do_something(payload.event, payload.destination)

WebhookHandler

※ You can use WebhookHandler

__init__(self, channel_secret)

handler = linebot.v3.WebhookHandler('YOUR_CHANNEL_SECRET')

handle(self, body, signature)

Handles webhooks with handlers added by the decorators add and default. If the signature does NOT match, InvalidSignatureError is raised.

handler.handle(body, signature)

add(self, event, message=None)

Add a handler method by using this decorator.

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    line_bot_api.reply_message(
        ReplyMessageRequest(
            reply_token=event.reply_token,
            messages=[TextMessage(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.

@handler.add(MessageEvent)
def handle_message(event, destination):
    # do something

If the arity of the handler method is more than one, a destination property in a webhook request is passed to it as the second argument.

@handler.add(FollowEvent)
def handle_follow():
    # do something

If the arity of the handler method is zero, the handler method is called with no arguments.

default(self)

Set the default handler method by using this decorator.

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

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

WebhookPayload

https://developers.line.biz/en/reference/messaging-api/#request-body

  • WebhookPayload
    • destination
    • events: list[Event]

Webhook event object

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

Hints

Examples

Sample echo-bot with asynchronous processings.

Sample echo-bot using FastAPI

Sample echo-bot using Flask

Sample bot using Flask

Switching richmenu script

Sample echo-bot using wsgiref.simple_server

How to deserializes JSON to FlexMessage or RichMenu

line-bot-python-sdk provides from_json method for each model. It deserializes the JSON into the specified model. Thus, you can send a JSON designed with Flex Message Simulator.

bubble_string = """{ type:"bubble", ... }"""
message = FlexMessage(alt_text="hello", contents=FlexContainer.from_json(bubble_string))
line_bot_api.reply_message(
    ReplyMessageRequest(
        reply_token=event.reply_token,
        messages=[message]
    )
)

How to get x-line-request-id header and error message

You may need to store the x-line-request-id header obtained as a response from several APIs. In this case, please use ~_with_http_info functions. You can get headers and status codes. The x-line-accepted-request-id or content-type header can also be obtained in the same way.

response = line_bot_api.reply_message_with_http_info(
    ReplyMessageRequest(
        reply_token=event.reply_token,
        messages=[TextMessage(text='see application log')]
    )
)
app.logger.info("Got response with http status code: " + str(response.status_code))
app.logger.info("Got x-line-request-id: " + response.headers['x-line-request-id'])
app.logger.info("Got response with http body: " + str(response.data))

You can get error messages from ApiException when you use MessagingApi. Each client defines its own exception class.

from linebot.v3.messaging import ApiException, ErrorResponse
try:
    line_bot_api.reply_message_with_http_info(
        ReplyMessageRequest(
            reply_token='invalid-reply-token',
            messages=[TextMessage(text='see application log')]
        )
    )
except ApiException as e:
    app.logger.info("Got response with http status code: " + str(e.status))
    app.logger.info("Got x-line-request-id: " + e.headers['x-line-request-id'])
    app.logger.info("Got response with http body: " + str(ErrorResponse.from_json(e.body)))

When you need to get x-line-accepted-request-id header from error response, you can get it: e.headers['x-line-accepted-request-id'].

Help and media

FAQ: https://developers.line.biz/en/faq/

News: https://developers.line.biz/en/news/

Versioning

This project respects semantic versioning

See http://semver.org/

Version 3.x

LINE's SDK developer team decided to generate SDK code based on OpenAPI spec. https://github.com/line/line-openapi

As a result, LINE bot sdk 3.x is not compatible with 2.x. It can follow the future API changes very quickly.

We will be maintaining only linebot.v3 going forward. To utilize the latest features, we recommend you gradually transition to linebot.v3 modules in your application, although you can still continue to use the 2.x linebot modules.

While we won't update linebot modules anymore, users can still continue to use the version 2.x linebot modules. We also welcome pull requests for the version 2.x and 3.x modules.

How to suppress deprecation warnings

If you keep using old line-bot-sdk library (version < 3.x) but use 3.x, you'll get

LineBotSdkDeprecatedIn30: Call to deprecated method get_bot_info. (Use 'from linebot.v3.messaging import MessagingApi' and 'MessagingApi(...).get_bot_info(...)' instead. See https://github.com/line/line-bot-sdk-python/blob/master/README.rst for more details.) -- Deprecated since version 3.0.0.

If it's noisy, you can suppress this warning as follows.

import warnings
from linebot import LineBotSdkDeprecatedIn30

## your code here
...

if __name__ == '__main__':
    warnings.filterwarnings("ignore", category=LineBotSdkDeprecatedIn30)

Contributing

Please check CONTRIBUTING before making a contribution.

For SDK developers

First install for development.

$ pip install -r requirements-dev.txt

You can generate new or fixed models and APIs by this command.

$ python generate-code.py

When you update line-bot-sdk-python version, please update linebot/__about__.py and generate code again.

If you edit README.rst, you should execute the following command to check the syntax of README.

$ python -m readme_renderer README.rst

Run tests

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

  • 3.8
  • 3.9
  • 3.10
  • 3.11
  • 3.12

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

tox

To run all tests against version 3.10, use:

$ tox -e py3.10

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

$ tox -e py3.10 -- tests/test_webhook.py

License

Copyright (C) 2016 LINE Corp.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

line-bot-sdk-python's People

Contributors

4geru avatar be-hase avatar bobuhiro11 avatar c-bata avatar ca-lee avatar clsung avatar cryeo avatar dependabot-preview[bot] avatar dependabot[bot] avatar github-actions[bot] avatar hungyichiun avatar hwonyo avatar intactio avatar kcvlex avatar loloicci avatar louis70109 avatar moznion avatar naari3 avatar nanato12 avatar nnsnodnb avatar o926428377 avatar okdtsk avatar okue avatar renovate[bot] avatar rotoyang avatar satetsu888 avatar tkgauri avatar tokuhirom avatar turfaa avatar yang-33 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

line-bot-sdk-python's Issues

Unexpect callback information on operation message. userId is null

Because I use line-bot-sdk-python, so I file issue here.

I find the Line Server is not provide expect callback for operation.

When I try to get "event.message.userId" message on JSON, I get as follow:

{
"message": {     
            "id": "7221963375040",
            "text": "TEST", 
            "type": "text"
            }, 
            "replyToken": "33f330692e5b493d8ba400652d62c14b",
            "source": {
                        "groupId": "C6f9ddd71af67bb47a3b00950aa51b59c", 
                        "type": "group", 
                        "userId": null
            }, 
            "timestamp": 1514533485276,
            "type": "message"
}

It missing some data under "userId" , so I cannot get "userId".

But it is not always happened.

Please let me know if you need any more detail.

Thank you.

Preview image is not updated

Hello I am trying to send an image data in my server to user. I have a static link to read the image. However we always update the image with different image with the same filename (overwrite). The original image file shows the right ones, but the preview always shows the first image (not updated version), but after I check in my server, both of the images have been updated.
How to force line to read again the preview image even the link is same?

I have 2 problem from webhook

  1. webhook url verify success
    but I'm not know that how I get userID like https://devdocs.line.me/en/#bot-api-get-profile

  2. if I write /callback that

@app.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']

    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)
    
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)

    return 'OK'

Bot is running normal. but webhook url can't verify

and when I insert method 'GET' into /callback ..

@app.route("/callback", methods=[**'GET',**'POST'])
def callback():
    signature = request.headers['X-Line-Signature']

    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    if request.method=='GET':
        return 'ok get'
    elif request.method=='POST':
        return 'ok post'

    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)

    return 'OK'

Bot is not running but webhook url can verify success.

I so confuse :(

Please help me. Thanks.

Environment variable.

How to fix this?

Specify LINE_CHANNEL_SECRET as environment variable.

cmd

My config like this

cmd 2

Text Message ContentMetadata

Is it possible to get the uid of anyone tagged in a message? (stored in the contentMetadata) - and if its not possible (i dont think it is) can it be added by any chance?

RichMenu is not display

Hi
I created a rich menu, but I can't see anymore at line

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)

I got error message "LineBotApiError [Not found]"

I use the following simple code to test my line userid and push message.

from linebot import LineBotApi
from linebot.models import TextSendMessage

line_bot_api = LineBotApi('mytoken')
#push message to one user
profile = line_bot_api.get_profile('my line user id')

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

line_bot_api.push_message('my line user id', TextSendMessage(text='Hello World!'))

I am pretty sure this id is correct because I use the other account in the same way can work.

However, this account will be an error message.(linebot.exceptions.LineBotApiError: <LineBotApiError [Not found]>) I also confirm that the settings are exactly the same.

Could you give me some advice?

Many thanks

how to send a message twice

How to send a message twice and pop up a new message bubble.

I've tried with "\ n" but it does not bring up a new message balloon.

Enhancement request: Join/Leave Event on Users

Hi @be-hase / @GuitarSucks

Currently, Join/Leave events are based on self. In other words, when Bot itself joins/leaves a group/room, it will receive the Join/Leave event.

The functionality my application is looking for, is Join/Leave events based on users. This means when a new user joins a group/room (in which Bot is present), Bot gets an event (preferably, this event includes userID of new user). This way, Bot can issue welcome message to the group/room, and give introductory instructions to new joins.

Will you consider this enhancement request? Thank you.

Difficulty parsing sources to gather my followers userids

I want to send a multicast message but can't figure out the syntax to do so.

I wanted to use WebHookParser but it's not being recognized when imported.

How could I do this using webhook handler?

Everytime I try:
'@handler.add(Source, message=TextMessage)
def handle_message(source):
line_bot_api.multicast(
event.source.userid,
TextSendMessage(text="hey")`

I know that's obviously wrong for both multicast and push messages. I'm new to this and could use help on the syntax. It would be helpful to create a code that prints specific pieces of parsed data I ask for.

I have tried a lot of variations similar to the kitchensink example here: https://github.com/line/line-bot-sdk-python/blob/master/examples/flask-kitchensink/app.py

I have another script that will trigger the multicast message. I just don't know how to gather up all of my users ids.

Any help would be appreciated, thank you.

Follow event on Join invite?

I am using v1.0.2 with the kitchenSink example.
My JoinEvent handler is

@handler.add(JoinEvent)
def handle_join(event):
    wplog.logger.info("Got join event")
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text='Joined this ' + event.source.type))

In a group chat between user ABC and bot, sequence of events:

  1. User ABC send invite to user DEF
  2. Bot sees Join Event and says "Joined this group"
  3. 5 mins later, user DEF accepts invite and joins group
  4. User DEF did not see Bot's msg "Joined this group"

In this correct? Why?

My expectation is:

  1. User ABC send invite to user DEF
  2. 5 mins later, user DEF accepts invite and joins group
  3. Bot sees Join Event and says "Joined this group" (a welcome msg)
  4. User DEF sees Bot's msg "Joined this group" (a welcome msg)

Thank you.

Clarification on using Messaging API with Business Accounts

Today, we support the API of Business Accounts to create a bot (old BOT API): https://developers.line.me/businessconnect/development-bot-server and it works great. We refresh the tokens as it is specified in the documentation.

Now, we are integrating with Messaging API. Messaging API seems to not need to refresh any token unless you use the Social API, and I am not sure if we should still be using any of the Business Connect API endpoints.

Is the new Messaging API spec the standard for all accounts to create a bot?

README typo

The second LocationMessage in the part "Webhook event object" should be StickerMessage

Why I can't reply the carousel template message, I can't figure out what's wrong

Hi, I'm trying to reply the carousel template message. However the Line API keep telling me that my message is invalid. Here is the log:

File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functionsrule.endpoint
File "button.py", line 33, in callback
handler.handle(body, signature)
File "/usr/local/lib/python2.7/dist-packages/linebot/webhook.py", line 227, in handle
func(event)
File "button.py", line 98, in handle_text_message
line_bot_api.reply_message(event.reply_token, carousel_template_message)
File "/usr/local/lib/python2.7/dist-packages/linebot/api.py", line 94, in reply_message
'/v2/bot/message/reply', data=json.dumps(data), timeout=timeout
File "/usr/local/lib/python2.7/dist-packages/linebot/api.py", line 262, in _post
self.__check_error(response)
File "/usr/local/lib/python2.7/dist-packages/linebot/api.py", line 271, in __check_error
raise LineBotApiError(response.status_code, error)
LineBotApiError: <LineBotApiError [A message (messages[0])\xa0in the request body is invalid]>

And here's my code:

carousel_template_message = TemplateSendMessage(
            alt_text='Carousel template',
            template=CarouselTemplate(
                columns=[
                    CarouselColumn(
                        title='this is menu1', text='description1',
                        actions=[
                            MessageTemplateAction(
                                label='message1', text='message text1'
                            ),
                            MessageTemplateAction(
                                label='message1', text='message text1'
                            ),
                            MessageTemplateAction(
                                label='message1', itext='message text1'
                            )
                        ]
                    ),
                    CarouselColumn(
                        title='this is menu2', text='description2',
                        actions=[
                            MessageTemplateAction(
                                label='message2', text='message text2'
                            ),
                            MessageTemplateAction(
                                label='message2', text='message text2'
                            ),
                            MessageTemplateAction(
                                label='message2', text='message text2'
                            )
                        ]
                    ),
                    CarouselColumn(
                        title='this is menu3', text='description2',
                        actions=[
                            MessageTemplateAction(
                                label='message3', text='message text3'
                            ),
                            MessageTemplateAction(
                                label='message3', text='message text3'
                            ),
                            MessageTemplateAction(
                                label='message3', text='message text3'
                            )
                        ]
                    )
                ]
            )
        )
 line_bot_api.reply_message(event.reply_token, carousel_template_message)

BTW ButtonsTemplate can reply well, but CarouselTemplate can't.

How are y'all deploying this? I can't figure out the syntax to deploy on heroku. I would love any help to get a callback url to paste to collect user ids and push messages. Thank!

Do this before creating an issue

  • Check the FAQ for LINE bots
  • Make sure your issue is related to the LINE Bot SDK. For general questions or issues about LINE bots, create an issue on the FAQ repository. Note that we don't provide technical support.

When creating an issue

  • Provide detailed information about the issue you had with the SDK
  • Provide logs if possible

What is the <to> in push_message command in Messaging API?

Hi, I'm new to Line Messanger and Messaging API of line-bot-SDK-python.

I have tried to use the push_message command in Messaging API in order to send messages to my friends, but I can't send messages. How to get the , ID of the receiver, of my friends, groups, rooms? Where can I see those informations? What is ID of the receiver?

Thanks.

Question about tagged group members

Best I can tell, there is no way to enable the 'tagging' feature through the API such that by adding @username the group member is alerted as being 'mentioned in a post'...
Is anyone aware of a way to do this through the API/this SDK?

Feel free to remove this question if it's totally off topic.
Thanks!

Line API Keep Telling me that my message is invalid, but I can't figure out what's wrong

Here's the dump. It's a Carousel. I'm pretty sure its within the max length of anything and I provided everything that's not optional. Thanks

{"altText": "Choose who to kill by typing '/ww act 3' by using the ids below\n8\t : Iklil Nur\n3\t : Rizqi Nur\n19\t : Juang\n7\t : A. M. Hafidz", "template": {"columns": [{"actions": [{"label": "Iklil Nur", "text": "/ww act 8 3", "type": "message"}, {"label": "Rizqi Nur", "text": "/ww act 3 3", "type": "message"}, {"label": "Juang", "text": "/ww act 19 3", "type": "message"}], "text": "Choose who to kill", "thumbnailImageUrl": null, "title": null}, {"actions": [{"label": "A. M. Hafidz", "text": "/ww act 7 3", "type": "message"}], "text": "Choose who to kill", "thumbnailImageUrl": null, "title": null}], "type": "carousel"}, "type": "template"}

The error message was "A message (messages[0]) in the request body is invalid"

Audio output is not consistent with audio input

I'm trying to send audio message via Line. The message was successfully sent from Line app. Then I get the binary via chunking. But it's weird that the binary output doesn't give the same voice as the original one. Any idea?

Cannot adjust imageAspectRatio.

Hi,
I cannot change imageAspectRatio to sqaure for carousel. It looks like code in here is differece with code from pip install.

Thank you in advance.

Cannot Retrieve image sent by line users.

Situation:
I sent a image to the bot that I built,but the bot cannot recv my image.

I use the method as follows:

message_content = line_bot_api.get_message_content(message_id)
file_path = "C:\workplace\ngrok-line-bot\message\image\1.png"
with open(file_path,'wb') as fd:
	for chunk in message_content.iter_content():
		fd.write(chunk) 

Result:
the image cannot be sent and my bot also cannot recv.


I'm looking forward for your answer. Thank you :D

pip3 install line-bot-sdk error

#sudo pip3 install line-bot-sdk
Collecting line-bot-sdk
Using cached line_bot_sdk-1.5.0-py2.py3-none-any.whl
Collecting future (from line-bot-sdk)
Using cached future-0.16.0.tar.gz
Complete output from command python setup.py egg_info:
/opt/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'entry_points'
/opt/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'include_package_data'
/opt/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'install_requires'
/opt/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'test_suite'
/opt/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'tests_require'
usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: -c --help [cmd1 cmd2 ...]
or: -c --help-commands
or: -c cmd --help

error: invalid command 'egg_info'

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-1djsaejn/future/

Sending Images using reply_message function

Hello,

How do you reply with an text message and image message. I have tried using the ImageSendMessage class but i keep getting the same error. Just as a test i sent the url of a random 250x250 jpeg i found on the internet and that did not work.

Here is the traceback

Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.5/dist-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functionsrule.endpoint
File "./main.py", line 76, in callback
preview_image_url=eikoImageResponce
File "/usr/local/lib/python3.5/dist-packages/linebot/api.py", line 94, in reply_message
'/v2/bot/message/reply', data=json.dumps(data), timeout=timeout
File "/usr/local/lib/python3.5/dist-packages/linebot/api.py", line 230, in _post
self.__check_error(response)
File "/usr/local/lib/python3.5/dist-packages/linebot/api.py", line 239, in __check_error
raise LineBotApiError(response.status_code, error)
linebot.exceptions.LineBotApiError: <LineBotApiError [The request body has 2 error(s)]>

It says i have two errors in the request body, but I don't really know what they are. In the API reference (https://devdocs.line.me/en/#common-specifications) they show an error message with the summary I am receiving above, with the details included. Is there a way to display the details of the error?

Sent Photos Are Not Displaying for Those Using Data

I'm not entirely sure if this is the API or line settings.

I have an issue where a bot keyword triggers the bot to send a photo to the group. If the user is using solely data, the photo either displays an incorrect photo or doesn't load at all. The photos are displayed perfectly for those who are using wifi.

Is there any insight on this? I'm sure it could be a whole host of reasons. One odd thing is that screenshots and other photos sent manually by users are being displayed fine under data. It's only images sent by the bot that are causing problems.

Thanks for the help.

Has anyone figured out how to properly post an image?

I have tried absolutely everything to take a https png url, download it, convert it to the proper sizes, and return it as a jpg. Even taking a small 200px x 200px jpg image and trying to return it just results in the image url being displayed.

Want to make sure its not a bug in the ImageSendMessage function before I drive myself crazy.

bers

Do this before creating an issue

  • Check the FAQ for LINE bots
  • Make sure your issue is related to the LINE Bot SDK. For general questions or issues about LINE bots, create an issue on the FAQ repository. Note that we don't provide technical support.

When creating an issue

  • Provide detailed information about the issue you had with the SDK
  • Provide logs if possible

InvalidSignatureError exception raised

Hi, I'm trying to run simple bot echo script. However the bot didn't received my message and it simply returning InvalidSignatureError. Here is the debug:

[2017-02-16 22:55:13,415] ERROR in app: Exception on /callback [POST] Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request()
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args)
File "bot.py", line 60, in callback print parser.parse(body, signature)
File "/usr/local/lib/python2.7/site-packages/linebot/webhook.py", line 124, in parse 'Invalid signature. signature=' + signature)
InvalidSignatureError: <InvalidSignatureError [Invalid signature. signature=Tt4HKTuQmW/Fzg+y35GEazfK7t9au90BUBwo6+9DCHU=]>

I suspect that it related to the signature check mechanism because I ran the script in local tunneled via ngrok.io. Is that really the problem?

Repeated error message.

I started from a fresh LAMP stack on Ubuntu 16.04, updated it and installed the latest version of pip.
Then I installed the line bot sdk, and all the requirements.
I made a new file, test.py and copy pasted the echobot script into it, changing the channel access token and secret. I also changed the app.run() to app.run(host="myip",port=443) since the webhook url i gave was https://myip:443/.
I ran this, and repeatedly got the same error code:

203.104.146.154 - - [22/Nov/2017 02:44:07] code 400, message Bad HTTP/0.9 request type ('\x16\x03\x03\x00\x82\x01\x00\x00~\x03\x03Z\x14\xe4w\xca\x12\xc4$\xae\xaa\xcb\x02\x1bF*\xa2S/\x11\xcd\\w\x0e~.\x03\xb2')
203.104.146.154 - - [22/Nov/2017 02:44:07] "▒~Z▒w▒▒$▒▒▒*▒S/▒\w~.▒
                                                                 ▒6▒,▒+▒/▒▒▒/5E" 400 -

Not quite sure what to do tho, and any help would be appreciated.

Bobot

Do this before creating an issue

  • Check the FAQ for LINE bots
  • Make sure your issue is related to the LINE Bot SDK. For general questions or issues about LINE bots, create an issue on the FAQ repository. Note that we don't provide technical support.

When creating an issue

  • Provide detailed information about the issue you had with the SDK
  • Provide logs if possible

NameError: name 'TextSendMessage' is not defined

i only want to use push mesagee
when i test push message

Traceback (most recent call last):
File "<pyshell#2>", line 1, in
line_bot_api.push_message('u307947f4bsdfedff2sdf04c81f39a89ed07',TextSendMessage(text='Hello World!'))
NameError: name 'TextSendMessage' is not defined

what's problem
thanks!

What type of Messaging API plan support push message?

I am trying out Messaging API and couldn't get push_message to work. Is there a specific type of Messaging API that support push_message. It seems I can only reply message.

Here is my error message.
{"message":"Access to this API is not available for your account"}

Issue with SSL: required for all webhooks, but when it's plugged into Flask examples, it doesn't work

Hello,

Current Line API appears to require SSL for all webhooks (i.e. not just webhook URL verification). When I set up a working SSL context for Flask (see below), with a valid certificate chain from Let's Encrypt (root CA ISRG which is trusted by Line API), nothing appears to happen.

If I launch the examples (e.g. Flash echo bot) as is, I get HTTPS negotiation requests from Line API (Flask/Werkzeug complains as it's basically unexpected binary data, and can't handle it). However, if I set up a working HTTPS with a valid certificate (not self-signed), no webhook events are reported - I think Line API drops the connection since it is not satisfied with the HTTPS negotiation, but I'm yet to find a way for Werkzeug/whatever to debug-level report me all connection initiation attempts and how they look like:

        import ssl
        ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        ctx.load_cert_chain('pb1.mkj.lt/cert.pem', 'pb1.mkj.lt/privkey.pem')
        app.run(debug=options.debug, host="0.0.0.0", port=int(options.port), ssl_context=ctx)

This runs fine, but no webhooks are reported from the Line API. The webhook URL verification on Line Manager also fails without further explanation.

How should this be done, and is there a way to debug SSL issues / get info from Line API what fails in particular?

Thank you!
Kostas

P.S. I've also just tried with ssl.PROTOCOL_TLSv1_2 - same result.

Script bot

Do this before creating an issue

  • Check the FAQ for LINE bots
  • Make sure your issue is related to the LINE Bot SDK. For general questions or issues about LINE bots, create an issue on the FAQ repository. Note that we don't provide technical support.

When creating an issue

  • Provide detailed information about the issue you had with the SDK
  • Provide logs if possible

Images do not show up on the desktop client

Ive properly formatted the images according to the API specs and images display perfectly fine on mobile, tablet, and chrome app versions of line but no desktop client on any platform is able to view images.

Really not sure where ive gone wrong...

create an ubuntu 16.04 server running a LAMP stack (from DigitalOcean)
link the domain name doodspav.com to the server

update and install pip
$ sudo apt-get update && sudo apt-get -y upgrade
$ sudo apt-get install python-pip
$ pip install --upgrade pip`

update and install SSL certificate
(from certbot.eff.org)
$ sudo apt-get install software-properties-common $ sudo add-apt-repository ppa:certbot/certbot $ sudo apt-get update $ sudo apt-get install python-certbot-apache $ sudo certbot --apache

install line-bot-sdk and dependancies
$ pip install future $ pip install --upgrade requests $ pip install line-bot-sdk $ pip install --upgrade pyopenssl $ pip install flask

create line.py
(I've replaced the Channel Secret and Access Token)
Also i have no idea why i import OpenSSL

from flask import Flask, request, abort
from OpenSSL import SSL
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
)
app = Flask(name)
line_bot_api = LineBotApi('CHANNEL_ACCESS_TOKEN')
handler = WebhookHandler('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))
context = ("/etc/letsencrypt/live/doodspav.com/fullchain.pem","/etc/letsencrypt/live/doodspav.com/privkey.pem")
if name == "main":
app.run(host="0.0.0.0",port=5000,ssl_context=context)

i've put the webhook url as doodspav.com:5000/
then run the script

sudo ufw allow 5000
python line.py

this is the printed response on my server whenever i send a message in a chat with the bot:
my_ip - - [24/Nov/2017 22:20:09] "POST / HTTP/1.1" 404 -

i'm honestly not sure what to do since it looks like other peoples code

emoji(Sticons) do not show up on the Line client

problem

Line user sends emoji(sticons) to my bot, and my bot return the same emoji(sticons).
But, the emoji(sticons) cannot show up.

It shows it's sysbol code, like (clov)(clov)(thinking of him)(Moon cool)

codes

line_bot_api.reply_message( event.reply_token, TextSendMessage(text= message_text))

logs

..."message":{"type":"text","id":"6521045438173","text":"(clov)(clov)(thinking of him)(Moon cool)"}}]}

Content Bot for Home posts

Hello,

I'm new to working with Line, but I want to create a Bot that can read the Home messages (public profile) of a user and eventually can download those contents. I looked through the Messaging API and Social API but couldn't find anything related to the home profile. So my questions are can I handle the home page as a room/channel? Are there any related information that could help me with this project or is the idea entirely impossible?

I really appreciate any help you can provide.

Add datetime picker support

With the datetime picker template action, you can provide an easy way for users to pick a date and time without having to type it in manually. The datetime picker action can be used in any type of template message and returns a postback event when the action is tapped.

Note: The datetime picker action is supported on LINE app versions iOS 7.9.0 and Android 7.12.0 and higher.

https://developers.line.me/news?ny=2017&nm=09

Y

Do this before creating an issue

  • Check the FAQ for LINE bots
  • Make sure your issue is related to the LINE Bot SDK. For general questions or issues about LINE bots, create an issue on the FAQ repository. Note that we don't provide technical support.

When creating an issue

  • Provide detailed information about the issue you had with the SDK
  • Provide logs if possible

some user or group id is None

First of all, I'm sorry my English is very bad

My bot gets some user or group id is None
This error is not accidental
None values for users or groups are always None
This problem caused me to be unable to identify who my users are

Webhook URL cannot be verified.

I use the codes in my project directly and I deploy my project onHeroku successfully.

The codes what I use is:

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')   #I put my 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()

But the error appeared like that:

https://intense-anchorage-90708.herokuapp.com/callback
A http status of the response was '500 INTERNAL SERVER ERROR'.

I need your help. Thanks a lot.

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.