サンプル

Typetalk Token

Typetalk トークンを使用 も参照してください。

Python

前準備

pip install requests
ソースコード
import requests

url = 'https://typetalk.com/api/v1/topics/xxxx'
data = {'message':'Hello, Typetalk!'}
headers = { 'X-TYPETALK-TOKEN': 'xxxxxxxxxxxxxxxxxxxx'}
r = requests.post(url, json = data, headers = headers)
print(r.status_code)
print(r.json())

Ruby

ソースコード
require 'net/https'
require 'json'

# setup a http client
http = Net::HTTP.new('typetalk.com', 443)
http.use_ssl = true

# post a message
path = '/api/v1/topics/xxx'
params = { message: 'Hello, Typetalk!' }
headers = {
  'Content-Type' => 'application/json',
  'X-TYPETALK-TOKEN' => 'xxxxxxxxxxxxxxxxxxxx'
}
res = http.post(path, params.to_json, headers)
puts res.code
puts res.body

Node.js

ソースコード

var https = require('https');

var options = {
    hostname: 'typetalk.com',
    path: '/api/v1/topics/xxx',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-TYPETALK-TOKEN': 'xxxxxxxxxxxxxxxxxxxx'
    }
};
var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});
req.write(JSON.stringify({'message': 'Hello, Typetalk!'}));
req.end();

Outgoing Webhook & Typetalk Token

オウム返しサンプルです。 “@echo+ こんにちは” と投稿したら、ボットが “@yourname こんにちは” と返します。 Outgoing Webhook も参照してください。

PHP

ソースコード

<?php
$json_string = file_get_contents('php://input');
$post = json_decode($json_string)->post;
$message = str_replace('@echo+', '@' . $post->account->name, $post->message);

$result = array(
    'message' => $message,
    'replyTo' => $post->id
);

header("Content-Type: application/json; charset=utf-8");
echo json_encode($result);
?>

Google Apps Script

ソースコード

function doPost(e) {
  var jsonString = e.postData.getDataAsString();
  var post = JSON.parse(jsonString).post;
  var message = post.message.replace(/@echo\+/g, '@' + post.account.name);

  var result =
  {
    "message" : message,
    "replyTo" : post.id
  };

  return ContentService.createTextOutput(JSON.stringify(result))
    .setMimeType(ContentService.MimeType.JSON);
}

設定

Play Framework (Scala)

Outgoing Webhook のサンプルコード

Client Credential

Client Credential を使ってアクセストークンを取得 も参照してください。

Python (requests)

前準備

pip install requests

ソースコード

import requests

clientId = 'xxxxxxxxxxxxxxxxxxxx'
clientSecret = 'xxxxxxxxxxxxxxxxxxxx'
topicId = 'xxx'
msg = 'Hello, Typetalk!'

res = requests.post("https://typetalk.com/oauth2/access_token", {
        'client_id': clientId,
        'client_secret': clientSecret,
        'grant_type': 'client_credentials',
        'scope': 'topic.post'
        })
accessToken = res.json()['access_token']

requests.post('https://typetalk.com/api/v1/topics/'+topicId,{
        'message': msg
        }, headers={
        'Authorization':'Bearer '+accessToken
        })

Python (urllib2)

Typetalk に通知するための Ansible モジュール ( Ansible Documentation )

Ruby

ソースコード

require 'net/https'
require 'uri'
require 'json'

client_id = 'xxxxxxxxxxxxxxxxxxxx'
client_secret = 'xxxxxxxxxxxxxxxxxxxx'
topic_id = 'x'
msg = 'Hello!'

# setup a http client
http = Net::HTTP.new('typetalk.com', 443)
http.use_ssl = true

# get an access token
res = http.post(
  '/oauth2/access_token',
  "client_id=#{client_id}&client_secret=#{client_secret}&grant_type=client_credentials&scope=topic.post"
)
json = JSON.parse(res.body)
access_token = json['access_token']

# post a message
req = Net::HTTP::Post.new("/api/v1/topics/#{topic_id}")
req['Authorization'] = "Bearer #{access_token}"
req.set_form_data({:message=>msg})
http.request(req)

Perl

前準備

cpanm Furl JSON

ソースコード

use strict;
use warnings;

use Furl;
use JSON qw(decode_json);

my $client_id     = 'xxxxxxxxxxxxxxxxxxxx';
my $client_secret = 'xxxxxxxxxxxxxxxxxxxx';
my $topic_id      = 'xxx';
my $message       = 'Hello, Typetalk!';

my $client = Furl->new();
my $res    = $client->post(
    'https://typetalk.com/oauth2/access_token',
    [],
    [
        client_id     => $client_id,
        client_secret => $client_secret,
        grant_type    => 'client_credentials',
        scope         => 'topic.post',
    ],
);
die $res->status_line unless $res->is_success;
my $auth = decode_json( $res->content );

$client->post(
    'https://typetalk.com/api/v1/topics/' . $topic_id,
    [
        Authorization => 'Bearer ' . $auth->{access_token},
    ],
    [
        message => $message,
    ]
);

Java (Apache HttpClient)

必要なもの

'org.apache.httpcomponents:httpclient:4.3.2'
'com.google.code.gson:gson:2.2.4'

ソースコード

String clientId = "xxxxxxxxxxxxxxxxxxxx";
String clientSecret = "xxxxxxxxxxxxxxxxxxxx";
String topicId = "xxx";
String message = "Hello Typetalk!";

HttpClient client = HttpClientBuilder.create().build();
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {}.getType();

List<NameValuePair> tokenParams = new ArrayList<NameValuePair>();
tokenParams.add(new BasicNameValuePair("client_id", clientId));
tokenParams.add(new BasicNameValuePair("client_secret", clientSecret));
tokenParams.add(new BasicNameValuePair("grant_type", "client_credentials"));
tokenParams.add(new BasicNameValuePair("scope", "topic.post"));

HttpPost tokenPost = new HttpPost("https://typetalk.com/oauth2/access_token");
tokenPost.setEntity(new UrlEncodedFormEntity(tokenParams));

HttpResponse response = client.execute(tokenPost);
Map<String, String> json = gson.fromJson(EntityUtils.toString(response.getEntity(), "UTF-8"), type);
String accessToken = json.get("access_token");

List<NameValuePair> messageParams = new ArrayList<NameValuePair>();
messageParams.add(new BasicNameValuePair("message", message));

HttpPost messagePost = new HttpPost("https://typetalk.com/api/v1/topics/" + topicId);
messagePost.setEntity(new UrlEncodedFormEntity(messageParams));
messagePost.addHeader("Authorization", "Bearer " + accessToken);
client.execute(messagePost);

Java (Google OAuth Client)

Typetalk に通知するための Jenkins のプラグイン ( Jenkins Wiki )

Go

ソースコード

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/url"
)

type Auth struct {
    AccessToken  string `json:"access_token"`
    TokenType    string `json:"token_type"`
    ExpiresIn    int    `json:"expires_in"`
    RefreshToken string `json:"refresh_token"`
}

var (
    clientId     = "xxxxxxxxxxxxxxxxxxxx"
    clientSecret = "xxxxxxxxxxxxxxxxxxxx"
    topicId      = "xxx"
    message      = "Hello, Typetalk!"
)

func main() {
    resp, err := http.PostForm(
        "https://typetalk.com/oauth2/access_token",
        url.Values{
            "client_id":     { clientId },
            "client_secret": { clientSecret },
            "grant_type":    { "client_credentials" },
            "scope":         { "topic.post" }})
    if err != nil {
        panic(err)
    }
    var d Auth
    err = json.NewDecoder(resp.Body).Decode(&d)
    if err != nil {
        panic(err)
    }

    resp, err = http.PostForm(
        fmt.Sprintf("https://typetalk.com/api/v1/topics/%s", topicId),
        url.Values{
            "access_token": {d.AccessToken},
            "message":      {message}})
    if err != nil {
        panic(err)
    }
}

Shell Script

必要なもの

ソースコード

clientid=xxxxxxxxxxxxxxxxxxxx
clientsecret=xxxxxxxxxxxxxxxxxxxx
topicid=xxx
message="Hello, Typetalk!"

access_token=$(curl https://typetalk.com/oauth2/access_token -X POST --data-urlencode "client_id=${clientid}" -d "client_secret=${clientsecret}" -d "grant_type=client_credentials" -d "scope=topic.post" | jq -r .access_token)
curl https://typetalk.com/api/v1/topics/${topicid} -X POST -H "Authorization:Bearer $access_token" --data-urlencode "message=${message}"

Objective-C

ソースコード

NSString *clientId = @"xxxxxxxxxxxxxxxxxxxx";
NSString *clientSecret = @"xxxxxxxxxxxxxxxxxxxx";
long topicId = x;
NSString *msg = @"Hello!";

// get an access token
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSURL *url = [NSURL URLWithString:@"https://typetalk.com/oauth2/access_token"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
req.HTTPMethod = @"POST";
req.HTTPBody = [[NSString stringWithFormat:@"client_id=%@&client_secret=%@&grant_type=client_credentials&scope=topic.post", clientId, clientSecret] dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:req queue:queue
    completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSError *jsonParsingError = nil;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParsingError];
    NSString *accessToken = json[@"access_token"];

    // post a message
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://typetalk.com/api/v1/topics/%ld", topicId]];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    req.HTTPMethod = @"POST";
    req.HTTPBody = [[NSString stringWithFormat:@"message=%@", [msg stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] dataUsingEncoding:NSUTF8StringEncoding];
    [req setValue:[NSString stringWithFormat:@"Bearer %@", accessToken] forHTTPHeaderField:@"Authorization"];
    [NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    }];
}];

Scala (dispatch-classic)

必要なもの

"net.databinder" %% "dispatch-http" % "0.8.10",
"net.databinder" %% "dispatch-http-json" % "0.8.10",

ソースコード

import dispatch.classic._
import dispatch.classic.json.JsHttp._

val clientId = "xxxxxxxxxxxxxxxxxxxx"
val clientSecret = "xxxxxxxxxxxxxxxxxxxx"
val topicId = xxx
val message = "Hello Typetalk!"

val h = new Http
val tokenReq = url("https://typetalk.com/oauth2/access_token") << Map(
  "client_id" -> clientId,
  "client_secret" -> clientSecret,
  "grant_type" -> "client_credentials",
  "scope" -> "topic.post")

