Setup

Most examples are HTTP(S) based.
For an XMPP example, have a look at the Python XMPP callback example.

Check the section Getting Started for an overview on how to set up a service account, configure authentication and configure callbacks.

Programming Language Support

You are not forced to use any particular programming language to access the Rogerthat API. You can use any language which supports HTTP, SSL and JSON.

This includes Python, PHP, Perl, Java, .NET, JavaScript, Objective-C, C/C++. It is also trivially simple to write shell scripts using curl or wget, …

Java Example

There is an open source project to simplify the Java integration of Rogerthat. All information is available at https://github.com/fastgeert/Rogerth.at-Messenger-java-api-bindings/wiki

Apart from rogerthat_api.jar, the following jar is required in your classpath: download SimpleJSON

In case you want to send the JSON requests yourself, do not forget to UTF-8 encode the JSON content before putting it in the request body. Also, when parsing responses, treat them as UTF-8.

Requests from your service to Rogerthat

For this example we need a few imports

import com.mobicage.rogerthat.Answer;
import com.mobicage.rogerthat.AnswerType;
import com.mobicage.rogerthat.Api;
import com.mobicage.rogerthat.MessageFlag;
import com.mobicage.rogerthat.RogerthatAPIException;

The core code is shown below

// Initialize API

final Api rogerthatApi = new Api();
rogerthatApi.setApiKey("YOUR TOP SECRET API KEY"); // Edit this line

// Request friendship
try {
    rogerthatApi.inviteFriend("john@example.com", "John",
        "Do you want to get service notifications?", "invitation 0001");
} catch (RogerthatAPIException e) {
    e.printStackTrace();
    System.err.println(e.getFields());
}

// Send a message

final com.mobicage.rogerthat.Message m = new com.mobicage.rogerthat.Message();

m.setMessage("Hi how are you?");
m.addMember("john@example.com");   // Edit this line
m.addMember("olivia@example.com"); // Edit this line

m.addFlag(MessageFlag.ALLOW_DISMISS);

final Answer good = new Answer();
good.setId("good");
good.setCaption("I'm fine!");
good.setType(AnswerType.BUTTON);
m.addAnswer(good);

final Answer bad = new Answer();
bad.setId("bad");
bad.setCaption("Not good");
bad.setType(AnswerType.BUTTON);
m.addAnswer(bad);

final Answer callme = new Answer();
callme.setId("callme");
callme.setCaption("Call me");
callme.setType(AnswerType.BUTTON);
callme.setAction("tel://+12223334444"); // Edit this line
m.addAnswer(callme);

try {
    rogerthatApi.sendMessage(m);
} catch (RogerthatAPIException e) {
    e.printStackTrace();
    System.err.println(e.getFields());
}

The resulting message arrives:

Callbacks from Rogerthat to your service

In this example we implement a callback servlet.

The simplest way to integrate is to create a subclass of com.mobicage.rogerthat.CallBackApiServlet

public class CallBackApiServlet extends com.mobicage.rogerthat.CallBackApiServlet {
    public CallBackApiServlet() {
        this.setSikKey("your secret service identifier key");
        this.setCallbackApi(new CallBackApi() {

            public void messageUpdate(String messageKey, String member, Set status,
                                      String answerId, long receivedTimestamp,
                                      long acknowledgeTimestamp, String tag) {
                // I received a message status update or a one-click response
                if (answerId == null) {
                    log("User " + member + " has received message with tag " + tag);
                } else {
                    log("User " + member + " has clicked a one-click response with id "
                                + answerId);
                }
            }

            public void friendRemoved(String email) {
                log("User " + email + " is no longer a relation of this service");
                // Now I can no longer send messages to that user
            }

            public FriendInviteResult friendInvited(String email, String name,
                                                    String message) {
                log("User " + email + " wants to become friends with my service");
                return FriendInviteResult.ACCEPTED;
            }

            public void friendInviteResult(String email, FriendInviteResult result,
                                           String tag) {
                // I invited a user earlier; the user accepted or refused my request
            }
        });
    }

}

