Skip to main content

What is a Telegram Bot

Get a Telegram Bot API TOKEN:

  • Open Telegram and search for @BotFather
  • Create a new bot by following the steps from the image: Telegram Bot API Token Creation

Setup

pip install DjTbot
python manage.py makemigrations
python manage.py migrate

Run Bot

python manage.py runbot

Create users & groups

python manage.py createsuperuser
python manage.py runserver

Create T bot groups and users:
browse to http://127.0.0.1:8000/tbot/
Users in group Admins can also manage groups and users via bot commands

Create your own commands

1.- Start a new django app django-admin startapp myapp
2.- Add your app to settings.INSTALLED_APPS (ProjectName/ProjectName/settings/base.py)
3.- Create a commands.py file inside your app

commands.py example:

from DjTbot.commands import Command


class Example1Command(Command):
    command = ['example', 'e']  # One command can be call with many names
    help_text = 'Example command'
    usage = '/example'
    allowed_groups = ['mygroup']

    def run(self, update, context):
        context.bot.sendMessage(chat_id=update.message.chat_id, text='message')
        self.send_ussage(context.bot, update)
        self.admin_broadcast(context.bot, "Example command called")

*** Arguments sent to commands can be accessible through context.args or you can use the following code snippet:

Parsing arguments with TelegramArgumentParser

arguments.py
from abc import ABCMeta, abstractmethod
from DjTbot.arguments import TelegramArgumentParser


class TBotArgumentParser(TelegramArgumentParser, metaclass=ABCMeta):
    @abstractmethod
    def add_arguments(self):
        pass

    @staticmethod
    def factory(command_class_name):
        parsers = {
            'AddGroupCommand': TelegramIDGroupArgumentParser,
            # Add here as many parsers as you need, key values must be the same as the command class name
        }
        return parsers[command_class_name]()


# All your Argument parsers must inherit form the one created above 
class TelegramIDGroupArgumentParser(TBotArgumentParser):
    def add_arguments(self):
        # add_argument syntaxis from argparse https://docs.python.org/3/library/argparse.html
        self.add_argument('telegram_id', type=int)
        self.add_argument('group')
comands.py
from DjTbot.utils import addgroup
from DjTbot.commands import CommandWithArgumentsMixin, Command
from DjTbot.arguments import TBotArgumentParser


class TBotCommandWithArgumentsMixin(CommandWithArgumentsMixin):
    argument_parser_factory_class = TBotArgumentParser


class AddGroupCommand(TBotCommandWithArgumentsMixin, Command):  # You must follow this order on inherited classes
    command = ['addgroup']
    help_text = 'Add user to group'
    usage = '/addgroup telegram_id group_name'
    allowed_groups = ['Admins']

    def command_call(self, arguments, update, context):
        try:
            addgroup(arguments.telegram_id,
                     arguments.group)  # Access your arguments with the given name in add_argument
        except Exception as e:
            self.admin_broadcast(context.bot, str(e))
            self.send_ussage(context.bot, update)

4.- (optional) Create a listeners.py file inside your app if you wish to process messages. Example:

import logging
from DjTbot.core.listeners import Listener, Filters


logger = logging.getLogger("DjTbot")


class LocationProcess(Listener):
    allowed_groups = ['Admins']
    filters = Filters.location

    def run(self, update, context):
        logger.debug(update)
        a = update.message.location
        context.bot.sendMessage(chat_id=update.message.chat_id, text="Hola {}\n Estas en\n Latitud {}\nLongitud: {}"
                                .format(update.message.from_user['first_name'], a['latitude'], a['longitude']))


class RepeatListener(Listener):
    filters = Filters.text

    def run(self, update, context):
        context.bot.sendMessage(chat_id=update.message.chat_id, text=update.message.text)

Management commands

There are also some management commands

addgroup
adduser
addusertogroup
clear_api_key
createbotadmin
lsgroups
lsusers
removeuserfromgroup
rmgroup
rmuser
runbot
sendmessage

sendmessage

usage: manage.py sendmessage [-h]
                             (--user USER | --user-id USER_ID | --group GROUP | --all)
                             [--version] [-v {0,1,2,3}] [--settings SETTINGS]
                             [--pythonpath PYTHONPATH] [--traceback]
                             [--no-color] [--force-color]
                             message

PythonTelegram Bot Documentation

Metadata

Release files for DjTbot 0.0.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for DjTbot 0.0.7
File Size Uploaded Provenance Actions
DjTbot-0.0.7.tar.gz 12.2 kB Without provenance Details for DjTbot-0.0.7.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for DjTbot 0.0.7
File Interpreter ABI Platform Actions
DjTbot-0.0.7-py3-none-any.whl Python 3 none any Details for DjTbot-0.0.7-py3-none-any.whl

Total release size: 30.8 kB

Release files / DjTbot-0.0.7.tar.gz

Download URL DjTbot-0.0.7.tar.gz
Size 12.2 kB
Tags Source
SHA-256 checksum
How to use checksums
4af410fa0d9356585a782339b433d56293d54ee916be2bb4b765323504accbea
BLAKE2b-256 checksum
How to use checksums
2ec0c6c9395efcf4a3aabb4d9bdd40e714664b814d11b09ff8db90f6835af7f3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.8.1

Release files / DjTbot-0.0.7-py3-none-any.whl

Download URL DjTbot-0.0.7-py3-none-any.whl
Size 18.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
526266b5980002c903f15299da832392cfc1236d2ce17060a8f836e1a55ef3f0
BLAKE2b-256 checksum
How to use checksums
6df477f0836c3bda055e35851a22be3bafeb9068c2bb19d011d20631b4d4ad5d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.8.1

Security for DjTbot 0.0.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.7 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page