Contents

Samples

Typetalk Token

See also Using Bot’s Typetalk Token.

Python

Preparation

pip install requests

Source code

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

Source code

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

Source code

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

If you post “@echo+ Hi.”, the bot returns “@yourname Hi”. See Outgoing Webhook.

PHP

Source code

<?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

Source code

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);
}

Setting

  1. Publish -> Deploy as web app… -> Who has access to the app: Anyone, even anonymous -> Deploy in your Apps Script menu
  2. Copy and paste “Current web app URL” into Webhook URL of the bot in Typetalk.

Play Framework (Scala)

Example code for Webhook

Client Credential

See also Get access token using client credentials.

Python (requests)

Preparation

pip install requests

Source code

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)

Ansible module which notifies to Typetalk ( Ansible Documentation )

Ruby

Source code

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

Preparation

cpanm Furl JSON

Source code

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)

Dependencies

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

Source code

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)

Jenkins plugin which notifies to Typetalk ( Jenkins Wiki )

Go

Source code

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

Requirements

Source code

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

Source code

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)

Dependencies

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

Source code

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)

Source code

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)

References

System.Web.Extensions

Source code

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)

References

System.Net.Http
System.Web.Extensions

Source code

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

Preparation

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

Source code

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

See also Get access token using 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

See also Streaming (beta).

Node

Example code for Streaming API

Python

Example code for Streaming API

CoffeeScript (hubot)

A hubot adapter for Typetalk (https://www.npmjs.org/package/hubot-typetalk)