.NET Example

There is an open source project to simplify the .NET integration of Rogerthat. All information is available at https://github.com/fastgeert/Rogerth.at-Messenger-dotnet-api-bindings/wiki

This project contains example code.

Python Example

The Nagios Rogerthat Notifier is an excellent example on how to use Python to communicate with Rogerthat users. A Python Twisted Server is used to receive the callbacks.

TPS sends message to Rogerthat

A simple example on how to send a friend invitation to a user, and then send a message to him.

  • The first time you run the code, the friend invitation will be sent to the user. Sending the message will raise an error since the user is not yet connected to the service.
  • If you accept the friend request, then run the code again, you will get an error inviting the friend, and the message will be sent correctly.

Obviously you must replace “INSERT SECRET API KEY” with your API Key.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2
import uuid

try:
    import json
except ImportError:
    import simplejson as json

API_KEY = 'INSERT SECRET API KEY'
URL = 'https://rogerth.at/api/1'
HEADERS = {
    'Content-Type': 'application/json-rpc; charset=utf-8',
    'X-Nuntiuz-API-key': API_KEY,
}

def call_rogerthat(data):
    json_data = json.dumps(data) # json.dumps exports by default a utf-8 encoded string
    print 'Request:', json_data
    request = urllib2.Request(URL, json_data, HEADERS)
    response = urllib2.urlopen(request)
    print 'Response code:', response.getcode()
    print 'Response:', response.read()

print '\nFriend invitation\n'

data = {}
data['id'] = str(uuid.uuid4())
data['method'] = 'friend.invite'
data['params'] = {
    'email': 'john@example.com',
    'name': 'John',
    'message': 'Do you want to get service notifications?',
    'tag': 'invitation tag',
    'language': 'en',
}

call_rogerthat(data)

print '\nMessage to friend\n'

data = {}
data['id'] = str(uuid.uuid4())
data['method'] = 'messaging.send'
data['params'] = {
    'answers': [
        {'action': None,
         'caption': "I'm fine!",
         'id': 'good',
         'type': 'button'},
        {'action': None,
         'caption': 'Not good',
         'id': 'bad',
         'type': 'button'},
        {'action': 'tel://+12223334444',
         'caption': 'Call me',
         'id': 'callme',
         'type': 'button'},
    ],
    'branding': None,
    'flags': 1,
    'alert_flags': 1,
    'members': ['john@example.com'],
    'message': 'Hello, how are you',
    'parent_message_key': None,
    'sender_answer': None,
    'tag': 'my message tag 0001',
}

call_rogerthat(data)

print

TPS receives message from Rogerthat using XMPP

The format of an XMPP callback message is described in the section Getting Started.

The code example requires:

First you should create an XMPP account. You can create one for free on jabber.org.
Next, start the python script commandline as follows

python bot.py user@jabber.org password

Here is the code bot.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import xmpp
import base64
import logging
try:
    import json
except ImportError:
    import simplejson as json

# Insert here your Rogerthat Service Identification Key
SIK = 'INSERT SERVICE IDENTIFIER KEY HERE'

def handle_test_request(params, response):
    '''No need to change this mandatory test callback handler'''
    logging.info('Received test request')
    value = params['value']
    response['result'] = value

def handle_messaging_update(params, response):
    '''Received message update. Possibilities:
       - message received by user
       - message dismissed by user (clicked 'Roger That' button)
       - one-click respone button clicked by user'''
    msg_status = params['status']
    if (msg_status & MESSAGE_STATUS_ACKED):
        answer = params['answer_id']
        if answer:
            logging.info('User %(member)s answered %(answer_id)s on message %(message_key)s' % params)
        else:
            logging.info('User %(member)s dismissed message %(message_key)s' % params)
    else:
        logging.info('User %(member)s received message %(message_key)s' % params)

def handle_friend_invited(params, response):
    ''' A user invited your service to become friend. You can accept or decline. '''
    logging.info('Received friend invitation from %(email)s' % params)
    response['result'] = 'accepted'

def handle_friend_broke_up(params, response):
    ''' A user decided to break up friendship with a service. There is no way to refuse this. '''
    logging.info('Received friend breakup request from %(email)s' % params)

def handle_friend_invite_result(params, response):
    ''' You invited a user. He accepted or declined. '''
    logging.info('Received invitation result from %(email)s with value %(result)s' % params)

####################################################################

CALLBACK_SERVER = 'bot@callback.rogerth.at'
MESSAGE_STATUS_RECEIVED = 1
MESSAGE_STATUS_ACKED = 2

HANDLERS = { 'test.test'           : handle_test_request,
             'messaging.update'    : handle_messaging_update,
             'friend.broke_up'     : handle_friend_broke_up,
             'friend.invite_result': handle_friend_invite_result,
             'friend.invited'      : handle_friend_invited,
}

logging.getLogger().setLevel(logging.INFO)

def handle_request(request):
    logging.info('>>> Incoming request: %s' % request)
    method = request['method']
    response = { 'id': request['id'], 'result': None, 'error': None }

    if method in HANDLERS:
        HANDLERS[method](request['params'], response)
        return response

    logging.error('Unsupported method: %s' % method)
    return None

def rogerthat_handler(conn, incoming_message):
    from_ = incoming_message.getFrom()
    if from_ != CALLBACK_SERVER:
        logging.error('Wrong sender: %s' % from_)
        return

    children = incoming_message.getChildren()
    assert (len(children) == 1)

    callElem = children[0]
    assert callElem.name == 'call'
    assert callElem.getNamespace() == 'mobicage:comm'
    assert callElem.has_attr('sik')
    assert callElem.getAttr('sik') == SIK

    request = json.loads(base64.decodestring(callElem.getData()))
    result_dict = handle_request(request)

    if result_dict is None:
        return

    message = xmpp.Message(to=str(incoming_message.getFrom()),
                           frm=str(incoming_message.getTo()))
    result_node = message.addChild(name='result', namespace='mobicage:comm')
    result_node.setAttr('sik', SIK)
    result_node.setData(base64.encodestring(json.dumps(result_dict)))

    conn.send(message)

def StepOn(conn):
    try:
        conn.Process(1)
    except KeyboardInterrupt:
        return 0
    except:
        logging.exception('Exception happened while processing incoming request')
    return 1

def GoOn(conn):
    while StepOn(conn): pass

if len(sys.argv) < 3:
    print 'Usage: bot.py username@server.net password'
else:
    jid = xmpp.JID(sys.argv[1])
    user, server, password = jid.getNode(), jid.getDomain(), sys.argv[2]

    conn = xmpp.Client(server)#,debug=[])
    conres = conn.connect()
    if not conres:
        print 'Unable to connect to server %s!' % server
        sys.exit(1)
    if conres<>'tls':
        print 'Warning: unable to establish secure connection - TLS failed!'
    authres = conn.auth(user,password)
    if not authres:
        print 'Unable to authorize on %s - check login/password' % server
        sys.exit(1)
    if authres  'sasl':
        print 'Warning: unable to perform SASL auth os %s. Old authentication method used!' % server
    conn.RegisterHandler('message', rogerthat_handler)
    conn.sendInitPresence()
    print 'Bot started.'
    GoOn(conn)

TPS disconnects user

#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2
import time
import random
import sys

from rogerthat import *

try:
    import json
except ImportError:
    import simplejson as json

API_KEY = 'INSERT SECRET API KEY'
URL = 'https://rogerth.at/api/1'
HEADERS = {
    'Content-Type': 'application/json-rpc',
    'X-Nuntiuz-API-key': API_KEY,
}

RECIPIENT = 'john@example.com'    # User to be disconnected from TPS 



def call_rogerthat(data):
    json_data = json.dumps(data)
    print 'Request:', json_data
    request = urllib2.Request(URL, json_data, HEADERS)
    response = urllib2.urlopen(request)
    print 'Response code:', response.getcode()
    print 'Response:', response.read()

def get_json(parentkey=None):
    id = str(random.randint(1,10000000))
    jsonrpcid = 'jsonrpc id ' + id
    data = {}
    data['id'] = jsonrpcid
    data['method'] = 'friend.break_up'
    data['params'] = {
        'email': RECIPIENT
    }
    return data

call_rogerthat(get_json())

PHP Example

Example PHP call from Third Party Service to Rogerthat

In the following PHP code snippet you should put your API Key where it says “INSERT SECRET API KEY”.

TPS invites a user

<? php
$r = new HttpRequest('https://rogerth.at/api/1', HttpRequest::METH_POST);
$r->setContentType('application/json-rpc; charset=utf-8');
$r->addHeaders(array('X-Nuntiuz-API-Key' => 'INSERT SECRETE API KEY'));

$data = array();

$data['method'] = 'friend.invite';
$data['id'] = uniqid('rogerthat_');
$data['params'] = array(
    'email' => 'john@example.com',
    'name' => 'John Doe',
    'message' => 'This is your car repair service',
    'language' => 'en',
    'tag' => 'msg tag 0001',
);

$r->setRawPostData(json_encode($data));
$r->send();
echo 'Response code: ', $r->getResponseCode();
echo $r->getResponseBody();
?>

TPS sends a message to a user

<?php
$r = new HttpRequest('https://rogerth.at/api/1', HttpRequest::METH_POST);
$r->setContentType('application/json-rpc; charset=utf-8');
$r->addHeaders(array('X-Nuntiuz-API-Key' => 'INSERT SECRET API KEY'));

$data = array();

$data['method'] = 'messaging.send';
$data['id'] = uniqid('rogerthat_');
$data['params'] = array(
    'parent_message_key' => NULL,
    'message' => 'Hey how are you',
    'answers' => array(
        array('id' => 'fine',
              'caption' => 'fine',
              'action' => NULL,
              'type' => 'button',
        ),
        array('id' => 'notok',
              'caption' => 'not good',
              'action' => NULL,
              'type' => 'button',
        ),
    ),
    'sender_answer' => NULL,
    'flags' => 31,
    'alert_flags' => 1,
    'members' => array('john@example.com'),    // Replace user account
    'branding' => NULL,
    'tag' => 'msg tag 0001',
);

$r->setRawPostData(json_encode($data));
$r->send();
echo 'Response code: ', $r->getResponseCode();
echo $r->getResponseBody();
?>

Example PHP callback from Rogerthat to Third Party Service

The following code snippet provides the following functionality:

  • Accept user invitations who want to connect to a service
  • Automatically start a message flow when a user presses the POKE button of your service
  • Respond to the test.test callback

In the first few lines of the example code you should modify the API key, SIK key, and message flow id, according to your specific settings.

<?php
// /////////////////////////
// Customize this section

$SECRET_API_KEY = '<<< insert your API key here >>>';
$SECRET_SIK_KEY = '<<< insert your SIK key here >>>';
$MESSAGE_FLOW_FOR_DEFAULT_POKE = '<<< insert your message flow id here, or use NULL >>>';
$MESSAGE_FLOWS_FOR_POKE = array( '<<< insert a tag >>>' => '<<< insert your message flow id here >>>',
                                 '<<< insert another tag >>>' => '<<< insert another message flow id here >>>'  );

function fail($message) {
 die($message);
}

function accept_friend($friend_email) {
 // In this example, we accept everybody
 return True;
}

// /////////////////////////

function get_response_data($json_rpc_id) {
  $response_data =  array();
  $response_data['error'] = NULL;
  $response_data['result'] = NULL;
  $response_data['id'] = $json_rpc_id;
  return $response_data;
}

