SlideShare ist ein Scribd-Unternehmen logo
1 von 23
Downloaden Sie, um offline zu lesen
1 /
78 1 ( ) ( (
0- 35
78 1 ( ) ) (
24 :
3 = 01 1 : 1 = : = :. 1 /: 0:/? 1 2
I
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--------------------------------------------
-----------")
# -*- 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
#
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
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
# 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
# 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
# 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
# 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
# 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
# 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
PythonでJWT生成からボット作成、投稿までやってみた
PythonでJWT生成からボット作成、投稿までやってみた
PythonでJWT生成からボット作成、投稿までやってみた
PythonでJWT生成からボット作成、投稿までやってみた

Weitere ähnliche Inhalte

Was ist angesagt?

20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked about
Tatsuhiko Miyagawa
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
Bill Chang
 

Was ist angesagt? (20)

TerminalでTwitter
TerminalでTwitterTerminalでTwitter
TerminalでTwitter
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked about
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find Fraudsters
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
Presentation1
Presentation1Presentation1
Presentation1
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
Perl6 operators and metaoperators
Perl6   operators and metaoperatorsPerl6   operators and metaoperators
Perl6 operators and metaoperators
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Asciidoctor New, Noteworthy and Beyond Devoxx-2017
Asciidoctor New, Noteworthy and Beyond Devoxx-2017Asciidoctor New, Noteworthy and Beyond Devoxx-2017
Asciidoctor New, Noteworthy and Beyond Devoxx-2017
 
Session8
Session8Session8
Session8
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
Eric Redmond – Distributed Search on Riak 2.0 - NoSQL matters Barcelona 2014
Eric Redmond – Distributed Search on Riak 2.0 - NoSQL matters Barcelona 2014Eric Redmond – Distributed Search on Riak 2.0 - NoSQL matters Barcelona 2014
Eric Redmond – Distributed Search on Riak 2.0 - NoSQL matters Barcelona 2014
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
 
Php
PhpPhp
Php
 

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

From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
Night Sailer
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
Yuren Ju
 
Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7
Masahiro Nagano
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
AidIQ
 
Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6
fisher.w.y
 
Recovery of lost or corrupted inno db tables(mysql uc 2010)
Recovery of lost or corrupted inno db tables(mysql uc 2010)Recovery of lost or corrupted inno db tables(mysql uc 2010)
Recovery of lost or corrupted inno db tables(mysql uc 2010)
Aleksandr Kuzminsky
 

Ähnlich wie PythonでJWT生成からボット作成、投稿までやってみた (20)

Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Produce nice outputs for graphical, tabular and textual reporting in R-Report...
Produce nice outputs for graphical, tabular and textual reporting in R-Report...Produce nice outputs for graphical, tabular and textual reporting in R-Report...
Produce nice outputs for graphical, tabular and textual reporting in R-Report...
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JS
 
Novidades do c# 7 e 8
Novidades do c# 7 e 8Novidades do c# 7 e 8
Novidades do c# 7 e 8
 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
 
Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6
 
C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8
 
Using Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasetsUsing Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasets
 
RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”
 
Recovery of lost or corrupted inno db tables(mysql uc 2010)
Recovery of lost or corrupted inno db tables(mysql uc 2010)Recovery of lost or corrupted inno db tables(mysql uc 2010)
Recovery of lost or corrupted inno db tables(mysql uc 2010)
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Cassandra summit keynote 2014
Cassandra summit keynote 2014Cassandra summit keynote 2014
Cassandra summit keynote 2014
 
Optimizando MySQL
Optimizando MySQLOptimizando MySQL
Optimizando MySQL
 
Socket.io
Socket.ioSocket.io
Socket.io
 

Kürzlich hochgeladen

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Kürzlich hochgeladen (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 

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

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9. 1 / 78 1 ( ) ( ( 0- 35 78 1 ( ) ) ( 24 : 3 = 01 1 : 1 = : = :. 1 /: 0:/? 1 2 I
  • 10. 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-------------------------------------------- -----------")
  • 11. # -*- 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
  • 12. # 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
  • 13. 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
  • 14. # 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
  • 15. # 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
  • 16. # 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
  • 17. # 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
  • 18. # 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
  • 19. # 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