Skip to main content

from oscarbot.response import TGResponse

TG Core from Oscar

Telegram bot core only for webhooks way working

Telegram bot core, created in django style with routing and views(handlers) where you can use included builders for menu or messages

Installing / Getting started

This is package only for using with Django project.

pip install django-oscarbot

Initial Configuration

In settings.py file you need to specify application for tg use:

OSCARBOT_APPS = ['main']

# set Telegram api token in your env variables TELEGRAM_API_TOKEN
TELEGRAM_API_TOKEN = '1234567890:AaBbCcDd...'

# set Telegram api url in your env variables TELEGRAM_URL
TELEGRAM_URL = 'https://api.telegram.org/bot'

# set location Bot model
OSCARBOT_BOT_MODEL = 'oscarbot.Bot'

# set location Bot User model
OSCARBOT_BOT_USER_MODEL = 'oscarbot.User'

# set the location of the TextProcessor to process user messages
TELEGRAM_TEXT_PROCESSOR = 'your_app.text_processor.handler'

# set the text of the message that the bot will send if it does not understand how to process it (not required).
NOT_UNDERSTAND_MESSAGE = 'Sorry, I do not understand you.'

# set a menu for the message that the bot will send if it does not understand how to process it (not required).
NOT_UNDERSTAND_MENU = 'your_app.menus.your_menu'  # Default - None

# whether to update the message when the bot does not understand how to process the user's message (not required).
NOT_UNDERSTAND_NEED_UPDATE = False  # Default - False

# Whether to delete a message if the bot does not understand how to process a user's message (not required).
NOT_UNDERSTAND_IS_DELETE_MESSAGE = True  # Default - False

# set Telegram message parse mode (not required):
TELEGRAM_PARSE_MODE = 'MARKDOWN'  # Default - 'HTML'

In root urls add include urls from library:

urlpatterns = [
    path('', include('oscarbot.urls'))
    ...
]

Run django server and open localhost:8000/admin/ and create new bot, at least fill bot token for testing ability

Features

  • User model
from oscarbot.models import User

some_user = User.objects.filter(username='@maslov_oa').first()
  • Menu and Buttons builder
from oscarbot.menu import Menu, Button


button_list = [
    Button(text='Text for callback', callback='/some_callback/'),
    Button(text='Text for external url', url='https://oscarbot.site/'),
    Button(text='Web app view', web_app='https://oscarbot.site/'),
]

menu = Menu(button_list)
  • Message builder
from oscarbot.shortcut import QuickBot

quick_bot = QuickBot(
    chat=111111111,
    message='Hello from command line',
    token='token can be saved in DB and not required'
)
quick_bot.send()
  • Application with routing and views(handlers):

    example application

  • Command to add or update a bot in the database

python manage.py create_bot_db
  • Long polling server for testing
python manage.py runbot
  • Update messages available
# TODO: work in progress
  • Set webhook for bot
python manage.py setwh
  • Messages log
# TODO: work in progress
  • Storage for text messages

Make template of file inside any application from OSCARBOT_APPS setting

python manage.py messages

Collect all controllers-function which includes in router files

python manage.py messagee --collect

Hard reset template messages (it will clear your entered text)

python manage.py messagee --force

Usage: After collecting routers you need to text your messages in messages.yaml

You can skip message at all:

def start(user):
    return TGResponse()

Or you can create custom message alias and message inside of messages.yaml:

messages:
  start: Hi!
  custom_message: This is custom Hi!

After that you can use custom message alias though # symbol:

def start(user):
    return TGResponse(message='#custom_message')

In case you need paste arguments you can use templates strings in yaml:

