🅿️

PythonでLINE Messaging APIを使用する

に公開
4

この記事では、Pythonを使用してLINE Botからメッセージを送信するコードを公開します。linebot.v3.messaging モジュールを活用し、簡潔かつ効率的にLINEメッセージを送るプログラムです。

import os
import linebot.v3.messaging as bot
from dotenv import load_dotenv
load_dotenv()

# LINE_BOT_ACCESS_TOKENは、Messaging API設定のチャネルアクセストークン
LINE_BOT_ACCESS_TOKEN = os.getenv('LINE_BOT_ACCESS_TOKEN')
# LINE_USER_ID は チャネル基本設定の”あなたのユーザーID”
LINE_USER_ID = os.getenv('LINE_USER_ID')

configuration = bot.Configuration(
    access_token=LINE_BOT_ACCESS_TOKEN
)

message_dict = {
    "to": LINE_USER_ID,
    "messages": [
        {"type": "text", "text": "Hello, world1"},
        {"type": "text", "text": "Hello, world2"}
    ]
}

with bot.ApiClient(configuration) as api:
    api_instance = bot.MessagingApi(api)
    push_message_request = bot.PushMessageRequest.from_dict(
        message_dict)
    try:
        res = api_instance.push_message(push_message_request)
        print("Successful sending!!")
        print(res)
    except Exception as e:
        print(f"Exception : {e}")

https://developers.line.biz/ja/reference/messaging-api/#send-push-message
https://github.com/line/line-bot-sdk-python?tab=readme-ov-file

Discussion

sweet_melonsweet_melon

はじめまして。
ラズベリーパイを買い替えたところV3になってしまい、奮闘しているところで拝見しました。
'LINE_BOT_ACCESS_TOKEN'と'LINE_USER_ID'を私のものに書き換え実行してもエラーが出てしまいます。
以下です。

Traceback (most recent call last):
File "/home/pi/linetast.py", line 24, in <module>
with bot.ApiClient(configuration) as api:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/pi/.local/lib/python3.11/site-packages/linebot/v3/messaging/api_client.py", line 77, in init
self.default_headers['Authorization'] = 'Bearer ' + configuration.access_token
^~~~~~~~~~~~~~~~~~
TypeError: can only concatenate str (not "NoneType") to str

お手数ですがご教授いただけますと幸いです。
よろしくお願いいたします。

sweet_melonsweet_melon

申し訳ありません、同様のエラーなのです。
os.getenvを除くとエラーなく送信できるのですが、、、何故か自分にしか届きません。
友達全員に配信したいのですが、どこがいけないのでしょうか。
よろしくお願いいたします。

sweet_melonsweet_melon

すみません、また自己解決いたし、完成しました。
これからも参考にさせていただきます。