Skip to content

Instantly share code, notes, and snippets.

@flyudvik
Last active March 22, 2017 04:06
Show Gist options
  • Save flyudvik/d1359a1ec7b618c2333103b84f7523b7 to your computer and use it in GitHub Desktop.
Save flyudvik/d1359a1ec7b618c2333103b84f7523b7 to your computer and use it in GitHub Desktop.
django python-telegram-api integration
# coding: utf-8
"""
This module contains a simple integration with django.
To install on your django project, you need to register all bots on settings, add one line on
your urls and create a register method it will received a dispatcher to add all handlers of
your bot.
///////// settings.py
TELEGRAM_BOT_WEBHOOK_PATH = 'telegram_webhook' # it's default
TELEGRAM_BOT = [{
'token': '{YOUR_BOT_TOKEN}',
'register': 'myapp.dispatcher.register', # register method that will be called
}]
## urls.py file
urlpatterns = [
...
url(r'^', include('telegram.contrib.django')),
...
]
## myapp/dispatcher.py
from telegram.ext import CommandHandler
def start(bot, update):
bot.sendMessage(update.message.chat_id, text='Hi from telegram bot inside django project!')
def help(bot, update):
bot.sendMessage(update.message.chat_id, text='This is a help message')
def error(bot, update):
bot.sendMessage(update.message.chat_id, text='Command not founded.')
# this method will be called on start of application
def register(dispatcher):
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("help", help))
dp.add_error_handler(error)
"""
import json
import logging
from telegram import Bot
from telegram import Update
from telegram.ext import Dispatcher
from django.conf.urls import url
from django.utils.module_loading import import_string
from django.conf import settings
from django.http import Http404, HttpResponse
from django.utils.decorators import method_decorator
from django.views import generic
from django.views.decorators.csrf import csrf_exempt
from django.contrib.sites.models import Site
logger = logging.getLogger(__name__)
REGISTERED_BOTS = {}
WEBHOOK_PATH = getattr(settings, "TELEGRAM_BOT_WEBHOOK_PATH", 'telegram_webhook')
def register_webhooks(force=False):
global REGISTERED_BOTS
if REGISTERED_BOTS and not force:
return
REGISTERED_BOTS = {}
for bot_config in settings.TELEGRAM_BOT:
bot = Bot(bot_config['token'])
current_site = Site.objects.get_current()
url = 'https://' + current_site.domain + prepend_webhook_base('/', WEBHOOK_PATH)
bot.set_webhook(url)
dispatcher = Dispatcher(bot, None, workers=0)
register = import_string(bot_config['register'])
register(dispatcher)
REGISTERED_BOTS[bot.token] = {'dispatcher': dispatcher, 'bot': bot}
logger.info('bot %s [%s] registered!' % (bot.name, bot.token), url)
@method_decorator(csrf_exempt, name='dispatch')
class TelegramView(generic.View):
http_method_names = ['post']
@classmethod
def as_view(cls, **kwargs):
register_webhooks()
return super(TelegramView, cls).as_view(**kwargs)
def post(self, request, token):
registered_bot = REGISTERED_BOTS.get(token, None)
if not registered_bot:
return Http404
bot = registered_bot['bot']
dispatcher = registered_bot['dispatcher']
json_string = request.body.decode('utf-8')
update = Update.de_json(json.loads(json_string), bot)
dispatcher.process_update(update)
return HttpResponse(status=200)
def prepend_webhook_base(path, prefix=None):
if prefix:
return prefix + r'/' + path
return path
urlpatterns = [
url(prepend_webhook_base(r'^(?P<token>[-_:a-zA-Z0-9]+)/$', WEBHOOK_PATH),
TelegramView.as_view(),
name='telegram_webhook'),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment