From 251ae0d5caf3ae1be70b2de00e844a4045c2cf6c Mon Sep 17 00:00:00 2001 From: Alexander Pitkin Date: Wed, 8 Mar 2017 20:39:58 +0300 Subject: [PATCH 1/2] Added sample django project --- .gitignore | 5 + README.rst | 33 +++- sampleproject/bot/__init__.py | 0 sampleproject/bot/admin.py | 3 + sampleproject/bot/apps.py | 7 + sampleproject/bot/migrations/__init__.py | 0 sampleproject/bot/models.py | 5 + sampleproject/bot/telegrambot.py | 47 ++++++ sampleproject/bot/tests.py | 3 + sampleproject/bot/views.py | 3 + sampleproject/manage.py | 25 +++ sampleproject/sampleproject/__init__.py | 0 .../sampleproject/local_settings.sample.py | 7 + sampleproject/sampleproject/settings.py | 154 ++++++++++++++++++ sampleproject/sampleproject/urls.py | 22 +++ sampleproject/sampleproject/wsgi.py | 16 ++ 16 files changed, 325 insertions(+), 5 deletions(-) create mode 100644 sampleproject/bot/__init__.py create mode 100644 sampleproject/bot/admin.py create mode 100644 sampleproject/bot/apps.py create mode 100644 sampleproject/bot/migrations/__init__.py create mode 100644 sampleproject/bot/models.py create mode 100644 sampleproject/bot/telegrambot.py create mode 100644 sampleproject/bot/tests.py create mode 100644 sampleproject/bot/views.py create mode 100644 sampleproject/manage.py create mode 100644 sampleproject/sampleproject/__init__.py create mode 100644 sampleproject/sampleproject/local_settings.sample.py create mode 100644 sampleproject/sampleproject/settings.py create mode 100644 sampleproject/sampleproject/urls.py create mode 100644 sampleproject/sampleproject/wsgi.py diff --git a/.gitignore b/.gitignore index 5363db9..9e19897 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,8 @@ output/*/index.html # Sphinx docs/_build +exampleproject/db.sqlite3 +env/ +.idea/ +/sampleproject/sampleproject/local_settings.py +/sampleproject/db.sqlite3 diff --git a/README.rst b/README.rst index 84a92ba..0148e50 100644 --- a/README.rst +++ b/README.rst @@ -21,7 +21,7 @@ Quickstart Install django-telegrambot:: pip install django-telegrambot - + Configure your installation --------------------------- @@ -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`` :: @@ -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)) @@ -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: diff --git a/sampleproject/bot/__init__.py b/sampleproject/bot/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sampleproject/bot/admin.py b/sampleproject/bot/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/sampleproject/bot/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/sampleproject/bot/apps.py b/sampleproject/bot/apps.py new file mode 100644 index 0000000..5c0a163 --- /dev/null +++ b/sampleproject/bot/apps.py @@ -0,0 +1,7 @@ +from __future__ import unicode_literals + +from django.apps import AppConfig + + +class BotConfig(AppConfig): + name = 'bot' diff --git a/sampleproject/bot/migrations/__init__.py b/sampleproject/bot/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sampleproject/bot/models.py b/sampleproject/bot/models.py new file mode 100644 index 0000000..bd4b2ab --- /dev/null +++ b/sampleproject/bot/models.py @@ -0,0 +1,5 @@ +from __future__ import unicode_literals + +from django.db import models + +# Create your models here. diff --git a/sampleproject/bot/telegrambot.py b/sampleproject/bot/telegrambot.py new file mode 100644 index 0000000..43bf222 --- /dev/null +++ b/sampleproject/bot/telegrambot.py @@ -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) + + diff --git a/sampleproject/bot/tests.py b/sampleproject/bot/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/sampleproject/bot/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/sampleproject/bot/views.py b/sampleproject/bot/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/sampleproject/bot/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/sampleproject/manage.py b/sampleproject/manage.py new file mode 100644 index 0000000..c395c15 --- /dev/null +++ b/sampleproject/manage.py @@ -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) diff --git a/sampleproject/sampleproject/__init__.py b/sampleproject/sampleproject/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sampleproject/sampleproject/local_settings.sample.py b/sampleproject/sampleproject/local_settings.sample.py new file mode 100644 index 0000000..b325b94 --- /dev/null +++ b/sampleproject/sampleproject/local_settings.sample.py @@ -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 = ['', ] diff --git a/sampleproject/sampleproject/settings.py b/sampleproject/sampleproject/settings.py new file mode 100644 index 0000000..6180d45 --- /dev/null +++ b/sampleproject/sampleproject/settings.py @@ -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 diff --git a/sampleproject/sampleproject/urls.py b/sampleproject/sampleproject/urls.py new file mode 100644 index 0000000..7eec06a --- /dev/null +++ b/sampleproject/sampleproject/urls.py @@ -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')), +] diff --git a/sampleproject/sampleproject/wsgi.py b/sampleproject/sampleproject/wsgi.py new file mode 100644 index 0000000..b6a327a --- /dev/null +++ b/sampleproject/sampleproject/wsgi.py @@ -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() From d027544a5dc988aa1020459043ca2c14704afa79 Mon Sep 17 00:00:00 2001 From: Alexander Pitkin Date: Thu, 9 Mar 2017 00:44:16 +0300 Subject: [PATCH 2/2] Updated .gitignore --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index 9e19897..7eb1436 100644 --- a/.gitignore +++ b/.gitignore @@ -42,7 +42,6 @@ output/*/index.html # Sphinx docs/_build -exampleproject/db.sqlite3 env/ .idea/ /sampleproject/sampleproject/local_settings.py