Writing chatbots for Byteball

tonyofbyteball edited this page Jul 10, 2018 · 13 revisions

Chatbots communicate with users and offer various services. The services are usually connected with payments.


To run a chatbot, you need a headless node. Headless nodes are full nodes by default. A subset of the functionality might work in light nodes too, but keep in mind that it was designed for full nodes only.

Create a new node.js package for your bot. You will definitely need modules from byteballcore (add it to your project's dependencies) and if you are going to send payments, you will also need headless-byteball. Your package.json should list these dependencies:

"dependencies": {
	"headless-byteball": "git+https://github.com/byteball/headless-byteball.git",
	"byteballcore": "^0.2.33",

In your module, require() wallet.js even if you are not using any of its functions (it handles messages from the hub):



In your conf (conf.js or conf.json) specify your bot name and a pairing secret that will be part of your pairing code:

exports.deviceName = 'My test bot';
exports.permanent_pairing_secret = '0000';

When you start your node, it will print its full pairing code:

====== my pairing code: A2WMb6JEIrMhxVk+I0gIIW1vmM3ToKoLkNF8TqUV5UvX@byteball.org/bb#0000

The pairing code consists of your node's public key (device public key), hub address, and pairing secret (after #).

Publish this pairing code on your website as a link with byteball: scheme, users will be able to open a chat with your bot by clicking your link (the link opens in their Byteball app and starts a chat):

<a href="byteball:A2WMb6JEIrMhxVk+I0gIIW1vmM3ToKoLkNF8TqUV5UvX@byteball.org/bb#0000">Chat with my test bot</a>

You also need this pairing code to add your bot to the Bot Store.


If you need to inspect the DAG (most likely, you need) and see the details of any transaction, require the db module

var db = require('byteballcore/db.js');

and run any SQL queries on your copy of the Byteball database. You can also add your custom tables. Obviously, you don't want to modify any data outside your custom tables.

Receiving chat messages

To receive chat messages, subscribe to 'text' events on event bus:

var eventBus = require('byteballcore/event_bus.js');
eventBus.on('text', function(from_address, text){
    // your code here

from_address is user's device address (not to be confused with payment addresses), text is his message.

Sending chat messages

var device = require('byteballcore/device.js');
device.sendMessageToDevice(user_device_address, 'text', 'Text message from bot to user');

Receiving pairing notifications

When a user pairs his device with your bot (e.g. by clicking the link to your bot), you receive a pairing notification and can welcome the user:

eventBus.on('paired', function(from_address, pairing_secret){
	var device = require('byteballcore/device.js');
	device.sendMessageToDevice(from_address, 'text', getMyWelcomeText());

The behavior of your event handler can depend on pairing_secret, the second argument of the event handler. For example, you can have a one-time (non-permanent) pairing secret equal to session ID on your website; after the user clicks the pairing link and opens chat, you can link his chat session with his web session, see Authenticating users on websites.


To give access to predefined commands, format your responses this way:

click this link: [Command name](command:command code)

The user will see the text in square brackets "Command name", it will be highlighted as a link, and when the user clicks it, his app will send command code text to your bot.

Requesting payments

When you include a valid Byteball address anywhere in the text of your response to the user, the address will be automatically highlighted in the user's chat window, and after clicking it the user will be able to pay arbitrary amount of arbitrary asset to this address.

When you want to request a specific amount of a specific asset, format your payment request this way:

Any text before [payment description, will be ignored](byteball:YOURBYTEBALLADDRESS?amount=123000&asset=base) any text after

Amount is in the smallest units, such as bytes. If you omit &asset=... part, base asset (bytes) is assumed. If you want to request payment in another asset, indicate its identifier such as oj8yEksX9Ubq7lLc+p6F2uyHUuynugeVq4+ikT67X6E= for blackbytes (don't forget to url-encode it).

You will likely want to generate a unique payment address per user, per transaction. This code sample might help:

var walletDefinedByKeys = require('byteballcore/wallet_defined_by_keys.js');
walletDefinedByKeys.issueNextAddress(wallet, 0, function(objAddress){
	var byteball_address = objAddress.address;
	// work with this address, then send it over to the user
	device.sendMessageToDevice(user_device_address, 'text', "Please pay to "+byteball_address);

Waiting for payments

If you include a headless wallet

var headlessWallet = require('headless-byteball');

you can get notified when any of your addresses receives a payment

eventBus.on('new_my_transactions', function(arrUnits){
	// react to receipt of payment(s)

arrUnits is an array of units (more accurately, unit hashes) that contained any transaction involving your addresses. The event new_my_transactions is triggered for outgoing transactions too, you should check if the new transaction credits one of the addresses you are expecting payments to.

Waiting for finality of payments

To get notified when any of your transactions become stable (confirmed), subscribe to my_transactions_became_stable event:

eventBus.on('my_transactions_became_stable', function(arrUnits){
	// react to payment(s) becoming stable

arrUnits is again the array of units that just became stable and they contained at least one transaction involving your addresses.

The above events work in both full and light nodes. If your node is full, you can alternatively subscribe to event mci_became_stable which is emitted each time a new main chain index (MCI) becomes stable:

eventBus.on('mci_became_stable', function(mci){
	// check if there are any units you are interested in 
	// that had this MCI and react to their becoming stable

Sending payments

To send payments, you need to include a headless wallet

var headlessWallet = require('headless-byteball');

and use this function:

headlessWallet.issueChangeAddressAndSendPayment(asset, amount, user_byteball_address, user_device_address, function(err, unit){
	if (err){
		// something went wrong, maybe put this payment on a retry queue
	// handle successful payment

asset is the asset you are paying in (null for bytes), amount is payment amount in the smallest units. If the payment was successful, you get its unit in the callback and can save it or watch further events on this unit.

There are many other functions for sending payments, for example sending multiple payments in multiple assets at the same time, see exports of https://github.com/byteball/headless-byteball/blob/master/start.js.

Offering smart contracts

When you want to create a new smart contract with a user, your sequence is usually as follows:

  • you ask the user to send his payment address (it will be included in the contract)
  • you define a new contract using the user's address and your address as parties of the contract
  • you pay your share to the contract
  • at the same time, you send a specially formatted payment request (different from the payment request above) to the user to request his share. You start waiting for the user's payment
  • the user views the contract definition in his wallet and agrees to pay
  • you receive the payment notification and wait for it to get confirmed
  • after the payment is confirmed, the contract is fully funded

Most steps are already familiar, we'll discuss creating and offering contracts below. These two steps are similar to what happens in the GUI wallet when a user designs a new contract. For further details see https://github.com/byteball/byteball/blob/master/src/js/controllers/correspondentDevice.js#L289.

Creating contract definition

Create a javascript object that defines the contract:

var arrDefinition = ['or', [
	['and', [
		['address', USERADDRESS],
		conditions when user can unlock the contract
	['and', [
		['address', MYADDRESS],
		conditions when I can unlock the contract

Create another object that describes the positions of your and user addresses in the above definition:

var device = require('byteballcore/device.js');
var assocSignersByPath = {
	'r.0.0': {
		address: user_address,
		member_signing_path: 'r', // unused, should be always 'r'
		device_address: user_device_address
	'r.1.0': {
		address: my_address,
		member_signing_path: 'r', // unused, should be always 'r'
		device_address: device.getMyDeviceAddress()

The keys of this object are r (from "root") followed by indexes into arrays in the definition's or and and conditions. Since the conditions can be nested, there can be many indexes, they are separated by dot.

Then you create the smart contract address:

var walletDefinedByAddresses = require('byteballcore/wallet_defined_by_addresses.js');
walletDefinedByAddresses.createNewSharedAddress(arrDefinition, assocSignersByPath, {
	ifError: function(err){
		// handle error
	ifOk: function(shared_address){
		// new shared address created

If the address was successfully created, it was also already automatically sent to the user, so the user's wallet will know it.

Sending a request for contract payment

To request the user to pay his share to the contract, create the below javascript object objPaymentRequest which contains both the payment request and the definition of the contract, encode the object in base64, and send it over to the user:

var arrPayments = [{address: shared_address, amount: peer_amount, asset: peerAsset}];
var assocDefinitions = {};
assocDefinitions[shared_address] = {
	definition: arrDefinition,
	signers: assocSignersByPath
var objPaymentRequest = {payments: arrPayments, definitions: assocDefinitions};
var paymentJson = JSON.stringify(objPaymentRequest);
var paymentJsonBase64 = Buffer(paymentJson).toString('base64');
var paymentRequestCode = 'payment:'+paymentJsonBase64;
var paymentRequestText = '[your share of payment to the contract]('+paymentRequestCode+')';
device.sendMessageToDevice(correspondent.device_address, 'text', paymentRequestText);

The user's wallet will parse this message, display the definition of the contract in a user readable form, and offer the user to pay the requested amount. Your payment-waiting code will be called when the payment is seen on the DAG.

Requesting to sign a message

See https://github.com/byteball/byteballcore/wiki/Verifying-address-by-a-signed-message

Accepting private profiles

See https://github.com/byteball/byteballcore/wiki/Using-attested-private-profiles

Code samples

For working samples of code that implements the above functions, see the source code of existing chatbots:

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.