val token = h(tokenReq ># ('access_token ? str))
println(token)

val postReq = url(s"https://typetalk.com/api/v1/topics/$topicId") <:<
  Map("Authorization" -> s"Bearer $token") <<
  Map("message" -> message)
h(postReq >>> System.out)

Scala (Play Framework)

ソースコード

import play.api.libs.ws.WS
import scala.concurrent._
import ExecutionContext.Implicits.global

val clientKey = "xxxxxxxxxxxxxxxxxxxx"
val clientSecret = "xxxxxxxxxxxxxxxxxxxx"
val message = "Hello Typetalk!"
val topicId = xxx
val params = Map(
  "client_id" -> Seq(clientKey),
  "client_secret" -> Seq(clientSecret),
  "scope" -> Seq("topic.post"),
  "grant_type" -> Seq("client_credentials"))

WS.url("https://typetalk.com/oauth2/access_token").post(params).flatMap {
  response =>
    {
      val accessToken = (response.json \ "access_token").as[String]
      WS.url(s"https://typetalk.com/api/v1/topics/${topicId}")
        .withHeaders(("Authorization", s"Bearer ${accessToken}"))
        .post(Map("message" -> Seq(message)))
    }
}.map {
  response => (println(response.json))
}

C# (WebClient)

参照設定

System.Web.Extensions

ソースコード

using System.Web.Script.Serialization

...

var clientId = "xxxxxxxxxxxxxxxxxxxx";
var clientSecret = "xxxxxxxxxxxxxxxxxxxx";
var topicId = xxx;

var client = new WebClient();
var res = client.UploadValues("https://typetalk.com/oauth2/access_token",
    new NameValueCollection()
    {
        {"client_id", clientId},
        {"client_secret", clientSecret},
        {"grant_type", "client_credentials"},
        {"scope", "topic.post"}
    });
var dic = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(Encoding.UTF8.GetString(res));
var accessToken = dic["access_token"];

client.Headers.Add("Authorization", "Bearer " + accessToken);
client.UploadValues("https://typetalk.com/api/v1/topics/" + topicId,
    new NameValueCollection() {{"message", "Hello, Typetalk!"}});

C# (HttpClient)

参照設定

System.Net.Http
System.Web.Extensions

ソースコード

using System.Net.Http
using System.Web.Script.Serialization

...

private async void button1_Click(object sender, EventArgs e)
{
    var clientId = "xxxxxxxxxxxxxxxxxxxx";
    var clientSecret = "xxxxxxxxxxxxxxxxxxxx";
    var topicId = xxx;

    var client = new HttpClient();

    var content = new FormUrlEncodedContent(new Dictionary<string, string>() {
        { "client_id", clientId },
        { "client_secret", clientSecret },
        { "grant_type", "client_credentials" },
        { "scope", "topic.post" }
    });

    await client.PostAsync("https://typetalk.com/oauth2/access_token", content).ContinueWith(res =>
        {
            var str = res.Result.Content.ReadAsStringAsync().Result;
            var dic = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(str);
            var accessToken = dic["access_token"];
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
            return client.PostAsync("https://typetalk.com/api/v1/topics/" + topicId,
                new FormUrlEncodedContent(new Dictionary<string, string>(){{ "message", "Hello, Typetalk!" }})).Result;
        });
    MessageBox.Show("Posted!");
}

Haxe/Neko

前準備

$ haxelib install hxssl
$ haxe -main Typetalk -lib hxssl -neko Typetalk.n
$ nekotools boot Typetalk.n
$ ./Typetalk

ソースコード

package ;

import haxe.Json;
import haxe.Http;
class Typetalk {

    static function main() {
        var clientId = "xxxxxxxxxxxxxxxxxxxx";
        var clientSecret = "xxxxxxxxxxxxxxxxxxxx";
        var topicId = xxx;
        var message = "Hello, Typetalk!";
        var r = new Http("https://typetalk.com/oauth2/access_token");

        r.setParameter("client_id", clientId);
        r.setParameter("client_secret", clientSecret);
        r.setParameter("grant_type", "client_credentials");
        r.setParameter("scope", "topic.post");

        r.onData = function(data:String) {
            var token = Json.parse(data).access_token;
            var post = new Http("https://typetalk.com/api/v1/topics/" + topicId);
            post.setHeader("Authorization", "Bearer " + token);
            post.setParameter("message", message);
            post.onData = function(data:String) {
                trace(data);
            };

            post.request(true);
        };
        r.request(true);
    }
}

Authorization Code

Authorization Code を使ってアクセストークンを取得 も参照してください。

PHP

authorize.php

<?php
$data = array(
  'client_id' => 'xxxxxxxxxxxxxxxxxxxx',
  'redirect_uri' => 'http://localhost/redirect.php',
  'scope' => 'topic.post',
  'response_type' => 'code');

header("Location: https://typetalk.com/oauth2/authorize?" . http_build_query($data), 301);
?>

redirect.php

<?php
$url = 'https://typetalk.com/oauth2/access_token';
$fields = array(
    'client_id' => 'xxxxxxxxxxxxxxxxxxxx',
    'client_secret' => 'xxxxxxxxxxxxxxxxxxxx',
    'redirect_uri' => 'http://localhost/redirect.php',
    'grant_type' => 'authorization_code',
    'code' => $_GET['code']
);
$options = array('http' => array(
    'method' => 'POST',
    'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
    'content' => http_build_query($fields)));

$json = json_decode(file_get_contents($url, false, stream_context_create($options)));
$token = $json->access_token;
?>

<html>
<body>
<form action="message.php" method="POST">
<input type="hidden" name="token" value="<?= $token ?>">
TopicId<br>
<input type="text" name="topic_id"><br>
Message<br>
<input type="text" name="message"><br>
<input type="submit">
</form>
</body>
</html>

message.php

<?php
$url = 'https://typetalk.com/api/v1/topics/' . $_POST['topic_id'];
$fields = array(
    'message' => $_POST['message']
);
$options = array('http' => array(
    'method' => 'POST',
    'header' => "Content-Type: application/x-www-form-urlencoded\r\nAuthorization: Bearer " . $_POST['token'],
    'content' => http_build_query($fields)));

file_get_contents($url, false, stream_context_create($options));
?>
<html><body>Posted!</body></html>

Streaming API

ストリーミング(ベータ) も参照してください。

Node

Streaming API のサンプル

Python

Streaming API のサンプル

CoffeeScript (hubot)

Typetalk 用の hubot アダプタ (https://www.npmjs.org/package/hubot-typetalk)