try {

  header('Content-type: application/json-rpc; charset=utf-8');
  $headers = getallheaders();

  $SIK_HEADER = 'X-Nuntiuz-Service-Key';

  $authenticated = False;
  if (array_key_exists($SIK_HEADER, $headers))
    if ($headers[$SIK_HEADER] === $SECRET_SIK_KEY)
      $authenticated = True;

  if (!$authenticated)
    fail('Authentication failed!');

  $request_data = json_decode(file_get_contents('php://input'), true);
  $method = $request_data['method'];
  $json_rpc_id = $request_data['id'];
  $params = $request_data['params'];

  if ($method === 'friend.invited') {

    $friend_accepted = accept_friend($params['email']);

    $response_data = get_response_data($json_rpc_id);
    if ($friend_accepted)
      $response_data['result'] = 'accepted';
    else
      $response_data['result'] = 'declined';

    echo json_encode($response_data);

  } elseif ($method === 'friend.invite_result') {

    $response_data = get_response_data($json_rpc_id);
    echo json_encode($response_data);

  } elseif ($method === 'friend.broke_up') {

    $response_data = get_response_data($json_rpc_id);
    echo json_encode($response_data);

  } elseif ($method === 'test.test') {

    $response_data = get_response_data($json_rpc_id);
    $response_data['result'] = $params['value'];
    echo json_encode($response_data);

  } elseif ($method === 'messaging.poke') {

    $sender_email = $params['email'];
    $response_data = get_response_data($json_rpc_id);
    echo json_encode($response_data);

    $poketag = $params['tag'];
    $launchflow = NULL;
    
    if ($poketag == NULL) {
        $launchflow = $MESSAGE_FLOW_FOR_DEFAULT_POKE;
    } else {
        if (array_key_exists($poketag, $MESSAGE_FLOWS_FOR_POKE))
            $launchflow = $MESSAGE_FLOWS_FOR_POKE[$poketag];
    }

    if ($launchflow != NULL) {

      $data = array();
      $data['method'] = 'messaging.start_flow';
      $data['id'] = uniqid('rogerthat_');
      $data['params'] = array(
        'members' => array($sender_email),
        'flow' => $launchflow,
        'parent_message_key' => null
      );

      
      // // If your php server does not support HttpRequest, comment the following lines:
      $r = new HttpRequest('https://rogerth.at/api/1', HttpRequest::METH_POST);
      $r->setContentType('application/json-rpc; charset=utf-8');
      $r->addHeaders(array('X-Nuntiuz-API-Key' => $SECRET_API_KEY));
      $r->setRawPostData(json_encode($data));
      $r->send();
      $r->getResponseCode(); // Should be checked for errors
      $r->getResponseBody(); // Should be checked for errors

      // // If your php server does not support HttpRequest, uncomment the following lines:
      // $ch = curl_init();
      // curl_setopt($ch, CURLOPT_URL, 'https://rogerth.at/api/1');
      // curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json-rpc; charset="utf-8"', 'X-Nuntiuz-API-Key: ' . $SECRET_API_KEY));
      // curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
      // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
      // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      // $result = curl_exec($ch); // Should be checked for errors
      // curl_close($ch);

    }

  } elseif ($method === 'messaging.update') {

    // We do not process this result
    $response_data = get_response_data($json_rpc_id);
    echo json_encode($response_data);

  } elseif ($method === 'messaging.form_update') {

    // We do not process this result
    $response_data = get_response_data($json_rpc_id);
    echo json_encode($response_data);

  } elseif ($method === 'messaging.flow_member_result') {

    // We do not process this result
    $response_data = get_response_data($json_rpc_id);
    echo json_encode($response_data);

  } else {

    $response_data = get_response_data($json_rpc_id);
    $response_data['error'] = array();
    $response_data['error']['message'] = 'JSON-RPC method '.$method.' not implemented';
    echo json_encode($response_data);

  }

} catch (Exception $e) {

  fail('Caught exception: ' . $e->getMessage());

}

?>