dxiwaicosmo2023
@dxiwaicosmo2023

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

LINE WORKS API エンドポイントにあたるAPI_IDがわからなくて困っています

解決したいこと

LINE WORKS APIを使って、既存のBotから簡単なメッセージを自分のIDに受信できるようにしたいのですが、エンドポイントにあたるAPI_IDというのが、LINE WORKSのデベロッパーコンソールのどの情報がAPI_IDなのかわかりません。わかる方がいたら教えてください。

発生している問題・エラー

url = f'https://apis.worksmobile.com/r/{api_id}/message/send'
例)下記のpythonのエンドポイントの「YOUR_API_ID」どうしてもわからない。LINE WORKS Developers コンソールを見てもどこに書いてあるのかわからない。
import requests
import json

# 生成したトークン
token = '◎◎◎'

# APIエンドポイント
api_id = 'YOUR_API_ID'  # 自分のAPI IDに置き換えてください
url = f'https://apis.worksmobile.com/r/{api_id}/message/send'

# ヘッダー
headers = {
    'Authorization': f'Bearer {token}',
    'Content-Type': 'application/json'
}

# メッセージ送信のペイロード
payload = {
    "botNo": 12345,  # Bot番号に置き換えてください
    "accountId": "recipient_account_id",  # 受信者のアカウントIDに置き換えてください
    "content": {
        "type": "text",
        "text": "Hello, this is a test message!"
    }
}

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

# レスポンスの表示
print(response.status_code)
print(response.json())

自分で試したこと

下記のコードでトークンを生成しました。

from jose import jwt
import datetime

# 秘密鍵のパスを設定
SECRET_KEY = r'C:\Users\◎◎◎\Desktop\pythondesu\private_◎◎◎.key'
client_id = '◎◎◎'
service_account_id = '◎◎◎'

# 秘密鍵を読み込む
with open(SECRET_KEY, 'r') as f:
    private_key = f.read()

# 現在のタイムスタンプをUTCタイムゾーンで取得
current_time = int(datetime.datetime.now(datetime.timezone.utc).timestamp())

# JWTのペイロードを設定
payload = {
    'iss': client_id,
    'sub': service_account_id,
    'iat': current_time,
    'exp': current_time + 3600  # 有効期限を1時間後に設定
}

# JWTトークンを生成
token = jwt.encode(payload, private_key, algorithm='RS256')

# 生成したトークンを表示
print(f'Generated Token: {token}')

0

1Answer

↑「API 2.0 では API ID は使用しません」とあります。
 間違っていたらごめんなさい。

1Like

Comments

  1. すごい。ありがとうございます。
    API2.0は仕様が変わっていたのですね。本当に助かりました。
    さらに続いて質問なのですが、
    Botから自分のチャンネルID宛にメッセージを送りたいと思っており、LINE WORKS Developers コンソールで作成したBotLINE WORKS管理画面で公開をしました。
    生成したトークンには問題なく、下のpythonをただ、実行しただけなのですが、401エラーが返ってきます。何か見落としていることってあるのでしょうか?お分かりになる方がいらっしゃったら、アドバイスよろしくお願いします。

    import requests
    import json
    
    # 生成したトークンをここに設定
    token = 'YOUR_GENERATED_JWT_TOKEN'
    
    # APIエンドポイント
    bot_id = '7993940'  # 画像で確認したBot ID
    channel_id = '49074358'  # 画像で確認したチャンネルID
    url = f'https://www.worksapis.com/v1.0/bots/{bot_id}/channels/{channel_id}/messages'
    
    # ヘッダー
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    
    # メッセージ送信のペイロード
    payload = {
        "content": {
            "type": "text",
            "text": "Hello, this is a test message from API 2.0!"
        }
    }
    
    # リクエストの送信
    response = requests.post(url, headers=headers, data=json.dumps(payload))
    
    # レスポンスの表示
    print(response.status_code)
    print(response.json())
    

    ##返ってくるエラー

    401
    {'code': 'UNAUTHORIZED', 'description': 'Malformed authentication token'}
    

    mimamori.png

  2. エラーメッセージのとおり、「不正な認証トークン」では?

    ユーザーへの送信でも同じエラーでしょうか?
    https://www.worksapis.com/v1.0/bots/{botId}/users/{userId}/messages

  3. ↑ によると、User Account 認証Service Account 認証 があるようですが、いずれも、メッセージの送信の前に、認証シーケンスが必要と読めます。

  4. よくわかっていなくてすみません。つまりJWTで生成したトークンさえあればBOTとの連携に使えると思っていたのですが、認証シーケンスというのが必要なのですね。つまりアクセストークンが必要ということなのでしょうか?以下のようなpythonでの取得でしょうか?

    import requests
    
    # 生成したJWTトークンをここに設定
    jwt_token = 'YOUR_GENERATED_JWT_TOKEN'
    
    # アクセストークンを取得するためのエンドポイント
    auth_url = 'https://auth.worksmobile.com/oauth2/v2.0/token'
    
    # ヘッダー
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    
    # ボディデータ
    data = {
        'assertion': jwt_token,
        'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'scope': 'bot'
    }
    
    # アクセストークンの取得
    response = requests.post(auth_url, headers=headers, data=data)
    print(response.text)  # レスポンスの内容を表示
    response.raise_for_status()
    token_response = response.json()
    access_token = token_response['access_token']
    print(f'Access Token: {access_token}')
    

    ##その後はこれでやっとBotからユーザにメッセージを送れるのでしょうか?

    import requests
    import json
    
    # 取得したアクセストークンをここに設定
    access_token = 'YOUR_OBTAINED_ACCESS_TOKEN'
    
    # APIエンドポイント
    bot_id = '7993940'
    user_id = '****@*'
    url = f'https://www.worksapis.com/v1.0/bots/{bot_id}/users/{user_id}/messages'
    
    # ヘッダー
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    
    # メッセージ送信のペイロード
    payload = {
        "content": {
            "type": "text",
            "text": "Hello, this is a test message from API 2.0!"
        }
    }
    
    # リクエストの送信
    try:
        response = requests.post(url, headers=headers, data=json.dumps(payload))
        response.raise_for_status()
        print(response.status_code)
        print(response.json())
    except requests.exceptions.HTTPError as err:
        print(f"HTTP error occurred: {err}")
        print(response.status_code)
        print(response.text)
    except Exception as err:
        print(f"Other error occurred: {err}")
    
  5. ↓ こちらの記事は読まれましたか?

  6. ありがとうございます。0から始めるの記事をちゃんと読みました。理解ができました。以下のソースコードでやっとBotからメッセージを送ることができました。
    本当に助かりました。感謝いたします。

    import requests
    import json
    from jose import jwt
    import datetime
    
    # 設定
    SECRET_KEY = r'C:\Users\.key'
    client_id = 'BBBBBBBBBBBBBB'
    client_secret = 'AAAAAAAAAAAA'
    service_account_id = 'AAAAAAA@IIII'
    bot_id = 'UUUUUU'
    user_id = 'your@id'
    
    # 秘密鍵を読み込む
    with open(SECRET_KEY, 'r') as f:
        private_key = f.read()
    
    # JWTのペイロードを設定
    current_time = int(datetime.datetime.now(datetime.timezone.utc).timestamp())
    payload = {
        'iss': client_id,
        'sub': service_account_id,
        'iat': current_time,
        'exp': current_time + 3600  # 有効期限を1時間後に設定
    }
    
    # JWTトークンを生成
    jwt_token = jwt.encode(payload, private_key, algorithm='RS256')
    print(f'Generated Token: {jwt_token}')
    
    # アクセストークンを取得するためのエンドポイント
    auth_url = 'https://auth.worksmobile.com/oauth2/v2.0/token'
    
    # ヘッダー
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    
    # ボディデータ
    data = {
        'assertion': jwt_token,
        'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': 'bot'
    }
    
    # アクセストークンの取得
    response = requests.post(auth_url, headers=headers, data=data)
    print(response.text)  # レスポンスの内容を表示
    response.raise_for_status()
    token_response = response.json()
    access_token = token_response['access_token']
    print(f'Access Token: {access_token}')
    
    # メッセージの送信
    url = f'https://www.worksapis.com/v1.0/bots/{bot_id}/users/{user_id}/messages'
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    payload = {
        "content": {
            "type": "text",
            "text": "Hello, this is a test message from API 2.0!"
        }
    }
    
    # リクエストの送信
    try:
        response = requests.post(url, headers=headers, data=json.dumps(payload))
        response.raise_for_status()
        print(response.status_code)
        if response.headers.get('Content-Type') == 'application/json':
            response_json = response.json()
            print(response_json)
        else:
            print("Response content is not in JSON format")
            print(response.text)
    except requests.exceptions.HTTPError as err:
        print(f"HTTP error occurred: {err}")
        print(response.status_code)
        print(response.text)
    except Exception as err:
        print(f"Other error occurred: {err}")
    

Your answer might help someone💌