LineworksのAPIドキュメントは以下になります
https://developers.worksmobile.com/jp/docs/introduction
今回はAPIの仕様がV2で変更になっていたようなので修正依頼を受け、その際の調査結果をメモしておきます
事前準備
まず必要な情報は以下になります。
client_id = "xxxx" client_secret = "xxxx" service_account_id = "xxxx.serviceaccount@xxxxx" bot_id = "111111" privatekey =
また認証情報作成には「pyjwt」というライブラリが必要なのでインストールしてください
!pip install pyjwt -q
アクセストークンの取得
APIを叩くための認証情報としてアクセストークンが必要になります
import jwt
from datetime import datetime
import urllib
import json
import requests
BASE_AUTH_URL = "https://auth.worksmobile.com/oauth2/v2.0"
def __get_jwt(client_id: str, service_account: str, privatekey: str) -> str:
"""Generate JWT for access token
:param client_id: Client ID
:param service_account: Service Account
:param privatekey: Private Key
:return: JWT
"""
current_time = datetime.now().timestamp()
iss = client_id
sub = service_account
iat = current_time
exp = current_time + (60 * 60) # 1 hour
jws = jwt.encode(
{
"iss": iss,
"sub": sub,
"iat": iat,
"exp": exp
}, privatekey, algorithm="RS256")
return jws
def get_access_token(client_id: str, client_secret: str, service_account: str, privatekey: str, scope: str) -> dict:
"""Get Access Token
:param client_id: Client ID
:param client_secret: Client ID
:param service_account: Service Account
:param privatekey: Private Key
:param scope: OAuth Scope
:return: response
"""
# Get JWT
jwt = __get_jwt(client_id, service_account, privatekey)
# Get Access Token
url = '{}/token'.format(BASE_AUTH_URL)
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
params = {
"assertion": jwt,
"grant_type": urllib.parse.quote("urn:ietf:params:oauth:grant-type:jwt-bearer"),
"client_id": client_id,
"client_secret": client_secret,
"scope": scope,
}
form_data = params
r = requests.post(url=url, data=form_data, headers=headers)
body = json.loads(r.text)
return body
# get_jwt(client_id, service_account_id, privatekey)
outh_data = get_access_token(client_id, client_secret, service_account_id, privatekey, scope='bot, bot.read')
access_token = outh_data['access_token']
print(access_token)
botに譲渡する権限するは’bot, bot.read’ みたいな感じで文字列で,区切りで指定します。
上記を実行するとアクセストークンが取得できます。
参照:https://qiita.com/mmclsntr/items/5ee3b7f2422b05bc256c
メッセージ送信(ユーザー)
参照: https://developers.worksmobile.com/jp/docs/bot-user-message-send
import json
import requests
# 送信内容
content = {
"content": {
"type": "text",
"text": "テストメッセージ" # 送信するテキスト内容
}
}
# 送信先
user_id = 'xxxx@xxxx'
BASE_API_URL = "https://www.worksapis.com/v1.0"
def send_message_to_user(content: dict, bot_id: str, user_id: str, access_token: str):
"""Send message to a user
:param content: Message content
:param bot_id: Bot ID
:param user_id: User ID
:param access_token: Access Token
"""
url = "{}/bots/{}/users/{}/messages".format(BASE_API_URL, bot_id, user_id)
headers = {
'Content-Type' : 'application/json',
'Authorization': 'Bearer ' + access_token
}
params = content
form_data = json.dumps(params)
print(url)
r = requests.post(url=url, data=form_data, headers=headers)
print(r,r.text)
r.raise_for_status()
send_message_to_user(content, bot_id, user_id, access_token)
print('メッセージを送信しました!')
メッセージ送信(ルーム)
ドキュメント: https://developers.worksmobile.com/jp/docs/bot-channel-message-send
import json
import requests
# 送信内容
content = {
"content": {
"type": "text",
"text": "hello" # 送信するテキスト内容
}
}
# 送信先
channel_id = '<チャンネルID>'
BASE_API_URL = "https://www.worksapis.com/v1.0"
def send_message_to_user(content: dict, bot_id: str, channel_id: str, access_token: str):
"""Send message to a user
:param content: Message content
:param bot_id: Bot ID
:param channel_id: channel ID
:param access_token: Access Token
"""
url = "{}/bots/{}/channels/{}/messages".format(BASE_API_URL, bot_id, channel_id)
# print("Bearer {}".format(access_token))
headers = {
'Content-Type' : 'application/json',
'Authorization': 'Bearer ' + access_token
}
params = content
form_data = json.dumps(params)
r = requests.post(url=url, data=form_data, headers=headers)
print(r,r.text)
r.raise_for_status()
send_message_to_user(content, bot_id, channel_id, access_token)
print('メッセージを送信しました')
固定メニュー作成
ドキュメント: https://developers.worksmobile.com/jp/docs/bot-persistentmenu-create#PersistentMenuActionStruct
import json
import requests
BASE_API_URL = "https://www.worksapis.com/v1.0"
def create_menu(content: dict, bot_id: str, access_token: str):
"""Send message to a user
:param content: Message content
:param bot_id: Bot ID
:param access_token: Access Token
"""
url = "{}/bots/{}/persistentmenu".format(BASE_API_URL, bot_id)
# print("Bearer {}".format(access_token))
headers = {
'Content-Type' : 'application/json',
'Authorization': 'Bearer ' + access_token
}
params = content
form_data = json.dumps(params)
r = requests.post(url=url, data=form_data, headers=headers)
print(r,r.text)
r.raise_for_status()
create_menu(
{
"content": {
"actions": [
{
"type": "message", #メニュータイプ
"label": "Example label", #項目に表示されるラベル
"text": "Example text",
"postback": "Example postback",
},
{
"type": "message", #メニュータイプ
"label": "Example label", # 項目に表示されるラベル
"text": "Example text",
"postback": "Example postback",
}, {
"type": "message", #メニュータイプ
"label": "Example label", # 項目に表示されるラベル
"text": "Example text",
"postback": "Example postback",
},
{
"type": "uri", #メニュータイプ
"label": "Example Homepage", # 項目に表示されるラベル
"uri": "https://example.com",
}
]
}
}
, bot_id, access_token)

コメント