Write your First mesibo Enabled Application - Python

Estimated reading time: 11 minutes

In this part, we will create a simple real-time app for Python.

The app will allow you to log in as two different users so that you can try various mesibo features. We will cover the following in this part.

Please go through the following prerequisites before you read further.

Prerequisites and Download Source Code

  • Read the section Create Users to learn about creating an app in mesibo console and creating users & access tokens for your app.
  • Installed the mesibo Python Package by following the instructions here. Mesibo Python Package is still under-development and supports the following platforms. However, it is completely functional.
    • CentOS / RedHat 7.x or above
    • Debian / Ubuntu
    • Mac OS (In Progress)
    • Raspberry Pi (In Progress)
  • See the examples directory on the mesibo Python GitHub repo for runnable example scripts.
  • Basic knowledge of writing and running Python code

Configure and Build First Python App

Now let’s quickly start coding:

From the mesibo python package import the function class Mesibo and the callback class MesiboListener

from mesibo import Mesibo
from mesibo import MesiboListener

Code Explanation

Initialize mesibo

Before you send and receive real-time messages and calls, you need to initialize mesibo. The initialization involves the following steps:

  1. Use setAccessToken to set the user’s access token that you obtained while creating the user
  2. Set up mesibo to invoke your listener class using addListener
  3. Set up database to store sent and received messages using setDatabase (Optional)
  4. Start mesibo

Note that, except addListener, all other initialization functions should be only called once.

Now, initialize mesibo like shown below

# Get access token and app id by creating a mesibo user
# See https://mesibo.com/documentation/tutorials/get-started/
ACCESS_TOKEN = "xxxx"
APP_ID = "xxxx"

# Create a Mesibo Instance
api = Mesibo()

# Set Listener
listener = PyMesiboListener()
api.addListener(listener)

# Set your AUTH_TOKEN obtained while creating the user 
if(Mesibo.RESULT_FAIL == api.setAccessToken(ACCESS_TOKEN)):
    print("===> Invalid ACCESS_TOKEN: ", ACCESS_TOKEN)
    print("See https://mesibo.com/documentation/tutorials/get-started/")
    exit(1) 

# Set APP_ID which you used to create AUTH_TOKEN
api.setAppName(APP_ID)

# Set the name of the database
api.setDatabase("mesibo.db")

# Start mesibo, 
api.start()

send_text_message(api, "456", "Hello from Python!")

#Wait for the application to exit
api.wait()

mesibo invokes a class of Listeners for various events.

Derive from the MesiboListener class to implement listeners as shown below.

If you have a time-consuming action to perform inside any of the listeners, it is recommended that you run the time intensive function in a new thread, so that you don’t block mesibo listeners

class PyMesiboListener(MesiboListener):

    def Mesibo_OnConnectionStatus(self, status):
        """A status = 1 means the listener 
        successfully connected to the mesibo server
        """
        print("## Mesibo_OnConnectionStatus: ", status)
        return 0

    def Mesibo_OnMessage(self, msg_params, data):
        """Invoked on receiving a new message 
        or reading database messages
        data: bytearray 
        """
        message = None
        try:
            # try to decode string
            message = data.decode(encoding="utf-8", errors="strict") 
            print("\n ## Received message:", message)
        except:
            pass
        
        print("\n ## Mesibo_OnMessage: ", msg_params)
        print("## Received Data: \n", data)
        # handle: integer, bytes, etc

        return 0

    def Mesibo_OnMessageStatus(self, msg_params):
        """Invoked when the status 
        of an outgoing or sent message is changed. msg_params.status can be
        sent, delivered, or read
        """
        print("## Mesibo_OnMessageStatus", msg_params)
        return 0

    def Mesibo_OnActivity(self, msg_params, activity):
        print("## on_activity", msg_params, activity)
        return 0
    
    def Mesibo_OnFile(self, msg_params, file_params):
        print("## on_file", msg_params, file_params)
        return 0 

That’s it - you are now ready to send and receive your first real-time message.

Sending and Receiving Messages

Now we will quickly learn how to send messages in real-time.

To send messages, we will use sendMessage real-time API for which we will need destination user, message-id, and the message itself. Invoke the following function anywhere from your code to send a text message. In a later section, we will learn how to send rich messages.

def send_text_message(api, address, message):
    params = Mesibo.MessageParams()
    params.peer = address
    params.flag = Mesibo.FLAG_READRECEIPT | Mesibo.FLAG_DELIVERYRECEIPT
    mid = api.random()
    api.sendMessage(params, mid, message)

For example:

# api is the Mesibo instance
send_text_message(api, "456", "Hello from Python!")

Once you send a message, the recipient will receive the message through Mesibo_OnMessage. mesibo will inform the sender of the message about the status of the message - sent, delivered, or read through the listener Mesibo_onMessageStatus.

Group Messaging

Group messaging is no different from the one-to-one messaging. You can invoke the same messaging APIs to send a group message, instead of the user’s profile, you need to use group profile.

For example, here is an example of how you can send a message to a group. Let’s say you have a group with the group-id 96568. Now, you use the same function that you use for sending a one-to-one message, but instead of using the user profile, you first get the group profile using the group-id and use it to send group message.

params = Mesibo.MessageParams();
params.groupid = 96568;
params.flag = Mesibo.FLAG_READRECEIPT | Mesibo.FLAG_DELIVERYRECEIPT;
message = "This is a group message";     
api.sendMessage(params, api.random(), message);

A message sent will be delivered to all members of the group and you will get the message delivery and read status for each user.

Creating a Group

To create a group and add members, you need to use the Group Management APIs. This is the recommended approach. However, you can also create a group and add/remove members by using backend APIs and mesibo console if requires.

You can create a new group by calling createGroup API, with name and the Group Listener Object.

It will send a request to the server to create a new group. When a group is created, callback function in the listener will be called with the group profile. You can then add members to the group using group profile APIs.

You can now use this new group profile for messaging, adding more members or changing group name, description, picture, etc.

Adding members to a Group

You can add members, and admins to the group by calling addMembers API of the group profile. You need to pass the addresses of the users to be added as group members, permissions to be granted and admin permissions if you are adding them as group admins.

For example,

Reading Messages

mesibo provides a set of APIs deal with stored messages in the database and sending read receipts. A read receipt is an acknowledgment that the user has read the message.

To read stored messages from the database, you need to create a read session and set the criteria to read messages; for example,

  • read all messages
  • read messages from a sender
  • read messages for a particular group
  • read messages matching a search query etc.

The read session you create filters the messages in the database based on the criteria provided and gives the resulting list of messages to you.

Reading Modes

There are two modes of operation:

  • Read Messages and call logs. This mode is enabled by default
  • Read Summary (active conversations), read the latest message from each user and group. This allows you to get a snapshot of all the communicating users and groups. You can then create another read session to read messages for any of those users or groups.

Reading Order

Once you set a read session, you can start reading messages by calling read API. You can read messages in the first-in-first-out (FIFO) mode or the last-in-first-out (LIFO) mode. In the first-in-first-out model, the oldest messages are read first. By default, the first-in-first-out mode is disabled.

Read Receipts

You can enable the automatic sending of read-receipts every time you read a message. This can be achieved by enabling a read-receipt for the read session. On reading or receiving a message, read receipts will be automatically sent if

  • The app is set to be in the foreground
  • Sending Read Receipt is enabled for the reading session, AND
  • Read receipt requested by the sender, AND
  • A new real-time or database message matches the read session.

A call to read will return the number of messages read. You can call read on demand. For example, in the case of a messaging app, you only need to show the latest messages on the screen initially. So, first, you can call read(10) to load the last 10 messages. As the user scrolls up the chat history, you can call read again. All subsequent calls to read will read older messages.

To read messages for a user,

class MesiboReadListener(MesiboListener):
    def Mesibo_OnMessage(self, msg_params, data):
        """Invoked on receiving a new message 
        or reading database messages
        data: python byte array 
        """
        print("## Mesibo_OnMessage: ", msg_params)
        print("## data: ", data)
        return 0

api = Mesibo()

# Set the name of the database
if(Mesibo.RESULT_FAIL == api.setDatabase("mesibo-241095.db")):
    print("Unable to set database")
    exit(1)

# Create listener through which you will be notified of messages read
listener = MesiboReadListener()

user_address = "123" #Example 
rs = api.ReadDbSession(user_address, 0, None, listener);
rs.enableReadReceipt(True);
rs.read(100);

To read messages for a group,

groupid = 96876 #Example
rs = api.ReadDbSession(None, groupid, None, listener);
rs.enableReadReceipt(True);
rs.read(100);

To read the last message from each user (summary),

rs = api.ReadDbSession(None, 0, None, listener);
rs.enableSummary(True);
rs.read(100);

On calling read, the listener Mesibo_OnMessage will be called for each message read in the database in this read session.

Sending Files >>

mesibo, get-started, tutorial, python