シンプルなメッセージをpythonで送りたいのだが、「Grant type is not supported」とエラーになってしまう

ic_2c21b7

2024.06.06既読 174

以下に記載したのが、APIをつかった簡単なpythonでメッセージを配信するコードです。
エラーとしてデバッグが
Grant type is not supportedと出てきます。dataとして送る値が間違っているのでしょうか?わかる方がいらっしゃったら教えてください。



1.pythonコード
import requests
# アクセストークンを取得する関数
def get_access_token(client_id, client_secret):
   url = "https://auth.worksmobile.com/oauth2/v2.0/token"
   headers = {
       "Content-Type": "application/x-www-form-urlencoded"
   }
   data = {
       "grant_type": "client_credentials",
       "client_id": client_id,
       "client_secret": client_secret,
       "scope": "bot"
   }
   response = requests.post(url, headers=headers, data=data)
   if response.status_code == 200:
       return response.json()["access_token"]
   else:
       raise Exception(f"Failed to obtain access token: {response.status_code}, {response.text}")
# メッセージを送信する関数
def send_message(access_token, api_id, bot_no, user_email, message):
   url = f"https://apis.worksmobile.com/r/{api_id}/message/v1/bot/{bot_no}/message/push"
   headers = {
       "Authorization": f"Bearer {access_token}",
       "Content-Type": "application/json"
   }
   data = {
       "botNo": bot_no,
       "accountId": user_email,
       "content": {
           "type": "text",
           "text": message
       }
   }
   
   response = requests.post(url, headers=headers, json=data)
   if response.status_code == 200:
       print(f"Message sent successfully to {user_email}")
   else:
       print(f"Failed to send message: {response.status_code}, {response.text}")
# メイン関数
def main():
   client_id = "**********"  # サービスアカウントのClient ID
   client_secret = "**********"  # サービスアカウントのClient Secret
   # アクセストークンを取得
   try:
       access_token = get_access_token(client_id, client_secret)
       print(f"Access Token: {access_token}")
       
       # メッセージを送信
       api_id = "********"  # API ID
       bot_no = "*******"  # Bot ID
       user_email = "********@*****"  # 送信先のユーザーのメールアドレス
       message = "Hello World!"  # 送信するメッセージ
       send_message(access_token, api_id, bot_no, user_email, message)
       
   except Exception as e:
       print(f"An error occurred: {e}")
if __name__ == "__main__":
   main()
2.デバッグ
python C:\Users\5032\Desktop\jikken10.py
An error occurred: Failed to obtain access token: 400, {"error_description":"Grant type is not supported.","error":"unsupported_grant_type","error_uri":"See document on https://developers.worksmobile.com/docs/auth-oauth"}


コメント0

前の投稿 修正方
次の投稿API:Security【外部ブラウザ設定の有効化】ができない
リスト

まだ、解決できませんか?
今すぐ実際に使用しているLINE WORKSユーザーに質問してみましょう。