6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

line-bot-sdk-python V3のコードサンプル

Last updated at Posted at 2024-03-13

はじめに

慣れないpythonでLINEBotを作ろうとして、line-bot-sdk-pythonを使っていましたが、公式ドキュメントのサンプルが2024年3月時点で全然整備されていないので、最新版のV3のコードサンプルを自分用にまとめます。

パパッと作りたい人は以下参考にしてみてください

コードサンプル

試したものから随時追加していきます。

共通部分

from linebot.v3.messaging import (
    Configuration,
    ApiClient,
    MessagingApi,
)
configuration = Configuration(access_token=CHANNEL_ACCESS_TOKEN)
 with ApiClient(configuration) as api_client:
        line_bot_api = MessagingApi(api_client)
        ## ここから下はそれぞれ

reply_message

from linebot.v3.messaging import (
    ReplyMessageRequest,
    TextMessage,
)
message=TextMessage(text='返信メッセージ')

line_bot_api.reply_message_with_http_info(
            ReplyMessageRequest(
                reply_token=event.reply_token,
                messages=[message]
            )
        )

quick_reply

from linebot.v3.messaging import (
    ReplyMessageRequest,
    TextMessage,
    QuickReply,
    QuickReplyItem,
    MessageAction
)
items = [
    QuickReplyItem(
        action=MessageAction(
            label="Ruby",
            text="Rubyが好き"
        )
    ),
    QuickReplyItem(
        action=MessageAction(
            label="Python",
            text="Pythonが好き"
        )
    )
]
quick_reply = QuickReply(items=items)

message=TextMessage(text='返信メッセージ', quickReply=quick_reply)

line_bot_api.reply_message_with_http_info(
            ReplyMessageRequest(
                reply_token=event.reply_token,
                messages=[message]
            )
        )

クイックリプライでは他にも以下のアクションが使える。

  • Postback action
  • URI action
  • Datetime picker action
  • Camera action
  • Camera roll action
  • Location action
  • Richmenu Switch Action
  • Clipboard action

対応するクラスが以下に _action.pyというファイル名でまとめてあるので、対応するものを使う
https://github.com/line/line-bot-sdk-python/tree/master/linebot/v3/messaging/models

参考

send_message

from linebot.v3.messaging import (
    PushMessageRequest,
    TextMessage,
)
message=TextMessage(text='送信メッセージ')

line_bot_api.push_message_with_http_info(
            PushMessageRequest(
                to='送信先のID',
                messages=[message]
            )
        )

参考記事

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?