LoginSignup
1
0

LINE WORKS の Contact API で連絡先データを取得する Python コード サンプル

Last updated at Posted at 2023-12-19

LINE WORKS は一般の LINE ユーザーや LINE WORKS の他テナントのユーザーともやり取りできます。

それらの外部ユーザーの情報は連絡先データに格納されています。

ここでは LINE WORKS の Contact API で連絡先データを取得する Python コードのサンプルを紹介します。

以下の API を利用します。
TITLE: 連絡先リストの取得
URL: https://developers.worksmobile.com/jp/docs/contact-list?lang=ja

このスクリプトでは、各連絡先の「姓」、「名」、「外部ユーザーID」、「外部ユーザータイプ」を抽出し、カンマ区切りの形式で 1 行ずつ出力します。

用途に応じて、必要な情報を適宜に出力してください。

実際のアクセストークンをコードに設定し、ローカル環境やクラウドベースのPython環境でスクリプトを実行します。

import requests

# アクセストークンとその他の初期設定
access_token = 'YOUR_ACCESS_TOKEN'  # ここに実際のアクセストークンを設定
url = "https://www.worksapis.com/v1.0/contacts"
headers = {'Authorization': f'Bearer {access_token}'}

params = {
    'count': 100,  # 1回のリクエストで取得する連絡先の数
}

all_contacts = []  # すべての連絡先を格納するリスト

while True:
    response = requests.get(url, headers=headers, params=params)
    if response.status_code != 200:
        print("Error:", response.status_code, response.text)
        break

    data = response.json()
    all_contacts.extend(data.get('contacts', []))

    # nextCursorが存在しない場合はループを終了
    next_cursor = data.get('responseMetaData', {}).get('nextCursor')
    if not next_cursor:
        break

    # nextCursorをパラメータに設定して次のリクエストを準備
    params['cursor'] = next_cursor

# 各連絡先の特定フィールドをカンマ区切りで出力
for contact in all_contacts:
    last_name = contact.get('contactName', {}).get('lastName', '')
    first_name = contact.get('contactName', {}).get('firstName', '')

    linked_external_user = contact.get('linkedExternalUser')
    if linked_external_user is not None:
        external_user_id = linked_external_user.get('id', '')
        external_user_type = linked_external_user.get('type', '')
    else:
        external_user_id = ''
        external_user_type = ''

    print(f"{last_name}, {first_name}, {external_user_id}, {external_user_type}")

1
0
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
1
0