├── tgbot ├── __init__.py ├── handlers │ ├── __init__.py │ ├── admin │ │ ├── __init__.py │ │ ├── static_text.py │ │ ├── utils.py │ │ └── handlers.py │ ├── utils │ │ ├── __init__.py │ │ ├── info.py │ │ ├── decorators.py │ │ ├── error.py │ │ └── files.py │ ├── location │ │ ├── __init__.py │ │ ├── static_text.py │ │ ├── keyboards.py │ │ └── handlers.py │ ├── onboarding │ │ ├── __init__.py │ │ ├── manage_data.py │ │ ├── static_text.py │ │ ├── keyboards.py │ │ └── handlers.py │ └── broadcast_message │ │ ├── __init__.py │ │ ├── manage_data.py │ │ ├── keyboards.py │ │ ├── static_text.py │ │ ├── utils.py │ │ └── handlers.py ├── main.py ├── system_commands.py └── dispatcher.py ├── users ├── __init__.py ├── migrations │ ├── __init__.py │ ├── 0002_alter_user_user_id.py │ ├── 0003_rm_unused_fields.py │ └── 0001_initial.py ├── apps.py ├── forms.py ├── templates │ └── admin │ │ └── broadcast_message.html ├── tasks.py ├── admin.py └── models.py ├── utils ├── __init__.py └── models.py ├── runtime.txt ├── DOKKU_SCALE ├── .buildpacks ├── .github ├── imgs │ ├── containers_status.png │ └── bot_commands_example.jpg └── workflows │ └── dokku.yml ├── .env_example ├── LocalDockerfile ├── dtb ├── __init__.py ├── asgi.py ├── wsgi.py ├── celery.py ├── urls.py ├── views.py └── settings.py ├── Procfile ├── requirements.txt ├── manage.py ├── run_polling.py ├── docker-compose.yml ├── .gitignore ├── README.md └── LICENSE /tgbot/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /users/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.8.3 -------------------------------------------------------------------------------- /tgbot/handlers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /users/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tgbot/handlers/admin/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tgbot/handlers/utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tgbot/handlers/location/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tgbot/handlers/onboarding/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /DOKKU_SCALE: -------------------------------------------------------------------------------- 1 | web=1 2 | worker=0 3 | beat=0 4 | -------------------------------------------------------------------------------- /tgbot/handlers/broadcast_message/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.buildpacks: -------------------------------------------------------------------------------- 1 | https://github.com/heroku/heroku-buildpack-python.git#v191 -------------------------------------------------------------------------------- /tgbot/handlers/onboarding/manage_data.py: -------------------------------------------------------------------------------- 1 | SECRET_LEVEL_BUTTON = 'SCRT_LVL' 2 | -------------------------------------------------------------------------------- /users/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class UsersConfig(AppConfig): 5 | name = 'users' 6 | -------------------------------------------------------------------------------- /.github/imgs/containers_status.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ohld/django-telegram-bot/HEAD/.github/imgs/containers_status.png -------------------------------------------------------------------------------- /.github/imgs/bot_commands_example.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ohld/django-telegram-bot/HEAD/.github/imgs/bot_commands_example.jpg -------------------------------------------------------------------------------- /tgbot/handlers/broadcast_message/manage_data.py: -------------------------------------------------------------------------------- 1 | CONFIRM_DECLINE_BROADCAST = 'CNFM_DCLN_BRDCST' 2 | CONFIRM_BROADCAST = 'CONFIRM' 3 | DECLINE_BROADCAST = 'DECLINE' 4 | -------------------------------------------------------------------------------- /tgbot/handlers/location/static_text.py: -------------------------------------------------------------------------------- 1 | SEND_LOCATION = "Send 🌏🌎🌍" 2 | share_location = "Would you mind sharing your location?" 3 | thanks_for_location = "Thanks for 🌏🌎🌍" 4 | -------------------------------------------------------------------------------- /users/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | 3 | 4 | class BroadcastForm(forms.Form): 5 | _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) 6 | broadcast_text = forms.CharField(widget=forms.Textarea) 7 | -------------------------------------------------------------------------------- /.env_example: -------------------------------------------------------------------------------- 1 | DJANGO_DEBUG=True 2 | DATABASE_URL=sqlite:///db.sqlite3 3 | #DATABASE_URL=postgres://postgres:postgres@db:5432/postgres # when using PostgreSQL via docker-compose 4 | TELEGRAM_TOKEN=1725447442:AATuNIAicSPdePxxTHdbO1X_4hfAnONOyiA -------------------------------------------------------------------------------- /LocalDockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.8.10 2 | 3 | ENV PYTHONUNBUFFERED=1 4 | 5 | RUN mkdir /code 6 | WORKDIR /code 7 | 8 | COPY requirements.txt /code/ 9 | RUN pip install --upgrade pip 10 | RUN pip install -r requirements.txt 11 | 12 | COPY . /code/ 13 | -------------------------------------------------------------------------------- /dtb/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, unicode_literals 2 | 3 | # This will make sure the app is always imported when 4 | # Django starts so that shared_task will use this app. 5 | from .celery import app as celery_app 6 | 7 | __all__ = ('celery_app',) -------------------------------------------------------------------------------- /tgbot/handlers/admin/static_text.py: -------------------------------------------------------------------------------- 1 | command_start = '/stats' 2 | 3 | secret_admin_commands = f"⚠️ Secret Admin commands\n" \ 4 | f"{command_start} - bot stats" 5 | 6 | users_amount_stat = "Users: {user_count}\n" \ 7 | "24h active: {active_24}" 8 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | release: python manage.py migrate --noinput 2 | web: gunicorn --bind :$PORT --workers 4 --worker-class uvicorn.workers.UvicornWorker dtb.asgi:application 3 | worker: celery -A dtb worker -P prefork --loglevel=INFO 4 | beat: celery -A dtb beat --loglevel=INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler 5 | -------------------------------------------------------------------------------- /users/templates/admin/broadcast_message.html: -------------------------------------------------------------------------------- 1 | {% extends "admin/base_site.html" %} 2 | 3 | {% block content %} 4 |
{% csrf_token %} 5 | {{ form }} 6 | 7 | 8 |
9 | {% endblock %} 10 | 11 | -------------------------------------------------------------------------------- /tgbot/handlers/onboarding/static_text.py: -------------------------------------------------------------------------------- 1 | start_created = "Sup, {first_name}!" 2 | start_not_created = "Welcome back, {first_name}!" 3 | unlock_secret_room = "Congratulations! You've opened a secret room👁‍🗨. There is some information for you:\n" \ 4 | "Users: {user_count}\n" \ 5 | "24h active: {active_24}" 6 | github_button_text = "GitHub" 7 | secret_level_button_text = "Secret level🗝" 8 | -------------------------------------------------------------------------------- /tgbot/main.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | 4 | import telegram 5 | from telegram import Bot 6 | 7 | from dtb.settings import TELEGRAM_TOKEN 8 | 9 | 10 | bot = Bot(TELEGRAM_TOKEN) 11 | TELEGRAM_BOT_USERNAME = bot.get_me()["username"] 12 | # Global variable - the best way I found to init Telegram bot 13 | try: 14 | pass 15 | except telegram.error.Unauthorized: 16 | logging.error("Invalid TELEGRAM_TOKEN.") 17 | sys.exit(1) 18 | -------------------------------------------------------------------------------- /dtb/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for dtb project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /dtb/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for dtb project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /users/migrations/0002_alter_user_user_id.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.8 on 2021-12-01 16:54 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('users', '0001_initial'), 10 | ] 11 | 12 | operations = [ 13 | migrations.AlterField( 14 | model_name='user', 15 | name='user_id', 16 | field=models.PositiveBigIntegerField(primary_key=True, serialize=False), 17 | ), 18 | ] 19 | -------------------------------------------------------------------------------- /tgbot/handlers/location/keyboards.py: -------------------------------------------------------------------------------- 1 | from telegram import ReplyKeyboardMarkup, KeyboardButton 2 | 3 | from tgbot.handlers.location.static_text import SEND_LOCATION 4 | 5 | 6 | def send_location_keyboard() -> ReplyKeyboardMarkup: 7 | # resize_keyboard=False will make this button appear on half screen (become very large). 8 | # Likely, it will increase click conversion but may decrease UX quality. 9 | return ReplyKeyboardMarkup( 10 | [[KeyboardButton(text=SEND_LOCATION, request_location=True)]], 11 | resize_keyboard=True 12 | ) 13 | -------------------------------------------------------------------------------- /users/migrations/0003_rm_unused_fields.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-12-01 17:47 2 | 3 | from django.db import migrations 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('users', '0002_alter_user_user_id'), 10 | ] 11 | 12 | operations = [ 13 | migrations.RemoveField( 14 | model_name='user', 15 | name='is_banned', 16 | ), 17 | migrations.RemoveField( 18 | model_name='user', 19 | name='is_moderator', 20 | ), 21 | ] 22 | -------------------------------------------------------------------------------- /.github/workflows/dokku.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | with: 16 | fetch-depth: 0 17 | 18 | - id: deploy 19 | name: Deploy to dokku 20 | uses: idoberko2/dokku-deploy-github-action@v1 21 | with: 22 | ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }} 23 | dokku-host: 't.okhlopkov.com' 24 | app-name: 'dtb' 25 | git-push-flags: '--force' 26 | -------------------------------------------------------------------------------- /tgbot/handlers/utils/info.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | from telegram import Update 4 | 5 | 6 | def extract_user_data_from_update(update: Update) -> Dict: 7 | """ python-telegram-bot's Update instance --> User info """ 8 | user = update.effective_user.to_dict() 9 | 10 | return dict( 11 | user_id=user["id"], 12 | is_blocked_bot=False, 13 | **{ 14 | k: user[k] 15 | for k in ["username", "first_name", "last_name", "language_code"] 16 | if k in user and user[k] is not None 17 | }, 18 | ) 19 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pytz 2 | requests 3 | python-dotenv 4 | 5 | ipython==8.5.0 # enhanced python interpreter 6 | 7 | # Django 8 | django==3.2.9 9 | django-cors-headers==3.13.0 10 | django-debug-toolbar==3.6.0 11 | whitenoise==6.2.0 # for serving static files 12 | 13 | # Django 3.0 async requirements 14 | gunicorn==20.1.0 15 | uvicorn==0.18.3 16 | 17 | # Databases 18 | psycopg2-binary==2.9.9 19 | dj-database-url==1.0.0 20 | 21 | # Distributed async tasks 22 | celery==5.2.7 23 | redis==4.3.4 24 | django-celery-beat==2.3.0 25 | 26 | # Telegram 27 | python-telegram-bot==13.15 # last sync version 28 | 29 | # monitoring 30 | # sentry-sdk 31 | -------------------------------------------------------------------------------- /tgbot/handlers/onboarding/keyboards.py: -------------------------------------------------------------------------------- 1 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 2 | 3 | from tgbot.handlers.onboarding.manage_data import SECRET_LEVEL_BUTTON 4 | from tgbot.handlers.onboarding.static_text import github_button_text, secret_level_button_text 5 | 6 | 7 | def make_keyboard_for_start_command() -> InlineKeyboardMarkup: 8 | buttons = [[ 9 | InlineKeyboardButton(github_button_text, url="https://github.com/ohld/django-telegram-bot"), 10 | InlineKeyboardButton(secret_level_button_text, callback_data=f'{SECRET_LEVEL_BUTTON}') 11 | ]] 12 | 13 | return InlineKeyboardMarkup(buttons) 14 | -------------------------------------------------------------------------------- /dtb/celery.py: -------------------------------------------------------------------------------- 1 | import os 2 | from celery import Celery 3 | 4 | # set the default Django settings module for the 'celery' program. 5 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings') 6 | 7 | app = Celery('dtb') 8 | 9 | # Using a string here means the worker doesn't have to serialize 10 | # the configuration object to child processes. 11 | # - namespace='CELERY' means all celery-related configuration keys 12 | # should have a `CELERY_` prefix. 13 | app.config_from_object('django.conf:settings', namespace='CELERY') 14 | 15 | # Load task modules from all registered Django app configs. 16 | app.autodiscover_tasks() 17 | app.conf.enable_utc = False 18 | 19 | -------------------------------------------------------------------------------- /tgbot/handlers/broadcast_message/keyboards.py: -------------------------------------------------------------------------------- 1 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 2 | 3 | from tgbot.handlers.broadcast_message.manage_data import CONFIRM_DECLINE_BROADCAST, CONFIRM_BROADCAST, DECLINE_BROADCAST 4 | from tgbot.handlers.broadcast_message.static_text import confirm_broadcast, decline_broadcast 5 | 6 | 7 | def keyboard_confirm_decline_broadcasting() -> InlineKeyboardMarkup: 8 | buttons = [[ 9 | InlineKeyboardButton(confirm_broadcast, callback_data=f'{CONFIRM_DECLINE_BROADCAST}{CONFIRM_BROADCAST}'), 10 | InlineKeyboardButton(decline_broadcast, callback_data=f'{CONFIRM_DECLINE_BROADCAST}{DECLINE_BROADCAST}') 11 | ]] 12 | 13 | return InlineKeyboardMarkup(buttons) 14 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /utils/models.py: -------------------------------------------------------------------------------- 1 | from django.core.exceptions import ObjectDoesNotExist 2 | from django.db import models 3 | 4 | 5 | nb = dict(null=True, blank=True) 6 | 7 | 8 | class CreateTracker(models.Model): 9 | created_at = models.DateTimeField(auto_now_add=True, db_index=True) 10 | 11 | class Meta: 12 | abstract = True 13 | ordering = ('-created_at',) 14 | 15 | 16 | class CreateUpdateTracker(CreateTracker): 17 | updated_at = models.DateTimeField(auto_now=True) 18 | 19 | class Meta(CreateTracker.Meta): 20 | abstract = True 21 | 22 | 23 | class GetOrNoneManager(models.Manager): 24 | """returns none if object doesn't exist else model instance""" 25 | def get_or_none(self, **kwargs): 26 | try: 27 | return self.get(**kwargs) 28 | except ObjectDoesNotExist: 29 | return None 30 | -------------------------------------------------------------------------------- /tgbot/handlers/broadcast_message/static_text.py: -------------------------------------------------------------------------------- 1 | broadcast_command = '/broadcast' 2 | broadcast_no_access = "Sorry, you don't have access to this function." 3 | broadcast_wrong_format = f'To send message to all your users,' \ 4 | f' type {broadcast_command} command with text separated by space.\n' \ 5 | f'For example:\n' \ 6 | f'{broadcast_command} Hello, my users! This bold text is for you, ' \ 7 | f'as well as this italic text.\n\n' \ 8 | f'Examples of using HTML style you can found here.' 9 | confirm_broadcast = "Confirm ✅" 10 | decline_broadcast = "Decline ❌" 11 | message_is_sent = "Message is sent ✅" 12 | declined_message_broadcasting = "Message broadcasting is declined ❌" 13 | error_with_html = "Can't parse your text in HTML style. Reason: \n{reason}" 14 | -------------------------------------------------------------------------------- /run_polling.py: -------------------------------------------------------------------------------- 1 | import os, django 2 | 3 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings') 4 | django.setup() 5 | 6 | from telegram import Bot 7 | from telegram.ext import Updater 8 | 9 | from dtb.settings import TELEGRAM_TOKEN 10 | from tgbot.dispatcher import setup_dispatcher 11 | 12 | 13 | def run_polling(tg_token: str = TELEGRAM_TOKEN): 14 | """ Run bot in polling mode """ 15 | updater = Updater(tg_token, use_context=True) 16 | 17 | dp = updater.dispatcher 18 | dp = setup_dispatcher(dp) 19 | 20 | bot_info = Bot(tg_token).get_me() 21 | bot_link = f"https://t.me/{bot_info['username']}" 22 | 23 | print(f"Polling of '{bot_link}' has started") 24 | # it is really useful to send '👋' emoji to developer 25 | # when you run local test 26 | # bot.send_message(text='👋', chat_id=) 27 | 28 | updater.start_polling() 29 | updater.idle() 30 | 31 | 32 | if __name__ == "__main__": 33 | run_polling() 34 | -------------------------------------------------------------------------------- /tgbot/handlers/admin/utils.py: -------------------------------------------------------------------------------- 1 | import io 2 | import csv 3 | 4 | from datetime import datetime 5 | from django.db.models import QuerySet 6 | from typing import Dict 7 | 8 | 9 | def _get_csv_from_qs_values(queryset: QuerySet[Dict], filename: str = 'users'): 10 | keys = queryset[0].keys() 11 | 12 | # csv module can write data in io.StringIO buffer only 13 | s = io.StringIO() 14 | dict_writer = csv.DictWriter(s, fieldnames=keys) 15 | dict_writer.writeheader() 16 | dict_writer.writerows(queryset) 17 | s.seek(0) 18 | 19 | # python-telegram-bot library can send files only from io.BytesIO buffer 20 | # we need to convert StringIO to BytesIO 21 | buf = io.BytesIO() 22 | 23 | # extract csv-string, convert it to bytes and write to buffer 24 | buf.write(s.getvalue().encode()) 25 | buf.seek(0) 26 | 27 | # set a filename with file's extension 28 | buf.name = f"{filename}__{datetime.now().strftime('%Y.%m.%d.%H.%M')}.csv" 29 | 30 | return buf 31 | -------------------------------------------------------------------------------- /tgbot/handlers/utils/decorators.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | from typing import Callable 3 | 4 | from telegram import Update, ChatAction 5 | from telegram.ext import CallbackContext 6 | 7 | from users.models import User 8 | 9 | 10 | def admin_only(func: Callable): 11 | """ 12 | Admin only decorator 13 | Used for handlers that only admins have access to 14 | """ 15 | 16 | @wraps(func) 17 | def wrapper(update: Update, context: CallbackContext, *args, **kwargs): 18 | user = User.get_user(update, context) 19 | 20 | if not user.is_admin: 21 | return 22 | 23 | return func(update, context, *args, **kwargs) 24 | 25 | return wrapper 26 | 27 | 28 | def send_typing_action(func: Callable): 29 | """Sends typing action while processing func command.""" 30 | 31 | @wraps(func) 32 | def command_func(update: Update, context: CallbackContext, *args, **kwargs): 33 | update.effective_chat.send_chat_action(ChatAction.TYPING) 34 | return func(update, context, *args, **kwargs) 35 | 36 | return command_func 37 | -------------------------------------------------------------------------------- /tgbot/handlers/location/handlers.py: -------------------------------------------------------------------------------- 1 | import telegram 2 | from telegram import Update 3 | from telegram.ext import CallbackContext 4 | 5 | from tgbot.handlers.location.static_text import share_location, thanks_for_location 6 | from tgbot.handlers.location.keyboards import send_location_keyboard 7 | from users.models import User, Location 8 | 9 | 10 | def ask_for_location(update: Update, context: CallbackContext) -> None: 11 | """ Entered /ask_location command""" 12 | u = User.get_user(update, context) 13 | 14 | context.bot.send_message( 15 | chat_id=u.user_id, 16 | text=share_location, 17 | reply_markup=send_location_keyboard() 18 | ) 19 | 20 | 21 | def location_handler(update: Update, context: CallbackContext) -> None: 22 | # receiving user's location 23 | u = User.get_user(update, context) 24 | lat, lon = update.message.location.latitude, update.message.location.longitude 25 | Location.objects.create(user=u, latitude=lat, longitude=lon) 26 | 27 | update.message.reply_text( 28 | thanks_for_location, 29 | reply_markup=telegram.ReplyKeyboardRemove(), 30 | ) 31 | -------------------------------------------------------------------------------- /dtb/urls.py: -------------------------------------------------------------------------------- 1 | """dtb URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | import debug_toolbar 17 | from django.contrib import admin 18 | from django.urls import path, include 19 | from django.views.decorators.csrf import csrf_exempt 20 | 21 | from . import views 22 | 23 | urlpatterns = [ 24 | path('tgadmin/', admin.site.urls), 25 | path('__debug__/', include(debug_toolbar.urls)), 26 | path('', views.index, name="index"), 27 | path('super_secter_webhook/', csrf_exempt(views.TelegramBotWebhookView.as_view())), 28 | ] 29 | -------------------------------------------------------------------------------- /dtb/views.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | from django.views import View 4 | from django.http import JsonResponse 5 | from telegram import Update 6 | 7 | from dtb.celery import app 8 | from dtb.settings import DEBUG 9 | from tgbot.dispatcher import dispatcher 10 | from tgbot.main import bot 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | @app.task(ignore_result=True) 16 | def process_telegram_event(update_json): 17 | update = Update.de_json(update_json, bot) 18 | dispatcher.process_update(update) 19 | 20 | 21 | def index(request): 22 | return JsonResponse({"error": "sup hacker"}) 23 | 24 | 25 | class TelegramBotWebhookView(View): 26 | # WARNING: if fail - Telegram webhook will be delivered again. 27 | # Can be fixed with async celery task execution 28 | def post(self, request, *args, **kwargs): 29 | if DEBUG: 30 | process_telegram_event(json.loads(request.body)) 31 | else: 32 | # Process Telegram event in Celery worker (async) 33 | # Don't forget to run it and & Redis (message broker for Celery)! 34 | # Locally, You can run all of these services via docker-compose.yml 35 | process_telegram_event.delay(json.loads(request.body)) 36 | 37 | # e.g. remove buttons, typing event 38 | return JsonResponse({"ok": "POST request processed"}) 39 | 40 | def get(self, request, *args, **kwargs): # for debug 41 | return JsonResponse({"ok": "Get request received! But nothing done"}) 42 | -------------------------------------------------------------------------------- /tgbot/handlers/admin/handlers.py: -------------------------------------------------------------------------------- 1 | from datetime import timedelta 2 | 3 | from django.utils.timezone import now 4 | from telegram import ParseMode, Update 5 | from telegram.ext import CallbackContext 6 | 7 | from tgbot.handlers.admin import static_text 8 | from tgbot.handlers.admin.utils import _get_csv_from_qs_values 9 | from tgbot.handlers.utils.decorators import admin_only, send_typing_action 10 | from users.models import User 11 | 12 | 13 | @admin_only 14 | def admin(update: Update, context: CallbackContext) -> None: 15 | """ Show help info about all secret admins commands """ 16 | update.message.reply_text(static_text.secret_admin_commands) 17 | 18 | 19 | @admin_only 20 | def stats(update: Update, context: CallbackContext) -> None: 21 | """ Show help info about all secret admins commands """ 22 | text = static_text.users_amount_stat.format( 23 | user_count=User.objects.count(), # count may be ineffective if there are a lot of users. 24 | active_24=User.objects.filter(updated_at__gte=now() - timedelta(hours=24)).count() 25 | ) 26 | 27 | update.message.reply_text( 28 | text, 29 | parse_mode=ParseMode.HTML, 30 | disable_web_page_preview=True, 31 | ) 32 | 33 | 34 | @admin_only 35 | @send_typing_action 36 | def export_users(update: Update, context: CallbackContext) -> None: 37 | # in values argument you can specify which fields should be returned in output csv 38 | users = User.objects.all().values() 39 | csv_users = _get_csv_from_qs_values(users) 40 | update.message.reply_document(csv_users) 41 | -------------------------------------------------------------------------------- /tgbot/handlers/onboarding/handlers.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from django.utils import timezone 4 | from telegram import ParseMode, Update 5 | from telegram.ext import CallbackContext 6 | 7 | from tgbot.handlers.onboarding import static_text 8 | from tgbot.handlers.utils.info import extract_user_data_from_update 9 | from users.models import User 10 | from tgbot.handlers.onboarding.keyboards import make_keyboard_for_start_command 11 | 12 | 13 | def command_start(update: Update, context: CallbackContext) -> None: 14 | u, created = User.get_user_and_created(update, context) 15 | 16 | if created: 17 | text = static_text.start_created.format(first_name=u.first_name) 18 | else: 19 | text = static_text.start_not_created.format(first_name=u.first_name) 20 | 21 | update.message.reply_text(text=text, 22 | reply_markup=make_keyboard_for_start_command()) 23 | 24 | 25 | def secret_level(update: Update, context: CallbackContext) -> None: 26 | # callback_data: SECRET_LEVEL_BUTTON variable from manage_data.py 27 | """ Pressed 'secret_level_button_text' after /start command""" 28 | user_id = extract_user_data_from_update(update)['user_id'] 29 | text = static_text.unlock_secret_room.format( 30 | user_count=User.objects.count(), 31 | active_24=User.objects.filter(updated_at__gte=timezone.now() - datetime.timedelta(hours=24)).count() 32 | ) 33 | 34 | context.bot.edit_message_text( 35 | text=text, 36 | chat_id=user_id, 37 | message_id=update.callback_query.message.message_id, 38 | parse_mode=ParseMode.HTML 39 | ) -------------------------------------------------------------------------------- /tgbot/handlers/utils/error.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import traceback 3 | import html 4 | 5 | import telegram 6 | from telegram import Update 7 | from telegram.ext import CallbackContext 8 | 9 | from dtb.settings import TELEGRAM_LOGS_CHAT_ID 10 | from users.models import User 11 | 12 | 13 | def send_stacktrace_to_tg_chat(update: Update, context: CallbackContext) -> None: 14 | u = User.get_user(update, context) 15 | 16 | logging.error("Exception while handling an update:", exc_info=context.error) 17 | 18 | tb_list = traceback.format_exception(None, context.error, context.error.__traceback__) 19 | tb_string = ''.join(tb_list) 20 | 21 | # Build the message with some markup and additional information about what happened. 22 | # You might need to add some logic to deal with messages longer than the 4096 character limit. 23 | message = ( 24 | f'An exception was raised while handling an update\n' 25 | f'
{html.escape(tb_string)}
' 26 | ) 27 | 28 | user_message = """ 29 | 😔 Something broke inside the bot. 30 | It is because we are constantly improving our service but sometimes we might forget to test some basic stuff. 31 | We already received all the details to fix the issue. 32 | Return to /start 33 | """ 34 | context.bot.send_message( 35 | chat_id=u.user_id, 36 | text=user_message, 37 | ) 38 | 39 | admin_message = f"⚠️⚠️⚠️ for {u.tg_str}:\n{message}"[:4090] 40 | if TELEGRAM_LOGS_CHAT_ID: 41 | context.bot.send_message( 42 | chat_id=TELEGRAM_LOGS_CHAT_ID, 43 | text=admin_message, 44 | parse_mode=telegram.ParseMode.HTML, 45 | ) 46 | else: 47 | logging.error(admin_message) 48 | -------------------------------------------------------------------------------- /users/tasks.py: -------------------------------------------------------------------------------- 1 | """ 2 | Celery tasks. Some of them will be launched periodically from admin panel via django-celery-beat 3 | """ 4 | 5 | import time 6 | from typing import Union, List, Optional, Dict 7 | 8 | import telegram 9 | 10 | from dtb.celery import app 11 | from celery.utils.log import get_task_logger 12 | from tgbot.handlers.broadcast_message.utils import send_one_message, from_celery_entities_to_entities, \ 13 | from_celery_markup_to_markup 14 | 15 | logger = get_task_logger(__name__) 16 | 17 | 18 | @app.task(ignore_result=True) 19 | def broadcast_message( 20 | user_ids: List[Union[str, int]], 21 | text: str, 22 | entities: Optional[List[Dict]] = None, 23 | reply_markup: Optional[List[List[Dict]]] = None, 24 | sleep_between: float = 0.4, 25 | parse_mode=telegram.ParseMode.HTML, 26 | ) -> None: 27 | """ It's used to broadcast message to big amount of users """ 28 | logger.info(f"Going to send message: '{text}' to {len(user_ids)} users") 29 | 30 | entities_ = from_celery_entities_to_entities(entities) 31 | reply_markup_ = from_celery_markup_to_markup(reply_markup) 32 | for user_id in user_ids: 33 | try: 34 | send_one_message( 35 | user_id=user_id, 36 | text=text, 37 | entities=entities_, 38 | parse_mode=parse_mode, 39 | reply_markup=reply_markup_, 40 | ) 41 | logger.info(f"Broadcast message was sent to {user_id}") 42 | except Exception as e: 43 | logger.error(f"Failed to send message to {user_id}, reason: {e}") 44 | time.sleep(max(sleep_between, 0.1)) 45 | 46 | logger.info("Broadcast finished!") 47 | 48 | 49 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | 3 | services: 4 | db: 5 | image: postgres:12 6 | container_name: dtb_postgres 7 | restart: always 8 | volumes: 9 | - postgres_data:/var/lib/postgresql/data/ 10 | environment: 11 | - POSTGRES_USER=postgres 12 | - POSTGRES_PASSWORD=postgres 13 | env_file: 14 | - ./.env 15 | ports: 16 | - "5433:5432" 17 | redis: 18 | image: redis:alpine 19 | container_name: dtb_redis 20 | web: 21 | build: 22 | context: . 23 | dockerfile: LocalDockerfile 24 | container_name: dtb_django 25 | restart: always 26 | command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" 27 | volumes: 28 | - .:/code 29 | ports: 30 | - "8000:8000" 31 | env_file: 32 | - ./.env 33 | depends_on: 34 | - db 35 | bot: 36 | build: 37 | context: . 38 | dockerfile: LocalDockerfile 39 | container_name: dtb_bot 40 | restart: always 41 | command: python run_polling.py 42 | env_file: 43 | - ./.env 44 | depends_on: 45 | - web 46 | celery: 47 | build: 48 | context: . 49 | dockerfile: LocalDockerfile 50 | container_name: dtb_celery 51 | restart: always 52 | command: celery -A dtb worker --loglevel=INFO 53 | volumes: 54 | - .:/code 55 | env_file: 56 | - ./.env 57 | depends_on: 58 | - redis 59 | - web 60 | celery-beat: 61 | build: 62 | context: . 63 | dockerfile: LocalDockerfile 64 | container_name: dtb_beat 65 | restart: always 66 | command: celery -A dtb beat -l info --scheduler django_celery_beat.schedulers.DatabaseScheduler 67 | volumes: 68 | - .:/code 69 | env_file: 70 | - ./.env 71 | depends_on: 72 | - redis 73 | - celery 74 | - web 75 | 76 | volumes: 77 | postgres_data: 78 | -------------------------------------------------------------------------------- /tgbot/system_commands.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | from telegram import Bot, BotCommand 4 | 5 | from tgbot.main import bot 6 | 7 | 8 | def set_up_commands(bot_instance: Bot) -> None: 9 | 10 | langs_with_commands: Dict[str, Dict[str, str]] = { 11 | 'en': { 12 | 'start': 'Start django bot 🚀', 13 | 'stats': 'Statistics of bot 📊', 14 | 'admin': 'Show admin info ℹ️', 15 | 'ask_location': 'Send location 📍', 16 | 'broadcast': 'Broadcast message 📨', 17 | 'export_users': 'Export users.csv 👥', 18 | }, 19 | 'es': { 20 | 'start': 'Iniciar el bot de django 🚀', 21 | 'stats': 'Estadísticas de bot 📊', 22 | 'admin': 'Mostrar información de administrador ℹ️', 23 | 'ask_location': 'Enviar ubicación 📍', 24 | 'broadcast': 'Mensaje de difusión 📨', 25 | 'export_users': 'Exportar users.csv 👥', 26 | }, 27 | 'fr': { 28 | 'start': 'Démarrer le bot Django 🚀', 29 | 'stats': 'Statistiques du bot 📊', 30 | 'admin': "Afficher les informations d'administrateur ℹ️", 31 | 'ask_location': 'Envoyer emplacement 📍', 32 | 'broadcast': 'Message de diffusion 📨', 33 | "export_users": 'Exporter users.csv 👥', 34 | }, 35 | 'ru': { 36 | 'start': 'Запустить django бота 🚀', 37 | 'stats': 'Статистика бота 📊', 38 | 'admin': 'Показать информацию для админов ℹ️', 39 | 'broadcast': 'Отправить сообщение 📨', 40 | 'ask_location': 'Отправить локацию 📍', 41 | 'export_users': 'Экспорт users.csv 👥', 42 | } 43 | } 44 | 45 | bot_instance.delete_my_commands() 46 | for language_code in langs_with_commands: 47 | bot_instance.set_my_commands( 48 | language_code=language_code, 49 | commands=[ 50 | BotCommand(command, description) for command, description in langs_with_commands[language_code].items() 51 | ] 52 | ) 53 | 54 | 55 | set_up_commands(bot) 56 | -------------------------------------------------------------------------------- /users/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.http import HttpResponseRedirect 3 | from django.shortcuts import render 4 | 5 | from dtb.settings import DEBUG 6 | 7 | from users.models import Location 8 | from users.models import User 9 | from users.forms import BroadcastForm 10 | 11 | from users.tasks import broadcast_message 12 | from tgbot.handlers.broadcast_message.utils import send_one_message 13 | 14 | 15 | @admin.register(User) 16 | class UserAdmin(admin.ModelAdmin): 17 | list_display = [ 18 | 'user_id', 'username', 'first_name', 'last_name', 19 | 'language_code', 'deep_link', 20 | 'created_at', 'updated_at', "is_blocked_bot", 21 | ] 22 | list_filter = ["is_blocked_bot", ] 23 | search_fields = ('username', 'user_id') 24 | 25 | actions = ['broadcast'] 26 | 27 | def broadcast(self, request, queryset): 28 | """ Select users via check mark in django-admin panel, then select "Broadcast" to send message""" 29 | user_ids = queryset.values_list('user_id', flat=True).distinct().iterator() 30 | if 'apply' in request.POST: 31 | broadcast_message_text = request.POST["broadcast_text"] 32 | 33 | if DEBUG: # for test / debug purposes - run in same thread 34 | for user_id in user_ids: 35 | send_one_message( 36 | user_id=user_id, 37 | text=broadcast_message_text, 38 | ) 39 | self.message_user(request, f"Just broadcasted to {len(queryset)} users") 40 | else: 41 | broadcast_message.delay(text=broadcast_message_text, user_ids=list(user_ids)) 42 | self.message_user(request, f"Broadcasting of {len(queryset)} messages has been started") 43 | 44 | return HttpResponseRedirect(request.get_full_path()) 45 | else: 46 | form = BroadcastForm(initial={'_selected_action': user_ids}) 47 | return render( 48 | request, "admin/broadcast_message.html", {'form': form, 'title': u'Broadcast message'} 49 | ) 50 | 51 | 52 | @admin.register(Location) 53 | class LocationAdmin(admin.ModelAdmin): 54 | list_display = ['id', 'user_id', 'created_at'] 55 | -------------------------------------------------------------------------------- /users/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-08-25 10:43 2 | 3 | from django.db import migrations, models 4 | import django.db.models.deletion 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | initial = True 10 | 11 | dependencies = [ 12 | ] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name='User', 17 | fields=[ 18 | ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), 19 | ('updated_at', models.DateTimeField(auto_now=True)), 20 | ('user_id', models.IntegerField(primary_key=True, serialize=False)), 21 | ('username', models.CharField(blank=True, max_length=32, null=True)), 22 | ('first_name', models.CharField(max_length=256)), 23 | ('last_name', models.CharField(blank=True, max_length=256, null=True)), 24 | ('language_code', models.CharField(blank=True, help_text="Telegram client's lang", max_length=8, null=True)), 25 | ('deep_link', models.CharField(blank=True, max_length=64, null=True)), 26 | ('is_blocked_bot', models.BooleanField(default=False)), 27 | ('is_banned', models.BooleanField(default=False)), 28 | ('is_admin', models.BooleanField(default=False)), 29 | ('is_moderator', models.BooleanField(default=False)), 30 | ], 31 | options={ 32 | 'ordering': ('-created_at',), 33 | 'abstract': False, 34 | }, 35 | ), 36 | migrations.CreateModel( 37 | name='Location', 38 | fields=[ 39 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 40 | ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), 41 | ('latitude', models.FloatField()), 42 | ('longitude', models.FloatField()), 43 | ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.user')), 44 | ], 45 | options={ 46 | 'ordering': ('-created_at',), 47 | 'abstract': False, 48 | }, 49 | ), 50 | ] 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | dtb/static 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | .python-version 87 | 88 | # pipenv 89 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 90 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 91 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 92 | # install all needed dependencies. 93 | #Pipfile.lock 94 | 95 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 96 | __pypackages__/ 97 | 98 | # Celery stuff 99 | celerybeat-schedule 100 | celerybeat.pid 101 | 102 | # SageMath parsed files 103 | *.sage.py 104 | 105 | # Environments 106 | .env 107 | .venv 108 | env/ 109 | venv/ 110 | ENV/ 111 | env.bak/ 112 | venv.bak/ 113 | dtb_venv/ 114 | 115 | # Spyder project settings 116 | .spyderproject 117 | .spyproject 118 | 119 | # Rope project settings 120 | .ropeproject 121 | 122 | # mkdocs documentation 123 | /site 124 | 125 | # mypy 126 | .mypy_cache/ 127 | .dmypy.json 128 | dmypy.json 129 | 130 | # Pyre type checker 131 | .pyre/ 132 | .DS_Store 133 | 134 | #PyCharm 135 | .idea/ 136 | 137 | #Docker 138 | .Dockerfile.swp -------------------------------------------------------------------------------- /tgbot/handlers/broadcast_message/utils.py: -------------------------------------------------------------------------------- 1 | from typing import Union, Optional, Dict, List 2 | 3 | import telegram 4 | from telegram import MessageEntity, InlineKeyboardButton, InlineKeyboardMarkup 5 | 6 | from dtb.settings import TELEGRAM_TOKEN 7 | from users.models import User 8 | 9 | 10 | def from_celery_markup_to_markup(celery_markup: Optional[List[List[Dict]]]) -> Optional[InlineKeyboardMarkup]: 11 | markup = None 12 | if celery_markup: 13 | markup = [] 14 | for row_of_buttons in celery_markup: 15 | row = [] 16 | for button in row_of_buttons: 17 | row.append( 18 | InlineKeyboardButton( 19 | text=button['text'], 20 | callback_data=button.get('callback_data'), 21 | url=button.get('url'), 22 | ) 23 | ) 24 | markup.append(row) 25 | markup = InlineKeyboardMarkup(markup) 26 | return markup 27 | 28 | 29 | def from_celery_entities_to_entities(celery_entities: Optional[List[Dict]] = None) -> Optional[List[MessageEntity]]: 30 | entities = None 31 | if celery_entities: 32 | entities = [ 33 | MessageEntity( 34 | type=entity['type'], 35 | offset=entity['offset'], 36 | length=entity['length'], 37 | url=entity.get('url'), 38 | language=entity.get('language'), 39 | ) 40 | for entity in celery_entities 41 | ] 42 | return entities 43 | 44 | 45 | def send_one_message( 46 | user_id: Union[str, int], 47 | text: str, 48 | parse_mode: Optional[str] = telegram.ParseMode.HTML, 49 | reply_markup: Optional[List[List[Dict]]] = None, 50 | reply_to_message_id: Optional[int] = None, 51 | disable_web_page_preview: Optional[bool] = None, 52 | entities: Optional[List[MessageEntity]] = None, 53 | tg_token: str = TELEGRAM_TOKEN, 54 | ) -> bool: 55 | bot = telegram.Bot(tg_token) 56 | try: 57 | m = bot.send_message( 58 | chat_id=user_id, 59 | text=text, 60 | parse_mode=parse_mode, 61 | reply_markup=reply_markup, 62 | reply_to_message_id=reply_to_message_id, 63 | disable_web_page_preview=disable_web_page_preview, 64 | entities=entities, 65 | ) 66 | except telegram.error.Unauthorized: 67 | print(f"Can't send message to {user_id}. Reason: Bot was stopped.") 68 | User.objects.filter(user_id=user_id).update(is_blocked_bot=True) 69 | success = False 70 | else: 71 | success = True 72 | User.objects.filter(user_id=user_id).update(is_blocked_bot=False) 73 | return success 74 | -------------------------------------------------------------------------------- /tgbot/dispatcher.py: -------------------------------------------------------------------------------- 1 | """ 2 | Telegram event handlers 3 | """ 4 | from telegram.ext import ( 5 | Dispatcher, Filters, 6 | CommandHandler, MessageHandler, 7 | CallbackQueryHandler, 8 | ) 9 | 10 | from dtb.settings import DEBUG 11 | from tgbot.handlers.broadcast_message.manage_data import CONFIRM_DECLINE_BROADCAST 12 | from tgbot.handlers.broadcast_message.static_text import broadcast_command 13 | from tgbot.handlers.onboarding.manage_data import SECRET_LEVEL_BUTTON 14 | 15 | from tgbot.handlers.utils import files, error 16 | from tgbot.handlers.admin import handlers as admin_handlers 17 | from tgbot.handlers.location import handlers as location_handlers 18 | from tgbot.handlers.onboarding import handlers as onboarding_handlers 19 | from tgbot.handlers.broadcast_message import handlers as broadcast_handlers 20 | from tgbot.main import bot 21 | 22 | 23 | def setup_dispatcher(dp): 24 | """ 25 | Adding handlers for events from Telegram 26 | """ 27 | # onboarding 28 | dp.add_handler(CommandHandler("start", onboarding_handlers.command_start)) 29 | 30 | # admin commands 31 | dp.add_handler(CommandHandler("admin", admin_handlers.admin)) 32 | dp.add_handler(CommandHandler("stats", admin_handlers.stats)) 33 | dp.add_handler(CommandHandler('export_users', admin_handlers.export_users)) 34 | 35 | # location 36 | dp.add_handler(CommandHandler("ask_location", location_handlers.ask_for_location)) 37 | dp.add_handler(MessageHandler(Filters.location, location_handlers.location_handler)) 38 | 39 | # secret level 40 | dp.add_handler(CallbackQueryHandler(onboarding_handlers.secret_level, pattern=f"^{SECRET_LEVEL_BUTTON}")) 41 | 42 | # broadcast message 43 | dp.add_handler( 44 | MessageHandler(Filters.regex(rf'^{broadcast_command}(/s)?.*'), broadcast_handlers.broadcast_command_with_message) 45 | ) 46 | dp.add_handler( 47 | CallbackQueryHandler(broadcast_handlers.broadcast_decision_handler, pattern=f"^{CONFIRM_DECLINE_BROADCAST}") 48 | ) 49 | 50 | # files 51 | dp.add_handler(MessageHandler( 52 | Filters.animation, files.show_file_id, 53 | )) 54 | 55 | # handling errors 56 | dp.add_error_handler(error.send_stacktrace_to_tg_chat) 57 | 58 | # EXAMPLES FOR HANDLERS 59 | # dp.add_handler(MessageHandler(Filters.text, )) 60 | # dp.add_handler(MessageHandler( 61 | # Filters.document, , 62 | # )) 63 | # dp.add_handler(CallbackQueryHandler(, pattern="^r\d+_\d+")) 64 | # dp.add_handler(MessageHandler( 65 | # Filters.chat(chat_id=int(TELEGRAM_FILESTORAGE_ID)), 66 | # # & Filters.forwarded & (Filters.photo | Filters.video | Filters.animation), 67 | # , 68 | # )) 69 | 70 | return dp 71 | 72 | 73 | n_workers = 0 if DEBUG else 4 74 | dispatcher = setup_dispatcher(Dispatcher(bot, update_queue=None, workers=n_workers, use_context=True)) 75 | -------------------------------------------------------------------------------- /tgbot/handlers/broadcast_message/handlers.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | import telegram 4 | from telegram import Update 5 | from telegram.ext import CallbackContext 6 | 7 | from dtb.settings import DEBUG 8 | from .manage_data import CONFIRM_DECLINE_BROADCAST, CONFIRM_BROADCAST 9 | from .keyboards import keyboard_confirm_decline_broadcasting 10 | from .static_text import broadcast_command, broadcast_wrong_format, broadcast_no_access, error_with_html, \ 11 | message_is_sent, declined_message_broadcasting 12 | from users.models import User 13 | from users.tasks import broadcast_message 14 | 15 | 16 | def broadcast_command_with_message(update: Update, context: CallbackContext): 17 | """ Type /broadcast . Then check your message in HTML format and broadcast to users.""" 18 | u = User.get_user(update, context) 19 | 20 | if not u.is_admin: 21 | update.message.reply_text( 22 | text=broadcast_no_access, 23 | ) 24 | else: 25 | if update.message.text == broadcast_command: 26 | # user typed only command without text for the message. 27 | update.message.reply_text( 28 | text=broadcast_wrong_format, 29 | parse_mode=telegram.ParseMode.HTML, 30 | ) 31 | return 32 | 33 | text = f"{update.message.text.replace(f'{broadcast_command} ', '')}" 34 | markup = keyboard_confirm_decline_broadcasting() 35 | 36 | try: 37 | update.message.reply_text( 38 | text=text, 39 | parse_mode=telegram.ParseMode.HTML, 40 | reply_markup=markup, 41 | ) 42 | except telegram.error.BadRequest as e: 43 | update.message.reply_text( 44 | text=error_with_html.format(reason=e), 45 | parse_mode=telegram.ParseMode.HTML, 46 | ) 47 | 48 | 49 | def broadcast_decision_handler(update: Update, context: CallbackContext) -> None: 50 | # callback_data: CONFIRM_DECLINE_BROADCAST variable from manage_data.py 51 | """ Entered /broadcast . 52 | Shows text in HTML style with two buttons: 53 | Confirm and Decline 54 | """ 55 | broadcast_decision = update.callback_query.data[len(CONFIRM_DECLINE_BROADCAST):] 56 | 57 | entities_for_celery = update.callback_query.message.to_dict().get('entities') 58 | entities, text = update.callback_query.message.entities, update.callback_query.message.text 59 | 60 | if broadcast_decision == CONFIRM_BROADCAST: 61 | admin_text = message_is_sent 62 | user_ids = list(User.objects.all().values_list('user_id', flat=True)) 63 | 64 | if DEBUG: 65 | broadcast_message( 66 | user_ids=user_ids, 67 | text=text, 68 | entities=entities_for_celery, 69 | ) 70 | else: 71 | # send in async mode via celery 72 | broadcast_message.delay( 73 | user_ids=user_ids, 74 | text=text, 75 | entities=entities_for_celery, 76 | ) 77 | else: 78 | context.bot.send_message( 79 | chat_id=update.callback_query.message.chat_id, 80 | text=declined_message_broadcasting, 81 | ) 82 | admin_text = text 83 | 84 | context.bot.edit_message_text( 85 | text=admin_text, 86 | chat_id=update.callback_query.message.chat_id, 87 | message_id=update.callback_query.message.message_id, 88 | entities=None if broadcast_decision == CONFIRM_BROADCAST else entities, 89 | ) 90 | -------------------------------------------------------------------------------- /users/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import Union, Optional, Tuple 4 | 5 | from django.db import models 6 | from django.db.models import QuerySet, Manager 7 | from telegram import Update 8 | from telegram.ext import CallbackContext 9 | 10 | from tgbot.handlers.utils.info import extract_user_data_from_update 11 | from utils.models import CreateUpdateTracker, nb, CreateTracker, GetOrNoneManager 12 | 13 | 14 | class AdminUserManager(Manager): 15 | def get_queryset(self): 16 | return super().get_queryset().filter(is_admin=True) 17 | 18 | 19 | class User(CreateUpdateTracker): 20 | user_id = models.PositiveBigIntegerField(primary_key=True) # telegram_id 21 | username = models.CharField(max_length=32, **nb) 22 | first_name = models.CharField(max_length=256) 23 | last_name = models.CharField(max_length=256, **nb) 24 | language_code = models.CharField(max_length=8, help_text="Telegram client's lang", **nb) 25 | deep_link = models.CharField(max_length=64, **nb) 26 | 27 | is_blocked_bot = models.BooleanField(default=False) 28 | 29 | is_admin = models.BooleanField(default=False) 30 | 31 | objects = GetOrNoneManager() # user = User.objects.get_or_none(user_id=) 32 | admins = AdminUserManager() # User.admins.all() 33 | 34 | def __str__(self): 35 | return f'@{self.username}' if self.username is not None else f'{self.user_id}' 36 | 37 | @classmethod 38 | def get_user_and_created(cls, update: Update, context: CallbackContext) -> Tuple[User, bool]: 39 | """ python-telegram-bot's Update, Context --> User instance """ 40 | data = extract_user_data_from_update(update) 41 | u, created = cls.objects.update_or_create(user_id=data["user_id"], defaults=data) 42 | 43 | if created: 44 | # Save deep_link to User model 45 | if context is not None and context.args is not None and len(context.args) > 0: 46 | payload = context.args[0] 47 | if str(payload).strip() != str(data["user_id"]).strip(): # you can't invite yourself 48 | u.deep_link = payload 49 | u.save() 50 | 51 | return u, created 52 | 53 | @classmethod 54 | def get_user(cls, update: Update, context: CallbackContext) -> User: 55 | u, _ = cls.get_user_and_created(update, context) 56 | return u 57 | 58 | @classmethod 59 | def get_user_by_username_or_user_id(cls, username_or_user_id: Union[str, int]) -> Optional[User]: 60 | """ Search user in DB, return User or None if not found """ 61 | username = str(username_or_user_id).replace("@", "").strip().lower() 62 | if username.isdigit(): # user_id 63 | return cls.objects.filter(user_id=int(username)).first() 64 | return cls.objects.filter(username__iexact=username).first() 65 | 66 | @property 67 | def invited_users(self) -> QuerySet[User]: 68 | return User.objects.filter(deep_link=str(self.user_id), created_at__gt=self.created_at) 69 | 70 | @property 71 | def tg_str(self) -> str: 72 | if self.username: 73 | return f'@{self.username}' 74 | return f"{self.first_name} {self.last_name}" if self.last_name else f"{self.first_name}" 75 | 76 | 77 | class Location(CreateTracker): 78 | user = models.ForeignKey(User, on_delete=models.CASCADE) 79 | latitude = models.FloatField() 80 | longitude = models.FloatField() 81 | 82 | objects = GetOrNoneManager() 83 | 84 | def __str__(self): 85 | return f"user: {self.user}, created at {self.created_at.strftime('(%H:%M, %d %B %Y)')}" 86 | -------------------------------------------------------------------------------- /tgbot/handlers/utils/files.py: -------------------------------------------------------------------------------- 1 | """ 2 | 'document': { 3 | 'file_name': 'preds (4).csv', 'mime_type': 'text/csv', 4 | 'file_id': 'BQACAgIAAxkBAAIJ8F-QAVpXcgUgCUtr2OAHN-OC_2bmAAJwBwAC53CASIpMq-3ePqBXGwQ', 5 | 'file_unique_id': 'AgADcAcAAudwgEg', 'file_size': 28775 6 | } 7 | 'photo': [ 8 | {'file_id': 'AgACAgIAAxkBAAIJ-F-QCOHZUv6Kmf_Z3eVSmByix_IwAAOvMRvncIBIYJQP2Js-sAWGaBiVLgADAQADAgADbQADjpMFAAEbBA', 'file_unique_id': 'AQADhmgYlS4AA46TBQAB', 'file_size': 13256, 'width': 148, 'height': 320}, 9 | {'file_id': 'AgACAgIAAxkBAAIJ-F-QCOHZUv6Kmf_Z3eVSmByix_IwAAOvMRvncIBIYJQP2Js-sAWGaBiVLgADAQADAgADeAADkJMFAAEbBA', 'file_unique_id': 'AQADhmgYlS4AA5CTBQAB', 'file_size': 50857, 'width': 369, 'height': 800}, 10 | {'file_id': 'AgACAgIAAxkBAAIJ-F-QCOHZUv6Kmf_Z3eVSmByix_IwAAOvMRvncIBIYJQP2Js-sAWGaBiVLgADAQADAgADeQADj5MFAAEbBA', 'file_unique_id': 'AQADhmgYlS4AA4-TBQAB', 'file_size': 76018, 'width': 591, 'height': 1280} 11 | ] 12 | 'video_note': { 13 | 'duration': 2, 'length': 300, 14 | 'thumb': {'file_id': 'AAMCAgADGQEAAgn_XaLgADAQAHbQADQCYAAhsE', 'file_unique_id': 'AQADWoxsmi4AA0AmAAI', 'file_size': 11684, 'width': 300, 'height': 300}, 15 | 'file_id': 'DQACAgIAAxkBAAIJCASO6_6Hj8qY3PGwQ', 'file_unique_id': 'AgADeQcAAudwgEg', 'file_size': 102840 16 | } 17 | 'voice': { 18 | 'duration': 1, 'mime_type': 'audio/ogg', 19 | 'file_id': 'AwACAgIAAxkBAAIKAAFfkAu_8Ntpv8n9WWHETutijg20nAACegcAAudwgEi8N3Tjeom0IxsE', 20 | 'file_unique_id': 'AgADegcAAudwgEg', 'file_size': 4391 21 | } 22 | 'sticker': { 23 | 'width': 512, 'height': 512, 'emoji': '🤔', 'set_name': 's121356145_282028_by_stickerfacebot', 'is_animated': False, 24 | 'thumb': { 25 | 'file_id': 'AAMCAgADGQEAAgJUX5A5icQq_0qkwXnihR_MJuCKSRAAAmQAA3G_Owev57igO1Oj4itVTZguAAMBAAdtAAObPwACGwQ', 'file_unique_id': 'AQADK1VNmC4AA5s_AAI', 'file_size': 14242, 'width': 320, 'height': 320 26 | }, 27 | 'file_id': 'CAACAgIAAxkBAAICVF-QOYnEKv9KpMF54oUfzCbgikkQAAJkAANxvzsHr-e4oDtTo-IbBA', 'file_unique_id': 'AgADZAADcb87Bw', 'file_size': 25182 28 | } 29 | 'video': { 30 | 'duration': 14, 'width': 480, 'height': 854, 'mime_type': 'video/mp4', 31 | 'thumb': {'file_id': 'AAMCAgADGQEAAgoIX5BAQy-AfwmWLgADAQAHbQADJhAAAhsE', 'file_unique_id': 'AQAD5H8Jli4AAyYQAAI', 'file_size': 9724, 'width': 180, 'height': 320}, 32 | 'file_id': 'BAACAgIIAAKaCAACCcGASLV2hk3MavHGGwQ', 33 | 'file_unique_id': 'AgADmggAAgnBgEg', 'file_size': 1260506}, 'caption': '50603' 34 | } 35 | """ 36 | from typing import Dict 37 | 38 | import telegram 39 | from telegram import Update 40 | from telegram.ext import CallbackContext 41 | 42 | from users.models import User 43 | 44 | ALL_TG_FILE_TYPES = ["document", "video_note", "voice", "sticker", "audio", "video", "animation", "photo"] 45 | 46 | 47 | def _get_file_id(m: Dict) -> str: 48 | """ extract file_id from message (and file type?) """ 49 | 50 | for doc_type in ALL_TG_FILE_TYPES: 51 | if doc_type in m and doc_type != "photo": 52 | return m[doc_type]["file_id"] 53 | 54 | if "photo" in m: 55 | best_photo = m["photo"][-1] 56 | return best_photo["file_id"] 57 | 58 | 59 | def show_file_id(update: Update, context: CallbackContext) -> None: 60 | """ Returns file_id of the attached file/media """ 61 | u = User.get_user(update, context) 62 | 63 | if u.is_admin: 64 | update_json = update.to_dict() 65 | file_id = _get_file_id(update_json["message"]) 66 | message_id = update_json["message"]["message_id"] 67 | update.message.reply_text( 68 | text=f"`{file_id}`", 69 | parse_mode=telegram.ParseMode.HTML, 70 | reply_to_message_id=message_id 71 | ) 72 | -------------------------------------------------------------------------------- /dtb/settings.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import sys 4 | 5 | import dj_database_url 6 | import dotenv 7 | 8 | from pathlib import Path 9 | 10 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 11 | BASE_DIR = Path(__file__).resolve().parent.parent 12 | 13 | 14 | # Load env variables from file 15 | dotenv_file = BASE_DIR / ".env" 16 | if os.path.isfile(dotenv_file): 17 | dotenv.load_dotenv(dotenv_file) 18 | 19 | 20 | # SECURITY WARNING: keep the secret key used in production secret! 21 | SECRET_KEY = os.getenv( 22 | "DJANGO_SECRET_KEY", 23 | 'x%#3&%giwv8f0+%r946en7z&d@9*rc$sl0qoql56xr%bh^w2mj', 24 | ) 25 | 26 | if os.environ.get('DJANGO_DEBUG', default=False) in ['True', 'true', '1', True]: 27 | DEBUG = True 28 | else: 29 | DEBUG = False 30 | 31 | ALLOWED_HOSTS = ["*",] # since Telegram uses a lot of IPs for webhooks 32 | 33 | 34 | INSTALLED_APPS = [ 35 | 'django.contrib.admin', 36 | 'django.contrib.auth', 37 | 'django.contrib.contenttypes', 38 | 'django.contrib.sessions', 39 | 'django.contrib.messages', 40 | 'django.contrib.staticfiles', 41 | 42 | # 3rd party apps 43 | 'django_celery_beat', 44 | 'debug_toolbar', 45 | 46 | # local apps 47 | 'users.apps.UsersConfig', 48 | ] 49 | 50 | MIDDLEWARE = [ 51 | 'django.middleware.security.SecurityMiddleware', 52 | 'django.contrib.sessions.middleware.SessionMiddleware', 53 | 'django.middleware.csrf.CsrfViewMiddleware', 54 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 55 | 'django.contrib.messages.middleware.MessageMiddleware', 56 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 57 | 58 | 'whitenoise.middleware.WhiteNoiseMiddleware', 59 | 'corsheaders.middleware.CorsMiddleware', 60 | 'debug_toolbar.middleware.DebugToolbarMiddleware', 61 | 62 | 'django.middleware.common.CommonMiddleware', 63 | ] 64 | 65 | INTERNAL_IPS = [ 66 | # ... 67 | '127.0.0.1', 68 | # ... 69 | ] 70 | 71 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 72 | 73 | CORS_ORIGIN_ALLOW_ALL = True 74 | CORS_ALLOW_CREDENTIALS = True 75 | 76 | ROOT_URLCONF = 'dtb.urls' 77 | 78 | TEMPLATES = [ 79 | { 80 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 81 | 'DIRS': [], 82 | 'APP_DIRS': True, 83 | 'OPTIONS': { 84 | 'context_processors': [ 85 | 'django.template.context_processors.debug', 86 | 'django.template.context_processors.request', 87 | 'django.contrib.auth.context_processors.auth', 88 | 'django.contrib.messages.context_processors.messages', 89 | ], 90 | }, 91 | }, 92 | ] 93 | 94 | WSGI_APPLICATION = 'dtb.wsgi.application' 95 | ASGI_APPLICATION = 'dtb.asgi.application' 96 | 97 | 98 | # Database 99 | # https://docs.djangoproject.com/en/3.0/ref/settings/#databases 100 | 101 | DATABASES = { 102 | 'default': dj_database_url.config(conn_max_age=600, default="sqlite:///db.sqlite3"), 103 | } 104 | 105 | # Password validation 106 | # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators 107 | 108 | AUTH_PASSWORD_VALIDATORS = [ 109 | { 110 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 111 | }, 112 | { 113 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 114 | }, 115 | { 116 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 117 | }, 118 | { 119 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 120 | }, 121 | ] 122 | 123 | 124 | # Internationalization 125 | # https://docs.djangoproject.com/en/3.0/topics/i18n/ 126 | 127 | LANGUAGE_CODE = 'en-us' 128 | TIME_ZONE = 'UTC' 129 | USE_I18N = True 130 | USE_L10N = True 131 | USE_TZ = True 132 | 133 | 134 | # Static files (CSS, JavaScript, Images) 135 | # https://docs.djangoproject.com/en/3.0/howto/static-files/ 136 | STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' 137 | 138 | PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) 139 | STATIC_URL = '/static/' 140 | STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') 141 | 142 | 143 | # -----> CELERY 144 | REDIS_URL = os.getenv('REDIS_URL', 'redis://redis:6379') 145 | BROKER_URL = REDIS_URL 146 | CELERY_BROKER_URL = REDIS_URL 147 | CELERY_RESULT_BACKEND = REDIS_URL 148 | CELERY_ACCEPT_CONTENT = ['application/json'] 149 | CELERY_TASK_SERIALIZER = 'json' 150 | CELERY_RESULT_SERIALIZER = 'json' 151 | CELERY_TIMEZONE = TIME_ZONE 152 | CELERY_TASK_DEFAULT_QUEUE = 'default' 153 | 154 | 155 | # -----> TELEGRAM 156 | TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN") 157 | if TELEGRAM_TOKEN is None: 158 | logging.error( 159 | "Please provide TELEGRAM_TOKEN in .env file.\n" 160 | "Example of .env file: https://github.com/ohld/django-telegram-bot/blob/main/.env_example" 161 | ) 162 | sys.exit(1) 163 | 164 | TELEGRAM_LOGS_CHAT_ID = os.getenv("TELEGRAM_LOGS_CHAT_ID", default=None) 165 | 166 | # -----> SENTRY 167 | # import sentry_sdk 168 | # from sentry_sdk.integrations.django import DjangoIntegration 169 | # from sentry_sdk.integrations.celery import CeleryIntegration 170 | # from sentry_sdk.integrations.redis import RedisIntegration 171 | 172 | # sentry_sdk.init( 173 | # dsn="INPUT ...ingest.sentry.io/ LINK", 174 | # integrations=[ 175 | # DjangoIntegration(), 176 | # CeleryIntegration(), 177 | # RedisIntegration(), 178 | # ], 179 | # traces_sample_rate=0.1, 180 | 181 | # # If you wish to associate users to errors (assuming you are using 182 | # # django.contrib.auth) you may enable sending PII data. 183 | # send_default_pii=True 184 | # ) 185 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # django-telegram-bot 2 | 3 |

