Create Publication

We are looking for publications that demonstrate building dApps or smart contracts!
See the full list of Gitcoin bounties that are eligible for rewards.

Tutorial Thumbnail
Intermediate · 1 hour

Algorand-Telegram Interactions: Part 1 - The Basics

Every application we use is simply a human-machine interaction. You input or hit a command button and a return message is sent back to you. This is how a Telegram bot operates. You invoke a command, and it performs some background processes and return to you the result. If you are on a search for an application with an enormous user base to increase visibility for your business, product, services or project, you should consider exploring Telegram.

This introductory tutorial get you started building a bot which connects to the Algorand blockchain. Your Telegram username will be linked to your Algorand account and used to invoke transactions on the network.

Things you will be exposed to:

  • Working with Algorand Python SDK
  • Creating a Telegram bot and token
  • Running Algorand-based transactions within the Telegram App

Requirements

Requirements

  • Algorand Python SDK: pip install py-algorand-sdk
  • Telegram Module: pip install python-telegram-bot
  • Telegram Application + Username

Background

Telegram is a messaging application with fascinating end-to-end encryption which has made it famous to date. It also provides front-end service to developers looking to implement their ideas but have little or no experience with front-end development. As back-end devs, we spent most of the time in the engine room. For me, working with front-end frameworks has been quite tough to experiment my idea but with Telegram bot, it has became real. If you are looking to building decentralized applications such as supplychain, digital payment etc, you might want to consider this model.

Steps

Create Telegram Bot and Extract Token

Firstly, we will need a way to identifier our bot (i.e Bot Token) and the Bot Father helps you to get it. It is the base for all Telegram bots, helps you manage your bot(s). It is important we create a bot and get a token before moving on to coding. See How to set up a bot.

How-to:

  • Open the Telegram app, search for BotFather and Start a conversation with it.
  • Send the /newbot command to create a new bot for yourself.
  • Supply the Bot’s name and username. This should get you a new bot if the names are unique i.e not already available. A token will be provided to you which should be kept secret. Anyone with it can control your bot.
  • We will need the token later.

EditorImages/2021/01/09 13:39/image_2021-01-09_143935.png

Open your editor, I’d recommend Pycharm if you don’t already use one. Import the necessary modules. Before you proceed, do familiarize with the python-telegram library and a few examples here.

Get the Tutorial Code

Start by cloning the project repository from GitHub:

$ git clone https://github.com/bobeu/algo-telegram-bot
$ cd algo-telegram-bot/algo-telegram-bot-tut-1

Connect your Program to Algorand

Let’s connect to an Algorand node. In your editor, open connection.py.

from algosdk.v2client import algo
url = ""SPECIFY THE V2 URL HERE""
algod_token = "SPECIFY YOUR ACCESS TOKEN HERE"

def connect():
    # Here I use a third party API service to connect to the algod client 
    # since I don't enough resources to run a full node. 
    # Algorand has provided more information on how you can connect
    # to the client even if you cannot run a node and still have
    # access to a lot of features just as if you're running a node. 
    # https://developer.algorand.org

    algod_url = url
    algod_auth = os.environ.get('ALGODTOKEN')
    headers = {"X-API-Key": algod_token}
    try:
        return algod.AlgodClient(algod_auth, algod_url, headers)
    except Exception as e:
        return e


algod_client = connect()

Three things are crucial to getting connected thus:

  • algod_url : An address or path pointing to the Algorand client. It should be in this format –> https://testnet-algorand.api.purestake.io/ps2 which specifies we want to connect to the Algorand Testnet V2 client.

  • algo_auth : An access token. Since we are not running a node, hence we can subscribe to third party service. See https://purestake.com .

  • header : You should specify this to inform the client you’re connecting with via a third party.

Info

Please diligently follow the documentation in the code below. I have provide much of the explanation in comment to enable you understand as you code along.

Let’s create a simple application that reads from the Algorand blockchain. With it, users will be able to perform the following functions that run on the Algorand Testnet.

Open main.py file in your editor. In this file you’ll find the functions:

  • start() - Greets and provides guides to new user, and initiates conversation with the bot.

def start(update, context):
    user = update.message.from_user
    reply = "Hi {}! I am ALGOMessenger.".format(user['first_name'])
    reply += (
        "I can help you with a few things.\n"
        "Tell me what you need to do.\n"
        "They should be from the menu.\n"
        "Alert!\nYou should create an account first before running other ...

  • account_status() : Takes user’s account address/public key and returns all available information about it.

def account_status(update, context):

    pk = context.user_data['default_pk']
    status = algod_client.account_info(pk)
    for key, value in status.items():
        update.message.reply_text("{} : {}".format(key, value))

    return ConversationHandler.END ...

  • end_chat() : Every command initiates a conversation. So, this function terminates current session.

def end_chat(update, context):
    update.message.reply_text(
        "Your current session is terminated.\n"
        "Click /start to restart."
    )
    return ConversationHandler.END ...

  • query_balance(): This function returns the balance of an account address (both in Algos and ASA) you generated previously. So you should Create an account first before attempting to call the getBalance else, you error. When you create an account, the keys are stored in the Telegram user context and will be able to retrieve it later. It does not cover how to collect input from user.

def query_balance(update, context):
    pk = context.user_data['default_pk']
    update.message.reply_text(
            "Getting the balance on this address:   {}.".format(pk)
        )
    if len(pk) == 58:
        account_bal = algod_client.account_info(pk)['amount']
        update.message.reply_text(
                "Balance on your account: {}".format(account_bal)
            )...

  • get_mnemonic_from_sk() : Given a private key, it imports the corresponding mnemonic words (usually 25 word phrase).

def get_mnemonics_from_sk(update, context):

    sk = context.user_data['default_sk']
    phrase = mnemonic.from_private_key(sk)

  • create_account() : Generates and returns account key pair. Since this application runs on Testnet, user should create an account first in order to test other functions.

def create_account(update, context):
    """
    Returns the result of generating an account to user:
        - An Algorand address
        - A private key.
    """
    update.message.reply_text(
            "Hang on while I get you an account ..."
        )
    sk, pk = account.generate_account()
    update.message.reply_text("Your address:   {}\nPrivate Key:    {}\n".format(pk, sk))
    update.message.reply_text(
        "Keep your mnemonic phrase from prying eyes.\n"
        "\nI do not hold or manage your keys." ...

  • Other functions(): Except for main(), every other functions not sending query to the Algorand blockchain are supplementary:

    enquiry()
    help()
    done()

  • main.py holds the program logic. It determines how the whole program should run. It acts as a body for every peripherals of the program. First we create an updater, inside which we pass the bot token.
    We then access the dispatcher from the Updater class. Using the add_hander(), we supply the CommandHandler class. The CommandHandler usually takes 2 parameters: the command we want the bot to listen to and the callback function which is returned whenever a user invokes the command. Repeat this pattern for every defined function in this file

def main():
    # Create the Updater and pass it your bots token.
    # can be any valid name.
    pp = PicklePersistence(filename=<specify a name for here>)
    updater = Updater(<The token got from Bot Father should be here>, persistence=pp, use_context=True)

    # Get the dispatcher to register handlers
    # and handles the front-end
    dp = updater.dispatcher

    # For example, sending a /start command triggers the 
    # 'start' function
    # This is done using the Commandhandler module.
    # When using the CommandHandler function, omit the back slash, otherwise
    # it throws.

    dp.add_handler(CommandHandler('start', start))
    dp.add_handler(CommandHandler(
            'Create_account', create_account)
        )
    dp.add_handler(CommandHandler(
            'Get_Mnemonics_from_pky', get_mnemonics_from_sk
        ))
    dp.add_handler(CommandHandler(
            'Query_account_balance', query_balance)
        )
    dp.add_handler(CommandHandler('Account_status', account_status))
    dp.add_handler(CommandHandler('Done', end_chat))
    dp.add_handler(CommandHandler('About', enquire))
    dp.add_handler(CommandHandler('help', help_command))
    dp.add_handler(CommandHandler('enquire', enquire))

    # Starts the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process 
    # receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the 
    # bot gracefully.

    updater.idle()


if __name__ == '__main__':
    main()

Interact with Algorand Using Your Bot

Now that we are done with the code, let’s run it locally. Open Telegram and launch your bot. Or search for using the bot’s name, mine is Algobot20. Another way is to launch your bot directly from the Bot Father. Start a conversation with it, and you should see the bot respond to the right command if everything works well.

  • Search for the bot

EditorImages/2021/01/09 16:05/2.png

/start the bot

EditorImages/2021/01/09 16:05/3.png

  • /Create_account.
    • Copy the address.
    • Go to the dispenser and fund it with Test Algos

EditorImages/2021/01/09 16:06/4.png

  • Get the private key you previously generated and /Get_mnemonic_from_pky

EditorImages/2021/01/09 16:06/5.png

  • /Query_account_balance

EditorImages/2021/01/09 16:06/6.png

  • /Account_status gets account information.

EditorImages/2021/01/09 16:07/7.png

So far, the bot responds correctly. We are able to:

  • Create an account on Algorand Testnet.
  • Generate mnemonic keys from the private key. 
  • Query account balance.
  • Check the status of our account.

At this point, you might want to deploy it to a live server so anyone can interact with it. There are couple of methods available at your disposal such as using Heroku or Google cloud service. In part 2, I will walk you through how to deploy on the latter.

How does this help me as an Algorand developer?

The key take away from here is to be aware of the different and easier ways you can interact with the back-end. you can write and deploy a decentralized applications/smart contract on Algorand blockchain without learning web development. It might be an easier way to showcase your idea or product or demo. It as well good for production but do your own research to know which is suitable for your project depend on your target users. This tutorial gives only a tip of what you can create as Algorand developer.
Full code is available on Github.

References