Polybot Project: a Simple Pretty Logger


In a series of blog posts “Python : Telegram Bot Webhook Handler : A Multi-Bot/Multi-Language Design” (1-8) (see references) we discussed how we could design a multi-bot/multi-language webhook handler to host some Telegram bots each of which could speak any of (so far) three languages based on the user’s choice. At the last few posts, we chose the name polybot for this project.

Until this point, I ran the flask web framework locally on my home computer, and with some trick, I made this local flask server look like a full operational server under the reach of the Telegram server. I set up the real-world code of the webhook handler hosted by the local flask, and also reported the available webhook URLs to the Telegram system for each bot. I tested the code as well as the conversations with the local bots successfully during the progress of the blog posts of the series.

Today, I ported the codes to the remote server of PythonAnywhere, and I tested the codes successfully. There are three bots now available for the users’ tests. You could compare their behaviors and operations … in particular, how they could speak different languages, and how they handle different time zones based on the users’ preferences and settings:

Make sure to open the bots’ profile links above in a telegram application. Then start a conversation with each bot using a start command:

/start

In particular, try using the following commands:

/start
/intro
/help
/settings
/time
/hello

The command /help will tell you what each of these commands does. In particular, try examining the /time command each time you change your time zone information with /settings command. You could also try the command /hello each time you change the bot’s language.

If you have already tested Merex before, hopefully you won’t feel any change in his behavior since the new design is compatible with the older code with respect to the bots’ behavior to the commands and conversations … well almost.

There are a few technical details that have not been covered in the series of blog posts yet … such as the interactive mode of bot-user conversations; for example, how a user may change the bot’s language or their current time zone at the startup or using the bot’s settings. These technical details will be discussed in future blog posts.

Logging vs Pretty Printing

When using a local flask server, there is no limitations in using the standard print function of python. Neither is there any limitation in using the pretty print function; that is the pprint function of pprint module (see references).

These two functions help a lot in figuring out what your code is doing, and what sort of objects with what sort of structures your code is dealing with. I personally learnt a lot about the nature of the Telegram updates and messages merely with pretty-printing them and examining their structure before I write a suitable code in the webhook handler to manipulate the updates and messages and to provide a behavior with discipline for my bots.

In the remote servers such as PythonAnywhere, these two functions are not available as in a standard python console application or as in a local flask web framework. The best alternative is the server’s logging facility for which the standard python logging module looks fair enough (see references).

The available functionality of the logging module works fine as a replacement of the print function. In fact, you could still use this module for many other areas … including normal console-based applications, or more importantly, console-less applications. Our current remote server of PythonAnywhere is one of those console-less cases here.

A dedicated Pretty Log module : plog.py

The replacement of the pprint function using the logging module is simple: a single-file module plog.py could do it well:

# -*- coding: utf-8 -*-
#
#  plog.py
#

from pprint import pformat



class Plog :
    def __init__(self, logger) :
        self.logger = logger

    def info(self, *args, **kw_args) :
        Plog.pretty_log(self.logger, 'info', *args, **kw_args)

    def warning(self, *args, **kw_args) :
        Plog.pretty_log(self.logger, 'warning', *args, **kw_args)

    def error(self, *args, **kw_args) :
        Plog.pretty_log(self.logger, 'error', *args, **kw_args)

    def debug(self, *args, **kw_args) :
        Plog.pretty_log(self.logger, 'debug', *args, **kw_args)


    @staticmethod
    def pretty_log(logger, level, message, obj) :
        method = getattr(logger, level)
        method(message + '\n' + pformat(obj))

The instance object of the class Plog in this module helps to visualize various objects exactly the same way that the normal pprint function does. It prints a normal log text line followed by a structured python object.

Usage Examples

The usage is simple, too. In the main flask_app.py module; you could place these lines in the global area:

import logging
from plog import Plog

#~ logging.basicConfig(format='%(asctime)s [%(levelname)-8s] %(message)s', stream=sys.stderr, level=logging.DEBUG)
logging.basicConfig(format='[%(levelname)-8s] %(message)s', stream=sys.stderr, level=logging.DEBUG)
logger = logging.getLogger(__name__)
plog = Plog(logger)

You could use (un-comment) the basicConfig with %(asctime)s specifier, if your server does not insert current date/time automatically. In other modules:

import logging
from plog import Plog

logger = logging.getLogger(__name__)
plog = Plog(logger)

Apart from our new plog pretty logger, using logger defined as the codes above … instead of directly using logging itself … is the preferred and recommended way of using the logging module according to the documentations.

Now, to simply print a message (in its simplest form) in the system log, we could use one of the methods:

logger.info('some text message')
logger.warning('some text message')
logger.error('some text message')
logger.debug('some text message')

It prints a message it the system log with much more discipline than the normal print function. Each message line follows the rules that you set using the basicConfig method. Each of these methods (info, warning, …) are the various levels of the log which make the associated message text to be hidden or visible when you set or change the level of logging (refer to the documentation for a thorough insight).

And if you wish to pretty-print a python object, say, a dict object with a caption:

plog.info('some caption', some_object_such_as_a_list_or_a_dict)
plog.warning('some caption', some_object_such_as_a_list_or_a_dict)
plog.error('some caption', some_object_such_as_a_list_or_a_dict)
plog.debug('some caption', some_object_such_as_a_list_or_a_dict)

That’s it. For the text messages and captions, the f-string representation of the string literals in python 3.6 helps a lot in writing concise readable program codes for the logging stuff.

References:

Posted in Flask, Python, Telegram Bot | Tagged , , , , , , , , , | Leave a comment

Python : Telegram Bot Webhook Handler : A Multi-Bot/Multi-Language Design (8)


Multiple-Language Functionality

In this post, we will add the multiple languages functionality to the polybot project so that our bots could speak a few languages based on the corresponding user’s preference.

The plan is that a bot speaks the language of the user’s choice. In order to make the bot remember the user’s preference, we need to implement a session preserve-retrieve mechanism acting on a unique persistent data-ware for each individual bot-user pair communication. This is where we need the session data-ware. The practice is that the handle_chat function code loads the user-bot session data (if exists or uses the default data otherwise) as soon as the user sending the message and the bot referenced in the webhook URL are known, and saves the session data just before the handle_chat function returns. It is necessary to save the session data at the end because it is probable that the codes inside the processing message functions modify the session data for the next updates. For example, user sends a bot command to change some preference.

The language of user’s choice as well as the gender of bot make it possible to find out which sentence code from which language database must be picked as the message text whenever the bot is meant to send a text or a reply message back to the user.

It is possible to use any SQL database (MySQL, SQLite, …) with unicode character set support to provide sentence codes of the supporting languages. That’s beyond the scope of this blog post, and if you plan to implement such a system, you may consider to convert my approach to a database-based sentence look-up. It’s not trivial but not difficult at all.

My approach is a simple lookup in a python config file code.ini; that is the [section] key=value ini file. The number of sentences used by the bots are few enough, and loading multiple config files (one for each language) is light and fast for our purpose.

Setting up code.ini File

The principle definitions are placed in a settings file code.ini as:

[main]
default_lang = en
languages = en, fa, fr
default_timezone = 'Europe/London'

In my design, the existence of English is a must, and it should never be eliminated. You nerds could figure out how you could eliminate English if you wish and let your language be the default. It’s not mandatory but useful and straightforward to use two letter ISO 639 language codes (https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) to identify the languages. Therefore, en, fa and fr are the codes for languages English, Persian (Farsi) and French respectively. It’s a great chance that I could understand these 3 languages at the time of writing this post; especially for French which has a clear distinction between the male and female speakers in some cases; and of course, especially for Persian since it is (like Arabic) a right-to-left (RTL) direction script. English and French are left-to-right (LTR).

The variable default_timezone is reserved for later when we wish to examine the user-bot interactive conversation. It is used to make bot remember the user’s timezone when generating a date/time string to be used in the message text.

This file, code.ini, is placed in the main directory of our project.

Setting up English code-en.ini codebook

The must-exist codebook file is code-en.ini and it is in a sub-directory codes. It is also used as a template for any other language codes. for each language defined in the code.ini settings above, there must be an existing matching code-xx.ini file in which xx is the 2-letter ISO 639 language code. Therefore, according to this setting, there must be two extra ini files: code-fa.ini and code-fr.ini.

We could have chosen to search the directory codes to automatically find the installed languages, and it would work fine. However, I decided that the settings:

languages = en, fa, fr

is a better choice if we want to quickly enable or disable some language whose associated code-xx.ini exists in the directory codes. Therefore, to install a new language: first, we must provide a properly translated codebook code-xx.ini file for that language and place it in the codes directory. Finally, we must add its ISO code name to the languages list in code.ini file.

The basic template for code-en.ini is :

[settings]
name = English
abbr = en
dir = ltr

[cal]
TIME_FORMAT = %Y-%m-%d   %H:%M:%S
LONG_TIME_FORMAT = %A %B %d, %Y   %H:%M:%S

month = JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
weekday[s] = SAT, SUN, MON, TUE, WED, THU, FRI
weekday = SATURDAY, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY

[file]
file_id_1 = file_name_1
file_id_2 = file_name_2
file_id_3[female] = file_name_female_3
file_id_3[male] = file_name_male_3

[codes]
code_1 = text_1
code_2 = text_2
code_3[female] = female version of text_3
code_3[male] = male version of text_3

[info]
code_1 = text_1
code_3[female] = female version of text_3
code_3[male] = male version of text_3

[warning]
code_2 = text_2
code_3[female] = female version of text_3
code_3[male] = male version of text_3

[error]
code_1 = text_1
code_2 = text_2
code_3[female] = female version of text_3
code_3[male] = male version of text_3


code_1 = text_1
code_2 = text_2
code_3[female] = female version of text_3
code_3[male] = male version of text_3

[tip]
code_1 = text_1
code_2 = text_2
code_3[female] = female version of text_3
code_3[male] = male version of text_3

[help]
code_1 = text_1
code_2 = text_2
code_3[female] = female version of text_3
code_3[male] = male version of text_3

