0
1

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 Messaging API

Posted at

LINE Messaging APIを使用したPythonメッセージ送信スクリプト

概要

このスクリプトは、LINE Messaging APIを使用してPythonからLINEにメッセージを送信する方法を示します。

コード

import requests
import json

##############
###LINE BOT###
##############

line_access_token = 'YOUR_ACCESS_TOKEN_HERE'
line_id = 'YOUR_LINE_ID_HERE'  # ユーザーIDまたはグループID

def send_line_message(access_token, line_id, message):
    """
    LINE Messaging APIを使用してメッセージを送信する関数

    Parameters:
        access_token (str): LINE Botのアクセストークン
        line_id (str): 送信先のユーザーIDまたはグループID
        message (str): 送信するメッセージ
    """
    url = 'https://api.line.me/v2/bot/message/push'

    # ヘッダーにアクセストークンを設定
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {access_token}'
    }

    # 送信するデータ(メッセージ内容と送信先ID)
    payload = {
        'to': line_id,
        'messages': [
            {
                'type': 'text',
                'text': message
            }
        ]
    }

    # POSTリクエストを送信
    response = requests.post(url, headers=headers, data=json.dumps(payload))

    # 結果を表示
    if response.status_code == 200:
        print("メッセージが正常に送信されました。")
    else:
        print(f"メッセージ送信に失敗しました。ステータスコード: {response.status_code}, 内容: {response.text}")

# 関数を呼び出してメッセージを送信
send_line_message(access_token=line_access_token, line_id=line_id, message="テストメッセージ")

解説

必要な準備

  1. requestsjsonライブラリをインストールする必要があります
  2. LINE Developersコンソールからアクセストークンを取得

主な機能

  • LINE Messaging APIを使用したメッセージ送信
  • エラーハンドリング付きのメッセージ送信関数

注意点

  • line_access_tokenは必ず非公開にしてください
  • 送信先のline_idは正確に設定してください

使用上の注意

  • LINE Messaging APIの利用規約を遵守してください
  • 個人情報の取り扱いには十分注意してください
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?