4 | 5 |

6 | 7 | Sexy Django + python-telegram-bot + Celery + Redis + Postgres + Dokku + GitHub Actions template. Production-ready Telegram bot with database, admin panel and a bunch of useful built-in methods. 8 | 9 | 10 | ⭐ graph: 11 | [![Sparkline](https://stars.medv.io/ohld/django-telegram-bot.svg)](https://stars.medv.io/ohld/django-telegram-bot) 12 | 13 | 14 | ### Check the example bot that uses the code from Main branch: [t.me/djangotelegrambot](https://t.me/djangotelegrambot) 15 | 16 | ## Features 17 | 18 | * Database: Postgres, Sqlite3, MySQL - you decide! 19 | * Admin panel (thanks to [Django](https://docs.djangoproject.com/en/3.1/intro/tutorial01/)) 20 | * Background jobs using [Celery](https://docs.celeryproject.org/en/stable/) 21 | * [Production-ready](https://github.com/ohld/django-telegram-bot/wiki/Production-Deployment-using-Dokku) deployment using [Dokku](https://dokku.com) 22 | * Telegram API usage in polling or [webhook mode](https://core.telegram.org/bots/api#setwebhook) 23 | * Export all users in `.csv` 24 | * Native telegram [commands in menu](https://github.com/ohld/django-telegram-bot/blob/main/.github/imgs/bot_commands_example.jpg) 25 | * In order to edit or delete these commands you'll need to use `set_my_commands` bot's method just like in [tgbot.dispatcher.setup_my_commands](https://github.com/ohld/django-telegram-bot/blob/main/tgbot/dispatcher.py#L150-L156) 26 | 27 | Built-in Telegram bot methods: 28 | * `/broadcast` — send message to all users (admin command) 29 | * `/export_users` — bot sends you info about your users in .csv file (admin command) 30 | * `/stats` — show basic bot stats 31 | * `/ask_for_location` — log user location when received and reverse geocode it to get country, city, etc. 32 | 33 | 34 | ## Content 35 | 36 | * [How to run locally](https://github.com/ohld/django-telegram-bot/#how-to-run) 37 | * [Quickstart with polling and SQLite](https://github.com/ohld/django-telegram-bot/#quickstart-polling--sqlite) 38 | * [Using docker-compose](https://github.com/ohld/django-telegram-bot/#run-locally-using-docker-compose) 39 | * [Deploy to production](https://github.com/ohld/django-telegram-bot/#deploy-to-production) 40 | * [Using dokku](https://github.com/ohld/django-telegram-bot/#deploy-using-dokku-step-by-step) 41 | * [Telegram webhook](https://github.com/ohld/django-telegram-bot/#https--telegram-bot-webhook) 42 | 43 | 44 | # How to run 45 | 46 | ## Quickstart: Polling & SQLite 47 | 48 | The fastest way to run the bot is to run it in polling mode using SQLite database without all Celery workers for background jobs. This should be enough for quickstart: 49 | 50 | ``` bash 51 | git clone https://github.com/ohld/django-telegram-bot 52 | cd django-telegram-bot 53 | ``` 54 | 55 | Create virtual environment (optional) 56 | ``` bash 57 | python3 -m venv dtb_venv 58 | source dtb_venv/bin/activate 59 | ``` 60 | 61 | Install all requirements: 62 | ``` 63 | pip install -r requirements.txt 64 | ``` 65 | 66 | Create `.env` file in root directory and copy-paste this or just run `cp .env_example .env`, 67 | don't forget to change telegram token: 68 | ``` bash 69 | DJANGO_DEBUG=True 70 | DATABASE_URL=sqlite:///db.sqlite3 71 | TELEGRAM_TOKEN= 72 | ``` 73 | 74 | Run migrations to setup SQLite database: 75 | ``` bash 76 | python manage.py migrate 77 | ``` 78 | 79 | Create superuser to get access to admin panel: 80 | ``` bash 81 | python manage.py createsuperuser 82 | ``` 83 | 84 | Run bot in polling mode: 85 | ``` bash 86 | python run_polling.py 87 | ``` 88 | 89 | If you want to open Django admin panel which will be located on http://localhost:8000/tgadmin/: 90 | ``` bash 91 | python manage.py runserver 92 | ``` 93 | 94 | ## Run locally using docker-compose 95 | If you want just to run all the things locally, you can use Docker-compose which will start all containers for you. 96 | 97 | ### Create .env file. 98 | You can switch to PostgreSQL just by uncommenting it's `DATABASE_URL` and commenting SQLite variable. 99 | ```bash 100 | cp .env_example .env 101 | ``` 102 | 103 | ### Docker-compose 104 | 105 | To run all services (Django, Postgres, Redis, Celery) at once: 106 | ``` bash 107 | docker-compose up -d --build 108 | ``` 109 | 110 | Check status of the containers. 111 | ``` bash 112 | docker ps -a 113 | ``` 114 | It should look similar to this: 115 |

116 | 117 |

118 | 119 | Try visit Django-admin panel. 120 | 121 | ### Enter django shell: 122 | 123 | ``` bash 124 | docker exec -it dtb_django bash 125 | ``` 126 | 127 | ### Create superuser for Django admin panel 128 | 129 | ``` bash 130 | python manage.py createsuperuser 131 | ``` 132 | 133 | ### To see logs of the container: 134 | 135 | ``` bash 136 | docker logs -f dtb_django 137 | ``` 138 | 139 | 140 | # Deploy to Production 141 | 142 | Production stack will include these technologies: 143 | 144 | 1) Postgres as main database for Django 145 | 2) Celery + Redis + easy scalable workers 146 | 3) Dokku as PaaS (will build app from sources and deploy it with zero downtime) 147 | 148 | All app's services that are going to be launched in production can be found in `Procfile` file. It includes Django webserver (Telegram event processing + admin panel) and Celery workers (background and periodic jobs). 149 | 150 | ## What is Dokku and how it works 151 | 152 | [Dokku](https://dokku.com/) is an open-source version of Heroku. 153 | 154 | I really like Heroku deployment approach: 155 | 1) you push commit to Main branch of your Repo 156 | 2) in couple minutes your new app is running 157 | 3) if something breaks during deployment - old app will not be shut down 158 | 159 | You can achieve the same approach with Dokku + Github Actions (just to trigger deployment). 160 | 161 | Dokku uses [buildpacks](https://buildpacks.io/) technology to create a Docker image from the code. No Dockerfile needed. Speaking about Python, it requires `requirements.txt`, `Procfile` files to run the things up. Also files `DOKKU_SCALE` and `runtime.txt` are useful to tweak configs to make the deployed app even better. E.g. in `DOKKU_SCALE` you can specify how many app instances should be run behind built-in load balancer. 162 | 163 | One disadvantage of Dokku that you should be warned about is that it can work with one server only. You can't just scale your app up to 2 machines using only small config change. You still can use several servers by providing correct .env URLs to deployed apps (e.g. DATABASE_URL) but it will require more time to setup. 164 | 165 | ## Deploy using Dokku: step-by-step 166 | 167 | I assume that you already have [Dokku installed](https://dokku.com/docs/getting-started/installation/) on your server. Let's also assume that the address of your server is ** (you will need a domain to setup HTTPs for Telegram webhook support). I'd recommend to have at least [2GB RAM and 2 CPU cores](https://m.do.co/c/260555f64021). 168 | 169 | ### Create Dokku app 170 | 171 | ``` bash 172 | dokku apps:create dtb 173 | ``` 174 | 175 | You might need to added `.env` variables to app, e.g. to specify Telegram token: 176 | 177 | ``` bash 178 | dokku config:set dtb TELEGRAM_TOKEN=..... 179 | ``` 180 | 181 | ### Postgres and Redis 182 | 183 | **Postgres** and **Redis** are configured as Dokku plugins on a server. 184 | They will automatically add REDIS_URL & DATABASE_URL .env vars to the app after being linked. 185 | You might need to install these Dokku plugins before. 186 | [Install Postgres](https://github.com/dokku/dokku-postgres), 187 | [install Redis](https://github.com/dokku/dokku-redis). 188 | 189 | ``` bash 190 | dokku postgres:create dtb 191 | dokku postgres:link dtb dtb 192 | 193 | dokku redis:create dtb 194 | dokku redis:link dtb dtb 195 | ``` 196 | 197 | ### Deploy on commit with Github Actions 198 | 199 | Go to file [.github/workflows/dokku.yml](https://github.com/ohld/django-telegram-bot/blob/main/.github/workflows/dokku.yml): 200 | 201 | 1. Enter your host name (address of your server), 202 | 2. Deployed dokku app name (in our case this is `dtb`), 203 | 3. Set `SSH_PRIVATE_KEY` secret variable via GitHub repo settings. This private key should have the **root ssh access** to your server. 204 | 205 | This will trigger Dokku's zero-downtime deployment. You would probably need to fork this repo to change file. 206 | 207 | After that you should see a green arrow ✅ at Github Actions tab that would mean your app is deployed successfully. If you see a red cross ❌ you can find the deployed logs in Github Actions tab and find out what went wrong. 208 | 209 | ## HTTPS & Telegram bot webhook 210 | 211 | ### Why you need to setup webhook 212 | 213 | Basic polling approach is really handy and can speed up development of Telegram bots. But it doesn't scale. Better approach is to allow Telegram servers push events (webhook messages) to your server when something happens with your Telegram bot. You can use built-in Dokku load-balancer to parallel event processing. 214 | 215 | ### HTTPS using Letsencrypt plugin 216 | 217 | For Telegram bot API webhook usage you'll need a **https** which can be setup using [Letsencrypt Dokku plugin](https://github.com/dokku/dokku-letsencrypt). You will need to attach a domain to your Django app before and specify a email (required by Letsencrypt) - you will receive notifications when certificates would become old. Make sure you achieved a successful deployment first (your app runs at , check in browser). 218 | 219 | ``` bash 220 | dokku domains:add dtb 221 | dokku config:set --global DOKKU_LETSENCRYPT_EMAIL= 222 | dokku letsencrypt:enable dtb 223 | ``` 224 | 225 | ### Setup Telegram Bot API webhook URL 226 | 227 | You need to tell Telegram servers where to send events of your Telegram bot. Just open in the browser: 228 | 229 | ``` 230 | https://api.telegram.org/bot/setWebhook?url=https:///super_secter_webhook/ 231 | ``` 232 | 233 | 234 | ### After deployment 235 | 236 | You can be sure that your app is deployed successfully if you see a green arrow at the latest workflow at Github Actions tab. 237 | 238 | You would need to create a superuser to access an admin panel at https:///tgadmin. This can be done using a standard way using django shell: 239 | 240 | 241 | ### Open shell in deployed app 242 | ``` shell 243 | dokku enter dtb web 244 | ``` 245 | 246 | ### Create Django super user 247 | Being inside a container: 248 | ``` bash 249 | python manage.py createsuperuser 250 | ``` 251 | 252 | After that you can open admin panel of your deployed app which is located at https:///tgadmin. 253 | 254 | ### Read app logs 255 | 256 | ``` bash 257 | dokku logs dtb -t 258 | ``` 259 | 260 | 261 | ---- 262 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2023 Daniil Okhlopkov 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------