Package: telegram-django
Django Telegram BotIntroductionDjango Telegram Botis the base class which helps to build custom commands for the django models. It allows getting historical data from django models, as well as develop custom pre-defined filters and execute custom django management commands (i.e. those which are executed throughpython manage.py $command)InstallDjango Telegram Botrequires python 3.8 or later and has the following dependencies:python-telegram-bot >=13.3django>=2.2.20Django Telegram Botcan be installed frompypi.orgusing pip:$ pip install telegram-djangoRunning The BotDefine your command class extending the baseFor example:from myapp.models import MyAppModel

from telegram_bot.telegram_conversation import TelegramConversation


class MyAppConversation(TelegramConversation):
    def __init__(self, logger, model_datetime_property, suffix):
        super().__init__(logger, model_datetime_property, suffix)
        self.model = MyAppModel

    @property
    def custom_commands(self):
        return [
            'custom_command1',
        ]
        
    @property
    def saved_filters(self):
        return [
            'count',
        ]

    def get_count(self, update):
        amount = self._get_initial_queryset().count()
        self._reply(update, amount)
        self._default_query_context()The methodcustom_commandsmust return a list of defined django commands which can be executed by this conversation handler. These commands are standard django commands which are normally executed viapython manage.py $command.
The methodsaved_filtersmust return a list of defined custom filters. The filter's body must be implemented in the same class using the conventionget_$filter_name, like in the example above: forcountfilter theget_countmethod is implemented.Add the following sections to yoursettings.py:Define application inINSTALLED_APPSINSTALLED_APPS = [
        ...
        'django_telegram',
        ...
    ]Add sectionTELEGRAM_BOTfor bot configurationTELEGRAM_BOT = {
    'CONVERSATIONS': [
        'myapp.package1.package2.MyAppConversation',
    ],
    'TOKEN': '',
    'COMMANDS_SUFFIX': None,
    'HISTORY_LOOKUP_MODEL_PROPERTY': ''
}Add sectiondjango_telegram_botto logger configurationLOGGING = {
...
    'loggers': {
...
        'django_telegram_bot': {
            'handlers': ['console'],
            'level': 'INFO',
        },
...
    },
...
}Settings description:VariableDescriptionTOKENTelegram Token for the bot. Please refer tohttps://core.telegram.org/botson how to create a bot.CONVERSATIONSList of FQDNs for classes which implement and provide conversation instancesHISTORY_LOOKUP_MODEL_PROPERTYProperty of the django model of DateTime type which is used to do history lookupsCOMMANDS_SUFFIXIn case of having multiple instances of the bot (with the same commands) we want to add some suffix to the commands, so that only specific bot is getting the command, so command becomesmyappconversation_${SUFFIX}. If there is no need to have multiple instances of the same bot in the chat -- just leave this asNone.Running The Botpython manage.py start_botMiddlewareThe library also provides a way to analyseresponses of type application/jsonand based on defined rules send pre-defined messages.
To enable middleware add the following line into yoursettings.MIDDLEWAREMIDDLEWARE = [
...
    'django_telegram.bot.middleware.TelegramMiddleware',
]Extend previously defined configuration insettings.pywith the followingTELEGRAM_BOT = {
    'CONVERSATIONS': [
        'myapp.package1.package2.MyAppConversation',
    ],
    'TOKEN': '',
    'COMMANDS_SUFFIX': None,
    'HISTORY_LOOKUP_MODEL_PROPERTY': '',
    'MIDDLEWARE': {
        'CHAT_ID': -12356789,
        'RULES': [{
            'view': 'view',
            'trigger_codes': [204, 200],
            'conditions': {
                'type': 'value',
                'field': 'field',
                'field_value': 'value',
            },
            'message': 'Message when this condition happened!',
        }],
    }
}Settings description:VariableDescriptionCHAT_IDTelegram chat id to where the bot must send messages. Typically an integer like-12345677898RULESList of rules objects which configure a case when message must be sentRULES[i].viewView id in resolver definition, i.e./v1/reports/fail/123URI would be areports-failRULES[i].trigger_codesList of HTTP codes in response where this rule needs to be triggeredRULES[i].conditionsOptional. Additional checks which need to be done before sending the messageRULES[i].conditions.typeType of condition, can be either 'function' (when validation is done by user defined function) or 'value' (when validation is done by simple field/value comparison of response JSON).RULES[i].conditions.functionRequired ifRULES[i].conditions.typeisfunctionotherwise ignored. User defined function which receives as input response JSON as dict and must return eitherTrueorFalseRULES[i].conditions.fieldRequired ifRULES[i].conditions.typeisvalueotherwise ignored. Field to look up in response JSONRULES[i].conditions.field_valueRequired ifRULES[i].conditions.typeisvalueotherwise ignored. Expected value to look up in response JSONRULES[i].messageMessage which needs to be sent to Telegram in case all conditions matchTestingCreate virtualenvInstall project dependenciespython -m pip install --upgrade pip
pip install poetry
poetry updateRun testspoetry run pytestLicenseDjango Telegram Botis released under theApache License Version 2.0.