There are two well-defined sections [settings] and [cal]. In section [settings], the general information about the language is defined: The native name of the language, its ISO code or abbreviation and its flow direction (LTR or RTL). In section [cal], all information about the calendar conventions are defined: The long and short representation of date/time (according to python’s datetime module: https://docs.python.org/3/library/datetime.html), the name of the months, the short and long names of the weekdays.

The sections [file] is used to point to the external files; that is, the values of the variables in this section are filenames rather than sentences in English or any other language. The content of each file is the text that a bot would send as a message text or reply to a user. Using the ExtendedInterpolation feature of configparser module (https://docs.python.org/3/library/configparser.html), it is possible to assign an automatic name for our files:

file_id_n = file_n_prefix-${settings:abbr}.txt

If we keep this pattern in all code-xx.ini files, then all the files are automatically labelled by each language; for example, file_n_prefix-en.txt, file_n_prefix-fa.txt, file_n_prefix-fr.txt, …

The external files are kept in a relative files sub-directory.

The other sections: [codes], [info], [warning], [error], [question]. [tip] and [help] are the mood or icon sections. In my design, the [codes] section is the default moodless sentence codes. If the variable key is missing in any other mood section, then the value would be searched in this [codes] section. It is a feature that we will add to our design. It’s not the default behavior of configparser module whose default section is called [DEFAULT]. Other mood sections indicates which emoji set must be used automatically along with the given sentence. The section names describe which emoji to use very well; for example, for the variables in [info], each equivalent sentence would be prefixed with ℹ️ emoji. For [tip], the emoji is a turned-on electric bulb and it is meant to suggest some tips.

The section [help] is a special section for an automatic help-string generation for any language in our design. This section would have an entry for each visible bot command so that a command /help could generate a help menu in each language. It could also be used to generate a help-string for each command for BotFather using /setcommands. Unfortunately, the Telegram system do not support multiple languages for this purpose, and we can do that only for one language. The Telegram system does not behave perfect for an RTL language either. So, our options reduce to English or French only. In my design the choice is English. The section [help] is also moodless.

For each phrase code code_n, there could be two varieties of entries in each mood sections: code_n[male] and code_n[female] which are automatically selected based on the gender of the bot. The rule is simple; for example, for a female bot, if code_n[female] exists, it is used … otherwise, the default code_n would be used. We would use a smart function, so that we will always use the key code_n (without gender prefix) whenever we want to send the associated sentence as a message text on behalf of the bot regardless of their gender.

In my design, I use this criteria to classify the sentences in the mood sections. If it is moodless or it could have multiple moods, it is placed under the [codes] section. If it has one clear mood, it is placed under that mood section.

For a realistic example, you could see the English version of code-xx.ini, that is, code-en.ini in the shared link: https://www.pythonanywhere.com/user/soheilnb/shares/1234e7c1702144b3b2ae3abe1171eda0/. Merex uses this database for the English version of the texts.

Dedicated module for multiple language support: lang_code.py

The module lang_code.py is independent of the rest of the code and works directly with code.ini and code-xx.ini files. It has two main parts: am init code which loads the language database, and a function bot_says with the following signature which is the central function for all automatic translations:

def bot_says(gender, lang, text, section=None, mood=None) :
    pass

The parameter gender is either “male” or “female” and specifies the gender of the bot. The parameter lang is the two-letter ISO language code. The parameter text is actually the code of the sentence to be picked for the given language and bot gender. There is no need at all to specify the [male] or [female] suffix for the code. That is done automatically by this function.

The parameter section is the explicit mood section of the text code if it is not specified in the text parameter itself. As we will soon see in the function implementation, the preferred method of specifying the mood is in the text code itself:

# preferred method : main mood is given in the text code 
reply_text = bot_says(my_bot_gender, user_lang, 'SOME_TEXT_CODE@info')

and

# alternative method : main mood given is section keyword
reply_text = bot_says(my_bot_gender, user_lang, 'SOME_TEXT_CODE', section='info')

In my design, both of these function calls (well, almost) return the same things. The first convention is the preferred and more convenient way to specify the mood section. The second method is useful whenever the text parameter is a variable and not a string literal. It helps us not to use the ugly combination : text_var + ‘@info’ for the text parameter.

The parameter mood is not to be mistaken with the mood sections; if you wish to append some emoji at the end of the text, you pass the emoji as the mood parameter. The mood icons according to the mood section names always come before the sentence text. And the extra emoji (given by the mood parameter) is appended at the end of the sentence. If one wishes a custom emoji at the beginning, they could either modify my code to cover more mood sections or they could simply insert the emoji where they like in the sentence value itself, and they would place the sentence in the [code] moodless section in which it has no default associated emoji at the beginning.

The implementation of the lang_code.py module is available in the shared link: https://www.pythonanywhere.com/user/soheilnb/shares/c4ce01244fb64f6abc1e117c6a208eb5/.

The auto_say function in proenv data-ware

Our bot may speak in a specific language only in a reply to a user’s command or a user’s conversation in general. In the context of a webhook operation, it is when an update arrives from the Telegram server, and our app.route function route_polybot_hook handles the update in the form of a request. Fortunately, the flask global g variable is always available during the processing of the request.

We almost never need to call the above function: bot_says, directly. We could use a more convenient function: auto_say which is defined as simple as:

def auto_say(text, section=None, mood=None) :
     gender = g.bot_info.gender
     lang = g.session.lang
     return bot_says(gender, lang, text, section=section, mood=mood)

proenv.auto_say = auto_say

We assumed that the session data-ware is available whenever this function is called, and it contains the user’s preferred language as the lang attribute or key name of session. The gender of bot is also available in the bot_info data-ware.

This auto_say function helps us to keep or mind free of the constant questions whether or bot is a male or female one, and which language is the user’s choice.

This function is placed in flask_app.py main module anywhere in the global area after the definition of proenv data-ware.

In other modules, if g is available under the name extras as the function parameter, we could use this function in the body code of that function as:

reply_text = extras.proenv.auto_say('Hello@codes')

which returns, for example, the bot’s greetings text in the language of the corresponding user’s choice … regarding the bot’s gender if that makes a difference.

Preserving and Retrieving user’s preferences: the session Data-ware

Two global functions: load_session and save_session are used to retrieve and preserve session data and information including users’ various preference per bot-user pair conversations:

def load_session(bot_name, sender_id, _dict_data=None, **kw_args) :
    pass

def save_session(data, bot_name, sender_id) :
    pass

The parameters bot_name and sender_id are the bot-user pair information used to uniquely identify which session data are referenced for saving or retrieval.

In load_session, the default data (if the session data is missing or it does not contain some specific required information) could be passed either by a python dictionary object or expando object (_dict_data), or by some key=value pairs directly pass as the kw_args argument represents the collection of such pairs as a dictionary object. It is possible to pass both parameters at the same time; that is, a dictionary object as well as key=value pairs in which case, the kw_args values override the final values in case some keys appear in both parameters. This function returns the loaded or the default session data-ware which is an expando object.

In save_session, the data to be preserved is passed to function as the first parameter (data). It is the session data-ware and must be the same expando object which is obtained by the load_session function … possibly with some value modified by the message processing code between load and save operations.

The implementation code is easy. It uses two helper functions load_pickle_data(pickle_file, default_data) and save_pickle_data(data, pickle_file) which loads and saves a python pickle file in general and a get_session_pickle_path(bot_name, sender_id) function which returns a unique path bases on the current bot name and user id. This path would be in a directory which could safely be assumed to be existing when this path is obtained; that is, the directory would be created if not exists.

def load_pickle_data(pickle_file, default_data) :
    data = Expando(default_data)
    if os.path.exists(pickle_file) :
        with open(pickle_file, 'rb') as ifile :
            saved_data = pickle.load(ifile)
            expando_update(data, saved_data)

    return data


def save_pickle_data(data, pickle_file) :
    with open(pickle_file, 'wb') as ofile :
        pickle.dump(data, ofile)



def get_session_pickle_path(bot_name, sender_id) :
    path = os.path.join(session_path, bot_name, f'U{sender_id}')
    if not os.path.exists(path) :
        os.makedirs(path, exist_ok=True)

    return os.path.join(path, '.session.pickle')


def load_session(bot_name, sender_id, _dict_data=None, **kw_args) :
    session_data = Expando(_dict_data)
    expando_update(session_data, kw_args)
    session_file = get_session_pickle_path(bot_name, sender_id)
    return load_pickle_data(session_file, session_data)


def save_session(data, bot_name, sender_id) :
    session_file = get_session_pickle_path(bot_name, sender_id)
    save_pickle_data(data, session_file)

A normal session related operation would be a sequence of three steps in this exact order:

1) load session data (remembered from the last conversation)
2) processing the message ... possibly modifying some variables in session data
3) save session data (to be use for the next conversation)

It is very import that these three steps take place in a single atomic step; there should not be another session load or save on the same bot-user pair occurring in this atomic step … that is … since the beginning of loading data until the end of saving data. We have set our webhook URL with the Telegram server using max_connections=1. That ensures that there is only one update be processing at any time. And that ensures that there would not be two or more simultaneous attempts to either load or save the same session data at any given instance of a Telegram update processing. If we do not want to rely on this theory, and we wish to ensure an atomic operation on session data, we could use the locking mechanism:

from lockfile import LockFile

...

def handle_chat(message, extras) :
    flavor = telepot.flavor(message)
    assert flavor == 'chat'

    content_type, chat_type, chat_id = telepot.glance(message, flavor=flavor)
    sender_id = message['from']['id']
    expando_update(extras.provars, content_type=content_type, chat_type=chat_type, chat_id=chat_id, sender_id=sender_id)
    extras.provars.sender_info = get_sender_info_summary(message)
    extras.provars.chat_info = get_chat_info_summary(message)
    extras.provars.auth = get_user_auth(message, extras)

    TEMP_SUFFIX = app.config['TEMP_SUFFIX']
    lock = LockFile(f'/tmp/.LOCK_polybot_{extras.bot_info.name}_U{sender_id}_{TEMP_SUFFIX}.lock')
    with lock:
        extras.session = load_session(extras.bot_info.name, sender_id, Expando(lang='en', tz='Europe/London', last_date=None))

        if content_type == 'text' :
            Command.process_text_message(message, extras)

        else :
            text = '{} says : You sent me a "{}" message.'.format(extras.bot_info.name, content_type)
            bot = extras.bot_info.bot
            bot.sendMessage(chat_id, text)


        extras.session.last_date = DT.now()
        save_session(extras.session, extras.bot_info.name, sender_id)


The constant TEMP_SUFFIX is another magic unique string. You could define it in config.py module like:

import hashlib

...

TEMP_SUFFIX = hashlib.md5(SECRET_KEY).hexdigest()

That is, using the MD5 hashing algorithm, you could create a unique hex string from your SECRET_KEY value. Then, use TEMP_SUFFIX value to create a unique path for the lock path in the global /tmp/ directory of the system.

That’s it! Now, our bots could speak multiple languages … one for each user based on their choice. Well, almost done! A few more alterations are to be done yet.

Modifying reply_to function

Most often, when any of the bots is meant to send a user a text message, it would be a reply to their message. In the blog post series number 6 : Providing Decorator for Bot Commands Using a Dedicated Message Text Processing Class (https://911programming.wordpress.com/2019/05/03/python-telegram-bot-webhook-handler-a-multi-bot-multi-language-design-6/) for the monobot project, a handy function, reply_to has been defined to simplify this reply. Now, we could write the polybot version with multi-language support as:

def reply_to(message, text, extras, forced_reply=False) :
    if text.startswith('AUTO:') :
        text = extras.proenv.auto_say(text[5:])

    bot = extras.bot_info.bot
    chat_id = extras.provars.chat_id
    bot.sendChatAction(chat_id, 'typing')

    if forced_reply or extras.provars.chat_type != 'private' :
        reply_to_message_id = message['message_id']

    else :
        reply_to_message_id = None

    bot.sendMessage(chat_id, text, reply_to_message_id=reply_to_message_id)

It’s basically the same function with a slight difference: if the text parameter of this function is already translated to the target language, we simply pass it to the function. Otherwise, if we have the phrase code, and we wish that the translation to the target language to take place in the reply_to function, we preppend the sentence code with a magic prefix ‘AUTO:’ in which case, the translation to the target languages is performed here in this function.

This reply_to function is a global function. We can add it as a static method of the Command decorator class as:

Command.reply_to = reply_to

The new faces of the two static methods in Command decorator: act_bad_command and act_no_command for polybot project would be:

    @staticmethod
    def act_bad_command(command, message, extras) :
        text = extras.proenv.auto_say('BAD_COMMAND@error') + ':\n\n' + command
        reply_to(message, text, extras, forced_reply=True)


    @staticmethod
    def act_no_command(command, message, extras) :
        reply_to(message, 'AUTO:NO_COMMAND@error', extras, forced_reply=True)

‘BAD_COMMAND‘ and ‘NO_COMMAND‘ are two sentence codes under the error mood section with various corresponding sentences in each language. In this two examples, you could see clearly how is it possible to obtain the translated text prior to reply_to function (the first case), and how is possible to let the reply_to function translate the sentence code automatically (the second case … using AUTO: prefix).

Modifying the bot act functions

Now, it’s time to modify the bot act functions (see previous blog posts of this series regarding the monobot project). It’s easy and straightforward. For example, for the hello (act_hello):

It was:

@Command(commands=['hello', 'hi'])
def act_hello(command, message, extras) :
    '''Greetings with this bot.'''
    text = f'Hello! Good to see you again! 🌺'
    Command.reply_to(message, text, extras)

Now it is :

@Command(commands=['hello', 'hi'])
def act_hello(command, message, extras) :
    '''hello@help'''
    text = extras.proenv.auto_say('HELLO@codes', mood='🌺')
    Command.reply_to(message, text, extras)

The obvious differences:

  • the function doc-string is a sentence code in [help] mood section now (hello@help). That’s for the automatic help generation in the language of user’s choice.
  • We don’t use the English texts for the replies anymore. We use phrase codes with auto_say function to generate the ultimate translated text.

Another example:

@Command(commands=['start'])
def act_start(command, message, extras) :
    '''start@help'''
    Command.reply_to(message, 'AUTO:START@codes', extras)

This example uses AUTO: prefix.

Language settings:

Merex et al do language and timezone settings at startup. That exact way of bot-user interactive conversation is beyond the scope of this blog post at the moment. I will leave that for a later blog post in this series.

Well, for now, our bots only speak the preset default language: English! How, we could allow user to choice his preferred language.

The simplest way is a dedicated command /language (could be abbreviated as /lang) for this purpose. We could write it such that without any argument, it reports the current language of the user’s choice. But with a single two-letter ISO language code (if valid) as the command parameter, it modifies the speaking language:

@Command(commands=['language', 'lang'])
def act_language(command, message, extras) :
    '''language@help'''
    if len(extras.provars.args) == 0 :
        Command.reply_to(message, 'AUTO:I_SPEAK@info', extras)

    else :
        new_lang = extras.provars.args[0]

        if new_lang in extras.proenv.languages :
            extras.session.lang = new_lang
            Command.reply_to(message, 'AUTO:LANG_CHANGED@info', extras)

        else :
            text = extras.proenv.auto_say('UNKNOWN_LANGUAGE@error') + ':\n\n' + new_lang
            Command.reply_to(message, text, extras)

The bold text extras.session.lang = new_lang does set the new value for the language preference. These sentence codes are supporting this function in each language:

[info]
I_SPEAK = I speak English.
LANG_CHANGED = I speak English now.

[error]
UNKNOWN_LANGUAGE = I do not know this language

with the exact punctuation. For other languages, these sentences must be properly translated mentioning the correct language in the place of English.

Shared links

The full source code of the polybot project so far is shared at PythonAnywhere at locations:

You could find other necessary shared links from the previous blog posts of this series.

That’s all. This is the end of this series of blog posts about multi-bot/multi-language webhook handler for the Telegram bots. In future, we will talk about other aspects of the design … such as implementing the interactive mode, user’s preferences and settings and helps, handling timezone, etc … in some independent blog posts.

Posted in Flask, Python, Web | Tagged , , , , , , , , , , | Leave a comment

Python : Telegram Bot Webhook Handler : A Multi-Bot/Multi-Language Design (7)


Setting up Multi-Bot Design – polybot project

From this blog post after, we focus on a multi-bot design: polybot project. The first step is to define our bots. Maybe the easiest way is to use a dedicated config file in an ini file of [section] key=value format; that is, something like :

[bot1]
username = BOT1_USERNAME
token = BOT1_TOKEN
gender = male OR female

[bot2]
username = BOT2_USERNAME
token = BOT2_TOKEN
gender = male OR female


[bot3]
username = BOT2_USERNAME
token = BOT3_TOKEN
gender = male OR female

We make sure to use the real-world information for as many bot as we have. the section names: bot1, bot2, and bot3 are the name of the bots. For the sake of clarity, the names are in lowercase. token is the bot’s authorization token string, and gender must be either male or female with male as default if not set or if miss-set. For Odin, the ini would be something like:

[odin]
username = odin_2020_bot
token = 802546293:AAEOWUGetwCubgqpIgK1l8g4C2w6iwHX3Eq
gender = male

The Odin’s token is an example here. It’s obviously fake. Of course, having the bot’s authorization token, it’s easy to obtain the bot’s name and username using the telepot.getMe method. Therefore, rewriting that information here is just like caching it. We call this ini file bots.ini and place it in the same directory as our flask_app.py script.

Now that the bots are introduced and configured in the bots.ini settings file, we can remove the unnecessary info from the config.py file. Now, config.py is like:

# -*- coding: utf-8 -*-
#
#  config.py
#
#

import os.path

HOST_URL = 'https://YOUR-BASE-URL-FOR-WEBHOOK'

# copy and paste from interactive python3 ... running this simple code :
# import os
# os.urandom(24)
# for example :
# SECRET_KEY = b'\xe6\x8d\xe8H\x89\xad\xb7\x19\xc5\xdb\xe7[\xe7\xe8\xdaA$\x0f\xd6Fl\x04`T'
# in python 3.6 you can also use secrets module : secrets.token_bytes(24)
SECRET_KEY = 'a 24-byte Byte Array' # it's a pre-generated secret key 

PROJECT = 'polybot' # or the name of your choice
APT_PATH = os.path.dirname(os.path.realpath(__file__))
PROXY_URL = 'YOUR PROXY URL' or None

# It's handy. Let the bot sometimes report to you something!
ADMIN_ID = MY_TELEGRAM_INTEGER_ID

If you have read the previous blog post, and you would like to follow this project design, you would need to place your information in this file. The shared link of this file in my PythonAnywhere account is https://www.pythonanywhere.com/user/soheilnb/shares/fe0549c50dca4bc8b9cd6193442e7d58/. I emphasize that you shouldn’t generate a new secret key (SECRET_KEY) each time this script is executed. You could change it from time to time if you like, but you shouldn’t do it in this script like:

import secrets
SECRET_KEY = secrets.token_bytes(24)

You should obtain this value by other means … for example, by running this code in interactive python:

Python 3.6.0 (default, Mar 18 2017, 02:34:49) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.                                                                                                         
>>> import secrets
>>> secrets.token_bytes(24)                                                                                                                                                    
b'\xa9\xd0\x82\x87#\x1f\xdf>%Jj\x16I\x9b\xdb\x14\xecj\xd6\xc8;\x0b\xbe\xa4'                                                                                                    
>>>                                                                                                                                                                            

And then copy and paste the generated value in your config.py file as the value of SECRET_KEY. Other values are as described in the previous blog post.

We could add the code to read the bot information and create a bot catalog here in config.py file. My choice is to keep this catalog clean and clear independent of other settings in a new file bot_catalog.py; That is something like (shared link at PythonAnywhere: https://www.pythonanywhere.com/user/soheilnb/shares/5565d9b86d244f94ba28aadcc3c19235/):

# -*- coding: utf-8 -*-
#
#  bot_catalog.py
#


import os, os.path
import configparser as confer
import hashlib
import urllib.parse
import telepot
from jet.expando import Expando, expando_update, bind_expando_method

# in python 3.6 you can generate such magic or secret sequences using secrets module :
# import secrets
#   e.g.
# secrets.token_urlsafe(8)
#   or
# secrets.token_bytes(8)
magic_hash_prefix = 'a secret magic string of your choice' # for example: 'ttAF99875m'
magic_hash_suffix = 'a secret magic string of your choice' # for example: 'nop-xt'
magic_route = 'a secret magic string of your choice' # for example 'jkm-111099-au'


bot_route = f'/bot-hook/{magic_route}/{{}}/{{}}/'


scriptdir = os.path.dirname(os.path.realpath(__file__))
ini_file = os.path.join(scriptdir, 'bots.ini')
config = confer.ConfigParser(interpolation = confer.ExtendedInterpolation())
config.read(ini_file)

bot_cat = {}
bots = Expando()

for section in config.sections() :
    bot_name = section
    catalog = config[section]

    token = catalog['token']

    bot_id = int(token.split(':', maxsplit=1)[0])
    hash_text = magic_hash_prefix + '$' + token + '+' + magic_hash_suffix
    hash_code = hashlib.md5(hash_text.encode('utf-8')).hexdigest()

    bot_info = Expando(
        id                      = bot_id,
        name                    = bot_name,
        username                = catalog['username'],
        token                   = token,
        gender                  = catalog['gender'],
        hash_code               = hash_code,
        route                   = bot_route.format(bot_name, hash_code),
        view_webhook_info_url   = f'https://api.telegram.org/bot{token}/getWebhookInfo',
        delete_webhook_url      = f'https://api.telegram.org/bot{token}/deleteWebhook',
        profile_link            = f't.me/{catalog["username"]}',

        bot                     = telepot.Bot(token)
    )

    bots[bot_name] = bot_info
    bot_cat[bot_name] = bot_info
    bot_cat[bot_id] = bot_info
    bot_cat[bot_info.username] = bot_info




BOT_CATALOG = bot_cat
BOTS = bots
BOT_ROUTE = bot_route.format('', '')

There are three magic strings (or extra secret keys) that I have generated to make sure that the webhook URL is extremely difficult to guess. The webhook path have a pattern like:

/bot-hook/MAGIC_ROUTE/BOT_NAME/BOT_HASHCODE

and BOT_HASHCODE is MD5 hashed hex string of the value:

MAGIG_HASH_PREFIX$BOT_TOKN+MAGIC_HASH_SUFFIX

that is,

BOT_HASHCODE = MD5(MAGIG_HASH_PREFIX$BOT_TOKN+MAGIC_HASH_SUFFIX) (HEX string)

I use this bot hash code to validate the request sent to the webhook handler. Because the webhook handler could process the requests for multiple bots, the webhook URLs themselves have information about the requested bot as well as a hash code which helps our code to validate the request. If the web framework was CGI-based, then we would probably have to place this information in a query string. A sample webhook URL with query string looks like:

https://BASE-URL/bot-hook/MAGIC_ROUTE?bot=BOT_NAME&hash_code=BOT_HASHCODE

I have tried it before, and the Telegram system accepts query strings without any problem or issue. However, in flask-based web framework, the preferred method is to use a variable path as above. The webhook URL in a flask web framework is just a deeper path like:

https://BASE-URL/bot-hook/MAGIC_ROUTE/BOT_NAME/BOT_HASHCODE

Of course, flask supports an efficient way to pass any part of a path chain to the app.route handler as a function parameter; that is, a webhook URL with variable bot name and bot hashcode would look like:

@app.route('https://BASE-URL/bot-hook/MAGIC_ROUTE/<bot_name>/<hashcode>', methods=['POST'])
def route_polybot_hook(bot_name, hashcode) :
    pass

a valid identifier enclosed in < and > in the path specifier of the app.route definition would be passed to the associated function as a parameter using the same name and order that appears in the path.

The hash code helps the webhook handler deal with a fake request made to the handler by URL:

/bot-hook/MAGIC_ROUTE/foo/bar 

Assuming a none existing bot foo with a silly hash code bar. It is not likely that a third party tries to reach our webhook handler with a fake request, but we the developers could do it with opening a valid or invalid in a browser. Our webhook handler must be prepared to deal safely with any situation.

In general, our webhook handler must anticipate any situation, and must be able to deal with it properly. When receiving an update from Telegram, if for example, it terminates with an error code because of an uncaught exception, then the Telegram server keeps re-sending the request over and over. Under any circumstance … even if the bot or its hash code is invalid … the webhook handler should terminate the request normally with no error status. It need not do anything except printing an error message in the server error log … but it must terminate the request normally.

Setting up flask_app.py

The first change in flask_app.py … our main flask script … is to load settings of our bots’ catalog information:

app = Flask(__name__)
app.config.from_object('config')
# new settings:
app.config.from_object('bot_catalog')

If we are using a remote flask application on a (for example) PythonAnywhere, then we could set webhook handler URL for all bots automatically in our code:

if SERVER_TYPE == 'REMOTE' :
    for bot_name, bot_info in app.config['BOTS'] :
        bot_info.bot.setWebhook(bot_info.webhook_url, max_connections=1)

There is no need to change any other part of the code but the main app.route path handler which handles the Telegram webhook requests:

@app.route(app.config['BOT_ROUTE'], methods=['POST'])
def route_polybot_hook(bot_name, hash_code) :
    # TODO : validating bot_name and hash_code
    g.proenv = proenv
    g.bot_info = app.config['BOTS'][bot_name]
    g.provars = Expando() # TODO: create provars based on current request context
    g.session = Expando() # TODO: create based on current user-bot pair

    update = request.get_json()
    if 'message' in update:
        # it's a chat message
        message = update['message']
        pprint(message)
        handle_chat(message, g)

    return 'OK'

First of all, the bot who is referenced by the request is not known by our code prior to the request, and hence, the app.route path is modified to a path which conveys information about the bot who must react to the request. Accordingly, the handler itself, receives two parameters: bot_name and hash_code. The other change is where our code could find the info about the bot: bot_info. It is not a global variable in this module anymore. It could be found in the bot catalog as part of the app.config settings information.

Taking into account validating the bot name and its associated hash code, the function code would look a little more complicated as:

@app.route(app.config['BOT_ROUTE'], methods=['POST'])
def route_polybot_hook(bot_name, hash_code) :
    error = None

    # validating bot_name
    if bot_name in app.config['BOTS'] :
        g.bot_info = app.config['BOTS'][bot_name]

        # validating bot hash_code
        if hash_code == g.bot_info.hash_code :
            g.proenv = proenv
            g.provars = Expando(bot_name=bot_name) # create provars based on current request context
            g.session = Expando() # TODO: create based on current user-bot pair

            try :
                update = request.get_json()
                if 'message' in update:
                    # it's a chat message
                    message = update['message']
                    pprint(message)
                    handle_chat(message, g)

            except Exception as why :
                error = why


        else :
            error = f'Invalid bot hash code: {hash_code}'

    else :
        error = f'Unexpected bot name: {bot_name}'

    if error :
        # TODO: print error in server error log
        # otherwise, it is useful in a local flask server:
        print(f'[ERROR] {error}')

    return 'OK'

It’s useful to catch any exception the inner code might raise. In this case, The Telegram server would not re-sent this request again. It’s a good strategy for the Telegram bot programmer to collect stack trace as a text and send the text to his own Telegram ID to find and fix unexpected bugs. That’s beyond the focus of this blog post; it’s fairly simple though.

Now, it is the time to test you handler. You can open any fake or real bot webhook handler in a browser. Set the app.route methods temporarily to ‘GET’ (instead of ‘POST’) to make it work in a browser. Otherwise, you could simply use the requests module of python. In interactive python, run this trivial code and inspect server error log … or if you run a local flask application, check the output of the program:

>>> import requests
>>>
>>> requests.post('http://127.0.0.1:5000/bot-hook/poh-1699901-yf/foo/bar/')
<Response [200]>
>>>

You can find the full flask_app.py code in my shared source link in PythonAnywhere: https://www.pythonanywhere.com/user/soheilnb/shares/46d17003f5974ca5ade2b8349a8680f5/

In next blog post, we will add code to support multiple language functionality for each bot.

Posted in Flask, Python, Telegram Bot | Tagged , , , , , , , , | Leave a comment

Python : Telegram Bot Webhook Handler : A Multi-Bot/Multi-Language Design (6)


6 – Providing Decorator for Bot Commands Using a Dedicated Message Text Processing Class

A good practice to design a bot command processing system is that we define a central engine which looks for the bot commands and settings automatically in our code. Then, it enables us to place our bot commands as well as their associated settings in the same place wherever we wish in our code. In python, it is possible with the help of the decorator functions or classes. As we will soon see, we need certain settings for some of our bot commands, and therefore, we would use a decorator class with parameters for this purpose.

We would use a common function declaration signature as we described in the previous blog post:

def act_some_command(command, message, extras) :
pass

The command parameter is the name of command being processed. We may rarely need this parameter in our code. It could be None in certain cases ; otherwise, it would be the text of the command sent by the user to our bots in uppercase. For example, if user sends this command:

/hello

then, the command parameter would be ‘HELLO‘. The message parameter is the user message as a python dict object. It contains some of the information that a typical telegram message would have: { from=sender, chat, (text|photo|video|…), reply_to_info, forward_from_info, date, … } (see https://core.telegram.org/bots/api#message for details). Finally, the extras parameter is the collection of four data-wares: proenv, provars, bot_info and session data which gives access to the environmental and context variables useful for processing a command (see previous blog posts).

We want to define the decorator class, so that we could use it like:

import re
...


# sample 1
# Simple command ... no special settings required.
# 'HI' and 'HELLO' are alias
@Command(commands=['HELLO', 'HI'])
def act_hello(command, message, extras) :
    # act name : hello
    pass


# sample 2
# executes if the message passes validating function func(msg)
# special treatment for a non-command message with some fancy emojis
# for example : suggest a sticker for this emoji
# choose text thoughtfully ... could cause Mr cancel issue
@Command(func=lambda msg : msg['text']=='🌺')
def act_emoji_hibiscus(command, message, extras) :
    # act name : emoji_hibuscus
    pass


# sample 3
# executes if the message text passes the regular expression
# example 1 ... regular expression object
@Command(regexp=re.complie(r'/who\s*am(?:\s*i\??)?', re.I))
def act_whoami(command, message, extras) :
    # act name : whoami
    pass


# sample 4
# executes if the message text passes the regular expression
# example 2 ... regular expression pattern
@Command(regexp=r'/who\s*are(?:\s*you\??)?')
def act_whoareyou(command, message, extras) :
    # act name : whoareyou
    pass


# sample 5
# does not executes at startup because it is not enabled
# could be enabled/disabled later by admin ... only admin
@Command(commands=['foo'], enabled=False)
def act_foo(command, message, extras) :
    # act name : foo
    pass


# sample 6
# only ADMIN level user can executes this command
@Command(commands=['enable_foo', 'disable_foo'], level='ADMIN')
def act_enable_foo(command, message, extras) :
    # act name : eneable_foo
    if command == 'ENABLE_FOO' :
        pass

    else :
        pass


Each of the sample pieces in the example above is an act function. An act function is a special function which automatically receives a message from a Telegram user via this bot, and responds to the message by a reply message or any other means. To declare a function to be an act, the act function must be decorated by a dedicated decorator class. The decorator class would be Command and it always takes some settings parameters. The Command decorator has no default action. For the sake of clarity, all of its parameters must be a keyword argument. The acts will be checked in the same sequence as defined, and multiple acts may satisfy the condition provided by the message text (or the message itself in general) in which case, checking the rest of acts would terminate as soon as an act function could process the message successfully and returns True (or None). If an act function cannot process a message, it would return False (returning nothing or None is considered True in my design … an explicit False must be returned otherwise).

In sample 1, the act function act_hello would be executed each time the user’s message text starts with /hello or /hi. These commands are specified by the commands keyword argument of the Command decorator.

@Command(commands=['HELLO', 'HI'])
def act_hello(command, message, extras) :
# act name : hello
pass
...

Unless the code of the act function takes different actions based on the actual command that user has sent bu checking the value of the first parameter: command, the act function does an identical action on both commands ‘HELLO’ and ‘HI’. Each act function has a name. The act name of the command is whatever after act_ prefix in the name of function if this identifier starts with the act_ sub-string; otherwise, it is the entire function name (hello for act_hello function). It’s not required but recommended that the act function name starts with the sub-string act_. If we use the same act name for two different act functions, the first act name is lost, and we cannot change the settings for that act function later, but that act does still exist, and would process the matching messages with its initial settings.

In sample 2, the act function act_emoji_hibiscus will be executed whenever the message text is a single 🌺 emoji. Obviously, it is not a command, and could be a trouble in the interactive mode (Mr cancel issue – see previous blog post). The criteria to decide whether this act function must be executed or not is a the return value of a function which takes a single argument: the telegram message, and returns a boolean value based on your logic. It needn’t to check only the text of message, it could check other things like the sender of the message or the time of the message. The criteria function is specified by the func keyword argument of the decorator class and could be specified as a simple lambda expression as in the example above.

In sample 3 and 4, a regular expression determines whether this act function must be executed or not. The regular expression is determined by the regexp function keyword argument and could be specified either as pattern string (sample 4) or pre-compiled object created by re.compile() method of re module (sample 3). The regular expression is examined on the message text only.

Sample 5 denotes a sample ‘foo’ act function that is initially disabled when the server runs. This is done by the enabled keyword argument of the Command decorator. Normally, this is a handy simple method to disable and enable the act functions for some commands rather than comment and uncomment an act function during the debug or test phase or for other temporary personal policies. I have decided that it’s a good idea to let the act function exist when it is disabled so that the administrators could enable and disable these acts later by any means such as another admin-level act function.

The command in sample 6 can be accessed exclusively by the application defined admin-level user. The level keyword argument of the Command decorator indicates the access level. This act is triggered by two different commands (‘ENABLE_FOO’, ‘DISABLE_FOO’), and the sample code denotes how the function code could differ based on the actual command sent by user. The only assumed existing levels are ADMIN (the highest level: lowest integral level value) and ANY (the lowest level: the greatest integral level value). My initial idea is that these levels could be typical for the users based on their membership level in a Telegram group: ADMIN, MANAGER, MEMBER, FRIEND, and ANY. The levels ADMIN and ANY must always be the endpoints of these set, and they must be arranged in order.

A Dedicated Access Level Class

It’s best to specify the access level in string, but use it in codes as integral values. Yes, a good representation is an enum. Another good one is our dedicated class:

from titlecase import titlecase
...

class AccessLevel :
    labels = ['ADMIN', 'MANAGER', 'MEMBER', 'FRIEND', 'ANY']

    def __init__(self, level=None) :
        self.level = level


    @property
    def level(self) :
        return self.value


    @level.setter
    def level(self, level) :
        if level is None :
            self.value = AccessLevel.ANY

        elif isinstance(level, int) :
            assert 0 <= level <= AccessLevel.ANY
            self.value = level

        elif isinstance(level, str) :
            self.value = self[level]

        elif isinstance(level, AccessLevel) :
            self.value = level.value

        else :
            raise Exception(f'Unexpected level type : {level} ({type(level)})')


    @property
    def label(self) :
        return AccessLevel.labels[self.value]


    @property
    def text(self) :
        return titlecase(AccessLevel.labels[self.value].replace('_', ' '))


    def __getitem__(self, key) :
        return getattr(self, key.upper())


    @staticmethod
    def valueof(label) :
        return getattr(AccessLevel, label)


    def __int__(self) :
        return self.value

    def __str__(self) :
        return f"AccessLevel(level='{self.label}')"

    def __repr__(self) :
        return f"{__name__}.AccessLevel(level='{self.label}')"


for value, label in enumerate(AccessLevel.labels) :
    setattr(AccessLevel, label, value)

The objects of this class could be initialized both by the integral value and the string representation of the access level. It could also provide both the integral and text representation of the access level. It would require a useful module titlecase:

pip install titlecase

Some examples in python interactive mode:

>>> # assuming it is defined in the module : access_level :
>>> from access_level import AccessLevel
>>>
>>> auth1 = AccessLevel('ANY') # an ANY-level user ... string init
>>> auth2 = AccessLevel(0) # an ADMIN-level user ... integral init
>>>
>>> auth1
access_level.AccessLevel(level='ANY')
>>> auth2
access_level.AccessLevel(level='ADMIN')
>>> auth1.level
4
>>> auth2.level
0
>>> auth1.label
'ANY'
>>> auth2.text
'Admin'
>>> AccessLevel.valueof('ANY')
4

The difference of AccessLevel.label and AccessLevel.text is that the former value is all uppercase with underscore character _ preserved (MULTIPLE_WORDS_EXAMPLE). It is more useful to be used for internal keys. The latter titlecases the value, and replaces the underscores with space (Multi Words Example). That is intended for human readability only.

For comparisons, AccessLevel.level gets the integral value of the access level.

To properly use this function, we need to define a suitable function to obtain the access level of the user sending the message to bot:

# checks sender's Telegram ID (message['from']['id'] or extras.provars.sender_id) and descides whether
# this user is ADMIN (program developer), MANAGER (a group admin), MEMBER, FRIEND or ANY (other users)
def get_user_auth(message, extras) :
    # TODO: more complex stuff here
    if extras.provars.sender_id == extras.proenv.config['ADMIN_ID'] :
        return AccessLevel(level='ADMIN')

    else :
        return AccessLevel(level='ANY')

This one is trivial sample function which classifies user as either ADMIN (me) or others. You could improve this code by checking more users with more widely access levels … either by searching in a lookup table that has been wired in your config.py file or by searching in a dynamic database table. Then later in the function handle_chat we need to add the user’s access level to the provars data-ware where our function code initializes it:

extras.provars.auth = get_user_auth(message, extras)

The Command Decorator Class Definition

The most important part of this project is the bot’s central engine … what we could also call the bot’s workshop. The module name is not important. It is bot_shop at the time I write this post. I may change it in future. What I like to make sure is that it is not likely to be used for anything else although my current choice is not a good taste I believe. The class decorator is defined as :

import re
import functools
from pprint import pprint
from jet.expando import Expando, expando_update, bind_expando_method
...

ref_re = re.compile(r'')
command_mention_re = re.compile(r'^/([\w]+)@([\w]+)\s*(.*)')
command_re = re.compile(r'^/([\w]+)\s*(.*)')
space_split_re = re.compile(r'\s+')
...

class Command :
    handlers = []
    act_names = {}

    def __init__(self, *, commands=None, func=None, regexp=None, enabled=True, hidden=False, level=None, usages=None) :
        self.commands = commands and tuple(map(str.upper, commands))
        self.func = func
        self.regexp = regexp
        self.hidden = hidden
        self.enabled = enabled
        self.auth = AccessLevel(level)
        self.act_name = None
        self.usages = usages

        Command.handlers.append(self)


    def __call__(self, cmd_func) :
        def wrapper(command, message, extras) :
            result = cmd_func(command, message, extras)
            return result is None or bool(result) is True

        functools.update_wrapper(self, cmd_func)
        if cmd_func.__name__.startswith('act_') :
            self.act_name = cmd_func.__name__.split('_', maxsplit=1)[1]

        else :
            self.act_name = cmd_func.__name__


        Command.act_names[self.act_name] = self

        self.command_function = wrapper
        wrapper.entry = self
        return wrapper


    @property
    def disabled(self) :
        return not self.enabled

    @disabled.setter
    def disabled(self, value) :
        self.enabled = not value


    @staticmethod
    def reply_to(message, text, extras, forced_reply=False) :
        bot = extras.bot_info.bot
        chat_id = extras.provars.chat_id
        bot.sendChatAction(chat_id, 'typing')

        if forced_reply or extras.provars.chat_type != 'private' :
            reply_to_message_id = message['message_id']

        else :
            reply_to_message_id = None

        bot.sendMessage(chat_id, text, reply_to_message_id=reply_to_message_id)



    @staticmethod
    def act_bad_command(command, message, extras) :
        text = f'🚫 Unknown command: {command}'
        Command.reply_to(message, text, extras, forced_reply=True)

    @staticmethod
    def act_no_command(command, message, extras) :
        text = f'🚫 No command in message:' + '\n\n' + message['text']
        Command.reply_to(message, text, extras, forced_reply=True)



    @staticmethod
    def split_message_text(text) :
        body_parts = text.split('\n', maxsplit=1)
        cmd_line = body_parts[0]
        tail = None if len(body_parts) == 1 else body_parts[1].strip()

        command     = None
        bot_mention = None
        line        = None

        omat = command_mention_re.match(text)
        if omat :
            command = omat.group(1).upper()
            bot_mention = omat.group(2).lower()
            line = omat.group(3).strip() or None

        else :
            omat = command_re.match(text)
            if omat :
                command = omat.group(1).upper()
                line = omat.group(2).strip() or None

            else :
                line = text.strip() or None


        args = (line and space_split_re.split(line)) or []

        if command :
            command_line = ('/' + command + ' ' + (line or '')).strip()

        else :
            command_line = line or ''


        return Expando(
            command         = command,
            bot_mention     = bot_mention,
            line            = line,
            args            = args,
            tail            = tail,
            command_line    = command_line)


    @staticmethod
    def process_command(command, message, extras) :


        for entry in Command.handlers :
            if entry.disabled :
                continue

            if extras.provars.auth.level > entry.auth.level :
                continue

            if command and entry.commands and command in entry.commands :
                result = entry.command_function(command, message, extras)
                if result :
                    return

            elif entry.func and entry.func(message) :
                result = entry.command_function(command, message, extras)
                if result :
                    return

            elif entry.regexp and extras.provars.command_line :
                if isinstance(entry.regexp, str) and re.match(entry.regexp, extras.provars.command_line, re.I) :
                    result = entry.command_function(command, message, extras)
                    if result :
                        return

                elif isinstance(entry.regexp, ref_re.__class__) and entry.regexp.match(extras.provars.command_line) :
                    result = entry.command_function(command, message, extras)
                    if result :
                        return

                #~ else :
                    #~ raise TypeError(f'Invalid type for regexp parameter: {type(entry.regexp)}')


        # if the loop ends with no return, the message has not been processed:
        if command :
            Command.act_bad_command(command, message, extras)

        else :
            Command.act_no_command(command, message, extras)


    @staticmethod
    def process_text_message(message, extras) :
        command_expo = Command.split_message_text(message['text'])
        expando_update(extras.provars, command_expo)

        # check bot reference exists, and if so, refers to our bot
        if extras.provars.bot_mention and extras.provars.bot_mention != extras.bot_info.username :
            print('[BOT-MISMATCH] ignored.')
            return

        # useful in local server:
        pprint(extras.provars.__dict__)

        # TODO: check interactive mode
        Command.process_command(extras.provars.command, message, extras)



In the current design for this blog post, I have defined both classes AccessLevel and Command in the same module bot_shop. The code can be viewed in my PythonAnywhere shared link : https://www.pythonanywhere.com/user/soheilnb/shares/f41f44c482134894b53bd98e22994fd9/

The decorator class has three central methods:

  • the initialization code (Command.__init__)
  • the act function collector (Command.__call__)
  • and the act function selector (Command.process_text_message)

The first two methods are automatically invoked when we decorate an function with this class … making that function an act function which executes a bot command.

The third method must be explicitly called in our handle_chat function where it is determined that the content type of the message is text. Upon execution, this function splits the message text to (command, bot_mention, line, args, tail) expo and add these values to provars. If the message has a bot mention, the mentioned bot must be this bot (Odin in my case). Otherwise, this message is simply ignored. Then it would look for a suitable act for the message if any. At this point, our bot does not handle an interactive conversation yet; otherwise the code in this function would decide whether the user message text is a command initially sent by the user, or it is a response to the previous conversation with this user.

The method Command.process_command is used internally only. It is only invoked by Command.process_text_message whenever it is determined that the message text is a command. Thinking carefully about the Mr cancel issue, we (the programmer) must decide when to invoke the method Command.process_command when our message text does not start with a /command pattern. A simple wise decision is to use some well-chosen emojis for each part. For example, the people’s name, address, telephone, etc should not start with an emoji. The well-known multiple-choice texts appear as keyboard shortcuts should always start with a single dedicated emoji … one that is not often used in normal texts; in particular not as the first character of the message. And for some texts to be considered as a command we can use some more complicated rules that are not likely to be used in any conversation.

The method Command.process_text_message must be aware of the function split_message_text(text), so we could define this method as a static method of the class Command. It’s not required but a good idea because it is the only place where this function is invoked. The same idea is behind using the two functions act_bad_command and act_no_command. These are two special case act functions which are invoked when there’s no proper act available for the user message (especially when it is a /command pattern text) or this message does not start with a command (and bot is not in a conversation with this user).

The static method Command.reply_to is a handy method for bot to reply to a user text message with a text message. It contains an automatic ‘Odin is typing…’ flash message (https://core.telegram.org/bots/api#sendchataction) and automatically or forcefully adds reply marker in the reply message. The rule is this: in a group or when set forceful, the bot reply message would have a reply marker (pointing to the message to which this message replies); otherwise, the reply marker is not shown. The reason behind this behavior is that, in a private chat with the bot, it is normally clear that the bot message is in reply to which message. But in groups, it is often confusing to find which is which … especially if we turn off the webhook for a noticeable period of time with a lot of bot commands and other messages posted to that group wall before the bot finds a chance to reply to its commands.

The property disabled is a handy inverted logic value of the enabled attribute.

Using the Decorator Class – Adding act Functions

Having this decorator class ready, it is fairly easy to implement the act functions. Let start to define an act function for the command /start:

@Command(commands=['start'])
def act_start(command, message, extras) :
    '''Start conversation with this bot.'''
    text = f'Hello! I am {extras.bot_info.name}. Nice to meet you.'
    Command.reply_to(message, text, extras)

Similarly, the act function for the commands /hello and /hi:

@Command(commands=['hello', 'hi'])
def act_hello(command, message, extras) :
    '''Greetings with this bot.'''
    text = f'Hello! Good to see you again! 🌺'
    Command.reply_to(message, text, extras)

An example for a none-command act function:

@Command(func=lambda m : m['text'] == '🌺', usages=['🌺'])
def act_emoji_hibiscus(command, message, extras) :
    '''Make this bot to send a flower sticker'''
    bot = extras.bot_info.bot
    chat_id = extras.provars.chat_id
    stricker_id = 'CAADBAADhgQAArOptAuUMDfnxyNbTAI'

    bot.sendSticker(chat_id, stricker_id)

This act function will be invoked upon receiving a text message with text containing a single emoji 🌺. The bot replies with sending back a flower sticker.

In a previous blog posts, I described two commands ‘/who am I?’ and ‘/who are you?’ for Merex. Here in full sample code, you can find how these two commands may be implemented: (https://www.pythonanywhere.com/user/soheilnb/shares/d737f543553b4247badd5229c6f8fc8b/)

# -*- coding: utf-8 -*-
#
#  bot_acts.py
#
#  shared link : https://www.pythonanywhere.com/user/soheilnb/shares/d737f543553b4247badd5229c6f8fc8b/
#

import os, os.path
import re
from collections import OrderedDict as ordict
from titlecase import titlecase
from bot_shop import Command

# see https://pastebin.com/DnRQD648
from jet.expando import Expando, expando_update, bind_expando_method



@Command(commands=['start'])
def act_start(command, message, extras) :
    '''Start conversation with this bot.'''
    text = f'Hello! I am {extras.bot_info.name}. Nice to meet you.'
    Command.reply_to(message, text, extras)


@Command(commands=['hello', 'hi'])
def act_hello(command, message, extras) :
    '''Greetings with this bot.'''
    text = f'Hello! Good to see you again! 🌺'
    Command.reply_to(message, text, extras)


@Command(func=lambda m : m['text'] == '🌺', usages=['🌺'])
def act_emoji_hibiscus(command, message, extras) :
    '''Make this bot to send a flower sticker'''
    bot = extras.bot_info.bot
    chat_id = extras.provars.chat_id
    stricker_id = 'CAADBAADhgQAArOptAuUMDfnxyNbTAI'

    bot.sendSticker(chat_id, stricker_id)



def get_sender_info(message) :
    private = message['chat']['type'] == 'private'

    def value_of(key) :
        if key == 'id' and not private :
            return '*' * len(str(message['from'][key]))

        elif key in message['from'] :
            return message['from'][key]

        else :
            return '-'

    data = ordict([(key, value_of(key)) for key in ('id', 'first_name', 'last_name', 'username')])
    return '\n'.join([f'{titlecase(key.replace("_", " "))} : {value}' for key, value in data.items()])



@Command(regexp=r'^/who\s*am\s*i\??', usages=['/whoami', '/who am I?'])
def act_whoami(command, message, extras) :
    '''This bot sais what he knows about you.'''
    provars = extras.provars
    bot = extras.bot_info.bot
    text = get_sender_info(message)
    profile_photo = bot.getUserProfilePhotos(provars.sender_id, offset=0, limit=1)

    max_size = 0
    file_id = None
    for file_data in profile_photo['photos'][0] :
        if file_data['file_size'] > max_size :
            max_size = file_data['file_size']
            file_id = file_data['file_id']

    if file_id is not None :
        bot.sendChatAction(provars.chat_id, 'upload_photo')
        bot.sendPhoto(provars.chat_id, file_id, caption=text)


def get_bot_info(data) :
    def value_of(key) :
        if key in data :
            return data[key]

        else :
            return '-'

    data = ordict([(key, value_of(key)) for key in ('id', 'first_name', 'username')])
    return '\n'.join([f'{titlecase(key.replace("_", " "))} : {value}' for key, value in data.items()])


@Command(regexp=re.compile(r'/who\s*are\s*you\??', re.I), usages=['/whoareyou', '/who are you?'])
def act_whoareyou(command, message, extras) :
    '''This bot sais who they are.'''
    provars = extras.provars
    bot = extras.bot_info.bot

    bot_data = bot.getMe()
    text = get_bot_info(bot_data) + '\n\n' + 'I am a bot.'
    profile_photo = bot.getUserProfilePhotos(bot_data['id'], offset=0, limit=1)

    max_size = 0
    file_id = None
    for file_data in profile_photo['photos'][0] :
        if file_data['file_size'] > max_size :
            max_size = file_data['file_size']
            file_id = file_data['file_id']

    if file_id is not None :
        bot.sendChatAction(provars.chat_id, 'upload_photo')
        bot.sendPhoto(provars.chat_id, file_id, caption=text)


@Command(commands=['foo'], enabled=False)
def act_foo(command, message, extras) :
    '''A foo test.'''
    Command.reply_to(message, 'FOO is enabled now!', extras)


@Command(commands=['enable_foo', 'disable_foo'], level='ADMIN')
def act_enable_foo(command, message, extras) :
    '''Enables/disables the foo test.'''
    act_foo.entry.enabled = command == 'ENABLE_FOO'
    enabled = 'enabled' if act_foo.entry.enabled else 'disabled'
    Command.reply_to(message, f'FOO is now {enabled}', extras)


@Command(commands=['enable', 'disable'], level='ADMIN')
def act_enable(command, message, extras) :
    '''Enables/disables some bot commands or list them.'''
    enable = command == 'ENABLE'
    disable = not enable

    if len(extras.provars.args) == 0 :
        act_names = [handler.act_name for handler in Command.handlers if handler.enabled == enable]
        if len(act_names) == 0 :
            text = f'No {command.lower()} command.'

        else :
            text = f'{titlecase(command)}d commands: ' + '\n\n' + '\n'.join(act_names)

        Command.reply_to(message, text, extras)

    else :
        text_line = []
        for act_name in extras.provars.args :
            if act_name == 'enable' :
                text_line.append(f'{act_name} : you cannot enable or disbale this act.')

            elif act_name not in Command.act_names :
                text_line.append(f'{act_name} : no such act.')

            else :
                Command.act_names[act_name].enabled = enable
                text_line.append(f'{act_name} : {titlecase(command)}d .')

        text = '\n'.join(text_line)
        Command.reply_to(message, text, extras)

ordict is my preferred shorter name for the python ordered dictionary class: OrderedDict.

We shift to multi-bot/multi-language design in the next blog post.

Posted in Flask, Python, Telegram Bot | Tagged , , , , , , , , | Leave a comment

Python : Telegram Bot Webhook Handler : A Multi-Bot/Multi-Language Design (5)


5 – Adding Commands in Single-Bot Design

Let your mind fly! Let it surf over the clouds! There is no limitation on imagination on what a bot in the Telegram system can do for us. You want to know what time it is in Paris now, … you want to notify the people in your group about the birthdays of members automatically, … you are a teacher and you want to let your students get their scores and ranks for each course in a confidential fashion, … similarly, you want to share the different parts of a database information to some people with different levels of access … you want to create an on the fly image with certain information related to the current situation and context … . All these things and many more are possible in the Telegram system with the great features you can get with the bots.

In order to get the most from a Telegram bot, you, the developer, must add some useful commands for your bot, and the users of the bot should type and send those commands to the bot. You could check some sample commands on an example bot. My recent post (https://911programming.wordpress.com/2019/04/21/python-telegram-bot-webhook-handler-a-multi-bot-multi-language-design-2/) introduces Merex (https://t.me/merex_900_bot) who speaks in three languages (at the moment), and can execute some sample commands. To check the commands that Merex can handle, type and send

/help

in a private conversation with Merex. That’s true. It is a bot command. In the Telegram system, a bot command starts with a slash. If you add your bot to a group, or super-group, the Telegram system will automatically forward any text message started with slash to the bot as well as all human user members. The other messages are not sent by default unless you change settings for your bot via the BotFather, or you assign your bot to be an administrator in group, or the message is a reply to the bot’s message. There are some more few exceptions.

If there are more than one bot in the group, the rule is a little more complex. It seems that the Telegram system sends a command like this to the bot which has been referenced the most recently. So, if there are more bots than one, to make sure that the command is forwarded to Merex and no other bot, you should mention bot in the command by appending bot’s username to the command. Merex username is merex_900_bot and he would be mentioned as @merex_900_bot.

Therefore, the command with bot mention is now :

/help@merex_900_bot

We are all programmers, and we are easily tempted to think of some command parameters for some of our commands. At the moment, Merex does not support this feature, but that is foreseen by me, and soon I may use this feature as well. I have already done it for some of my other bots in other projects, and it is easy. Oops! I have done it with the command /who of Merex: (/who am I? and /who are you?). As a good example, pure /help command could give the general help and the list of available commands while /help command could give help about a specific command; for example /help help. Taking bot mention into account, a bot command may be as complex as:

/help@merex_900_bot help

Our bot must be able to pick the name of the command … to check whether the message text has a bot mention or not, and whether the mention refers to them (to proceed) or not (to ignore) … and to check whether the message text has a tail after the command-mention or not.

My taste is that I allow the Ascii command parameters only in the same line as the command, and I use the lines after that for non-Ascii unicode texts or comments for educational purposes. That is, something like :

/help@merex_900_bot help

Use this command to get help for the command help

in which the word help after the command-mention is the command parameter, and because this is the command ‘HELP’, the next lines would be simply ignored as a comment.

So, that would be a simple python code which takes a message text, and split it to these parts: command, bot_mention, line, args, tail. All these values could be evaluated in the main handle_chat function and preserved in the request specific data-ware provars (refer to previous blog post for details). The command variable (provars.command or provars[‘command’]) contains the command name in all uppercase characters. for the example above, it is ‘HELP’. It would be None if the message does not start with a slash. The value of bot_mention is self-explanatory: it is the mentioned bot username if present; otherwise, it would be None. line would be anything after command-bot_mention until the end of line. If command is missing, then line would be the entire first line. If there’s nothing after command-bot_mention, line is None. args if the value of line splitted to a list of words. It is always a list even though an empty list … it is never None. The reason to use both line and args is that sometimes args is more useful and sometimes line is better to perform, for example, some regular expression test. And finally, tail is anything after the first line or None if there is nothing.

The function doing this split is not too difficult. If you are familiar with regular expressions, the code would be like this:

import re
...
command_mention_re = re.compile(r'^/([\w]+)@([\w]+)\s*(.*)')
command_re = re.compile(r'^/([\w]+)\s*(.*)')
space_split_re = re.compile(r'\s+')

def split_message_text(text) :
    body_parts = text.split('\n', maxsplit=1)
    cmd_line = body_parts[0]
    tail = None if len(body_parts) == 1 else body_parts[1].strip()
    command     = None
    bot_mention = None
    line        = None

    omat = command_mention_re.match(text)
    if omat :
        command = omat.group(1).upper()
        bot_mention = omat.group(2).lower()
        line = omat.group(3).strip() or None

    else :
        omat = command_re.match(text)
        if omat :
            command = omat.group(1).upper()
            line = omat.group(2).strip() or None

        else :
            line = text.strip() or None

    args = (line and space_split_re.split(line)) or []

    return Expando(command=command, 
        bot_mention=bot_mention, 
        line=line,
        args=args,
        tail=tail)

Maybe this is not the best code, and it could be done more pythonic and more efficiently (comment your suggestions), but it works fine. The return value of the function could be a dict or expando object which in both case, we could update provars data-ware with the return value of this function:

command_expo = split_message_text(message['text'])     
expando_update(extras.provars, command_expo)

The new handle_chat function would be like :

def handle_chat(message, extras) :
    flavor = telepot.flavor(message)
    assert flavor == 'chat'
    content_type, chat_type, chat_id = telepot.glance(message, flavor=flavor)
    sender_id = message['from']['id']
    expando_update(extras.provars, 
        content_type=content_type,
        chat_type=chat_type,
        chat_id=chat_id,
        sender_id=sender_id)
    extras.provars.sender_info = get_sender_info_summary(message)
    extras.provars.chat_info = get_chat_info_summary(message)

    if content_type == 'text' :
        command_expo = split_message_text(message['text'])
        expando_update(extras.provars, command_expo)

        # useful in local server:
        pprint(extras.provars.__dict__)

        # TODO: process the command here
        text = '{} says : You sent me a text message: \n\n{}'.format(extras.bot_info.name, message['text'])

    else :
        text = '{} says : You sent me a "{}" message.'.format(extras.bot_info.name, content_type)

    bot = extras.bot_info.bot
    bot.sendMessage(chat_id, text)

If testing in a local server, we could pprint the dictionray equivalent of the provars (extras.provars.__dict__) to examine what information is available in provars.

Two functions get_sender_info_summary and get_chat_info_summary are handy to quickly inspect sender info and chat info in a human readable digest format. It’s normally difficult to deal with only numeric Telegram IDs. The digest format is specially useful if one wants to store and later retrieve some information about the messages in database.

The definitions of these two functions requires no module to import :

def get_sender_info_summary(msg, ignore_lang=True) :
    parts = []

    if 'from' in msg :
        sender = msg['from']
        parts.append('{}:'.format(sender['id']))

        if 'first_name' in sender and sender['first_name'] is not None :
            parts.append(sender['first_name'])

        if 'last_name' in sender and sender['last_name'] is not None :
            parts.append(sender['last_name'])

        if 'username' in sender and sender['username'] is not None :
            parts.append('(@{})'.format(sender['username']))

        if 'is_bot' in sender and sender['is_bot'] :
            parts.append('[BOT]')

        if not ignore_lang and 'language_code' in sender and sender['language_code'] is not None :
            parts.append(''.format(sender['language_code']))


    return ' '.join(parts)


def get_chat_info_summary(msg, ignore_adm=True) :
    parts = []

    if 'chat' in msg :
        chat = msg['chat']
        parts.append('{}:'.format(chat['id']))

        if 'first_name' in chat and chat['first_name'] is not None :
            parts.append(chat['first_name'])

        if 'last_name' in chat and chat['last_name'] is not None :
            parts.append(chat['last_name'])

        if 'username' in chat and chat['username'] is not None :
            parts.append('(@{})'.format(chat['username']))


        if 'title' in chat and chat['title'] is not None :
            parts.append(chat['title'])

        if 'type' in chat and chat['type'] is not None :
            parts.append('[{}]'.format(chat['type']))

        if not ignore_adm and 'all_members_are_administrators' in chat and chat['all_members_are_administrators'] :
            parts.append('[ALL:ADMIN]')

    return ' '.join(parts)

Hello Mr cancel! Nice to meet you!

In groups, except for the cases when we make some specific settings … for example, with BotFather: we make our bot receive all messages (not only commands) … or in groups: we make our bot an administrator … our bot would only receive messages that start with a command (in the form: /command) with some exceptions such as when a user replies to the bot’s message. In a private chat, the bot receives all the messages. So, if the message is sent to our bot in a private chat, can we make the bot treat a message not started with slash as a command … by checking the first word of the text message? Of course! Is it a good idea? I would say no.

The reason is a possible issue which I call it here Mr cancel issue. Bots … much like the BotFather … could remember some parts of the previous conversations with a user. As matter of fact, the preferred method of passing the command parameters to a bot is not like the command-line arguments of a console command; the preferred method is that the bot asks for the parameters one by one interactively, and each time, the user just sends a simple answer in reply. To allow your bot to do this interactive conversation, they should remember the initiating command that started the interactive mode as well as the current state of the conversation. Now, imagine a scenario that your bot expects a user to enter their name in the interactive conversation, and the user decides to cancel this operation with a CANCEL command using the text cancel instead of /cancel! What happens in this case?!

A couple of trivial commands: ‘START’ and ‘HELLO’

The most important descision in this project is to decide how we want to install our (new) commands. There are two naiive methods.

The first method uses an if-elif-else ladder:

    if extras.provars.command == 'START' :
        act_start(command, message, extras)
        
    elif extras.provars.command == 'HELLO' :
        act_hello(command, message, extras)

    else :
        act_bad_command(command, message, extras)

The second method uses a dictionary lookup:

commands = {
    'START' : act_start,
    'HELLO' : act_hello,
}
...


    if command in commands :
        commands[command](command, message, extras)
        
    else :
        act_bad_command(command, message, extras)

The commands could be defined like:

def act_start(command, message, extras) :
    bot = extras.bot_info.bot
    chat_id = extras.provars.chat_id
    text = f'Hello! I am {extras.bot_info.name}. Nice to meet you.'
    bot.sendMessage(chat_id, text)
    
    
def act_hello(command, message, extras) :
    bot = extras.bot_info.bot
    chat_id = extras.provars.chat_id
    text = f'Hello! Good to see you again! 🌺'
    bot.sendMessage(chat_id, text)
    

def act_bad_command(command, message, extras) :
    bot = extras.bot_info.bot
    chat_id = extras.provars.chat_id
    text = f'🚫 Unknown command: {command}'
    bot.sendMessage(chat_id, text)    

In both of these methods, we must edit some part of the codes that we have already defined as well as placing a new function in the source file. Well, if we need to define a helpstring for each command, we can define a __doc__ string for ecah function. But we cannot access the list of available commands in the if-elif-else ladder. But what if we need some extras settings for each individual command, and where should we place the settings? We may make our command dictionary lookup cover more information about any command; that is something like:

commands = {
    'START' : (act_start, start_extra_info),
    'HELLO' : (act_hello, hello_extra_info),
}

and then we would define start_extra_info, hello_extra_info, … as we desire.

The sample code is placed in a pastebin link (https://pastebin.com/mDA3HLNT) for a trivial command dictionary lookup.

In the next blog post, we will define a function decorator class to automate all these definitions and settings … more favorably and in a more pythonic codes. Then, Installing a new command would reduce to place a new function with its decorator in our source file and that is all we need to do.

PythonAnywhere shared links:

Posted in Flask, Python, Telegram Bot | Tagged , , , , , , , | Leave a comment

Python : Telegram Bot Webhook Handler : A Multi-Bot/Multi-Language Design (4)


4 – Setting up the Webhook for a Single-Bot English Speaking Bot

To be able to understand and follow this post properly, you should have enough skills in python programming, and you must have some acquaintance with Flask web framework in python, or at least you should know what it is doing, and what it is supposed to do in our program. Obviously, you could setup a webhook handler in other programming languages, say PHP, and you could write the program code as a CGI script (in python or PHP). Once, I did it successfully with python as a CGI script, and it worked perfectly well. I am not going to judge here which is better: Flask or CGI based. In this series of blog posts, I just focus on Flask. Not comparing it with other web frameworks and applications, Flask is excellent for our purpose.

If you want to know more about flask, here is what I started myself:

I strongly recommend that you read the simple but very useful and fundamental blog post “Building a simple Telegram bot using PythonAnywhere” (https://blog.pythonanywhere.com/148/) by PythonAnywhere. Indeed, PythonAnywhere is the site which hosts some of my bots webhook codes. They generously provided me with all the tools and python modules that I need as well as the latest flask and python versions.

It’s the best idea if you run and test the code (the webhook section) provided by that blog post before you read the rest of this article.

4.1 Setting up the config file

Python programmers are well aware of the module configparser … a great module to deal with simple [section] key=value ini files. For basic config, I didn’t use this module. Instead, I use the Flask’s preferred settings method: simply a python module called config.py whose all-capital identifiers are automatically imported by the Flask object. Here is my sample code :

# -*- coding: utf-8 -*-
#
#  config.py
#
#

BOT_NAME = 'Odin'
BOT_USERNAME = 'odin_2020_bot'

BOT_ID = THE_BOT_INTEGER_ID
BOT_TOKEN = 'THE_BOT_TOKEN' # it is a combination of the form BOT_ID:PASS_PHRASE

# For a value for the SECRET_KEY below, you can obtain a unique value by :
# import uuid
# uuid.uuid4().hex
# ^-- Remember, that you should run this code in interactive python, and copy and paste the value you obtain there in the following string here:
# for example, SECRET_KEY = '6303ff14624646bc976a2591be029f82'
SECRET_KEY = 'a hexadecimal string' # it's a pre-generated UUID in hex format 

# if you are not familiar with python3.6 f-string, the following line is equivalent to
#
# WEBHOOK_ROUTE = '/odin/{SECRET_KEY}'.format(SECRET_KEY=SECRET_KEY)
#
# or simply :
#
# WEBHOOK_ROUTE = '/odin/{}'.format(SECRET_KEY)
WEBHOOK_ROUTE = f'/odin/{SECRET_KEY}'

# It's handy. Let the bot sometimes report to you something!
ADMIN_ID = MY_TELEGRAM_INTEGER_ID # It's my ID : the developer ID

I created a real bot named Odin for this project. I deliberately disguised some information about my bot here so that one of you the nerds do not try to take over the control of my bot! Obviously, you should you put all the real information in this file. Your bot ID and bot token must match the values you obtain from the Telegram’s BotFather; otherwise your bot wouldn’t work. You could do the tests I suggested in the previous post : https://911programming.wordpress.com/2019/04/21/python-telegram-bot-webhook-handler-a-multi-bot-multi-language-design-3/ by properly pasting your actual bot info in the placeholders I described.

Back to our config.py here, you should also paste your real telegram ID here as the actual value of ADMIN_ID if you want your bot to occasionally send you some text messages.

You won’t need to directly import this file in your main flask_app.py file. Normally, you let the Flask app object do it itself by passing its module name to flask app object:

from flask import Flask 
app = Flask(__name__)

# the method parameter is the config.py module's name
app.config.from_object('config')

Now, all the uppercase variables in config.py is accessible in app.config dict-like object, for example, the bot token would be app.config[‘BOT_TOKEN’] wherever app object is accessible. If we try to re-write the PythonAnywhere sample code with our new config setting, the code would be :

from flask import Flask, request
import telepot
import urllib3
proxy_url = "http://proxy.server:3128"
telepot.api._pools = {
'default': urllib3.ProxyManager(proxy_url=proxy_url, num_pools=3, maxsize=10, retries=False, timeout=30),
}
telepot.api._onetime_pool_spec = (urllib3.ProxyManager, dict(proxy_url=proxy_url, num_pools=1, maxsize=1, retries=False, timeout=30))

app = Flask(__name__)
app.config.from_object('config')

bot = telepot.Bot(app.config['BOT_TOKEN'])
bot.setWebhook("{}/{}".format(app.config['HOST_URL'], app.config['WEBHOOK_ROUTE']), max_connections=1)

@app.route(app.config['WEBHOOK_ROUTE'], methods=["POST"])
def telegram_webhook():
update = request.get_json()

if "message" in update:
text = update["message"]["text"]
chat_id = update["message"]["chat"]["id"]
bot.sendMessage(chat_id, "From the web: you said '{}'".format(text))

return "OK"

The only unresolved issue here is the unknown settings var ‘HOST_URL‘. It is a good practice trying to figure out what it is and setting it in the config.py source file properly. Have a look at the original blog post, and check what it has been substituted for.

None PythonAnyWhere sample code

Telepot official documentation has a sample code (https://github.com/nickoala/telepot/tree/master/examples/webhook) slightly different from the code recommended by PythonAnywhere. In Teleopot original code, no restriction is imposed on the maximum connections (max_connections) accepted from the Telegram super-server, and therefore, the default value (40) is set when you set the webhook for your bot. What this setting means is that your handler could be invoked multiple times at the same time, and your code must be ready to handle that. Telepot recommends using a class OrderedWebhook of the module telepot.loop to automatically re-order updates before your handle receives them so that your handle could process the updates in the right order. The idea behind this recommendation is that there is no guaranty that the updates (when having multiple connections is enabled) are seen and handled by your webhook method in the right sequence.

What we must be aware of at the moment is that there must be an extra function handle(msg) which is the function which actually handles the telegram updates. Bearing this in mind, our sample code would change to :

from telepot.loop import OrderedWebhook

...

def handle(msg) :
flavour = telepot.flavor(msg)
if flavour == 'chat' :
content_type, chat_type, chat_id = telepot.glance(msg, flavor=flavor)
if content_type == 'text' :
text = msg['text']
bot.sendMessage(chat_id, "From the web: you said '{}'".format(text))


webhook = OrderedWebhook(bot, handle)
webhook.run_as_thread()

@app.route(app.config['WEBHOOK_ROUTE'], methods=["POST"])
def telegram_webhook():
webhook.feed(request.data)
return 'OK'


The advantage of this code is that your webhook code could handle multiple updates at the same time. The update header is ripped off, and now you have the message data dictionary itself in your handle function. The parameter msg is not a good name despite what Telepot reference has chosen. Because it could also be a callback query or inline query or other types of message. To make sure that it is a chat message, you could use telepot.flavor method. A chat message has a flavor of ‘chat’. Review the Telepot introduction page (https://telepot.readthedocs.io/en/latest/) for more details.

For a single bot English speaking design. This code would be almost all right. But for a multiple-bot design, this code has certainly an important issue which we would review when we shift from single-bot design to multiple-bot. For now, It’s unlikely for the nature of our project, but if we need any useful context-dependent global variable of flask like g, request, etc, we would lose the access to them in the handle function because it is running in a different thread than the webhook function, and therefore, all the context data is invalid.

Originally, I designed this webhook handler on my local computer, and because I had no resource restriction, I used this OrderedWebhook method to handle maximum possible connections. I devised a simple data-ware mechanism to let my handle function thread obtain the required original thread variables in the cost of passing a unique key in the telegram message.

If you are using PythonAnywhere or a similar hosting site that restricts your maximum connections, or you feel that you could do well with only one connection at a time or you think that this issue and my explanations are mere headache, you could simply keep working with max_connections=1 when you set webhook for your bot and do your code as PythonAnywhere sample code.

Since my ultimate webhook code is ready and placed on PythonAnywhere site, I focus on the sample code by PythonAnyWhere. Maybe later, in another blog post I return to this issue with more details.

4.2 Setting up the Environment and Context Variables

In our multi-bot/multi-language design, we would normally need 4 types of environment and/or context variable sets:

  • Application and program related vars (proenv)
  • Update and request related vars (provars)
  • Bot information related vars (bot_info)
  • User preference and session related vars (session or session_data)

I have chosen these name due to my long programming habit, and this is my taste. You could choose your own favorite terminology if you prefer. The data-ware proenv contains all the program specific variables like the application and data path, settings, configs, databases, … . This proenv is set only once at the initialization phase of the program, and remains unchanged until the termination of program (or in the servers, forever). The data-ware provars is created once an update receives, and it would contain all information required about the update : type of update, the sender of the message, the chat id of the message, whether it is a text message, whether the chat is private or any kind of group or channel, … . This provars is created once an update arrives in our webhook handler, and exists unchanged until the message is fully processed and an “OK” is returned to the Telegram server. The date-ware bot_info is actually a variable of kind proenv in a single-bot design, but a variable of kind provars in a multiple-bot design, because in the former case, it is known at the startup and remains unchnaged until the end, but in the latter, it is known only when an update arrives, and two different updates could have two different set of bot_info variables. Like other provars variables, bot_info would cease to exist when an update is fully processed. Only for convenience and easy porting from single-bot to multi-bot design, we keep this info in separate data-ware called bot_info. Finally, the data-ware session is all variables unique per user-bot interactions and denotes the preferences of a particular user in relation to a particular bot. As an actual example, I may decide to talk to Merex in English with Europe/London timezone whereas I decide to talk to Odin in French with Europe/Paris timezone. So, there would be two different sets of session data for me: Me-Merex session data and Me-Odin session data. This session data is the only data-ware that may be modified during the handling of an update message; as an example, a bot command may cause the handler to change a user’s preferred language or timezone. A session data is retrieved (if exists) upon the arrival of an update and will be saved when the update is fully processed just before the webhook handler returns “OK”.

The good side of restricting the maximum connections to only one is that the famous and most useful data-ware variable g of flask module is available in any method and function which is called directly or indirectly by our webhook handler app.route function.

A Lightweight Expando Class

In python, it’s sometimes cumbersome to use dictionaries of dictionaries. It’s ugly … I believe … to use so many dictionary reference chains to obtain a variable like update[‘message’][‘chat’][‘id’]. Well, I prefer not to tamper the Telepot convention who has preferred not to tamper the structure designed by Telegram in JSON format. But for my own context variables: proenv, provars, bot_info, and session data, I prefer a more convenient data access. I have written a very simple class Expando which allows accessing object members both as an object attribute and as a dictionary entry. If you are familiar with the Javascript language, it’s much like a Javascript object. Of course, it has no predefined attribute (except those started with double hyphens). For those of you who are interested in implementation of such a class, there’s a pastebin link for the code. It’s easy and convenient to use it : (https://pastebin.com/DnRQD648 and/or if you have a PythonAnywhere account: https://www.pythonanywhere.com/user/soheilnb/shares/1869179f922941d2b2d0274381282ddb/). I normally put all my common well-defined modules in a package called jet, so I can use an Expando object like :

from jet.expando import Expando
# use as
# from expando import Expando
# if you place the module in the same directory as this script.

# simple empty object :
expo = Expando()

expo.a = 1

assert expo.a == expo['a']
# OK , no AssertionError

assert expo.a is expo['a']
# OK , no AssertionError

expo['b'] = 2
print(expo.b)
# 2

print(expo)
# Expando({'a': 1, 'b': 2})

# create from dictionary (shallow)
d = {'x' : 101, 'y' : 202}
e = Expando(d)
print(e)
# Expando({'x': 101, 'y': 202})

# create from another expando
f = Expando(e)
print(f)
# Expando({'x': 101, 'y': 202})

# create from on the fly key=value pair :
e = Expando(one=1, two=2, three=3)
print(e)
# Expando({'one': 1, 'two': 2, 'three': 3})

print('one' in e)
# True
print('foo' in e)
# False

# it cannot have any wired attribute including items() like a dictionary
# therefore, iteration is simply like :
for key, value in e :
print(f'{key}={value}')
# one=1
# two=2
# three=3

# or
for entry in e :
    print(entry)
 
# ('one', 1)
# ('two', 2)
# ('three', 3)




In a blog post in future, I would explain more about this class.

Setting up proenv and bot_info

As said before, proenv is full known at startup. In single-bot design, bot_info is also known. In multi-bot design, bot_info is not known prior to request from telegram server to our webhook handler, but it is one of the available records in our bot-ware collection.

We could put some useful information in proenv at start up :

# flask_app.py

...
import os, os.path
...

app = Flask(__name__)
app.config.from_object('config')

...

# properly define your favorite values for
# HOST_URL, PROJECT, APP_PATH
# in your config.py


host_url = app.config['HOST_URL']
home = os.path.expanduser('~')
project = app.config['PROJECT']
var_path = os.path.join(home, 'var', project)
session_path = os.path.join(var_path, 'sessions')

proenv = Expando(
app_path = app.config['APT_PATH'],
home = home,
project = project,
var_path = var_path,
session_path = session_path,

config = app.config
)

os.makedirs(session_path, exist_ok=True)

# config.py
# for full code check https://pastebin.com/016Khgex
#

...

import os.path

...

HOST_URL = 'https://YOUR-BASE-URL-FOR-WEBHOOK'
PROJECT = 'monobot' # or the name of your choice
APT_PATH = os.path.dirname(os.path.realpath(__file__))

bot_info in this project is simple :

# flask_app.py
...
import urllib.parse
...

bot_info = Expando(
id = app.config['BOT_ID'],
name = app.config['BOT_NAME'],
username = app.config['BOT_USERNAME'],
webhook_route = app.config['WEBHOOK_ROUTE'],
webhook_url = urllib.parse.join(app.config['HOST_URL'], app.config['WEBHOOK_ROUTE']),
bot = telepot.Bot(app.config['BOT_TOKEN'])
)

In monbot project, Odin speaks only English. There’s no point in assigning a gender to him. Otherwise, we could set it in bot_info definition here.

The webhook method is now like :

# flask.app.py
...
from flask import Flask, request, g
...
@app.route(bot_info.webhook_route, methods=['POST'])
def route_bot_hook() :
g.proenv = proenv
g.bot_info = bot_info
g.provars = Expando() # TODO: create provars based on current request context
g.session = Expando() # TODO: create based on current user-bot pair

update = request.get_json()

if 'message' in update:
# it's a chat message
message = update['message']
handle_chat(message, g)

return 'OK'

You should notice that the g object of flask module is not an expando object; for example, you could NOT access proenv like g[‘proenv’]. Only the four data-ware objects: proenv, provars, bot_info and session are expando.

Now, the handle_chat function does process the message :

# flask.py
...

def handle_chat(message, extras) :
flavor = telepot.flavor(message)
assert flavor == 'chat'
content_type, chat_type, chat_id = telepot.glance(message, flavor=flavor)

if content_type == 'text' :
text = '{} says : You sent me a text message: \n\n{}'.format(extras.bot_info.name, message['text'])

else :
text = '{} says : You sent me a "{}" message.'.format(extras.bot_info.name, content_type)

bot = extras.bot_info.bot
bot.sendMessage(chat_id, text)

You can see the full code in (https://pastebin.com/jZaQds9J). The code is written to work both locally in my computer (SERVER_TYPE = ‘LOCAL’) and in pythonAnywhere site (SERVER_TYPE = ‘REMOTE’). If running locally, a couple of extra commands are required to set and delete the webhook manually. In a blog post in future, I will explain about it. My current focus is on PythonAnywhere at the moment. Make sure to set SERVER_TYPE properly.

In the next post, We would see how this bot could handle user commands.

PythonAnyWhere shared links:

Posted in Flask, Python, Telegram Bot | Tagged , , , , , , , | Leave a comment

Python : Telegram Bot Webhook Handler : A Multi-Bot/Multi-Language Design (3)


Part 3 – Some bot programming practice

To start handling your bot with programming codes … as sci-tech robot movies say, uploading software in the robot! … you would need an internet connection with the ability to connect to the telegram super-server, your bot’s authorization string (bot’s token), and some real users’ (or groups’) telegram IDs including yours. If you don’t know your Telegram ID yet, you can ask it from Merex (read the previous blog post for details). If you have done the tutorial provided by PythonAnywhere (Building a simple Telegram bot using PythonAnywhere) successfully, you could modify the code provided by the tutorial slightly to obtain your Telegram ID using a magic phrase, for example, ‘my telegram id‘ (or whatever you prefer) in a private chat with your bot:

@app.route('/{}'.format(secret), methods=["POST"])
def telegram_webhook():
    update = request.get_json()

    if "message" in update:
        chat_id = update["message"]["chat"]["id"]
        
        if "text" in update["message"]:
            text = update["message"]["text"]
            chat_type = update["message"]["chat"]["type"]

            # "my telegram id" is your pass phrase
            if chat_type == "private" and text == "my telegram id" :
                sender_id = update["message"]["from"]["id"]
                bot.sendMessage(chat_id, "Your telegram ID : {}".format(sender_id))
                
            else :
                bot.sendMessage(chat_id, "From the web: you said '{}'".format(text))
                
        else:
            bot.sendMessage(chat_id, "From the web: sorry, I didn't understand that kind of message")
    return "OK"


The added portion is typed in bold so that you could easily compare it with the original text. You could ask a few of your friends to send this phrase to your bot using their own Telegram device to obtain their Telegram IDs. Then you could write down their IDs for the bot practices suggested in this post.

This is similar to what Merex is doing when you send the command

/who am I?

to Merex, and he sends you back your Telegram ID as well as other information he finds in the update[“message”][“from”] entry of the update message.

The checking for chat_type is not mandatory but useful and recommended. It makes sure that the user sends the message in a private chat with the bot. It could be an unimportant issue if the magic phrase does not starts with / because in the groups, the Telegram system would not send the messages not started with / to the bot. But what if you decide to mimic my ‘/who am I?’ command or start you magic phrase with a /, and make your magic phrase look like a command to the Telegram system? Then all members of the group could see your Telegram ID. It’s not a security issue … but I think of the nerds in the group who could create a bot especially for your Telegram ID with some evil intentions!

I emphasize as I mentioned earlier, you could refer to Merex (https://t.me/merex_900_bot) using your Telegram device and send either

/who am I?

or simply,

/whoami

and the reply from Merex contains some information about you including your Telegram ID.

Deaf Mode vs. Webhook handler

Telegram official document for the bot API (Bots: An introduction for developers) in a section (4. How are bots different from humans?) states some differences between the bots and humans among which there is one saying ‘Bots can’t initiate conversations with users.’. Well this is almost true. To be more precise, it is true in the context of a webhook handler for the bot. A webhook handler is a kind of event handler in which a bot (in fact, a running programming code for the bot) receives a notification from Telegram system about an incoming telegram message. That notification is called an update in the Telegram terminology and it contains the Telegram message itself. During the webhook operation, the bot does not do anything on their own. They waits for an incoming message to arrive, and processes it , and as a result of processing, they might reply the user sending the message with a text or other types of message. A bot behaves with discipline in this operation. The main aim of this series of blog posts is actually about the webhook handlers, and we will focus on that from next post after.

In this post we focus on the other face of bot programming which I call it the deaf mode! Deaf mode is always available even with a local computer. What we would need is an internet connection reaching the Telegram server (some countries block Telegram), a python program (even an interactive idle is often enough), a telepot module and some extra useful modules. Deaf mode operation could be done whether there is an active working webhook handler for the bot or not. Moreover, you could use your local computer for deaf mode programming for the bot while a webhook handler runs on another server across the other side of the world for the same bot. The only common thing between these two operations is the bot’s authorization token (and of course the bot’s profile info).

During the deaf mode (regardless of a webhook handler and independent to that), your bot is deaf, that is it doesn’t receive any update, message or command from any user by the Telegram system. All they could do is to send messages of text, photo or any other type specified by the Telegram document. All what we could do in the deaf mode with our bot, we could also do that in the context of webhook handler except for the fact that in the webhook handler, it must be initiated with a human user making some sort of conversation with the bot.

In the deaf mode, the operation would be started by the human behind the bot (we the programmer) or the programmer could set up a task scheduler to make the bot sends various messages (reminders, notifications, …) to certain people or groups (with known Telegram IDs) at regular intervals.

Starting the Practice

It is important to note that, here during this blog post, your bot is going to be deaf and could not hear your commands! To make him be able to respond to your commands, you would need to setup as a webhook handler (the preferred method) for your bot, and to do that, you would need a web server available to host your code. The other less preferred method is the message loop which you could run for few hours on your local computer.

For now, your bot could only speak (without listening), or do other activities like sending photos … . Let’s setup some basic initialization in python code. I am using python3.6 at the moment, and I expect that you understand its differences with older versions of python.

import telepot

# v---- a string like '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11'
BOT_TOKEN = 'YOUR_BOT_TOKEN' 

MY_ID = 123000321 # <--- It must be your real-world telegram ID, an integer

# Hopefully you wouldn't need a proxy to reach telegram server 
# otherwise, you should define it here

# giving a beating heart to your bot :
bot = telepot.Bot(BOT_TOKEN)

# to make bot say hello to you :
bot.sendMessage(MY_ID, 'Hi there!')

You could simply try it using the interactive python (idle) :

>>> import telepot
>>> BOT_TOKEN = 'YOUR_BOT_TOKEN'
>>> MY_ID = 123000321 # <--- It must be your real-world telegram ID, an integer
>>> bot = telepot.Bot(BOT_TOKEN)
>>> bot.sendMessage(MY_ID, 'Hi there!')
{'message_id': AN_INTEGER, 'from': {'id': YOUR_BOT_ID, 'is_bot': True, 'first_name': 'Your Bot Name', 'username': 'your_bot_username'}, 'chat': {'id': MY_ID, 'first_name': 'My Name', 'last_name': 'My Last Name', 'username': 'my_user_name', 'type': 'private'}, 'date': A_TIMESTAMP, 'text': 'Hi there!'}

If you wish to see better what telepot.sendMessage method returns, you could use pprint method of pprint module :

>>> from pprint import pprint
>>> result = bot.sendMessage(MY_ID, 'Hi there!')
>>> pprint(result)
{'chat': {'first_name': 'My Name',
'id': MY_ID,
'last_name': 'My Last Name',
'type': 'private',
'username': 'my_user_name'},
'date': A_TIMESTAMP,
'from': {'first_name': 'Your Bot Name',
'id': YOUR_BOT_ID,
'is_bot': True,
'username': 'your_bot_username'},
'message_id': AN_INTEGER,
'text': 'Hi there!'}

The dictionary object returned by the method is actually a telegram message of text type. This is the message format which has been sent to your telegram account … enveloped by some sort of header which is called an “update” in the telegram terminology. All telegram text messages have a structure like this possibly with some extra data indicating where this message has been forwarded from or which message this one is replying to. Other types of telegram messages could be photo, video, audio, document … . And other types of telegram updates (besides a message update) could be callback query, inline query, … .

You should distinguish between a chat and user clearly. A chat is where this message is published. It could be a channel, super-group, group or an individual user (private chat). A user (indicated by the key ‘from’ in the message) is the person (or bot) who has sent this message. It is possible that the “id” values within these two sub-dictionaries (i.e, message[“chat”][“id”]/message[“from”][“id”]) be the same in which case it indicates that the user specified has sent this message through their private chat (and for example, not through a group).

To send an image to yourself :

image_filename = 'path/to/image' # it's OS-dependent and must be a valid path to an existing image on your computer

with open(image_filename, 'rb') as image_opened_file_stream :
bot.sendPhoto(MY_ID, image_opened_file_stream, caption='Get this image!')


Again if you try to examine the object returned by telepot.sendPhoto method, it would be a typical photo message :

{'caption': 'Get this image!',
'chat': {'first_name': 'My Name',
'id': MY_ID,
'last_name': 'My Last Name',
'type': 'private',
'username': 'my_user_name'},
'date': A_TIMESTAMP,
'from': {'first_name': 'Your Bot Name',
'id': YOUR_BOT_ID,
'is_bot': True,
'username': 'your_bot_username'},
'message_id': AN_INTEGER,
'photo': [{'file_id': 'AgADBAADG7IxG3v_4VFu3njVfVvjidDcLBsABK5ap7SIGIvoEhQDA…',
'file_size': 1401,
'height': 90,
'width': 67},
{'file_id': 'AgADBAADG7IxG3v_4VFu3njVfVvjidDcLBsABOXR_xaIWjXmExQDA…',
'file_size': 26922,
'height': 320,
'width': 240},
{'file_id': 'AgADBAADG7IxG3v_4VFu3njVfVvjidDcLBsABJqXQTGC3Q-KFBQDA…',
'file_size': 88222,
'height': 752,
'width': 564}]}

The photo part in the message is typically an array of 3 images with three different sizes (thumbnail, normal, large). The file_id is a unique ID assigned by telegram for this size of this image.

A very useful tip:

If you know your friend’s telegram ID, and you want to share this image with them through your bot, you wouldn’t need to open a file stream, and send it again in binary format just as above. As matter of fact, Telegram API reference wouldn’t recommend that either. Telegram API reference says that whenever you have the file_id of an image, a video, a document, an audio, … ready in Telegram server, the preferred method to share that media item is through its unique ID that already saved in Telegram servers, and now after the first send, we have this ID! So, we could pick the file_id of the largest image (usually the last item in the array, but if you are a bit skeptic, you could scan all the (three) items in the array and pick the one with the largest file_size or largest width x height value. So, assuming that your friend’s telegram ID is FRIEND_ID and you have copied the file_id of the largest image in a variable : file_id :

FRIEND_ID = YOUR_FRIEND_TELEGRAM_ID # another unique integer

# v--- copy and paste from the message above or scan for the largest image
file_id = 'AgADBAADG7IxG3v_4VFu3njVfVvjidDcLBsABJqXQTGC3Q-KFBQDA…'

bot.sendPhoto(FRIEND_ID, file_id, caption='Get this image buddy!')

Notify the user with bot’s chat action

It’s a good practice to let your bot notify the user receiving the message with telepot.sendChatAction method. This will mimic the normal chat message when one user sends a text, photo, video, document or audio image to another. This method would cause a brief flashing message appear under chat info for about 5 seconds. To do this, write a code like the following immediately before where the telepot.sendMessage, telepot.sendPthoto, … is located in your code:

bot.sendChatAction(MY_ID, 'typing')
bot.sendMessage(MY_ID, 'Hi there!')

The chat_id (MY_ID in the example above) must match in both sendChatAction and sendMessage (sendPhoto, …) methods. For text messages, the chat action must be ‘typing’. For other media messages:

'upload_photo' - for photos
'record_video' or 'upload_video' - for videos
'record_audio' or 'upload_audio' - for audio files
'upload_document' - for general files
...

As the final word, your bot cannot send any message to themself or other bots. It’s against Telegram policy. You may probably figure out why!

Posted in Flask, Python, Telegram Bot | Tagged , , , | Leave a comment

Python : Telegram Bot Webhook Handler : A Multi-Bot/Multi-Language Design (2)


Part 2 – Sample operational bots

There are some bots available for full functional serious applications. There are also some of them available for user test. Merex is one of them. You could access Merex by opening this link in your telegram client application:

or searching his username (merex_900_bot). Merex speaks three languages. I decided to assign gender for the bots, because in some languages like French, the gender of the speaker affects the words they choose.

You could start conversation with Merex, by sending the following command (typing and then sending this text) to Merex :

/start

Upon executing this command, Merex would ask you the preferred language (some shortcut keyboard keys at the bottom of the screen will help you to type the name of language properly), and then the timezone in the format accepted by python pytz module. There’s a link in the message (https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) which helps you find and type the right spelling of the time zones. For example, For UK, the proper timezone value is Europe/London (the values in TZ database name column). I have modified the code a little … now it accepts the well-known capital cities or the major cities which are defined as timezone references (like New York) much easier. See the end of this post (section: Simplified Timezone Points) for more details.

As you can see in the image above, another command :

/who are you?

would make Merex introduce himself with a profile picture. A similar command:

/who am I?

makes Merex to say what he knows about you with your profile photo. You could see your own unique Telegram ID in the text included in the message.

You could explore the other commands by sending the HELP command :

/help

You could see the effect of changing your timezone by executing the TIME command :

/time

Simplified Timezone Points

In the original design, the user had to send the full formal name of the timezone point as defined in the List of tz database time zones. For example, for London, it is Europe/London and for New York, it is America/New_York and the exact case and hyphenation, according to pytz module is a must.

Thanks to the suggestion of a friend from PythonAnywhere, I added some code to let user send timezone points a little more friendly. For most cases, the continent prefix can be dropped. If it causes ambiguity, then the available matches are listed and the user is prompted to send the full formal name; for example Pacific/Samoa and US/Samoa. Usually the multiple matches like this all point to the same timezone … and maybe one of them is deprecated. At this time, it is not handled by my code, and the user would still have to type the full formal value. When there is no ambiguity, the mapping is done properly and it is now case-insensitive:

London --> Europe/London
Paris --> Europe/Paris
New York --> America/New_York

As in the third example above, hyphens may be replaced by any arbitrary number of white spaces (one space is required). It is case-insensitive now, so, London, london and LONDON all are acceptable.

Misspelling the timezone point or sending an invalid none-existing value is now handled slightly better. The user would not have to execute the /start command again. All they need to do is to send the correct value. But it is important to note that as long as the user has not sent the correct value, the bot remains in interactive mode.

Posted in Flask, Python, Telegram Bot | Tagged , , , , , | Leave a comment

Python : Telegram Bot Webhook Handler : A Multi-Bot/Multi-Language Design (1)


Part 1 – The non-programming part

If you are new to the concept of the Telegram bots and how you could write programs to manipulate them, you could review these references before you read this article:

This article is not a tutorial; neither for python programming nor for Telegram bots. There are so many good tutorial for python language. For bot programming, a very good starting point would be

This is a simple yet very useful starter for bot programming. Indeed, every programmer including me follows the steps similar to those instructed in this blog before they could figure out what next they could do with their bot. This blog post is by PythonAnywhere, a great site for hosting python programs with flask web back-end. PythonAnywhere is the site which generously offered me the latest python version with ability to install any python module I need. It also let me have a flask-based web server with a globally accessible URL which is a must because we would need a fixed URL to let the Telegram super-server know where is our bot handler (webhook URL) is located. There are methods that you could fake a global server to setup your webhook handler running on your local computer with a local flask server, but it is only good to test your code, and that wouldn’t make a true 724 available server, and eventually you would need to look for a real global server.

As each of the above references mentions, first of all you should create a bot before you could write a code for it. To start, talk to the BotFather … the creator of all other telegram bots. If successful, you would receive a bot’s authorization token for your bot by the BotFather. That is something like :

123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11 

(It’s the token given in the Telegrams API reference as an example, and obviously this exact string is fake and refers to a non-existing bot!) Your actual token would be a unique value which should be kept secret by you … the owner of the bot. The integer part before : is your bot’s unique Telegram ID, and the string after the colon is the pass-phrase of your bot. Your bot would also have a convenient name (could be whatever you like) … for example, R2D2_2019 … as well as a unique valid username ending with the sub-string ‘bot’ … for a matching example, r2d2_2019_bot … which you specify when you create your bot with BotFather.

In order to start testing your bot, you wouldn’t need to setup a webhook handler for the bot. Indeed, you wouldn’t even need a programming language like python to do it! All you need is a scratch notepad editor and a browser. For example, you could promptly create a telegram bot URL method in your notepad and open it in a browser! Try getMe method: assuming the the string above is your bot token (authorization code) prepend it by sub-string ‘bot’ :

bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11

Prepend it by the telegram specific API URL (https://api.telegram.org/) :

https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11

And finally, append the desire method (getMe) :

https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/getMe

And that’s all! Now open your method URL in a browser, and you would see a JSON text describing the bot! Remember that you should use your own bot token. This one is fake.

Try something, more interesting. If you know your Telegram unique ID, You could simply send yourself a text message by your bot. Assuming that your telegram ID is 123450, you could compose a sendMessage URL method :

https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/sendMessage?chat_id=123450&text=Hi+there+yes+it+me

I didn’t deliberately use any punctuation, because then I would have to “urlencode” my message text! Actually, I just did it now … what I would need to do for now is replacing space with ‘+’.

Posted in Flask, Python, Telegram Bot | Tagged , , , , , | Leave a comment

Spirograph for March 26, 2013


Spirograph-67

Spirograph for March 26, 2013.

Posted in Spirography | Leave a comment