messages:
  start: Hi, {1}! Is is your {2}`th visit!
  custom_message: This is custom Hi, {1}!

And in view:

def start(user):
    return TGResponse(text_args=['User Name', '10'])

or

def start(user):
    return TGResponse(
      messge='#custom_message', 
      text_args=['User Name']
    )

Project Structure

Django-project
├── first_app/
├── second_app/
├── config/
├── main
│   ├── menus
│   │   ├── __init__.py
│   │   └── start_menu.py
│   ├── views
│   │   ├── __init__.py
│   │   └── start.py
│   ├── __init__.py
│   ├── actions.py  
│   ├── admin.py  
│   ├── app.py  
│   ├── models.py  
│   ├── router.py
│   └── text_processor.py
├ manage.py
├ requirements.txt

Example menus/start_menu.py

from oscarbot.menu import Button, Menu


def get_start_menu() -> Menu:
    """Get start menu."""
    feedback_url = 'https://example.com'
    buttons = [
        Button('Home', callback='/start'),
        Button('Page', callback='/my_router/'),
        Button('Feedback', url=feedback_url),
    ]
    return Menu(buttons)

Example views/start.py

from oscarbot.response import TGResponse

from main.actions import YOUR_ACTION
from main.menus import start_menu
from users.models import TGUser


def star(user: TGUser) -> TGResponse:
    """Home."""
    user.clean_state()  # clean want_action and state_information
    user.want_action = YOUR_ACTION
    user.save()
    message = 'Welcome!'
    menu = start_menu.get_start_menu()
    return TGResponse(message, menu, need_update=False)

Example actions.py

from oscarbot.response import TGResponse

from main.menus import start_menu
from users.models import TGUser

YOUR_ACTION = 'main.action__your_action'


def action__your_action(user: TGUser, message: str) -> TGResponse:
    """Action."""
    user.state_information = message  # your logic
    user.save()
    message_response = 'Your message'
    menu = start_menu.get_start_menu()
    return TGResponse(message_response, menu, need_update=True, is_delete_message=True)

Example models.py

from django.contrib.auth.models import AbstractUser
from django.db import models
from oscarbot.models import BaseUser

NULLABLE = {'blank': True, 'null': True}


class User(AbstractUser):
    """User model."""

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'


class TGUser(BaseUser):
    """Telegram user."""
    user = models.OneToOneField(User, models.SET_NULL, **NULLABLE, related_name='tg_user', verbose_name='user tg')

    class Meta:
        verbose_name = 'profile Telegram'
        verbose_name_plural = 'profiles Telegram'

    def __str__(self):
        return f'{self.t_id}'

Example router.py

from oscarbot.router import route

from main.views import start

routes = [
    route('/start', start),
]

Example text_processor.py

from oscarbot.response import TGResponse

from main.menus import start_menu
from users.models import TGUser


def handler(user: TGUser, message: dict) -> TGResponse:
    """Handler."""
    message_response = 'Your message'
    menu = start_menu.get_start_menu()
    return TGResponse(message_response, menu)

Links

Licensing

The code in this project is licensed under MIT license.

Metadata

Release files for django-oscarbot 0.85

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

Source distribution (sdist)

Source distribution for django-oscarbot 0.85
File Size Uploaded
django_oscarbot-0.85.tar.gz 70.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-oscarbot 0.85
File Interpreter ABI Platform
django_oscarbot-0.85-py3-none-any.whl Python 3 none any Details

Total release size: 169.9 kB

Release files / django_oscarbot-0.85.tar.gz

Download URL django_oscarbot-0.85.tar.gz
Size 70.8 kB
Tags Source
SHA-256 checksum
How to use checksums
cf435dfbc88be93dabb04dc2f91d451e1e0d022c2249e68bb7e6a87f957d6b89
BLAKE2b-256 checksum
How to use checksums
96a3c2a738a67e8a4889bacd9f51dbf58aef8c91b321c07002c0e2382a336e32
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.11.12

Release files / django_oscarbot-0.85-py3-none-any.whl

Download URL django_oscarbot-0.85-py3-none-any.whl
Size 99.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6e3bf0b7b1c8f24366c7d5b16bf5532fa5817ef62d8bb0f419c64bc8cf2a4281
BLAKE2b-256 checksum
How to use checksums
2b866e175107fcb541e623d7612319f58e40e3f3ecaba0fd8dae80d466efc65c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.11.12

Release history Release notifications | RSS feed

This release

0.85 This release

2 release files

0.84

2 release files

0.83

2 release files

0.82

2 release files

0.81

2 release files

0.80

2 release files

0.79

2 release files

0.78

2 release files

0.77

2 release files

0.76

2 release files

0.75

2 release files

0.74

2 release files

0.73

2 release files

0.72

2 release files

0.71

2 release files

0.70

2 release files

0.69

2 release files

0.68

2 release files

0.67

2 release files

0.66

2 release files

0.65

2 release files

0.64

2 release files

0.63

2 release files

0.62

2 release files

0.61

2 release files

0.60

2 release files

0.59

2 release files

0.58

2 release files

0.57

2 release files

0.56

2 release files

0.55

2 release files

0.54

2 release files

0.53

2 release files

0.52

2 release files

0.51

2 release files

0.50

2 release files

0.49

2 release files

0.48

2 release files

0.47

2 release files

0.46

2 release files

0.45

2 release files

0.44

2 release files

0.43

2 release files

0.42

2 release files

0.41

2 release files

0.40

2 release files

0.39

2 release files

0.38

2 release files

0.37

2 release files

0.36

2 release files

0.35

2 release files

0.34

2 release files

0.33

2 release files

0.32

2 release files

0.31

2 release files

0.30

1 release file

0.29

2 release files

0.28

2 release files

0.27

2 release files

0.26

2 release files

0.25

2 release files

0.24

2 release files

0.23

2 release files

0.22

2 release files

0.21

2 release files

0.20

2 release files

0.19

2 release files

0.18

2 release files

0.17

2 release files

0.16

2 release files

0.15

2 release files

0.14

2 release files

0.13

2 release files

0.12

2 release files

0.11

2 release files

0.10

2 release files

0.9

2 release files

0.8

2 release files

0.7

2 release files

0.6

2 release files

0.5

2 release files

0.4

2 release files

0.3

2 release files

0.2

2 release files

0.1

1 release file

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