Write your First mesibo Enabled Application - Python

Estimated reading time: 11 minutes

In this part, we will create a simple real-time messaging and calling app for Python. This app will let you log in as two different users so that you can try various mesibo features.

We will quickly explore the following

  • Sending and Receiving Messages

  • Group Messaging

  • Reading Messages from database

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 supports the following platforms.
    • CentOS / RedHat 7.x or above
    • Debian / Ubuntu
    • Mac OS (both, x86 and M1 chip)
    • Raspberry Pi (64-bit)
  • 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

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 = "<use your user token>"
APP_ID = "com.mesibo.python"

# Create a Mesibo Instance
api = mesibo.getInstance()

# Enable or disable End-to-end-encryption
e2ee = api.e2ee();
e2ee.enable(1)

# 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()

input("Press Enter to to send a message...\n")
msg = MesiboMessage("destination")
msg.title = "Hello"
msg.message = "Hello message"
#msg.setContent("pic1.jpg")
#msg.setContent("https://mesibo.com")
msg.send()

#e2ee.getPublicCertificate("/root/pycert.cert")
#print("fingerPrint: " + e2ee.getFingerprint("destination"))

#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):
        """Invoked on receiving a new message 
        or reading database messages
        msg: Message Object 
        """
        try:
            if(msg.isRichMessage()):
                print("\n ## message:", msg.message)
                print("\n ## title:", msg.title)
                print("\n ## subtitle:", msg.subtitle)
                print("\n ## path:", msg.file.path)
                print("\n ## url:", msg.file.url)
                #print("\n ## tn:", msg.file.thumbnail)
            else:    
                print("\n ## Received data:", msg.data)
        except:
            pass

        print("\n ## Mesibo_onMessage: ", msg)
        return 0

    def Mesibo_onMessageUpdate(self, msg):
        """Invoked on receiving a message update
        """
        print("\n ## Mesibo_onMessageUpdate: ", msg)
        return 0

    def Mesibo_onMessageStatus(self, msg):
        """Invoked when the status 
        of an outgoing or sent message is changed.
        """
        print("## Mesibo_onMessageStatus", msg)
        return 0

    def Mesibo_onPresence(self, msg):
        print("## Mesibo_onPresence", msg)
        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 MesiboMessage real-time API for which we will need destination user or group, and the message itself.

msg = api.newMessage("destination")
msg.title = "Hello"
msg.message = "Hello message"
#msg.setContent("pic1.jpg")
msg.send()

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 a group message.

msg = MesiboMessage(96568)
msg.setContent("https://mesibo.com")
msg.send()

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 & Call History

mesibo provides a set of APIs to read messages and call history stored 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 call history
  • 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):
        """Invoked on receiving a new message 
        or reading database messages
        """
        print("## Mesibo_onMessage: ", msg)
        return 0

api = Mesibo()

# Set the name of the database
if(Mesibo.RESULT_FAIL == api.setDatabase("mesibo.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