Help Center
bots:sample

Example: creating a bot

This section walks you through developing a bot that supports auto-reply and approval. This information will be useful for application developers.

Create a page with an HTTPS address on your website, e.g. https://example.com/autoresponse. This event handler page will receive requests from your Pyrus bot. Add code to the event handler as follows:

1. Verify the signature to make sure that a request really comes from Pyrus.

  • Calculate the request body signature:

python:

def isSignatureCorrect(message, signature, secret):
	return calcSignature(message, secret) == signature;

def calcSignature(message, secret):
	reutrn toHex(hmac.new(secret, msg=message, digestmod=hashlib.sha1).digest())
	
def toHex(hash):
	result = '';
	for ch in hash:
		l = ord(ch) % 16
		h = ord(ch) // 16
		result += ''.join([toHexValue(h), toHexValue(l)])
	return result

def toHexValue(i):
	if i < 10 :
		return chr(ord('0') + i) 
	else:
		return chr(ord('A') + i - 10)
php:
strtoupper(hash_hmac(«sha1», $response_body_as_string, $security_key))
ruby:
OpenSSL::HMAC.hexdigest('sha1', security_key, response_body_as_string).upcase 

These functions convert a string request into a UTF byte array, and calculate an HMAC digest using the SHA1 secure hash algorithm.

  • Compare it to the X-Pyrus-Sig header to verify that the request has truly come from Pyrus. If the headers do not to match, the script is terminated.

2. Select Author.Id and Id values from received TaskWithNotes object (see the complete description):

{
  "Id": 5600,
  "Text": "New task",
  "Responsible": {
    "Id": 1731,
    "FirstName": "tester",
    "LastName": "papirus",
    "Email": "test@pyrus.com"
  },
  "CreateDate": "\/Date(1480667362000)\/",
  "ModifiedDate": "\/Date(1480667362000)\/",
  "ParentTaskId": 0,
  "Author": {
    "Id": 1731,
    "FirstName": "tester",
    "LastName": "papirus",
    "Email": "test@pyrus.com"
  },
  "Approvals": [[{
    "Person": {
      "Id": 21913,
      "FirstName": "bot",
      "LastName": "papirus",
      "Email": "bot@pyrus.com"
    }
    }],
    [{
    "Person": {
      "Id": 1731,
      "FirstName": "tester",
      "LastName": "papirus",
      "Email": "test@pyrus.com"
    }
    }]],
  "Notes": [{
    "CreateDate": "\/Date(1480667362000)\/",
    "Author": {
      "Id": 1731,
      "FirstName": "tester",
      "LastName": "papirus",
      "Email": "test@pyrus.com"
    },
    "ApprovalsAdded": [[{
      "Id": 21913,
      "FirstName": "bot",
      "LastName": "papirus",
      "Email": "bot@pyrus.com"
    }],
    [{
      "Id": 1731,
      "FirstName": "tester",
      "LastName": "papirus",
      "Email": "test@pyrus.com"
    }]],
    "Id": 12208
  }]
}

In the above example Author.Id = 1731 and Id = 5600.

3. Generate the response body:

	
{
  "TaskId": 5600,
  "Text": "Approved by bot.", 
  "ApprovalChoice": "Approved", 
  "ResponsibleId" : 1731  
}

In this example:

  • TaskId (mandatory parameter): the ID of the task that the bot has been working on.
  • Text (optional parameter): Comment text. If it is blank, the bot adds an empty text comment.
  • ApprovalChoice (optional parameter): Bot approval option. If no approval is required, the server ignores this parameter.
  • ResponsibleId (optional parameter): If a bot intends to change who is responsible for the task, it should fill this attribute. If left blank, the bot remains the task’s assignee.

4. Return the HTTP response '200 ОК' and the body as described above.

Here is a full example of a bot in python. You can find the previous example of bot's code with the signature verifying here.

import json
import time
import BaseHTTPServer
import hmac
import hashlib
import base64

HOST_NAME = '127.0.0.1'  # !!!Do not forget to replace the address!!!
PORT_NUMBER = 38081

class Payload(object):
	def __init__(self, j):
		self.__dict__ = json.loads(j)

class BotHandler(BaseHTTPServer.BaseHTTPRequestHandler):
	def do_POST(s):
		s.send_response(200)
		s.send_header("Content-type", "application/json")
		s.end_headers()
		
		message = Payload(s.rfile.read(int(s.headers['content-length'])))
		
		s.wfile.write("{\"Id\": %d, \"Text\": \"Hello world\", \"ApprovalChoice\": \"Approved\"}" % message.TaskId)
		
if __name__ == '__main__':
	httpd = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER), BotHandler)
	try:
		httpd.serve_forever()
	except KeyboardInterrupt:
		pass
	httpd.server_close()

Now, add the new bot and enter the address of event handler in the URL field (in our example, https://example.com/autoresponse).

To check out your work, assign a task to the bot in Pyrus with an approval request. Make sure that the task receives the Approved by bot reply, and that bot approval is enabled.

Was this article helpful?

Yes, thanks! No, I have a question