Skip to content

Instantly share code, notes, and snippets.

@nobuoka
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nobuoka/9520657 to your computer and use it in GitHub Desktop.
Save nobuoka/9520657 to your computer and use it in GitHub Desktop.
Typetalk のトピックに投稿する Groovy のサンプルコード
// clientId や clientSecret、topicId を設定して、groovy コマンドでこのファイルを実行すれば動きます。 (指定のトピックに投稿されます。)
// このサンプルコードはコピペ等でご自由にお使いください。 (問題が発生しても責任は負いかねます。)
String clientId = "XXXX"
String clientSecret = "XXXX"
// 投稿先トピックの ID
String topicId = "XXXX"
// 投稿するメッセージ
String message = "Groovy でこんにちは!"
// Groovy での HTTP 通信について: http://groovy.codehaus.org/modules/http-builder/doc/rest.html
// Grape で依存管理。 初回実行時はライブラリをダウンロードしてくるので時間がかかる。
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.+' )
import groovyx.net.http.ContentType
import groovyx.net.http.HttpResponseException
import groovyx.net.http.RESTClient
def typetalkClient = new RESTClient('https://typetalk.in')
// レスポンスの表示を行う
def printResponse = { res ->
println "--- response ---"
println "status: ${res.status}"
println "headers: ${res.allHeaders}"
println "data: ${res.data}"
}
// Access token の取得。 (1 回取得したら有効期限が切れるまで使いまわせる。)
String accessToken
try {
def res = typetalkClient.post(
path: '/oauth2/access_token',
requestContentType: ContentType.URLENC,
body: [
"client_id": clientId,
"client_secret": clientSecret,
"grant_type": "client_credentials",
"scope": "topic.post",
])
printResponse res
accessToken = res.data["access_token"]
} catch (HttpResponseException ex) {
// エラーレスポンスはこっちに来る。
def res = ex.response
printResponse res
System.exit 1
}
// 指定のトピックに指定のメッセージを投稿する。
try {
def res = typetalkClient.post(
// XXX topicId とか accessToken とかちゃんとエンコードすべき
path: "/api/v1/topics/${topicId}",
headers: [ "Authorization": "Bearer ${accessToken}" ],
requestContentType: ContentType.URLENC,
body: [ "message": message ])
printResponse res
} catch (HttpResponseException ex) {
def res = ex.response
printResponse res
System.exit 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment