SlideShare a Scribd company logo
1 of 23
Download to read offline
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生成からボット作成、投稿までやってみた

More Related Content

What's hot

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
 

What's hot (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
 

Similar to 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
 

Similar to 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
 

Recently uploaded

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
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
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 

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