Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

PythonでJWT生成からボット作成、投稿までやってみた

2,398 views

Published on

2019/2/18 LWUG :: Developers #1 Bot!Motto! LT資料

Published in: Software
  • Be the first to comment

PythonでJWT生成からボット作成、投稿までやってみた

  1. 1. 1 / 78 1 ( ) ( ( 0- 35 78 1 ( ) ) ( 24 : 3 = 01 1 : 1 = : = :. 1 /: 0:/? 1 2 I
  2. 2. def lambda_handler(event, context): print("-start--------------------------------------------------- --") global API_TOKEN API_TOKEN = get_server_token() # Bot bot_title = " " bot_description = " " manager_list = [“ ID1@ "] BOT_NO = regist_bot(bot_title, bot_description, manager_list) # Bot regist_bot_domain(BOT_NO) # Bot account_id_list = [‘ ID1 ', ' ID2 '] # set_member_list(BOT_NO,account_id_list) # room_description = " " ROOM_ID = create_room(BOT_NO, account_id_list, room_description) message_text=" " # send_text_message(BOT_NO, "", ROOM_ID,message_text) # # ACCOUNT_ID=" ID1@ " # send_text_message(BOT_NO,ACCOUNT_ID,"",message_text) # Bot leave_room(BOT_NO, ROOM_ID) # Bot # remove_list=[1234,5678,9012] remove_list = [BOT_NO] for item in remove_list: remove_bot(item) print("-end-------------------------------------------- -----------")
  3. 3. # -*- coding:utf-8 -*- import json import requests import datetime as dt import base64 from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA API_ID = ”API ID " SERVER_ID = “ ID " KEY_FILE_NAME = “private_20181126205039.key” ← API_TOKEN = “” ←API ( ) SERVER_API_CONSUMER_KEY = “Server API Consumer Key " DOMAIN_ID = “Domain ID ” ←Developer Console ID
  4. 4. # def get_server_token(): global API_ID api_url = "https://authapi.worksmobile.com/b/"+API_ID+"/server/token" headers = { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", } payload = { "grant_type": "urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer", "assertion": jwt_create() } res = requests.post(api_url, headers=headers, params=payload) access_token = json.loads(res.text)["access_token"] print("API_TOKEN:"+access_token) return access_token
  5. 5. def jwt_create(): global SERVER_ID jwt_header = { "alg": "RS256", "typ": "JWT" } jwt_header_base64 = dict_to_base64str(jwt_header) json_claim_set = { # Server List(ID ) ID "iss": SERVER_ID, # JWT UNIX ( :msec) "iat": int(dt.datetime.now().strftime('%s')), # JWT UNIX ( :msec) 30 "exp": int((dt.datetime.now()+dt.timedelta(minutes=30)).strftime('%s')) } json_claim_set_base64 = dict_to_base64str(json_claim_set) # {header BASE64 }.{JSON Claim set BASE64 } plain_text = jwt_header_base64+"."+json_claim_set_base64 # print("plain_text:"+plain_text+"¥n") # BASE64 Unicode signature_base64 = sign_rsa(plain_text) # print("signature_base64:"+signature_base64+"¥n") # JWT jwt = plain_text + "."+signature_base64 # print("JWT:"+jwt+"¥n") return jwt # Unicode Unicode BASE64 def sign_rsa(message): global KEY_FILE_NAME key = RSA.importKey(open(KEY_FILE_NAME).read()) # Unicode message_byte = message.encode('utf-8') # digest = SHA256.new(message_byte) # PKCS signer = PKCS1_v1_5.new(key) # (The signature encoded as a string.:bytes string) signature = signer.sign(digest) # BASE64 Unicode return base64.urlsafe_b64encode(signature).decode('utf-8') # BASE64 Unicode def dict_to_base64str(dict): # dump_text = json.dumps(dict) # print("input:"+dump_text+"¥n") # Unicode BASE64 Unicode base64_text = base64.urlsafe_b64encode( dump_text.encode('utf-8')).decode('utf-8') # print("result:"+base64_text+"¥n") return base64_text
  6. 6. # Bot def regist_bot(talkbot_name, description, manager_list, photo_url="https://developers.worksmobile.com/favicon.png", use_group_join=False): resource = "/message/registerBot/v4" payload = { "name": talkbot_name, "photoUrl": photo_url, "description": description, "managerList": manager_list, "useGroupJoin": use_group_join, } res = call_server_api(resource, payload) botNo = json.loads(res)["botNo"] print("botNo:"+str(botNo)) return botNo
  7. 7. # API def call_server_api(resource, payload): global API_ID global API_TOKEN global SERVER_API_CONSUMER_KEY # LINE WORKS API API_URL = "https://apis.worksmobile.com/"+API_ID+resource headers = { "Content-Type": "application/json; charset=UTF-8", "consumerKey": SERVER_API_CONSUMER_KEY, "Authorization": "Bearer "+API_TOKEN, } r = requests.post(API_URL, headers=headers, data=json.dumps(payload)) return r.text
  8. 8. # Bot def regist_bot_domain(botNo, use_public=False, use_permission=False): global DOMAIN_ID resource = "/message/registerBotDomain/v3" # usePublic:Bot ( : true: ) # usePermission:Bot ( : true: ) # set_member_list() Bot payload = { "botNo": botNo, "domainId": int(DOMAIN_ID), "usePublic": use_public, "usePermission": use_permission, } res = json.loads(call_server_api(resource, payload)) result = str(res["code"])+" "+res["message"] print("regist_bot_domain:"+result) return result # Bot (regist_bot_domain) Bot (usePermission) true( ) account_id_list Bot(botNo) def set_member_list(botNo, account_id_list): global DOMAIN_ID resource = "/message/setMemberList" payload = { "domainId": int(DOMAIN_ID), "botNo": botNo, "accountIdList": account_id_list } res = json.loads(call_server_api(resource, payload)) result = str(res["code"])+" "+res["message"] print("set_member_list:"+result) return result
  9. 9. # Bot def create_room(botNo, account_id_list, talkroom_title): resource = "/message/createRoom" payload = { "botNo": int(botNo), "accountIdList": account_id_list, "title": talkroom_title } res = call_server_api(resource, payload) roomId = json.loads(res)["roomId"] print("roomId:"+roomId) return roomId
  10. 10. # accountId roomId def send_text_message(botNo, accountId="", roomId="", send_text=" "): conte_dic = { "content": { "type": "text", "text": send_text, } } return send_message(botNo, accountId, roomId, conte_dic) # (content_dict ) def send_message(botNo, accountId="", roomId="", content_dict={}): resource = "/message/sendMessage/v2" payload = { "botNo": botNo, } # accountId roomId if accountId != "": payload.update({"accountId": str(accountId)}) elif roomId != "": payload.update({"roomId": str(roomId)}) else: print("accountId and roomId error.") payload.update(content_dict) res = json.loads(call_server_api(resource, payload)) result = str(res["code"])+" "+res["message"] print("send_message:"+result) return result
  11. 11. # Bot def leave_room(botNo, roomId): resource = "/message/leaveRoom" payload = { "botNo": int(botNo), "roomId": roomId, } res = json.loads(call_server_api(resource, payload)) result = str(res["code"])+" "+res["message"] print("leave_room:"+result) return result # Bot def remove_bot(botNo): resource = "/message/removeBot" payload = { "botNo": botNo, } res = json.loads(call_server_api(resource, payload)) result = str(res["code"])+" "+res["message"] print("remove_bot:"+result) return result

×