Skip to content

Commit

Permalink
Merge pull request #3 from peleccom/sample_django_project
Browse files Browse the repository at this point in the history
Sample django project
  • Loading branch information
JungDev authored Mar 24, 2017
2 parents 0567381 + d027544 commit dd0d41c
Show file tree
Hide file tree
Showing 16 changed files with 324 additions and 5 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,7 @@ output/*/index.html

# Sphinx
docs/_build
env/
.idea/
/sampleproject/sampleproject/local_settings.py
/sampleproject/db.sqlite3
33 changes: 28 additions & 5 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Quickstart
Install django-telegrambot::

pip install django-telegrambot

Configure your installation
---------------------------

Expand All @@ -41,7 +41,7 @@ And set your bots::
TELEGRAM_BOT_TOKENS = ('BOT_1_token','BOT_2_token',)
TELEGRAM_WEBHOOK_SITE = 'https://mysite.it'
TELEGRAM_WEBHOOK_BASE = '/baseurl'
#TELEGRAM_WEBHOOK_CERTIFICATE = 'cert.pem' #If your site use self-signed certificate, must be set with location of your public key certificate. (More info at https://core.telegram.org/bots/self-signed )
#TELEGRAM_WEBHOOK_CERTIFICATE = 'cert.pem' #If your site use self-signed certificate, must be set with location of your public key certificate. (More info at https://core.telegram.org/bots/self-signed )


Include in your urls.py the ``django_telegrambot.urls`` using the same value of ``TELEGRAM_WEBHOOK_BASE`` ::
Expand Down Expand Up @@ -80,17 +80,17 @@ Then use it in a project creating a module ``telegrambot.py`` in your app ::

def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))


def main():
logger.info("Loading handlers for telegram bot")

# Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS)
dp = DjangoTelegramBot.dispatcher
# To get Dispatcher related to a specific bot
# dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token
# dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username

# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
Expand Down Expand Up @@ -127,6 +127,29 @@ Does the code actually work?
(myenv) $ pip install -r requirements-test.txt
(myenv) $ python runtests.py

Sample Application
------------------
There a sample application in `sampleproject` directory. Here is installation instructions:

1. Install requirements with command

pip install -r requirements.txt
2. Copy file `local_settings.sample.py` as `local_settings.py` and edit your bot token

cp sampleproject/local_settings.sample.py sampleproject/local_settings.py

nano sampleproject/local_settings.py
3. Run Django migrations

python manage.py migrate
4. Run server

python manage.py runserver
5. To test webhook locally install `ngrok` application and run command

./ngrok http 8000
And change TELEGRAM_WEBHOOK_SITE and ALLOWED_HOSTS in local_settings.py file

Credits
---------
Required package:
Expand Down
Empty file added sampleproject/bot/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions sampleproject/bot/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
7 changes: 7 additions & 0 deletions sampleproject/bot/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from __future__ import unicode_literals

from django.apps import AppConfig


class BotConfig(AppConfig):
name = 'bot'
Empty file.
5 changes: 5 additions & 0 deletions sampleproject/bot/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from __future__ import unicode_literals

from django.db import models

# Create your models here.
47 changes: 47 additions & 0 deletions sampleproject/bot/telegrambot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
# Example code for telegrambot.py module
from telegram.ext import CommandHandler, MessageHandler, Filters
from django_telegrambot.apps import DjangoTelegramBot

import logging
logger = logging.getLogger(__name__)


# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
bot.sendMessage(update.message.chat_id, text='Hi!')


def help(bot, update):
bot.sendMessage(update.message.chat_id, text='Help!')


def echo(bot, update):
update.message.reply_text(update.message.text)


def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))


def main():
logger.info("Loading handlers for telegram bot")

# Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS)
dp = DjangoTelegramBot.dispatcher
# To get Dispatcher related to a specific bot
# dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token
# dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username

# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))

# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))

# log all errors
dp.add_error_handler(error)


3 changes: 3 additions & 0 deletions sampleproject/bot/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
3 changes: 3 additions & 0 deletions sampleproject/bot/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.shortcuts import render

# Create your views here.
25 changes: 25 additions & 0 deletions sampleproject/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#!/usr/bin/env python
import os
import sys
import sys
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(path)

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sampleproject.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
Empty file.
7 changes: 7 additions & 0 deletions sampleproject/sampleproject/local_settings.sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#settings.py
#Django Telegram Bot settings
TELEGRAM_BOT_TOKENS = ('BOT_1_token', 'BOT_2_token',)
TELEGRAM_WEBHOOK_SITE = 'https://mysite.it'
TELEGRAM_WEBHOOK_BASE = '/baseurl'
#TELEGRAM_WEBHOOK_CERTIFICATE = 'cert.pem' #If your site use self-signed certificate, must be set with location of your public key certificate. (More info at https://core.telegram.org/bots/self-signed )
ALLOWED_HOSTS = ['', ]
154 changes: 154 additions & 0 deletions sampleproject/sampleproject/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
"""
Django settings for sampleproject project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '2+(!v-t9)skqad%3637&#kj+!04!74q$ja@@ccavtf(h0)%1x!'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bot',
'django_telegrambot',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'sampleproject.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'sampleproject.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}


# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'': {
'handlers': ['console'],
'level': 'INFO',
'propagate': True,
},
},
}

try:
from local_settings import *
except:
pass
22 changes: 22 additions & 0 deletions sampleproject/sampleproject/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""sampleproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^baseurl/', include('django_telegrambot.urls')),
]
16 changes: 16 additions & 0 deletions sampleproject/sampleproject/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for sampleproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sampleproject.settings")

application = get_wsgi_application()

0 comments on commit dd0d41c

Please sign in to comment.