dxiwaicosmo2023
@dxiwaicosmo2023

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

LINE WORKS API BOTから画像を貼り付けで送れないので困っています

LINE WORKS API のBOTから画像を送りたい

LINE WORKS APIを使って、Botからテキストを送ることはできるのですが、
画像を貼り付けて(ビジュアルが表示されている状態)送ることができません。
送られた結果は、画像の表示がされず、グレーの四角が表示されます。
添付という状態で送ることはできますが、それだとダウンロードしないと表示が確認できないので、スタンプのように、トーク上にペタッと貼り付けた画像として送りたいのです。
お分かりになる方がどうかアドバイスをいただけると助かります。どうぞよろしくお願いいたします。

このあたりの記述が違うのかもしれません

image_url = f"https://apis-storage.worksmobile.com/r/{file_id}"
import requests
import json
from jose import jwt
import datetime

# 設定
SECRET_KEY = r'C:\Users\◎◎◎\Desktop\pythondesu\private_◎◎◎.key'
client_id = '◎◎◎◎◎◎◎◎◎'
client_secret = '◎◎◎◎◎◎'
service_account_id = '◎◎◎◎◎◎@◎◎◎◎◎◎'
bot_id = '7993940'
channel_id = '◎◎◎-◎◎◎-◎◎◎-◎◎◎-◎◎◎'
image_file_path = r'C:\Users\◎◎◎\Desktop\pythondesu\logo.png'  # 画像ファイルのパスを指定

# 秘密鍵を読み込む
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)
response.raise_for_status()
token_response = response.json()
access_token = token_response['access_token']
print(f'Access Token: {access_token}')

# ファイルのアップロードURLを取得
upload_url_request = f'https://www.worksapis.com/v1.0/bots/{bot_id}/attachments'
headers = {
    'Authorization': f'Bearer {access_token}',
    'Content-Type': 'application/json'
}
payload = {
    "fileName": "logo.png"
}

response = requests.post(upload_url_request, headers=headers, data=json.dumps(payload))
response.raise_for_status()
upload_url_response = response.json()
upload_url = upload_url_response['uploadUrl']
print(f'Upload URL: {upload_url}')

# ファイルのアップロード
with open(image_file_path, 'rb') as f:
    files = {'file': f}
    response = requests.post(upload_url, headers={'Authorization': f'Bearer {access_token}'}, files=files)
    response.raise_for_status()
    file_response = response.json()
    file_id = file_response['fileId']
    print(f'Uploaded File ID: {file_id}')

# 画像プレビューURLとリソースURLの設定
image_url = f"https://apis-storage.worksmobile.com/r/{file_id}"

# メッセージの送信
message_url = f'https://www.worksapis.com/v1.0/bots/{bot_id}/channels/{channel_id}/messages'
headers = {
    'Authorization': f'Bearer {access_token}',
    'Content-Type': 'application/json'
}
payload = {
    "content": {
        "type": "image",
        "previewUrl": image_url,  # プレビューURLを指定
        "resourceUrl": image_url  # 実際のリソースURLを指定
    }
}

# リクエストの送信
try:
    response = requests.post(message_url, headers=headers, data=json.dumps(payload))
    response.raise_for_status()
    print(response.status_code)
    if 'application/json' in response.headers.get('Content-Type'):
        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}")

上記のソースコードを送った結果(グレーになってしまって灰色の四角をクリックすると対応していないファイルです。と表示される)

スクリーンショット 2024-06-14 103728.png

0

1Answer

自己解決しました。
以下がソースコードになります。

import requests
import json
from jose import jwt
import datetime

# 設定
SECRET_KEY = r'C:\Users\◎◎◎\Desktop\pythondesu\private_◎◎◎.key'
client_id = '◎◎◎◎◎◎◎◎◎'
client_secret = '◎◎◎'
service_account_id = '◎◎◎@◎◎◎'
bot_id = '7993940'
channel_id = '◎◎◎-◎◎◎-◎◎◎-◎◎◎-◎◎◎'
image_file_path = r'C:\Users\◎◎◎\Desktop\pythondesu\file.png'

# 秘密鍵を読み込む
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
}

# 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)
response.raise_for_status()
token_response = response.json()
access_token = token_response['access_token']
print(f'Access Token: {access_token}')

# ファイルのアップロードURLを取得
upload_url_request = f'https://www.worksapis.com/v1.0/bots/{bot_id}/attachments'
headers = {
    'Authorization': f'Bearer {access_token}',
    'Content-Type': 'application/json'
}
payload = {
    "fileName": "file.png"
}

response = requests.post(upload_url_request, headers=headers, data=json.dumps(payload))
response.raise_for_status()
upload_url_response = response.json()
upload_url = upload_url_response['uploadUrl']
print(f'Upload URL: {upload_url}')

# ファイルのアップロード
with open(image_file_path, 'rb') as f:
    files = {'file': f}
    response = requests.post(upload_url, headers={'Authorization': f'Bearer {access_token}'}, files=files)
    response.raise_for_status()
    file_response = response.json()
    file_id = file_response['fileId']
    print(f'Uploaded File ID: {file_id}')

# 画像メッセージの送信
message_url = f'https://www.worksapis.com/v1.0/bots/{bot_id}/channels/{channel_id}/messages'
headers = {
    'Authorization': f'Bearer {access_token}',
    'Content-Type': 'application/json'
}
payload = {
    "type": "message",
    "source": {
        "userId": service_account_id,
        "channelId": channel_id,
        "domainId": 1  # 必要なドメインIDを指定
    },
    "issuedTime": datetime.datetime.now().isoformat(),
    "content": {
        "type": "image",
        "fileId": file_id
    }
}

# リクエストの送信
try:
    response = requests.post(message_url, headers=headers, data=json.dumps(payload))
    response.raise_for_status()
    print(response.status_code)
    if 'application/json' in response.headers.get('Content-Type'):
        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}")


0Like

Comments

  1. 解決したのであれば、本問をクローズしましょう

Your answer might help someone💌