├── .coveragerc ├── .editorconfig ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── modules.rst ├── readme.rst ├── telegrambot.bot_views.generic.rst ├── telegrambot.bot_views.rst ├── telegrambot.generic.rst ├── telegrambot.handlers.rst ├── telegrambot.management.rst ├── telegrambot.migrations.rst ├── telegrambot.models.rst ├── telegrambot.rst ├── telegrambot.templatetags.rst ├── telegrambot.test.factories.rst ├── telegrambot.test.rst └── usage.rst ├── requirements.txt ├── requirements ├── base.txt ├── dev.txt └── test.txt ├── runtests.py ├── setup.cfg ├── setup.py ├── telegrambot ├── __init__.py ├── admin.py ├── bot_views │ ├── __init__.py │ ├── decorators.py │ ├── generic │ │ ├── __init__.py │ │ ├── base.py │ │ ├── compound.py │ │ ├── detail.py │ │ ├── list.py │ │ └── responses.py │ └── login.py ├── handlers │ ├── __init__.py │ ├── conf.py │ └── resolver.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_bot.py │ ├── 0003_auto_20160202_1803.py │ ├── 0004_bot_https_port.py │ └── __init__.py ├── models │ ├── __init__.py │ ├── auth.py │ ├── bot.py │ └── telegram_api.py ├── serializers.py ├── templates │ └── telegrambot │ │ ├── authentication.html │ │ └── messages │ │ └── login_required.txt ├── templatetags │ ├── __init__.py │ └── telegrambot_filters.py ├── test │ ├── __init__.py │ ├── factories │ │ ├── __init__.py │ │ ├── auth.py │ │ ├── bot.py │ │ ├── telegram_lib.py │ │ └── user.py │ └── testcases.py ├── urls.py └── views.py ├── tests ├── __init__.py ├── bot_handlers.py ├── bot_handlers_empty.py ├── commands_views.py ├── models.py ├── settings.py ├── templates │ └── bot │ │ └── messages │ │ ├── command_author_detail_text.txt │ │ ├── command_author_list_keyboard.txt │ │ ├── command_author_list_text.txt │ │ ├── command_start_text.txt │ │ ├── command_unknown_text.txt │ │ ├── regex_author_name_text.txt │ │ └── unknown_message_text.txt ├── test_telegrambot.py └── urls.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | [report] 2 | omit = telegrambot/admin.py 3 | exclude_lines = 4 | def __str__ 5 | raise NotImplementedError 6 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.{py,rst,ini}] 12 | indent_style = space 13 | indent_size = 4 14 | 15 | [*.{html,css,scss,json,yml}] 16 | indent_style = space 17 | indent_size = 2 18 | 19 | [*.md] 20 | trim_trailing_whitespace = false 21 | 22 | [Makefile] 23 | indent_style = tab 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | __pycache__ 3 | 4 | # C extensions 5 | *.so 6 | 7 | # Packages 8 | *.egg 9 | *.egg-info 10 | dist 11 | build 12 | eggs 13 | parts 14 | bin 15 | var 16 | sdist 17 | develop-eggs 18 | .installed.cfg 19 | lib 20 | lib64 21 | 22 | # Installer logs 23 | pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | .coverage 27 | .tox 28 | nosetests.xml 29 | htmlcov 30 | 31 | # Translations 32 | *.mo 33 | 34 | # Mr Developer 35 | .mr.developer.cfg 36 | .project 37 | .pydevproject 38 | .settings/* 39 | 40 | # Complexity 41 | output/*.html 42 | output/*/index.html 43 | 44 | # Sphinx 45 | docs/_build 46 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | 3 | language: python 4 | 5 | python: 6 | - "3.6" 7 | - "3.5" 8 | - "3.4" 9 | - "2.7" 10 | 11 | 12 | env: 13 | - DJANGO_VERSION=1.10 14 | - DJANGO_VERSION=1.9 15 | - DJANGO_VERSION=1.8 16 | 17 | before_install: 18 | - pip install coveralls 19 | 20 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 21 | install: 22 | - pip install -q Django==$DJANGO_VERSION 23 | - pip install -r requirements/test.txt 24 | 25 | # command to run tests using coverage, e.g. python setup.py test 26 | script: coverage run --source telegrambot runtests.py 27 | 28 | after_success: 29 | - coveralls 30 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Juan Madurga 9 | 10 | Contributors 11 | ------------ 12 | 13 | None yet. Why not be the first? 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/jlmadurga/django-telegram-bot/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | django-telegram-bot could always use more documentation, whether as part of the 40 | official django-telegram-bot docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github.com/jlmadurga/django-telegram-bot/issues. 47 | 48 | If you are proposing a feature: 49 | 50 | * Explain in detail how it would work. 51 | * Keep the scope as narrow as possible, to make it easier to implement. 52 | * Remember that this is a volunteer-driven project, and that contributions 53 | are welcome :) 54 | 55 | Get Started! 56 | ------------ 57 | 58 | Ready to contribute? Here's how to set up `django-telegram-bot` for local development. 59 | 60 | 1. Fork the `django-telegram-bot` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/django-telegram-bot.git 64 | 65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 66 | 67 | $ mkvirtualenv django-telegram-bot 68 | $ cd django-telegram-bot/ 69 | $ python setup.py develop 70 | 71 | 4. Create a branch for local development:: 72 | 73 | $ git checkout -b name-of-your-bugfix-or-feature 74 | 75 | Now you can make your changes locally. 76 | 77 | 5. When you're done making changes, check that your changes pass flake8 and the 78 | tests, including testing other Python versions with tox:: 79 | 80 | $ pip install -r requirements/dev.txt 81 | $ make lint 82 | $ pip install -r requirements/test.txt 83 | $ make test 84 | $ make test all 85 | 86 | 87 | 6. Commit your changes and push your branch to GitHub:: 88 | 89 | $ git add . 90 | $ git commit -m "Your detailed description of your changes." 91 | $ git push origin name-of-your-bugfix-or-feature 92 | 93 | 7. Submit a pull request through the GitHub website. 94 | 95 | Pull Request Guidelines 96 | ----------------------- 97 | 98 | Before you submit a pull request, check that it meets these guidelines: 99 | 100 | 1. The pull request should include tests. 101 | 2. If the pull request adds functionality, the docs should be updated. Put 102 | your new functionality into a function with a docstring, and add the 103 | feature to the list in README.rst. 104 | 3. The pull request should work for Python 2.7, adn Python3. Check 105 | https://travis-ci.org/jlmadurga/django-telegram-bot/pull_requests 106 | and make sure that the tests pass for all supported Python versions. 107 | 108 | 109 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 0.1.0 (2016-21-01) 7 | ++++++++++++++++++ 8 | 9 | * First release on PyPI. 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016, Juan Madurga 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 9 | 10 | * Neither the name of django-telegram-bot nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | recursive-include telegrambot *.html *.png *.gif *js *.css *jpg *jpeg *svg *py *.txt 7 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs 2 | 3 | help: 4 | @echo "clean-build - remove build artifacts" 5 | @echo "clean-pyc - remove Python file artifacts" 6 | @echo "lint - check style with flake8" 7 | @echo "test - run tests quickly with the default Python" 8 | @echo "test-all - run tests on every Python version with tox" 9 | @echo "coverage - check code coverage quickly with the default Python" 10 | @echo "docs - generate Sphinx HTML documentation, including API docs" 11 | @echo "release - package and upload a release" 12 | @echo "sdist - package" 13 | 14 | clean: clean-build clean-pyc 15 | 16 | clean-build: 17 | rm -fr build/ 18 | rm -fr dist/ 19 | rm -fr *.egg-info 20 | 21 | clean-pyc: 22 | find . -name '*.pyc' -exec rm -f {} + 23 | find . -name '*.pyo' -exec rm -f {} + 24 | find . -name '*~' -exec rm -f {} + 25 | 26 | lint: 27 | flake8 telegrambot tests 28 | 29 | test: 30 | python runtests.py tests 31 | 32 | test-all: 33 | tox 34 | 35 | coverage: 36 | coverage run --source telegrambot runtests.py tests 37 | coverage report -m 38 | coverage html 39 | open htmlcov/index.html 40 | 41 | docs: 42 | rm -f docs/django-telegram-bot.rst 43 | rm -f docs/modules.rst 44 | sphinx-apidoc -o docs/ telegrambot 45 | $(MAKE) -C docs clean 46 | $(MAKE) -C docs html 47 | open docs/_build/html/index.html 48 | 49 | release: clean 50 | python setup.py sdist upload 51 | python setup.py bdist_wheel upload 52 | 53 | sdist: clean 54 | python setup.py sdist 55 | ls -l dist 56 | 57 | travis: lint 58 | coverage run --source telegrambot runtests.py tests -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============================= 2 | django-telegram-bot 3 | ============================= 4 | CI: 5 | 6 | .. image:: https://travis-ci.org/jlmadurga/django-telegram-bot.svg?branch=master 7 | :target: https://travis-ci.org/jlmadurga/django-telegram-bot 8 | 9 | .. image:: https://coveralls.io/repos/github/jlmadurga/django-telegram-bot/badge.svg?branch=master 10 | :target: https://coveralls.io/github/jlmadurga/django-telegram-bot?branch=master 11 | 12 | .. image:: https://requires.io/github/jlmadurga/django-telegram-bot/requirements.svg?branch=master 13 | :target: https://requires.io/github/jlmadurga/django-telegram-bot/requirements/?branch=master 14 | :alt: Requirements Status 15 | 16 | PyPI: 17 | 18 | 19 | .. image:: https://img.shields.io/pypi/v/django-telegram-bot.svg 20 | :target: https://pypi.python.org/pypi/django-telegram-bot 21 | 22 | Docs: 23 | 24 | .. image:: https://readthedocs.org/projects/django-telegram-bot/badge/?version=latest 25 | :target: https://readthedocs.org/projects/django-telegram-bot/?badge=latest 26 | :alt: Documentation Status 27 | 28 | Django app to write Telegram bots. Just define commands and how to handle them. 29 | 30 | **Try Permabots**: more stable django app for bots https://github.com/jlmadurga/permabots 31 | 32 | NOTE: Just for text messages at this moment. 33 | 34 | Documentation 35 | ------------- 36 | 37 | The full documentation is at https://django-telegram-bot.readthedocs.org. 38 | 39 | Telegram API documentation at https://core.telegram.org/bots/api 40 | 41 | Quickstart 42 | ---------- 43 | 44 | Install django-telegram-bot:: 45 | 46 | pip install django-telegram-bot 47 | 48 | Add ``telegrambot`` and ``rest_framework`` to your ``INSTALLED_APPS``, and run:: 49 | 50 | $ python manage.py migrate 51 | 52 | 53 | After creating a bot in Telegram Platform, create at least one bot with django admin. Token is the only 54 | required field. You may need to provided public key certificate for your server. https://core.telegram.org/bots/self-signed 55 | Heroku has https and ssl by default so it is a good option if you dont want to deal with that. 56 | 57 | Add webhook url to your urlpatterns:: 58 | 59 | url(r'^telegrambot/', include('telegrambot.urls', namespace="telegrambot")), 60 | 61 | Define the file where commands will be defined in ``urlpatterns`` variable, analogue to django ``urls`` 62 | and ``ROOT_URLCONF``:: 63 | 64 | TELEGRAM_BOT_HANDLERS_CONF = "app.handlers" 65 | 66 | Set bot commands handlers is very easy just as defining `urls` in django. Module with ``urlpatterns`` that list 67 | different handlers. You can `regex` directly or use shortcuts like `command` or `unknown_command` :: 68 | 69 | urlpatterns = [command('start', StartView.as_command_view()), 70 | command('author', AuthorCommandView.as_command_view()), 71 | command('author_inverse', AuthorInverseListView.as_command_view()), 72 | command('author_query', login_required(AuthorCommandQueryView.as_command_view())), 73 | unknown_command(UnknownView.as_command_view()), 74 | regex(r'author_(?P\w+)', AuthorName.as_command_view()), 75 | ] 76 | 77 | To set the webhook for telegram you need ``django.contrib.sites`` installed, ``SITE_ID`` configured 78 | in settings and with it correct value in the DB. The webhook for each bot is set when a Bot is saved and 79 | ``enabled`` field is set to true. 80 | 81 | Bot views responses with Telegram messages to the user who send the command with a text message and keyboard. 82 | Compound with a context and a template. The way it is handled is analogue to Django views. Visits docs for more 83 | details https://django-telegram-bot.readthedocs.io/en/latest/usage.html 84 | 85 | 86 | Features 87 | -------- 88 | 89 | * Multiple bots 90 | * Message handling definition. 91 | * Authentication 92 | * Text responses and keyboards. 93 | * Media messages not supported. 94 | * Only Markup parse mode. 95 | 96 | .. image:: https://raw.github.com/jlmadurga/django-oscar-telegram-bot/master/docs/imgs/list_commands.png 97 | 98 | .. image:: https://raw.github.com/jlmadurga/django-oscar-telegram-bot/master/docs/imgs/categories.png 99 | 100 | Running Tests 101 | -------------- 102 | 103 | Does the code actually work? 104 | 105 | :: 106 | 107 | source /bin/activate 108 | (myenv) $ pip install -r requirements/test.txt 109 | (myenv) $ make test 110 | (myenv) $ make test-all 111 | 112 | 113 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # complexity documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | cwd = os.getcwd() 22 | parent = os.path.dirname(cwd) 23 | sys.path.append(parent) 24 | 25 | import telegrambot 26 | 27 | # -- General configuration ----------------------------------------------------- 28 | 29 | # If your documentation needs a minimal Sphinx version, state it here. 30 | #needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be extensions 33 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix of source filenames. 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'django-telegram-bot' 50 | copyright = u'2016, Juan Madurga' 51 | 52 | # The version info for the project you're documenting, acts as replacement for 53 | # |version| and |release|, also used in various other places throughout the 54 | # built documents. 55 | # 56 | # The short X.Y version. 57 | version = telegrambot.__version__ 58 | # The full version, including alpha/beta/rc tags. 59 | release = telegrambot.__version__ 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | #language = None 64 | 65 | # There are two options for replacing |today|: either, you set today to some 66 | # non-false value, then it is used: 67 | #today = '' 68 | # Else, today_fmt is used as the format for a strftime call. 69 | #today_fmt = '%B %d, %Y' 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | exclude_patterns = ['_build'] 74 | 75 | # The reST default role (used for this markup: `text`) to use for all documents. 76 | #default_role = None 77 | 78 | # If true, '()' will be appended to :func: etc. cross-reference text. 79 | #add_function_parentheses = True 80 | 81 | # If true, the current module name will be prepended to all description 82 | # unit titles (such as .. function::). 83 | #add_module_names = True 84 | 85 | # If true, sectionauthor and moduleauthor directives will be shown in the 86 | # output. They are ignored by default. 87 | #show_authors = False 88 | 89 | # The name of the Pygments (syntax highlighting) style to use. 90 | pygments_style = 'sphinx' 91 | 92 | # A list of ignored prefixes for module index sorting. 93 | #modindex_common_prefix = [] 94 | 95 | # If true, keep warnings as "system message" paragraphs in the built documents. 96 | #keep_warnings = False 97 | 98 | 99 | # -- Options for HTML output --------------------------------------------------- 100 | 101 | # The theme to use for HTML and HTML Help pages. See the documentation for 102 | # a list of builtin themes. 103 | html_theme = 'default' 104 | 105 | # Theme options are theme-specific and customize the look and feel of a theme 106 | # further. For a list of options available for each theme, see the 107 | # documentation. 108 | #html_theme_options = {} 109 | 110 | # Add any paths that contain custom themes here, relative to this directory. 111 | #html_theme_path = [] 112 | 113 | # The name for this set of Sphinx documents. If None, it defaults to 114 | # " v documentation". 115 | #html_title = None 116 | 117 | # A shorter title for the navigation bar. Default is the same as html_title. 118 | #html_short_title = None 119 | 120 | # The name of an image file (relative to this directory) to place at the top 121 | # of the sidebar. 122 | #html_logo = None 123 | 124 | # The name of an image file (within the static path) to use as favicon of the 125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 126 | # pixels large. 127 | #html_favicon = None 128 | 129 | # Add any paths that contain custom static files (such as style sheets) here, 130 | # relative to this directory. They are copied after the builtin static files, 131 | # so a file named "default.css" will overwrite the builtin "default.css". 132 | html_static_path = ['_static'] 133 | 134 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 135 | # using the given strftime format. 136 | #html_last_updated_fmt = '%b %d, %Y' 137 | 138 | # If true, SmartyPants will be used to convert quotes and dashes to 139 | # typographically correct entities. 140 | #html_use_smartypants = True 141 | 142 | # Custom sidebar templates, maps document names to template names. 143 | #html_sidebars = {} 144 | 145 | # Additional templates that should be rendered to pages, maps page names to 146 | # template names. 147 | #html_additional_pages = {} 148 | 149 | # If false, no module index is generated. 150 | #html_domain_indices = True 151 | 152 | # If false, no index is generated. 153 | #html_use_index = True 154 | 155 | # If true, the index is split into individual pages for each letter. 156 | #html_split_index = False 157 | 158 | # If true, links to the reST sources are added to the pages. 159 | #html_show_sourcelink = True 160 | 161 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 162 | #html_show_sphinx = True 163 | 164 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 165 | #html_show_copyright = True 166 | 167 | # If true, an OpenSearch description file will be output, and all pages will 168 | # contain a tag referring to it. The value of this option must be the 169 | # base URL from which the finished HTML is served. 170 | #html_use_opensearch = '' 171 | 172 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 173 | #html_file_suffix = None 174 | 175 | # Output file base name for HTML help builder. 176 | htmlhelp_basename = 'django-telegram-botdoc' 177 | 178 | 179 | # -- Options for LaTeX output -------------------------------------------------- 180 | 181 | latex_elements = { 182 | # The paper size ('letterpaper' or 'a4paper'). 183 | #'papersize': 'letterpaper', 184 | 185 | # The font size ('10pt', '11pt' or '12pt'). 186 | #'pointsize': '10pt', 187 | 188 | # Additional stuff for the LaTeX preamble. 189 | #'preamble': '', 190 | } 191 | 192 | # Grouping the document tree into LaTeX files. List of tuples 193 | # (source start file, target name, title, author, documentclass [howto/manual]). 194 | latex_documents = [ 195 | ('index', 'django-telegram-bot.tex', u'django-telegram-bot Documentation', 196 | u'Juan Madurga', 'manual'), 197 | ] 198 | 199 | # The name of an image file (relative to this directory) to place at the top of 200 | # the title page. 201 | #latex_logo = None 202 | 203 | # For "manual" documents, if this is true, then toplevel headings are parts, 204 | # not chapters. 205 | #latex_use_parts = False 206 | 207 | # If true, show page references after internal links. 208 | #latex_show_pagerefs = False 209 | 210 | # If true, show URL addresses after external links. 211 | #latex_show_urls = False 212 | 213 | # Documents to append as an appendix to all manuals. 214 | #latex_appendices = [] 215 | 216 | # If false, no module index is generated. 217 | #latex_domain_indices = True 218 | 219 | 220 | # -- Options for manual page output -------------------------------------------- 221 | 222 | # One entry per manual page. List of tuples 223 | # (source start file, name, description, authors, manual section). 224 | man_pages = [ 225 | ('index', 'django-telegram-bot', u'django-telegram-bot Documentation', 226 | [u'Juan Madurga'], 1) 227 | ] 228 | 229 | # If true, show URL addresses after external links. 230 | #man_show_urls = False 231 | 232 | 233 | # -- Options for Texinfo output ------------------------------------------------ 234 | 235 | # Grouping the document tree into Texinfo files. List of tuples 236 | # (source start file, target name, title, author, 237 | # dir menu entry, description, category) 238 | texinfo_documents = [ 239 | ('index', 'django-telegram-bot', u'django-telegram-bot Documentation', 240 | u'Juan Madurga', 'django-telegram-bot', 'One line description of project.', 241 | 'Miscellaneous'), 242 | ] 243 | 244 | # Documents to append as an appendix to all manuals. 245 | #texinfo_appendices = [] 246 | 247 | # If false, no module index is generated. 248 | #texinfo_domain_indices = True 249 | 250 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 251 | #texinfo_show_urls = 'footnote' 252 | 253 | # If true, do not generate a @detailmenu in the "Top" node's menu. 254 | #texinfo_no_detailmenu = False 255 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. complexity documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to django-telegram-bot's documentation! 7 | ================================================================= 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | contributing 18 | authors 19 | history 20 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | At the command line:: 6 | 7 | $ pip install django-telegram-bot 8 | 9 | Add ``telegrambot`` and ``rest_framework`` to ``INSTALLED_APPS``:: 10 | 11 | INSTALLED_APPS=[ 12 | ... 13 | "rest_framework", 14 | "telegrambot", 15 | ... 16 | ] 17 | 18 | Migrate DB:: 19 | 20 | python manage.py migrate 21 | 22 | 23 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/modules.rst: -------------------------------------------------------------------------------- 1 | telegrambot 2 | =========== 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | telegrambot 8 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/telegrambot.bot_views.generic.rst: -------------------------------------------------------------------------------- 1 | telegrambot.bot_views.generic package 2 | ===================================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | telegrambot.bot_views.generic.base module 8 | ----------------------------------------- 9 | 10 | .. automodule:: telegrambot.bot_views.generic.base 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | telegrambot.bot_views.generic.compound module 16 | --------------------------------------------- 17 | 18 | .. automodule:: telegrambot.bot_views.generic.compound 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | telegrambot.bot_views.generic.detail module 24 | ------------------------------------------- 25 | 26 | .. automodule:: telegrambot.bot_views.generic.detail 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | telegrambot.bot_views.generic.list module 32 | ----------------------------------------- 33 | 34 | .. automodule:: telegrambot.bot_views.generic.list 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | 39 | telegrambot.bot_views.generic.responses module 40 | ---------------------------------------------- 41 | 42 | .. automodule:: telegrambot.bot_views.generic.responses 43 | :members: 44 | :undoc-members: 45 | :show-inheritance: 46 | 47 | 48 | Module contents 49 | --------------- 50 | 51 | .. automodule:: telegrambot.bot_views.generic 52 | :members: 53 | :undoc-members: 54 | :show-inheritance: 55 | -------------------------------------------------------------------------------- /docs/telegrambot.bot_views.rst: -------------------------------------------------------------------------------- 1 | telegrambot.bot_views package 2 | ============================= 3 | 4 | Subpackages 5 | ----------- 6 | 7 | .. toctree:: 8 | 9 | telegrambot.bot_views.generic 10 | 11 | Submodules 12 | ---------- 13 | 14 | telegrambot.bot_views.decorators module 15 | --------------------------------------- 16 | 17 | .. automodule:: telegrambot.bot_views.decorators 18 | :members: 19 | :undoc-members: 20 | :show-inheritance: 21 | 22 | telegrambot.bot_views.login module 23 | ---------------------------------- 24 | 25 | .. automodule:: telegrambot.bot_views.login 26 | :members: 27 | :undoc-members: 28 | :show-inheritance: 29 | 30 | 31 | Module contents 32 | --------------- 33 | 34 | .. automodule:: telegrambot.bot_views 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | -------------------------------------------------------------------------------- /docs/telegrambot.generic.rst: -------------------------------------------------------------------------------- 1 | telegrambot.generic package 2 | =========================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | telegrambot.generic.base module 8 | ------------------------------- 9 | 10 | .. automodule:: telegrambot.generic.base 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | telegrambot.generic.compound module 16 | ----------------------------------- 17 | 18 | .. automodule:: telegrambot.generic.compound 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | telegrambot.generic.detail module 24 | --------------------------------- 25 | 26 | .. automodule:: telegrambot.generic.detail 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | telegrambot.generic.list module 32 | ------------------------------- 33 | 34 | .. automodule:: telegrambot.generic.list 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | 39 | telegrambot.generic.responses module 40 | ------------------------------------ 41 | 42 | .. automodule:: telegrambot.generic.responses 43 | :members: 44 | :undoc-members: 45 | :show-inheritance: 46 | 47 | 48 | Module contents 49 | --------------- 50 | 51 | .. automodule:: telegrambot.generic 52 | :members: 53 | :undoc-members: 54 | :show-inheritance: 55 | -------------------------------------------------------------------------------- /docs/telegrambot.handlers.rst: -------------------------------------------------------------------------------- 1 | telegrambot.handlers package 2 | ============================ 3 | 4 | Submodules 5 | ---------- 6 | 7 | telegrambot.handlers.base module 8 | -------------------------------- 9 | 10 | .. automodule:: telegrambot.handlers.base 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | telegrambot.handlers.command module 16 | ----------------------------------- 17 | 18 | .. automodule:: telegrambot.handlers.command 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | telegrambot.handlers.message module 24 | ----------------------------------- 25 | 26 | .. automodule:: telegrambot.handlers.message 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | telegrambot.handlers.regex module 32 | --------------------------------- 33 | 34 | .. automodule:: telegrambot.handlers.regex 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | 39 | telegrambot.handlers.unknown_command module 40 | ------------------------------------------- 41 | 42 | .. automodule:: telegrambot.handlers.unknown_command 43 | :members: 44 | :undoc-members: 45 | :show-inheritance: 46 | 47 | 48 | Module contents 49 | --------------- 50 | 51 | .. automodule:: telegrambot.handlers 52 | :members: 53 | :undoc-members: 54 | :show-inheritance: 55 | -------------------------------------------------------------------------------- /docs/telegrambot.management.rst: -------------------------------------------------------------------------------- 1 | telegrambot.management package 2 | ============================== 3 | 4 | Subpackages 5 | ----------- 6 | 7 | .. toctree:: 8 | 9 | telegrambot.management.commands 10 | 11 | Module contents 12 | --------------- 13 | 14 | .. automodule:: telegrambot.management 15 | :members: 16 | :undoc-members: 17 | :show-inheritance: 18 | -------------------------------------------------------------------------------- /docs/telegrambot.migrations.rst: -------------------------------------------------------------------------------- 1 | telegrambot.migrations package 2 | ============================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | telegrambot.migrations.0001_initial module 8 | ------------------------------------------ 9 | 10 | .. automodule:: telegrambot.migrations.0001_initial 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | 16 | Module contents 17 | --------------- 18 | 19 | .. automodule:: telegrambot.migrations 20 | :members: 21 | :undoc-members: 22 | :show-inheritance: 23 | -------------------------------------------------------------------------------- /docs/telegrambot.models.rst: -------------------------------------------------------------------------------- 1 | telegrambot.models package 2 | ========================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | telegrambot.models.bot module 8 | ----------------------------- 9 | 10 | .. automodule:: telegrambot.models.bot 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | telegrambot.models.telegram_api module 16 | -------------------------------------- 17 | 18 | .. automodule:: telegrambot.models.telegram_api 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | 24 | Module contents 25 | --------------- 26 | 27 | .. automodule:: telegrambot.models 28 | :members: 29 | :undoc-members: 30 | :show-inheritance: 31 | -------------------------------------------------------------------------------- /docs/telegrambot.rst: -------------------------------------------------------------------------------- 1 | telegrambot package 2 | =================== 3 | 4 | Subpackages 5 | ----------- 6 | 7 | .. toctree:: 8 | 9 | telegrambot.generic 10 | telegrambot.migrations 11 | telegrambot.templatetags 12 | 13 | Submodules 14 | ---------- 15 | 16 | telegrambot.admin module 17 | ------------------------ 18 | 19 | .. automodule:: telegrambot.admin 20 | :members: 21 | :undoc-members: 22 | :show-inheritance: 23 | 24 | telegrambot.bot module 25 | ---------------------- 26 | 27 | .. automodule:: telegrambot.bot 28 | :members: 29 | :undoc-members: 30 | :show-inheritance: 31 | 32 | telegrambot.conf module 33 | ----------------------- 34 | 35 | .. automodule:: telegrambot.conf 36 | :members: 37 | :undoc-members: 38 | :show-inheritance: 39 | 40 | telegrambot.models module 41 | ------------------------- 42 | 43 | .. automodule:: telegrambot.models 44 | :members: 45 | :undoc-members: 46 | :show-inheritance: 47 | 48 | telegrambot.serializers module 49 | ------------------------------ 50 | 51 | .. automodule:: telegrambot.serializers 52 | :members: 53 | :undoc-members: 54 | :show-inheritance: 55 | 56 | telegrambot.tasks module 57 | ------------------------ 58 | 59 | .. automodule:: telegrambot.tasks 60 | :members: 61 | :undoc-members: 62 | :show-inheritance: 63 | 64 | telegrambot.urls module 65 | ----------------------- 66 | 67 | .. automodule:: telegrambot.urls 68 | :members: 69 | :undoc-members: 70 | :show-inheritance: 71 | 72 | telegrambot.views module 73 | ------------------------ 74 | 75 | .. automodule:: telegrambot.views 76 | :members: 77 | :undoc-members: 78 | :show-inheritance: 79 | 80 | 81 | Module contents 82 | --------------- 83 | 84 | .. automodule:: telegrambot 85 | :members: 86 | :undoc-members: 87 | :show-inheritance: 88 | -------------------------------------------------------------------------------- /docs/telegrambot.templatetags.rst: -------------------------------------------------------------------------------- 1 | telegrambot.templatetags package 2 | ================================ 3 | 4 | Submodules 5 | ---------- 6 | 7 | telegrambot.templatetags.telegrambot_filters module 8 | --------------------------------------------------- 9 | 10 | .. automodule:: telegrambot.templatetags.telegrambot_filters 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | 16 | Module contents 17 | --------------- 18 | 19 | .. automodule:: telegrambot.templatetags 20 | :members: 21 | :undoc-members: 22 | :show-inheritance: 23 | -------------------------------------------------------------------------------- /docs/telegrambot.test.factories.rst: -------------------------------------------------------------------------------- 1 | telegrambot.test.factories package 2 | ================================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | telegrambot.test.factories.auth module 8 | -------------------------------------- 9 | 10 | .. automodule:: telegrambot.test.factories.auth 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | telegrambot.test.factories.bot module 16 | ------------------------------------- 17 | 18 | .. automodule:: telegrambot.test.factories.bot 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | telegrambot.test.factories.telegram_lib module 24 | ---------------------------------------------- 25 | 26 | .. automodule:: telegrambot.test.factories.telegram_lib 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | telegrambot.test.factories.user module 32 | -------------------------------------- 33 | 34 | .. automodule:: telegrambot.test.factories.user 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | 39 | 40 | Module contents 41 | --------------- 42 | 43 | .. automodule:: telegrambot.test.factories 44 | :members: 45 | :undoc-members: 46 | :show-inheritance: 47 | -------------------------------------------------------------------------------- /docs/telegrambot.test.rst: -------------------------------------------------------------------------------- 1 | telegrambot.test package 2 | ======================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | telegrambot.test.factories module 8 | --------------------------------- 9 | 10 | .. automodule:: telegrambot.test.factories 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | telegrambot.test.testcases module 16 | --------------------------------- 17 | 18 | .. automodule:: telegrambot.test.testcases 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | 24 | Module contents 25 | --------------- 26 | 27 | .. automodule:: telegrambot.test 28 | :members: 29 | :undoc-members: 30 | :show-inheritance: 31 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Usage 3 | ======== 4 | 5 | First you need a telegram bot and its token, visit https://core.telegram.org/bots. 6 | 7 | 8 | After creating a bot in Telegram Platform, create at least one bot with django admin. Token is the only 9 | required field. You may need to provided public key certificate for your server. https://core.telegram.org/bots/self-signed 10 | Heroku has https and ssl by default so it is a good option if you dont want to deal with that. 11 | Add webhook url to your urlpatterns:: 12 | 13 | url(r'^telegrambot/', include('telegrambot.urls', namespace="telegrambot") 14 | 15 | Define whe file where bot views will be defined in ``urlpatterns`` variable, analogue to django ``urls`` 16 | and ``ROOT_URLCONF``:: 17 | 18 | TELEGRAM_BOT_HANDLERS_CONF = "app.handlers" 19 | 20 | Set bot views handlers is very easy just as defining `urls` in django. Module with ``urlpatterns`` that list 21 | different handlers:: 22 | 23 | urlpatterns = [command('start', StartView.as_command_view()), 24 | command('author', AuthorCommandView.as_command_view()), 25 | command('author_inverse', AuthorInverseListView.as_command_view()), 26 | command('author_query', login_required(AuthorCommandQueryView.as_command_view())), 27 | unknown_command(UnknownView.as_command_view()), 28 | regex(r'author_(?P\w+)', AuthorName.as_command_view()), 29 | ] 30 | 31 | Set bot views handlers is very easy just as defining `urls`in django. Module with ``bothandlers`` list 32 | of different handlers `command('command', command_view)`, `regex('re_expresion', command_view)`,...:: 33 | 34 | bothandlers = [command('start', StartView.as_command_view())] 35 | 36 | To set the webhook for telegram you need ``django.contrib.sites`` installed, ``SITE_ID`` configured 37 | in settings and with it correct value in the DB. The webhook for each bot is set when a Bot is saved and 38 | ``enabled`` field is set to true. 39 | 40 | 41 | Bot views responses with Telegram messages to the user with a text message and keyboard. 42 | Compound with a context and a template. The way it is handled is analogue to Django views. 43 | 44 | Define a bot view is really easy using generic classed views, analogues to django generic views. 45 | 46 | Simple view just with a template, image /start command just to wellcome:: 47 | 48 | class StartView(TemplateCommandView): 49 | template_text = "bot/messages/command_start_text.txt" 50 | 51 | List and detail views:: 52 | 53 | class AuthorListView(ListCommandView): 54 | template_text = "bot/messages/command_author_list_text.txt" 55 | template_keyboard = "bot/messages/command_author_list_keyboard.txt" 56 | model = Author 57 | context_object_name = "authors" 58 | ordering = "-name" 59 | 60 | class AuthorDetailView(DetailCommandView): 61 | template_text = "bot/messages/command_author_detail_text.txt" 62 | template_keyboard = "bot/messages/command_author_detail_keyboard.txt" 63 | context_object_name = "author" 64 | model = Author 65 | slug_field = 'name' 66 | 67 | Most common use of commands is to have ``/command`` with no args for getting list and ``/command element`` for 68 | getting detail of one concrete element. It is easy to define:: 69 | 70 | class AuthorCommandView(ListDetailCommandView): 71 | list_view_class = AuthorListView 72 | detail_view_class = AuthorDetailView 73 | 74 | Templates works just as normal django app. In /start command example it will search in templates dirs 75 | for ``bot/messages/command_start_text.txt`` to compound response message and 76 | ``bot/messages/command_start_keyboard.txt``. 77 | 78 | Authentication 79 | ------------------------- 80 | 81 | 82 | If you require to be authenticated to perform some commands you can decorate ``bot_views`` with ``login_required``. This 83 | is the flow the user will experience until being able to execute protected command: 84 | 85 | * If chat is not already authenticated a message with a web link will be returned to login through the web site. 86 | 87 | * Once logged, a link to open new authenticated chat will be returned to the user with `deep linking`_ mechanism. 88 | .. _deep linking: https://core.telegram.org/bots#deep-linking 89 | * The user starts this new chat and now the bot will identify this chat as authenticated until token expires. 90 | 91 | Define in ``settings`` the time life of a token:: 92 | 93 | TELEGRAM_BOT_TOKEN_EXPIRATION = 2 # two hours for a token to expire 94 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -r requirements/base.txt 2 | -------------------------------------------------------------------------------- /requirements/base.txt: -------------------------------------------------------------------------------- 1 | django>=1.8.0 2 | djangorestframework==3.3.2 3 | python-telegram-bot==5.3.0 4 | -------------------------------------------------------------------------------- /requirements/dev.txt: -------------------------------------------------------------------------------- 1 | -r base.txt 2 | bumpversion==0.5.3 3 | wheel==0.26.0 4 | Sphinx==1.3.5 5 | coverage 6 | flake8>=2.1.0 7 | tox>=1.7.0 8 | -------------------------------------------------------------------------------- /requirements/test.txt: -------------------------------------------------------------------------------- 1 | -r base.txt 2 | coverage 3 | mock==1.3.0 4 | flake8>=2.1.0 5 | tox>=1.7.0 6 | factory-boy==2.8.1 -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | try: 4 | from django.conf import settings 5 | from django.test.utils import get_runner 6 | 7 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings') 8 | try: 9 | import django 10 | setup = django.setup 11 | except AttributeError: 12 | pass 13 | else: 14 | setup() 15 | 16 | except ImportError: 17 | import traceback 18 | traceback.print_exc() 19 | raise ImportError("To fix this error, run: pip install -r requirements/test.txt") 20 | 21 | 22 | def run_tests(*test_args): 23 | if not test_args: 24 | test_args = ['tests'] 25 | 26 | # Run tests 27 | TestRunner = get_runner(settings) 28 | test_runner = TestRunner() 29 | 30 | failures = test_runner.run_tests(test_args) 31 | 32 | if failures: 33 | sys.exit(bool(failures)) 34 | 35 | 36 | if __name__ == '__main__': 37 | run_tests(*sys.argv[1:]) 38 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.6.0 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | 8 | [bumpversion:file:telegrambot/__init__.py] 9 | 10 | [wheel] 11 | universal = 1 12 | 13 | [flake8] 14 | ignore = E226,E302,E41,E702,W291,W293,E731,W292 15 | max-line-length = 160 16 | exclude = migrations 17 | 18 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | import sys 6 | 7 | import telegrambot 8 | 9 | try: 10 | from setuptools import setup 11 | except ImportError: 12 | from distutils.core import setup 13 | 14 | version = telegrambot.__version__ 15 | 16 | if sys.argv[-1] == 'publish': 17 | try: 18 | import wheel 19 | except ImportError: 20 | print('Wheel library missing. Please run "pip install wheel"') 21 | sys.exit() 22 | os.system('python setup.py sdist upload') 23 | os.system('python setup.py bdist_wheel upload') 24 | sys.exit() 25 | 26 | if sys.argv[-1] == 'tag': 27 | print("Tagging the version on github:") 28 | os.system("git tag -a %s -m 'version %s'" % (version, version)) 29 | os.system("git push --tags") 30 | sys.exit() 31 | 32 | readme = open('README.rst').read() 33 | history = open('HISTORY.rst').read().replace('.. :changelog:', '') 34 | 35 | setup( 36 | name='django-telegram-bot', 37 | version="0.6.0", 38 | description="""Django app to write Telegram bots""", 39 | long_description=readme + '\n\n' + history, 40 | author='Juan Madurga', 41 | author_email='jlmadurga@gmail.com', 42 | url='https://github.com/jlmadurga/django-telegram-bot', 43 | packages=[ 44 | 'telegrambot', 45 | ], 46 | include_package_data=True, 47 | install_requires=[ 48 | 'django>=1.8.0', 49 | 'python-telegram-bot==5.3.0', 50 | 'djangorestframework==3.3.2', 51 | ], 52 | license="BSD", 53 | zip_safe=False, 54 | keywords='django-telegram-bot', 55 | classifiers=[ 56 | 'Development Status :: 3 - Alpha', 57 | 'Framework :: Django', 58 | 'Framework :: Django :: 1.8', 59 | 'Framework :: Django :: 1.9', 60 | 'Intended Audience :: Developers', 61 | 'License :: OSI Approved :: BSD License', 62 | 'Natural Language :: English', 63 | 'Programming Language :: Python :: 2', 64 | 'Programming Language :: Python :: 2.7', 65 | 'Programming Language :: Python :: 3', 66 | 'Programming Language :: Python :: 3.4', 67 | 'Programming Language :: Python :: 3.5', 68 | ], 69 | ) 70 | -------------------------------------------------------------------------------- /telegrambot/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.6.0' 2 | -------------------------------------------------------------------------------- /telegrambot/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from telegrambot.models import Message, Chat, Update, User, Bot, AuthToken 3 | 4 | admin.site.register(Message) 5 | admin.site.register(Chat) 6 | admin.site.register(User) 7 | admin.site.register(Update) 8 | admin.site.register(Bot) 9 | admin.site.register(AuthToken) -------------------------------------------------------------------------------- /telegrambot/bot_views/__init__.py: -------------------------------------------------------------------------------- 1 | from telegrambot.bot_views.login import LoginBotView # NOQA -------------------------------------------------------------------------------- /telegrambot/bot_views/decorators.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | from telegrambot.models import Chat, Bot 3 | from django.core.urlresolvers import reverse 4 | 5 | 6 | def login_required(view_func): 7 | """ 8 | Decorator for command views that checks that the chat is authenticated, 9 | sends message with link for authenticated if necessary. 10 | """ 11 | @wraps(view_func) 12 | def wrapper(bot, update, **kwargs): 13 | chat = Chat.objects.get(id=update.message.chat.id) 14 | if chat.is_authenticated(): 15 | return view_func(bot, update, **kwargs) 16 | from telegrambot.bot_views.login import LoginBotView 17 | login_command_view = LoginBotView.as_command_view() 18 | bot_model = Bot.objects.get(token=bot.token) 19 | kwargs['link'] = reverse('telegrambot:auth', kwargs={'bot': bot_model.user_api.username}) 20 | return login_command_view(bot, update, **kwargs) 21 | return wrapper -------------------------------------------------------------------------------- /telegrambot/bot_views/generic/__init__.py: -------------------------------------------------------------------------------- 1 | from telegrambot.bot_views.generic.base import TemplateCommandView # noqa 2 | from telegrambot.bot_views.generic.compound import ListDetailCommandView # noqa 3 | from telegrambot.bot_views.generic.detail import DetailCommandView # noqa 4 | from telegrambot.bot_views.generic.list import ListCommandView # noqa 5 | from telegrambot.bot_views.generic.responses import (TextResponse, KeyboardResponse) # noqa -------------------------------------------------------------------------------- /telegrambot/bot_views/generic/base.py: -------------------------------------------------------------------------------- 1 | from telegrambot.bot_views.generic.responses import TextResponse, KeyboardResponse 2 | from telegram import ParseMode 3 | import sys 4 | import traceback 5 | import logging 6 | 7 | logger = logging.getLogger(__name__) 8 | PY3 = sys.version_info > (3,) 9 | 10 | class TemplateCommandView(object): 11 | template_text = None 12 | template_keyboard = None 13 | 14 | def get_context(self, bot, update, **kwargs): 15 | return None 16 | 17 | def handle(self, bot, update, **kwargs): 18 | try: 19 | ctx = self.get_context(bot, update, **kwargs) 20 | text = TextResponse(self.template_text, ctx).render() 21 | keyboard = KeyboardResponse(self.template_keyboard, ctx).render() 22 | # logger.debug("Text:" + str(text.encode('utf-8'))) 23 | # logger.debug("Keyboard:" + str(keyboard)) 24 | if text: 25 | if not PY3: 26 | text = text.encode('utf-8') 27 | bot.send_message(chat_id=update.message.chat_id, text=text, reply_markup=keyboard, parse_mode=ParseMode.MARKDOWN) 28 | else: 29 | logger.info("No text response for update %s" % str(update)) 30 | except: 31 | exc_info = sys.exc_info() 32 | traceback.print_exception(*exc_info) 33 | raise 34 | 35 | @classmethod 36 | def as_command_view(cls, **initkwargs): 37 | def view(bot, update, **kwargs): 38 | self = cls(**initkwargs) 39 | return self.handle(bot, update, **kwargs) 40 | return view 41 | -------------------------------------------------------------------------------- /telegrambot/bot_views/generic/compound.py: -------------------------------------------------------------------------------- 1 | from telegrambot.bot_views.generic.base import TemplateCommandView 2 | 3 | class ListDetailCommandView(TemplateCommandView): 4 | list_view_class = None 5 | detail_view_class = None 6 | 7 | @classmethod 8 | def as_command_view(cls, **initkwargs): 9 | def view(bot, update, **kwargs): 10 | command_args = update.message.text.split(' ') 11 | if len(command_args) > 1: 12 | self = cls.detail_view_class(command_args[1]) 13 | else: 14 | self = cls.list_view_class() 15 | return self.handle(bot, update, **kwargs) 16 | return view -------------------------------------------------------------------------------- /telegrambot/bot_views/generic/detail.py: -------------------------------------------------------------------------------- 1 | from telegrambot.bot_views.generic.base import TemplateCommandView 2 | from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist,\ 3 | FieldError 4 | 5 | class DetailCommandView(TemplateCommandView): 6 | model = None 7 | queryset = None 8 | context_object_name = None 9 | slug_field = 'slug' 10 | 11 | def __init__(self, slug=None): 12 | self.slug = slug 13 | 14 | def get_slug_field(self, **kwargs): 15 | """ 16 | Get the name of a slug field to be used to look up by slug. 17 | """ 18 | return self.slug_field 19 | 20 | def get_queryset(self): 21 | """ 22 | Return the `QuerySet` that will be used to look up the object. 23 | Note that this method is called by the default implementation of 24 | `get_object` and may not be called if `get_object` is overridden. 25 | """ 26 | if self.queryset is None: 27 | if self.model: 28 | return self.model._default_manager.all() 29 | else: 30 | raise ImproperlyConfigured( 31 | "%(cls)s is missing a QuerySet. Define " 32 | "%(cls)s.model, %(cls)s.queryset, or override " 33 | "%(cls)s.get_queryset()." % { 34 | 'cls': self.__class__.__name__ 35 | } 36 | ) 37 | return self.queryset.all() 38 | 39 | def get_slug(self, **kwargs): 40 | return self.slug 41 | 42 | def get_context(self, bot, update, **kwargs): 43 | queryset = self.get_queryset() 44 | if not self.slug_field: 45 | raise AttributeError("Generic detail view %s must be called with " 46 | "a slug." 47 | % self.__class__.__name__) 48 | slug_field = self.get_slug_field(**kwargs) 49 | slug = self.get_slug(**kwargs) 50 | if slug: 51 | try: 52 | object = queryset.get(**{slug_field: slug}) 53 | except FieldError: 54 | raise FieldError("Field %s not in valid. Review slug_field" % slug_field) 55 | except ObjectDoesNotExist: 56 | object = None 57 | else: 58 | object = None 59 | context = {'context_object_name': object} 60 | if self.context_object_name: 61 | context[self.context_object_name] = object 62 | return context -------------------------------------------------------------------------------- /telegrambot/bot_views/generic/list.py: -------------------------------------------------------------------------------- 1 | from telegrambot.bot_views.generic.base import TemplateCommandView 2 | from django.core.exceptions import ImproperlyConfigured 3 | from django.db.models.query import QuerySet 4 | from django.utils import six 5 | 6 | class ListCommandView(TemplateCommandView): 7 | queryset = None 8 | context_object_name = None 9 | model = None 10 | ordering = None 11 | 12 | def get_queryset(self): 13 | if self.queryset is not None: 14 | queryset = self.queryset 15 | if isinstance(queryset, QuerySet): 16 | queryset = queryset.all() 17 | elif self.model is not None: 18 | queryset = self.model._default_manager.all() 19 | else: 20 | raise ImproperlyConfigured( 21 | "%(cls)s is missing a QuerySet. Define " 22 | "%(cls)s.model, %(cls)s.queryset, or override " 23 | "%(cls)s.get_queryset()." % { 24 | 'cls': self.__class__.__name__ 25 | } 26 | ) 27 | ordering = self.get_ordering() 28 | if ordering: 29 | if isinstance(ordering, six.string_types): 30 | ordering = (ordering,) 31 | queryset = queryset.order_by(*ordering) 32 | return queryset 33 | 34 | def get_ordering(self): 35 | """ 36 | Return the field or fields to use for ordering the queryset. 37 | """ 38 | return self.ordering 39 | 40 | def get_context(self, bot, update, **kwargs): 41 | object_list = self.get_queryset() 42 | context = {'object_list': object_list} 43 | if self.context_object_name: 44 | context[self.context_object_name] = object_list 45 | return context -------------------------------------------------------------------------------- /telegrambot/bot_views/generic/responses.py: -------------------------------------------------------------------------------- 1 | from django.template import RequestContext, TemplateDoesNotExist 2 | from django.template.loader import get_template 3 | from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove 4 | import ast 5 | import logging 6 | from django.http.request import HttpRequest 7 | 8 | logger = logging.getLogger(__name__) 9 | 10 | class TemplateResponse(object): 11 | 12 | def __init__(self, template_name, ctx=None): 13 | self.template_name = template_name 14 | if ctx is None: 15 | self.ctx = {} 16 | else: 17 | self.ctx = ctx 18 | 19 | def render(self): 20 | if not self.template_name: 21 | return None 22 | try: 23 | logger.debug("Template name: %s" % self.template_name) 24 | template = get_template(self.template_name) 25 | except TemplateDoesNotExist: 26 | logger.debug("Template not found: %s" % self.template_name) 27 | return None 28 | # TODO: Avoid using a null HttRequest to context processors 29 | ctx = RequestContext(HttpRequest(), self.ctx) 30 | return template.render(ctx) 31 | 32 | class TextResponse(TemplateResponse): 33 | 34 | def __init__(self, template_text, ctx=None): 35 | super(TextResponse, self).__init__(template_text, ctx) 36 | 37 | class KeyboardResponse(TemplateResponse): 38 | 39 | def __init__(self, template_keyboard, ctx=None): 40 | super(KeyboardResponse, self).__init__(template_keyboard, ctx) 41 | 42 | def render(self): 43 | keyboard = super(KeyboardResponse, self).render() 44 | if keyboard: 45 | keyboard = ast.literal_eval(keyboard) 46 | keyboard = ReplyKeyboardMarkup(keyboard, resize_keyboard=True) 47 | else: 48 | keyboard = ReplyKeyboardRemove() 49 | return keyboard -------------------------------------------------------------------------------- /telegrambot/bot_views/login.py: -------------------------------------------------------------------------------- 1 | from telegrambot.bot_views.generic import TemplateCommandView 2 | from telegrambot.models import Bot 3 | 4 | class LoginBotView(TemplateCommandView): 5 | template_text = "telegrambot/messages/login_required.txt" 6 | 7 | def generate_link(self, bot, link): 8 | 9 | from django.contrib.sites.models import Site 10 | current_site = Site.objects.get_current() 11 | return 'https://%s%s' % (current_site.domain, link) 12 | 13 | def get_bot(self, bot): 14 | return Bot.objects.get(token=bot.token) 15 | 16 | def get_context(self, bot, update, **kwargs): 17 | 18 | context = {'bot': self.get_bot(bot), 19 | 'link': self.generate_link(bot, kwargs['link'])} 20 | return context -------------------------------------------------------------------------------- /telegrambot/handlers/__init__.py: -------------------------------------------------------------------------------- 1 | from telegrambot.handlers.conf import command # noqa 2 | from telegrambot.handlers.conf import message # noqa 3 | from telegrambot.handlers.conf import regex # noqa 4 | from telegrambot.handlers.conf import unknown_command # noqa 5 | from telegrambot.handlers.resolver import HandlerResolver, HandlerNotFound # noqa -------------------------------------------------------------------------------- /telegrambot/handlers/conf.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | def command(command, view): 4 | return url(r'^/%s(\s)*(?P\w*)' % command, view) 5 | 6 | def unknown_command(view): 7 | return url(r'^/(?P\w+).*', view) 8 | 9 | def regex(pattern, view): 10 | return url(pattern, view) 11 | 12 | def message(view): 13 | return url(r'^(?P.*)', view) -------------------------------------------------------------------------------- /telegrambot/handlers/resolver.py: -------------------------------------------------------------------------------- 1 | from django.core.urlresolvers import RegexURLResolver 2 | from django.core.urlresolvers import Resolver404 3 | 4 | class HandlerNotFound(Exception): 5 | pass 6 | 7 | 8 | class HandlerResolver(object): 9 | 10 | def __init__(self, conf): 11 | self.resolver = RegexURLResolver(r'^', conf) 12 | 13 | def resolve(self, update): 14 | try: 15 | resolver_match = self.resolver.resolve(update.message.text) 16 | return resolver_match 17 | except Resolver404: 18 | raise HandlerNotFound("No handler configured for %s" % update.message.text) -------------------------------------------------------------------------------- /telegrambot/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.1 on 2016-01-21 15:46 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | import django.db.models.deletion 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | initial = True 12 | 13 | dependencies = [ 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='Chat', 19 | fields=[ 20 | ('id', models.BigIntegerField(primary_key=True, serialize=False)), 21 | ('type', models.CharField(choices=[(b'private', 'Private'), (b'group', 'Group'), (b'supergroup', 'Supergroup'), (b'channel', 'Channel')], max_length=255)), 22 | ('title', models.CharField(blank=True, max_length=255, null=True)), 23 | ('username', models.CharField(blank=True, max_length=255, null=True)), 24 | ('first_name', models.CharField(blank=True, max_length=255, null=True)), 25 | ('last_name', models.CharField(blank=True, max_length=255, null=True)), 26 | ], 27 | options={ 28 | 'verbose_name': 'Chat', 29 | 'verbose_name_plural': 'Chats', 30 | }, 31 | ), 32 | migrations.CreateModel( 33 | name='Message', 34 | fields=[ 35 | ('message_id', models.BigIntegerField(primary_key=True, serialize=False, verbose_name='Id')), 36 | ('date', models.DateTimeField(verbose_name='Date')), 37 | ('text', models.TextField(blank=True, null=True, verbose_name='Text')), 38 | ('chat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='telegrambot.Chat', verbose_name='Chat')), 39 | ], 40 | options={ 41 | 'ordering': ['-date'], 42 | 'verbose_name': 'Message', 43 | 'verbose_name_plural': 'Messages', 44 | }, 45 | ), 46 | migrations.CreateModel( 47 | name='Update', 48 | fields=[ 49 | ('update_id', models.BigIntegerField(primary_key=True, serialize=False, verbose_name='Id')), 50 | ('message', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='updates', to='telegrambot.Message', verbose_name='Message')), 51 | ], 52 | options={ 53 | 'verbose_name': 'Update', 54 | 'verbose_name_plural': 'Updates', 55 | }, 56 | ), 57 | migrations.CreateModel( 58 | name='User', 59 | fields=[ 60 | ('id', models.BigIntegerField(primary_key=True, serialize=False)), 61 | ('first_name', models.CharField(max_length=255, verbose_name='First name')), 62 | ('last_name', models.CharField(blank=True, max_length=255, null=True, verbose_name='Last name')), 63 | ('username', models.CharField(blank=True, max_length=255, null=True, verbose_name='User name')), 64 | ], 65 | options={ 66 | 'verbose_name': 'User', 67 | 'verbose_name_plural': 'Users', 68 | }, 69 | ), 70 | migrations.AddField( 71 | model_name='message', 72 | name='forward_from', 73 | field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='forwarded_from', to='telegrambot.User', verbose_name='Forward from'), 74 | ), 75 | migrations.AddField( 76 | model_name='message', 77 | name='from_user', 78 | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='telegrambot.User', verbose_name='User'), 79 | ), 80 | ] 81 | -------------------------------------------------------------------------------- /telegrambot/migrations/0002_bot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.1 on 2016-01-30 13:07 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('telegrambot', '0001_initial'), 12 | ] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name='Bot', 17 | fields=[ 18 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 19 | ('name', models.CharField(blank=True, max_length=200, null=True, verbose_name='Name')), 20 | ('token', models.CharField(db_index=True, max_length=100, verbose_name='Token')), 21 | ('ssl_certificate', models.FileField(blank=True, null=True, upload_to=b'telegrambot/ssl/', verbose_name='SSL certificate')), 22 | ('enabled', models.BooleanField(default=True, verbose_name='Enable')), 23 | ('created', models.DateTimeField(auto_now_add=True, verbose_name=b'Date Created')), 24 | ('modified', models.DateTimeField(auto_now=True, verbose_name='Date Modified')), 25 | ], 26 | options={ 27 | 'verbose_name': 'Bot', 28 | 'verbose_name_plural': 'Bots', 29 | }, 30 | ), 31 | ] 32 | -------------------------------------------------------------------------------- /telegrambot/migrations/0003_auto_20160202_1803.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.1 on 2016-02-02 18:03 3 | from __future__ import unicode_literals 4 | 5 | from django.conf import settings 6 | from django.db import migrations, models 7 | import django.db.models.deletion 8 | 9 | 10 | class Migration(migrations.Migration): 11 | 12 | dependencies = [ 13 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 14 | ('telegrambot', '0002_bot'), 15 | ] 16 | 17 | operations = [ 18 | migrations.CreateModel( 19 | name='AuthToken', 20 | fields=[ 21 | ('key', models.CharField(max_length=40, primary_key=True, serialize=False)), 22 | ('created', models.DateTimeField(auto_now_add=True)), 23 | ('chat_api', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='auth_token', to='telegrambot.Chat')), 24 | ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='auth_token', to=settings.AUTH_USER_MODEL)), 25 | ], 26 | options={ 27 | 'verbose_name': 'Authentication Token', 28 | 'verbose_name_plural': 'Authentications Tokens', 29 | }, 30 | ), 31 | migrations.RemoveField( 32 | model_name='bot', 33 | name='name', 34 | ), 35 | migrations.AddField( 36 | model_name='bot', 37 | name='user_api', 38 | field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='bot', to='telegrambot.User', verbose_name='Bot User'), 39 | ), 40 | ] 41 | -------------------------------------------------------------------------------- /telegrambot/migrations/0004_bot_https_port.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import migrations, models 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ('telegrambot', '0003_auto_20160202_1803'), 11 | ] 12 | 13 | operations = [ 14 | migrations.AddField( 15 | model_name='bot', 16 | name='https_port', 17 | field=models.PositiveIntegerField(default=None, help_text='Leave empty if the bot webhook is published at the standard HTTPS port (443).', null=True, verbose_name='Webhook HTTPS port', blank=True), 18 | ), 19 | ] 20 | -------------------------------------------------------------------------------- /telegrambot/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jlmadurga/django-telegram-bot/becbc86a9735c794828eb5da39bd59647104ba34/telegrambot/migrations/__init__.py -------------------------------------------------------------------------------- /telegrambot/models/__init__.py: -------------------------------------------------------------------------------- 1 | from telegrambot.models.telegram_api import (User, Chat, Message, Update) # NOQA 2 | from telegrambot.models.bot import Bot # NOQA 3 | from telegrambot.models.auth import AuthToken # NOQA -------------------------------------------------------------------------------- /telegrambot/models/auth.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.db import models 3 | from django.utils.encoding import python_2_unicode_compatible 4 | from django.utils.translation import ugettext_lazy as _ 5 | from django.conf import settings 6 | from telegrambot.models import Chat 7 | import logging 8 | import os 9 | import binascii 10 | from django.utils.timezone import now 11 | from datetime import timedelta 12 | 13 | logger = logging.getLogger(__file__) 14 | 15 | 16 | AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') 17 | 18 | @python_2_unicode_compatible 19 | class AuthToken(models.Model): 20 | key = models.CharField(max_length=40, primary_key=True) 21 | user = models.OneToOneField(AUTH_USER_MODEL, related_name='auth_token', 22 | on_delete=models.CASCADE) 23 | chat_api = models.OneToOneField(Chat, related_name='auth_token', 24 | on_delete=models.CASCADE, blank=True, null=True) 25 | created = models.DateTimeField(auto_now_add=True) 26 | 27 | class Meta: 28 | verbose_name = _('Authentication Token') 29 | verbose_name_plural = _('Authentications Tokens') 30 | 31 | def save(self, *args, **kwargs): 32 | if not self.key: 33 | self.key = self.generate_key() 34 | return super(AuthToken, self).save(*args, **kwargs) 35 | 36 | def generate_key(self): 37 | return binascii.hexlify(os.urandom(20)).decode() 38 | 39 | def expired(self): 40 | 41 | return self.created < now() - timedelta(hours=int(getattr(settings, 'TELEGRAM_BOT_TOKEN_EXPIRATION', '24'))) 42 | 43 | def __str__(self): 44 | return self.key 45 | -------------------------------------------------------------------------------- /telegrambot/models/bot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.db import models 3 | from django.utils.encoding import python_2_unicode_compatible 4 | from django.utils.translation import ugettext_lazy as _ 5 | from django.conf import settings 6 | from telegram import Bot as BotAPI 7 | from django.db.models.signals import post_save 8 | from django.dispatch import receiver 9 | from django.core.urlresolvers import reverse 10 | import logging 11 | from telegrambot.models import User 12 | from telegrambot.handlers import HandlerResolver 13 | from telegrambot.handlers import HandlerNotFound 14 | 15 | logger = logging.getLogger(__file__) 16 | 17 | 18 | @python_2_unicode_compatible 19 | class Bot(models.Model): 20 | token = models.CharField(_('Token'), max_length=100, db_index=True) 21 | user_api = models.OneToOneField(User, verbose_name=_("Bot User"), related_name='bot', 22 | on_delete=models.CASCADE, blank=True, null=True) 23 | ssl_certificate = models.FileField(_("SSL certificate"), upload_to='telegrambot/ssl/', 24 | blank=True, null=True) 25 | https_port = models.PositiveIntegerField(_('Webhook HTTPS port'), blank=True, 26 | null=True, default=None, 27 | help_text=_('Leave empty if the bot webhook is published at the standard HTTPS port (443).')) 28 | enabled = models.BooleanField(_('Enable'), default=True) 29 | created = models.DateTimeField(_('Date Created'), auto_now_add=True) 30 | modified = models.DateTimeField(_('Date Modified'), auto_now=True) 31 | 32 | class Meta: 33 | verbose_name = _('Bot') 34 | verbose_name_plural = _('Bots') 35 | 36 | def __init__(self, *args, **kwargs): 37 | super(Bot, self).__init__(*args, **kwargs) 38 | self._bot = None 39 | if self.token: 40 | self._bot = BotAPI(self.token) 41 | 42 | def __str__(self): 43 | return "%s" % (self.user_api.first_name or self.token if self.user_api else self.token) 44 | 45 | def handle(self, update): 46 | handlerconf = settings.TELEGRAM_BOT_HANDLERS_CONF 47 | resolver = HandlerResolver(handlerconf) 48 | try: 49 | resolver_match = resolver.resolve(update) 50 | except HandlerNotFound: 51 | logger.warning("Handler not found for %s" % update) 52 | else: 53 | callback, callback_args, callback_kwargs = resolver_match 54 | callback(self, update, **callback_kwargs) 55 | 56 | def send_message(self, chat_id, text, parse_mode=None, disable_web_page_preview=None, **kwargs): 57 | self._bot.sendMessage(chat_id=chat_id, text=text, parse_mode=parse_mode, 58 | disable_web_page_preview=disable_web_page_preview, **kwargs) 59 | 60 | @receiver(post_save, sender=Bot) 61 | def set_api(sender, instance, **kwargs): 62 | # Always reset the _bot instance after save, in case the token changes. 63 | instance._bot = BotAPI(instance.token) 64 | 65 | # set webhook 66 | url = None 67 | cert = None 68 | if instance.enabled: 69 | webhook = reverse('telegrambot:webhook', kwargs={'token': instance.token}) 70 | from django.contrib.sites.models import Site 71 | current_site = Site.objects.get_current() 72 | if instance.https_port is None: 73 | url = 'https://' + current_site.domain + webhook 74 | else: 75 | url = 'https://' + current_site.domain + ':' + str(instance.https_port) + webhook 76 | if instance.ssl_certificate: 77 | instance.ssl_certificate.open() 78 | cert = instance.ssl_certificate 79 | 80 | instance._bot.setWebhook(webhook_url=url, 81 | certificate=cert) 82 | logger.info("Success: Webhook url %s for bot %s set" % (url, str(instance))) 83 | 84 | # complete Bot instance with api data 85 | if not instance.user_api: 86 | bot_api = instance._bot.getMe() 87 | 88 | botdict = bot_api.to_dict() 89 | modelfields = [f.name for f in User._meta.get_fields()] 90 | params = {k: botdict[k] for k in botdict.keys() if k in modelfields} 91 | user_api, _ = User.objects.get_or_create(**params) 92 | instance.user_api = user_api 93 | 94 | # Prevent signal recursion, and save. 95 | post_save.disconnect(set_api, sender=sender) 96 | instance.save() 97 | post_save.connect(set_api, sender=sender) 98 | 99 | logger.info("Success: Bot api info for bot %s set" % str(instance)) 100 | -------------------------------------------------------------------------------- /telegrambot/models/telegram_api.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.db import models 3 | from django.utils.encoding import python_2_unicode_compatible 4 | from django.utils.translation import ugettext_lazy as _ 5 | 6 | @python_2_unicode_compatible 7 | class User(models.Model): 8 | id = models.BigIntegerField(primary_key=True) 9 | first_name = models.CharField(_('First name'), max_length=255) 10 | last_name = models.CharField(_('Last name'), max_length=255, blank=True, null=True) 11 | username = models.CharField(_('User name'), max_length=255, blank=True, null=True) 12 | 13 | class Meta: 14 | verbose_name = _('User') 15 | verbose_name_plural = _('Users') 16 | 17 | def __str__(self): 18 | if self.first_name: 19 | return "%s" % self.first_name 20 | elif self.username: 21 | return "%s" % self.username 22 | else: 23 | return "%d" % self.id 24 | 25 | @python_2_unicode_compatible 26 | class Chat(models.Model): 27 | 28 | PRIVATE, GROUP, SUPERGROUP, CHANNEL = 'private', 'group', 'supergroup', 'channel' 29 | 30 | TYPE_CHOICES = ( 31 | (PRIVATE, _('Private')), 32 | (GROUP, _('Group')), 33 | (SUPERGROUP, _('Supergroup')), 34 | (CHANNEL, _('Channel')), 35 | ) 36 | 37 | id = models.BigIntegerField(primary_key=True) 38 | type = models.CharField(max_length=255, choices=TYPE_CHOICES) 39 | title = models.CharField(max_length=255, null=True, blank=True) 40 | username = models.CharField(max_length=255, null=True, blank=True) 41 | first_name = models.CharField(max_length=255, null=True, blank=True) 42 | last_name = models.CharField(max_length=255, null=True, blank=True) 43 | 44 | class Meta: 45 | verbose_name = _('Chat') 46 | verbose_name_plural = _('Chats') 47 | 48 | def __str__(self): 49 | return "%s" % (self.title or self.username) 50 | 51 | def is_authenticated(self): 52 | return hasattr(self, 'auth_token') and not self.auth_token.expired() 53 | 54 | @python_2_unicode_compatible 55 | class Message(models.Model): 56 | 57 | message_id = models.BigIntegerField(_('Id'), primary_key=True) 58 | from_user = models.ForeignKey(User, related_name='messages', verbose_name=_("User")) 59 | date = models.DateTimeField(_('Date')) 60 | chat = models.ForeignKey(Chat, related_name='messages', verbose_name=_("Chat")) 61 | forward_from = models.ForeignKey(User, null=True, blank=True, related_name='forwarded_from', 62 | verbose_name=_("Forward from")) 63 | text = models.TextField(null=True, blank=True, verbose_name=_("Text")) 64 | # TODO: complete fields with all message fields 65 | 66 | class Meta: 67 | verbose_name = 'Message' 68 | verbose_name_plural = 'Messages' 69 | ordering = ['-date', ] 70 | 71 | def __str__(self): 72 | return "(%s,%s)" % (self.from_user, self.text or '(no text)') 73 | 74 | class Update(models.Model): 75 | 76 | update_id = models.BigIntegerField(_('Id'), primary_key=True) 77 | message = models.ForeignKey(Message, null=True, blank=True, verbose_name=_('Message'), 78 | related_name="updates") 79 | 80 | class Meta: 81 | verbose_name = 'Update' 82 | verbose_name_plural = 'Updates' 83 | 84 | def __str__(self): 85 | return "%s" % self.update_id 86 | -------------------------------------------------------------------------------- /telegrambot/serializers.py: -------------------------------------------------------------------------------- 1 | from rest_framework import serializers 2 | from telegrambot.models import User, Chat, Message, Update, AuthToken 3 | from datetime import datetime 4 | import time 5 | 6 | class UserSerializer(serializers.HyperlinkedModelSerializer): 7 | id = serializers.IntegerField() 8 | 9 | class Meta: 10 | model = User 11 | fields = ('id', 'first_name', 'last_name', 'username') 12 | 13 | class ChatSerializer(serializers.HyperlinkedModelSerializer): 14 | id = serializers.IntegerField() 15 | 16 | class Meta: 17 | model = Chat 18 | fields = ('id', 'type', 'title', 'username', 'first_name', 'last_name') 19 | 20 | class TimestampField(serializers.Field): 21 | 22 | def to_internal_value(self, data): 23 | return datetime.fromtimestamp(data) 24 | 25 | def to_representation(self, value): 26 | return int(time.mktime(value.timetuple())) 27 | 28 | 29 | class MessageSerializer(serializers.HyperlinkedModelSerializer): 30 | message_id = serializers.IntegerField() 31 | # reserved word field 'from' changed dynamically 32 | from_ = UserSerializer(many=False, source="from_user") 33 | chat = ChatSerializer(many=False) 34 | date = TimestampField() 35 | text = serializers.CharField(required=True) 36 | 37 | def __init__(self, *args, **kwargs): 38 | super(MessageSerializer, self).__init__(*args, **kwargs) 39 | self.fields['from'] = self.fields['from_'] 40 | del self.fields['from_'] 41 | 42 | class Meta: 43 | model = Message 44 | fields = ('message_id', 'from_', 'date', 'chat', 'text') 45 | 46 | class UpdateSerializer(serializers.HyperlinkedModelSerializer): 47 | update_id = serializers.IntegerField() 48 | message = MessageSerializer(many=False) 49 | 50 | class Meta: 51 | model = Update 52 | fields = ('update_id', 'message') 53 | 54 | def create(self, validated_data): 55 | user, _ = User.objects.get_or_create(**validated_data['message']['from_user']) 56 | 57 | chat, created = Chat.objects.get_or_create(**validated_data['message']['chat']) 58 | 59 | # Associate chat to token if comes /start with token 60 | splitted_message = validated_data['message']['text'].split(' ') 61 | if len(splitted_message) > 1 and splitted_message[0] == '/start': 62 | try: 63 | token = AuthToken.objects.get(key=splitted_message[1]) 64 | token.chat_api = chat 65 | token.save() 66 | except AuthToken.DoesNotExist: 67 | # Do not associate with any token 68 | pass 69 | 70 | message, _ = Message.objects.get_or_create(message_id=validated_data['message']['message_id'], 71 | from_user=user, 72 | date=validated_data['message']['date'], 73 | chat=chat, 74 | text=validated_data['message']['text']) 75 | update, _ = Update.objects.get_or_create(update_id=validated_data['update_id'], 76 | message=message) 77 | 78 | return update -------------------------------------------------------------------------------- /telegrambot/templates/telegrambot/authentication.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 | {% trans "Start new chat to be authenticated" %} 3 | @{{ bot.user_api.username }} -------------------------------------------------------------------------------- /telegrambot/templates/telegrambot/messages/login_required.txt: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 | {% blocktrans with link=link %}You need an *authenticated chat* to perform this action please login [here]({{link}}){% endblocktrans %} -------------------------------------------------------------------------------- /telegrambot/templatetags/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jlmadurga/django-telegram-bot/becbc86a9735c794828eb5da39bd59647104ba34/telegrambot/templatetags/__init__.py -------------------------------------------------------------------------------- /telegrambot/templatetags/telegrambot_filters.py: -------------------------------------------------------------------------------- 1 | from django import template 2 | from django.http import QueryDict 3 | register = template.Library() 4 | 5 | @register.filter(name='keyboard_field') 6 | def keyboard_field(value, args=None): 7 | """ 8 | Format keyboard /command field. 9 | """ 10 | qs = QueryDict(args) 11 | per_line = qs.get('per_line', 1) 12 | field = qs.get("field", "slug") 13 | command = qs.get("command") 14 | convert = lambda element: "/" + command + " " + str(getattr(element, field)) 15 | group = lambda flat, size: [flat[i:i+size] for i in range(0, len(flat), size)] 16 | grouped = group(value, int(per_line)) 17 | new_list = [] 18 | for line in grouped: 19 | new_list.append([convert(e) for e in line]) 20 | return str(new_list).encode('utf-8') -------------------------------------------------------------------------------- /telegrambot/test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jlmadurga/django-telegram-bot/becbc86a9735c794828eb5da39bd59647104ba34/telegrambot/test/__init__.py -------------------------------------------------------------------------------- /telegrambot/test/factories/__init__.py: -------------------------------------------------------------------------------- 1 | from telegrambot.test.factories.auth import AuthTokenFactory # noqa 2 | from telegrambot.test.factories.bot import BotFactory # noqa 3 | from telegrambot.test.factories.telegram_lib import (UserLibFactory, ChatLibFactory, # noqa 4 | MessageLibFactory, UpdateLibFactory) # noqa 5 | from telegrambot.test.factories.user import UserWebFactory # noqa -------------------------------------------------------------------------------- /telegrambot/test/factories/auth.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from factory import SubFactory, DjangoModelFactory 3 | from telegrambot.test.factories.user import UserWebFactory 4 | from telegrambot.models import AuthToken 5 | 6 | class AuthTokenFactory(DjangoModelFactory): 7 | user = SubFactory(UserWebFactory) 8 | 9 | class Meta: 10 | model = AuthToken -------------------------------------------------------------------------------- /telegrambot/test/factories/bot.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from factory import DjangoModelFactory 3 | from telegrambot.models import Bot 4 | 5 | 6 | class BotFactory(DjangoModelFactory): 7 | class Meta: 8 | model = Bot 9 | token = "174446943:AAEcMXep4Uc51sAkYcTJC7vEoLmmxwnQgcc" -------------------------------------------------------------------------------- /telegrambot/test/factories/telegram_lib.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | import telegram 3 | from factory import Sequence, SubFactory, Factory 4 | from factory.fuzzy import FuzzyText 5 | from django.utils import timezone 6 | 7 | 8 | class UserLibFactory(Factory): 9 | class Meta: 10 | model = telegram.User 11 | id = Sequence(lambda n: n+1) 12 | first_name = Sequence(lambda n: 'first_name_%d' % n) 13 | last_name = Sequence(lambda n: 'last_name_%d' % n) 14 | username = Sequence(lambda n: 'username_%d' % n) 15 | 16 | class ChatLibFactory(Factory): 17 | class Meta: 18 | model = telegram.Chat 19 | id = Sequence(lambda n: n+1) 20 | type = "private" 21 | title = Sequence(lambda n: 'title_%d' % n) 22 | username = Sequence(lambda n: 'username_%d' % n) 23 | first_name = Sequence(lambda n: 'first_name_%d' % n) 24 | last_name = Sequence(lambda n: 'last_name_%d' % n) 25 | 26 | class MessageLibFactory(Factory): 27 | class Meta: 28 | model = telegram.Message 29 | message_id = Sequence(lambda n: n+1) 30 | from_user = SubFactory(UserLibFactory) 31 | date = timezone.now() 32 | chat = SubFactory(ChatLibFactory) 33 | text = FuzzyText() 34 | 35 | class UpdateLibFactory(Factory): 36 | class Meta: 37 | model = telegram.Update 38 | update_id = Sequence(lambda n: n+1) 39 | message = SubFactory(MessageLibFactory) -------------------------------------------------------------------------------- /telegrambot/test/factories/user.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from factory import Sequence, DjangoModelFactory, PostGenerationMethodCall 3 | from django.conf import settings 4 | 5 | class UserWebFactory(DjangoModelFactory): 6 | username = Sequence(lambda n: 'user_name_%d' % n) 7 | email = Sequence(lambda n: 'mail_%s@example.com' % n) 8 | password = PostGenerationMethodCall('set_password', 'seed') 9 | is_active = True 10 | is_superuser = False 11 | 12 | class Meta: 13 | model = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') -------------------------------------------------------------------------------- /telegrambot/test/testcases.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from django.test import TestCase 4 | from telegrambot.models import Update 5 | from telegrambot.test import factories 6 | from django.core.urlresolvers import reverse 7 | from rest_framework import status 8 | from telegram import ReplyKeyboardRemove 9 | try: 10 | from unittest import mock 11 | except ImportError: 12 | import mock # noqa 13 | import sys 14 | 15 | PY3 = sys.version_info > (3,) 16 | 17 | class BaseTestBot(TestCase): 18 | 19 | def setUp(self): 20 | with mock.patch("telegram.bot.Bot.setWebhook", callable=mock.MagicMock()): 21 | self.bot = factories.BotFactory() 22 | self.webhook_url = reverse('telegrambot:webhook', kwargs={'token': self.bot.token}) 23 | self.auth_url = reverse('telegrambot:auth', kwargs={'bot': self.bot.user_api.username}) 24 | self.update = factories.UpdateLibFactory() 25 | self.kwargs = {'content_type': 'application/json', } 26 | 27 | def assertUser(self, model_user, user): 28 | self.assertEqual(model_user.id, user.id) 29 | self.assertEqual(model_user.first_name, user.first_name) 30 | self.assertEqual(model_user.last_name, user.last_name) 31 | self.assertEqual(model_user.username, user.username) 32 | 33 | def assertChat(self, model_chat, chat): 34 | self.assertEqual(model_chat.id, chat.id) 35 | self.assertEqual(model_chat.type, chat.type) 36 | self.assertEqual(model_chat.title, chat.title) 37 | self.assertEqual(model_chat.username, chat.username) 38 | self.assertEqual(model_chat.first_name, chat.first_name) 39 | self.assertEqual(model_chat.last_name, chat.last_name) 40 | 41 | def assertMessage(self, model_message, message): 42 | self.assertEqual(model_message.message_id, message.message_id) 43 | self.assertUser(model_message.from_user, message.from_user) 44 | self.assertChat(model_message.chat, message.chat) 45 | # TODO: problems with UTCs 46 | # self.assertEqual(model_message.date, message.date) 47 | self.assertEqual(model_message.text, message.text) 48 | 49 | def assertUpdate(self, model_update, update): 50 | self.assertEqual(model_update.update_id, update.update_id) 51 | self.assertMessage(model_update.message, update.message) 52 | 53 | def assertInKeyboard(self, button, keyboard): 54 | found = False 55 | for line in keyboard: 56 | if button in line: 57 | found = True 58 | break 59 | self.assertTrue(found) 60 | 61 | def assertBotResponse(self, mock_send, command): 62 | args, kwargs = mock_send.call_args 63 | self.assertEqual(1, mock_send.call_count) 64 | self.assertEqual(kwargs['chat_id'], self.update.message.chat.id) 65 | self.assertEqual(kwargs['parse_mode'], command['out']['parse_mode']) 66 | if not command['out']['reply_markup']: 67 | self.assertTrue(isinstance(kwargs['reply_markup'], ReplyKeyboardRemove)) 68 | else: 69 | self.assertInKeyboard(command['out']['reply_markup'], kwargs['reply_markup'].keyboard) 70 | if not PY3: 71 | kwargs['text'] = kwargs['text'].decode('utf-8') 72 | self.assertIn(command['out']['text'], kwargs['text']) 73 | 74 | def _test_message_ok(self, action, update=None, number=1): 75 | if not update: 76 | update = self.update 77 | with mock.patch("telegram.bot.Bot.sendMessage", callable=mock.MagicMock()) as mock_send: 78 | if 'in' in action: 79 | update.message.text = action['in'] 80 | response = self.client.post(self.webhook_url, update.to_json(), **self.kwargs) 81 | # Check response 200 OK 82 | self.assertEqual(response.status_code, status.HTTP_200_OK) 83 | # Check 84 | self.assertBotResponse(mock_send, action) 85 | self.assertEqual(number, Update.objects.count()) 86 | self.assertUpdate(Update.objects.get(update_id=update.update_id), update) 87 | 88 | def _test_message_no_handler(self, action, update=None, number=1): 89 | if not update: 90 | update = self.update 91 | with mock.patch("telegram.bot.Bot.sendMessage", callable=mock.MagicMock()) as mock_send: 92 | if 'in' in action: 93 | update.message.text = action['in'] 94 | response = self.client.post(self.webhook_url, update.to_json(), **self.kwargs) 95 | # Check response 200 OK 96 | self.assertEqual(response.status_code, status.HTTP_200_OK) 97 | self.assertEqual(0, mock_send.call_count) 98 | self.assertEqual(number, Update.objects.count()) 99 | self.assertUpdate(Update.objects.get(update_id=update.update_id), update) -------------------------------------------------------------------------------- /telegrambot/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from django.views.decorators.csrf import csrf_exempt 3 | from telegrambot import views 4 | from django.contrib.auth.decorators import login_required 5 | 6 | 7 | urlpatterns = [ 8 | url(r'^webhook/(?P[-_:a-zA-Z0-9]+)/$', csrf_exempt(views.WebhookView.as_view()), name='webhook'), 9 | url(r'^auth/(?P[-_a-zA-Z0-9]+)/$', login_required(views.AuthView.as_view()), name='auth') 10 | ] -------------------------------------------------------------------------------- /telegrambot/views.py: -------------------------------------------------------------------------------- 1 | from rest_framework.views import APIView 2 | from telegrambot.serializers import UpdateSerializer 3 | from telegrambot.models import Bot, AuthToken 4 | from rest_framework.response import Response 5 | from rest_framework import status 6 | from telegram import Update 7 | import logging 8 | from django.views import generic 9 | import sys 10 | import traceback 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | class WebhookView(APIView): 15 | 16 | def post(self, request, token): 17 | serializer = UpdateSerializer(data=request.data) 18 | if serializer.is_valid(): 19 | serializer.save() 20 | try: 21 | bot = Bot.objects.get(token=token) 22 | bot.handle(Update.de_json(request.data, bot._bot)) 23 | except Bot.DoesNotExist: 24 | logger.warning("Token %s not associated to a bot" % token) 25 | return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND) 26 | except: 27 | exc_info = sys.exc_info() 28 | traceback.print_exception(*exc_info) 29 | logger.error("Error processing %s for token %s" % (request.data, token)) 30 | return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 31 | else: 32 | return Response(serializer.data, status=status.HTTP_200_OK) 33 | logger.error("Validation error: %s from message %s" % (serializer.errors, request.data)) 34 | return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 35 | 36 | 37 | class AuthView(generic.TemplateView): 38 | template_name = 'telegrambot/authentication.html' 39 | 40 | def get_context_data(self, **kwargs): 41 | ctx = super(AuthView, self).get_context_data(**kwargs) 42 | ctx['bot'] = self.get_bot(self.kwargs['bot']) 43 | ctx['token'] = self.get_token(self.request.user) 44 | return ctx 45 | 46 | def get_bot(self, name): 47 | return Bot.objects.get(user_api__username=name) 48 | 49 | def get_token(self, user): 50 | token, created = AuthToken.objects.get_or_create(user=user) 51 | if not created and token.expired(): 52 | token.delete() 53 | token = AuthToken.objects.create(user=user) 54 | return token -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jlmadurga/django-telegram-bot/becbc86a9735c794828eb5da39bd59647104ba34/tests/__init__.py -------------------------------------------------------------------------------- /tests/bot_handlers.py: -------------------------------------------------------------------------------- 1 | from tests.commands_views import StartView, AuthorCommandView, AuthorInverseListView, AuthorCommandQueryView, \ 2 | UnknownView, AuthorName, MessageView 3 | from telegrambot.handlers import command, unknown_command, regex, message 4 | from telegrambot.bot_views.decorators import login_required 5 | 6 | urlpatterns = [ 7 | command('start', StartView.as_command_view()), 8 | command('author_inverse', AuthorInverseListView.as_command_view()), 9 | command('author_query', AuthorCommandQueryView.as_command_view()), 10 | regex(r'^author_(?P\w+)', AuthorName.as_command_view()), 11 | command('author_auth', login_required(AuthorCommandView.as_command_view())), 12 | command('author', AuthorCommandView.as_command_view()), 13 | unknown_command(UnknownView.as_command_view()), 14 | message(MessageView.as_command_view()) 15 | ] -------------------------------------------------------------------------------- /tests/bot_handlers_empty.py: -------------------------------------------------------------------------------- 1 | urlpatterns = [ 2 | 3 | ] -------------------------------------------------------------------------------- /tests/commands_views.py: -------------------------------------------------------------------------------- 1 | from telegrambot.bot_views.generic import TemplateCommandView, ListCommandView, DetailCommandView, \ 2 | ListDetailCommandView 3 | from tests.models import Author 4 | 5 | class StartView(TemplateCommandView): 6 | template_text = "bot/messages/command_start_text.txt" 7 | 8 | class UnknownView(TemplateCommandView): 9 | template_text = "bot/messages/command_unknown_text.txt" 10 | 11 | class AuthorListView(ListCommandView): 12 | template_text = "bot/messages/command_author_list_text.txt" 13 | template_keyboard = "bot/messages/command_author_list_keyboard.txt" 14 | model = Author 15 | context_object_name = "authors" 16 | 17 | class AuthorInverseListView(AuthorListView): 18 | ordering = "-name" 19 | 20 | class AuthorDetailView(DetailCommandView): 21 | template_text = "bot/messages/command_author_detail_text.txt" 22 | context_object_name = "author" 23 | model = Author 24 | slug_field = 'name' 25 | 26 | class AuthorListQueryView(AuthorListView): 27 | queryset = Author.objects.all 28 | 29 | class AuthorDetailQueryView(AuthorDetailView): 30 | queryset = Author.objects 31 | 32 | class AuthorCommandView(ListDetailCommandView): 33 | list_view_class = AuthorListView 34 | detail_view_class = AuthorDetailView 35 | 36 | class AuthorCommandQueryView(ListDetailCommandView): 37 | list_view_class = AuthorListQueryView 38 | detail_view_class = AuthorDetailQueryView 39 | 40 | class MessageView(TemplateCommandView): 41 | template_text = "bot/messages/unknown_message_text.txt" 42 | 43 | class AuthorName(DetailCommandView): 44 | template_text = "bot/messages/regex_author_name_text.txt" 45 | context_object_name = "author" 46 | model = Author 47 | slug_field = 'name' 48 | 49 | def get_slug(self, **kwargs): 50 | return kwargs.get('name', None) 51 | -------------------------------------------------------------------------------- /tests/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.db import models 4 | from django.utils.encoding import python_2_unicode_compatible 5 | 6 | 7 | @python_2_unicode_compatible 8 | class Author(models.Model): 9 | name = models.CharField(max_length=100) 10 | 11 | def __str__(self): 12 | return self.name 13 | 14 | def get_absolute_url(self): 15 | return '/authors/%s/' % self.id -------------------------------------------------------------------------------- /tests/settings.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | DEBUG=True, 3 | USE_TZ=True 4 | DATABASES={ 5 | "default": { 6 | "ENGINE": "django.db.backends.sqlite3", 7 | } 8 | } 9 | ROOT_URLCONF="tests.urls" 10 | INSTALLED_APPS=[ 11 | "django.contrib.auth", 12 | "django.contrib.contenttypes", 13 | "django.contrib.sites", 14 | 'django.contrib.sessions', 15 | "rest_framework", 16 | "telegrambot", 17 | "tests" 18 | ] 19 | SITE_ID=1 20 | MIDDLEWARE_CLASSES = ( 21 | 'django.contrib.sessions.middleware.SessionMiddleware', 22 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 23 | 24 | ) 25 | SECRET_KEY = "shds8dfyhskdfhskdfhskdf" 26 | 27 | LOGGING = { 28 | 'version': 1, 29 | 'disable_existing_loggers': False, 30 | 'formatters': { 31 | 'verbose': { 32 | 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' 33 | }, 34 | 'simple': { 35 | 'format': '%(levelname)s %(message)s' 36 | }, 37 | }, 38 | 'filters': { 39 | 'require_debug_false': { 40 | '()': 'django.utils.log.RequireDebugFalse' 41 | } 42 | }, 43 | 'handlers': { 44 | 'console': { 45 | 'level': 'DEBUG', 46 | 'class': 'logging.StreamHandler', 47 | 'formatter': 'verbose' 48 | }, 49 | }, 50 | 'loggers': { 51 | 'telegrambot.views': { 52 | 'handlers': ['console'], 53 | 'propagate': False, 54 | 'level': 'DEBUG', 55 | }, 56 | } 57 | } 58 | 59 | TEMPLATES = [ 60 | { 61 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 62 | 'DIRS': [], 63 | 'APP_DIRS': True 64 | }, 65 | ] 66 | 67 | TELEGRAM_BOT_HANDLERS_CONF = "tests.bot_handlers" 68 | TELEGRAM_BOT_TOKEN_EXPIRATION = "2" # tow hours before a token expires 69 | -------------------------------------------------------------------------------- /tests/templates/bot/messages/command_author_detail_text.txt: -------------------------------------------------------------------------------- 1 | Author name:{{ author.name }} -------------------------------------------------------------------------------- /tests/templates/bot/messages/command_author_list_keyboard.txt: -------------------------------------------------------------------------------- 1 | {% load telegrambot_filters %}{% autoescape off %}{{ authors |keyboard_field:"command=author&field=name&per_line=1"}}{% endautoescape %} -------------------------------------------------------------------------------- /tests/templates/bot/messages/command_author_list_text.txt: -------------------------------------------------------------------------------- 1 | Select from list:{% for author in authors %} 2 | {{ author.name }}{% endfor %} -------------------------------------------------------------------------------- /tests/templates/bot/messages/command_start_text.txt: -------------------------------------------------------------------------------- 1 | Start command -------------------------------------------------------------------------------- /tests/templates/bot/messages/command_unknown_text.txt: -------------------------------------------------------------------------------- 1 | Unknown command -------------------------------------------------------------------------------- /tests/templates/bot/messages/regex_author_name_text.txt: -------------------------------------------------------------------------------- 1 | {% if author %}Author name:{{ author.name }}{% else %}Author not found{% endif %} -------------------------------------------------------------------------------- /tests/templates/bot/messages/unknown_message_text.txt: -------------------------------------------------------------------------------- 1 | Please, use _/help_ command to list commands -------------------------------------------------------------------------------- /tests/test_telegrambot.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from telegrambot.models import User, Chat, Bot, AuthToken 4 | from telegrambot.test import factories, testcases 5 | from factory import DjangoModelFactory, Sequence 6 | from tests.models import Author 7 | from django.core.urlresolvers import reverse 8 | from rest_framework import status 9 | from django.test.utils import override_settings 10 | from django.conf import settings 11 | from django.apps import apps 12 | try: 13 | from unittest import mock 14 | except ImportError: 15 | import mock # noqa 16 | 17 | 18 | ModelUser = apps.get_model(getattr(settings, 'AUTH_USER_MODEL', 'auth.User')) 19 | 20 | class AuthorFactory(DjangoModelFactory): 21 | class Meta: 22 | model = Author 23 | name = Sequence(lambda n: 'author_%d' % n) 24 | 25 | class TestBot(testcases.BaseTestBot): 26 | 27 | def test_enable_webhook(self): 28 | self.assertTrue(self.bot.enabled) 29 | with mock.patch("telegram.bot.Bot.setWebhook", callable=mock.MagicMock()) as mock_setwebhook: 30 | self.bot.save() 31 | args, kwargs = mock_setwebhook.call_args 32 | self.assertEqual(1, mock_setwebhook.call_count) 33 | self.assertIn(reverse('telegrambot:webhook', kwargs={'token': self.bot.token}), 34 | kwargs['webhook_url']) 35 | self.assertEqual(None, kwargs['certificate']) 36 | 37 | def test_custom_webhook_https_port(self): 38 | self.bot.https_port = 8443 39 | with mock.patch("telegram.bot.Bot.setWebhook", callable=mock.MagicMock()) as mock_setwebhook: 40 | self.bot.save() 41 | args, kwargs = mock_setwebhook.call_args 42 | self.assertIn(':8443' + reverse('telegrambot:webhook', kwargs={'token': self.bot.token}), 43 | kwargs['webhook_url']) 44 | 45 | def test_disable_webhook(self): 46 | self.bot.enabled = False 47 | with mock.patch("telegram.bot.Bot.setWebhook", callable=mock.MagicMock()) as mock_setwebhook: 48 | self.bot.save() 49 | args, kwargs = mock_setwebhook.call_args 50 | self.assertEqual(1, mock_setwebhook.call_count) 51 | self.assertEqual(None, kwargs['webhook_url']) 52 | self.assertEqual(None, kwargs['certificate']) 53 | 54 | def test_bot_user_api(self): 55 | with mock.patch("telegram.bot.Bot.setWebhook", callable=mock.MagicMock()): 56 | self.bot.user_api = None 57 | self.bot.save() 58 | self.assertEqual(self.bot.user_api.first_name, u'oscartest') 59 | self.assertEqual(self.bot.user_api.username, u'oscartest_bot') 60 | 61 | def test_no_bot_associated(self): 62 | Bot.objects.all().delete() 63 | self.assertEqual(0, Bot.objects.count()) 64 | response = self.client.post(self.webhook_url, self.update.to_json(), **self.kwargs) 65 | self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code) 66 | 67 | def test_not_valid_update(self): 68 | del self.update.message 69 | response = self.client.post(self.webhook_url, self.update.to_json(), **self.kwargs) 70 | self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code) 71 | 72 | class TestBotCommands(testcases.BaseTestBot): 73 | 74 | start = {'in': '/start', 75 | 'out': {'parse_mode': 'Markdown', 76 | 'reply_markup': '', 77 | 'text': "Start command" 78 | } 79 | } 80 | 81 | unknown = {'in': '/no_defined', 82 | 'out': {'parse_mode': 'Markdown', 83 | 'reply_markup': '', 84 | 'text': "Unknown command" 85 | } 86 | } 87 | 88 | author_list = {'in': '/author', 89 | 'out': {'parse_mode': 'Markdown', 90 | 'reply_markup': '/author author_1', 91 | 'text': "Select from list:\nauthor_1\nauthor_2" 92 | } 93 | } 94 | author_inverse_list = {'in': '/author_inverse', 95 | 'out': {'parse_mode': 'Markdown', 96 | 'reply_markup': '/author author_1', 97 | 'text': "Select from list:\nauthor_2\nauthor_1" 98 | } 99 | } 100 | 101 | author_detail = {'in': '/author author1', 102 | 'out': {'parse_mode': 'Markdown', 103 | 'reply_markup': '', 104 | 'text': "Author name:author1" 105 | } 106 | } 107 | 108 | author_list_query = {'in': '/author_query', 109 | 'out': {'parse_mode': 'Markdown', 110 | 'reply_markup': '/author author_1', 111 | 'text': "Select from list:\nauthor_1\nauthor_2" 112 | } 113 | } 114 | 115 | author_detail_query = {'in': '/author_query author_1', 116 | 'out': {'parse_mode': 'Markdown', 117 | 'reply_markup': '', 118 | 'text': "Author name:author_1" 119 | } 120 | } 121 | 122 | def test_start(self): 123 | self._test_message_ok(self.start) 124 | 125 | def test_unknown(self): 126 | self._test_message_ok(self.unknown) 127 | 128 | def test_author_list(self): 129 | AuthorFactory(name="author_1") 130 | AuthorFactory(name="author_2") 131 | self._test_message_ok(self.author_list) 132 | 133 | def test_author_inverse_list(self): 134 | AuthorFactory(name="author_1") 135 | AuthorFactory(name="author_2") 136 | self._test_message_ok(self.author_inverse_list) 137 | 138 | def test_author_detail(self): 139 | AuthorFactory(name="author1") 140 | self._test_message_ok(self.author_detail) 141 | 142 | def test_author_list_queryset(self): 143 | AuthorFactory(name="author_1") 144 | AuthorFactory(name="author_2") 145 | self._test_message_ok(self.author_list_query) 146 | 147 | def test_author_detail_queryset(self): 148 | AuthorFactory(name="author_1") 149 | self._test_message_ok(self.author_detail_query) 150 | 151 | def test_several_commands_from_same_user_and_chat(self): 152 | self._test_message_ok(self.start) 153 | user = self.update.message.from_user 154 | chat = self.update.message.chat 155 | update_2 = factories.UpdateLibFactory() 156 | update_2.message.from_user = user 157 | update_2.message.chat = chat 158 | self._test_message_ok(self.unknown, update_2, 2) 159 | self.assertEqual(User.objects.count(), 2) # bot user 160 | self.assertEqual(Chat.objects.count(), 1) 161 | 162 | class TestBotMessage(testcases.BaseTestBot): 163 | 164 | any_message = {'out': {'parse_mode': 'Markdown', 165 | 'reply_markup': '', 166 | 'text': "Please" 167 | } 168 | } 169 | 170 | def test_message_handler(self): 171 | self._test_message_ok(self.any_message) 172 | 173 | @override_settings(TELEGRAM_BOT_HANDLERS_CONF='tests.bot_handlers_empty') 174 | class TestBotNoHandlers(testcases.BaseTestBot): 175 | 176 | any_message = {'out': {'parse_mode': 'Markdown', 177 | 'reply_markup': '', 178 | 'text': "Please" 179 | } 180 | } 181 | 182 | def test_no_handler(self): 183 | self._test_message_no_handler(self.any_message) 184 | 185 | 186 | class TestBotRegex(testcases.BaseTestBot): 187 | 188 | author_name = {'in': 'author_authorname', 189 | 'out': {'parse_mode': 'Markdown', 190 | 'reply_markup': '', 191 | 'text': "Author name:authorname" 192 | } 193 | } 194 | 195 | author_not_found = {'in': 'author_notname', 196 | 'out': {'parse_mode': 'Markdown', 197 | 'reply_markup': '', 198 | 'text': "Author not found" 199 | } 200 | } 201 | 202 | def test_regex_handler_match(self): 203 | AuthorFactory(name="authorname") 204 | self._test_message_ok(self.author_name) 205 | 206 | def test_regex_handler_not_match(self): 207 | AuthorFactory(name="authorname") 208 | self._test_message_ok(self.author_not_found) 209 | 210 | class TestLoginRequiredBotView(testcases.BaseTestBot): 211 | 212 | author_login_required_not_auth = {'in': '/author_auth', 213 | 'out': {'parse_mode': 'Markdown', 214 | 'reply_markup': '', 215 | 'text': "You need an *authenticated chat*" + 216 | " to perform this action please login" + 217 | " [here](https://example.com/telegrambot/auth/" 218 | } 219 | } 220 | 221 | author_login_required_authed = {'in': '/author_auth', 222 | 'out': {'parse_mode': 'Markdown', 223 | 'reply_markup': '/author author_1', 224 | 'text': "Select from list:\nauthor_1" 225 | } 226 | } 227 | 228 | def test_login_required_not_auth(self): 229 | AuthorFactory(name="author_1") 230 | self._test_message_ok(self.author_login_required_not_auth) 231 | 232 | def test_login_required_already_auth(self): 233 | token = factories.AuthTokenFactory() 234 | token.save() 235 | chat, _ = self.chat_get_or_create() 236 | token.chat_api = chat 237 | token.save() 238 | AuthorFactory(name="author_1") 239 | self._test_message_ok(self.author_login_required_authed) 240 | 241 | @override_settings(TELEGRAM_BOT_TOKEN_EXPIRATION='-1') 242 | def test_login_required_expired_token(self): 243 | token = factories.AuthTokenFactory() 244 | token.save() 245 | chat, _ = self.chat_get_or_create() 246 | token.chat_api = chat 247 | token.save() 248 | AuthorFactory(name="author_1") 249 | self._test_message_ok(self.author_login_required_not_auth) 250 | 251 | def chat_get_or_create(self): 252 | data = self.update.message.chat.to_dict() 253 | modelfields = [f.name for f in Chat._meta.get_fields()] 254 | params = {k: data[k] for k in data.keys() if k in modelfields} 255 | return Chat.objects.get_or_create(**params) 256 | 257 | 258 | class TestAuthView(testcases.BaseTestBot): 259 | 260 | user_args = {'username': 'username', 261 | 'email': 'test@test.com', 262 | 'password': 'password'} 263 | 264 | def test_token_creation(self): 265 | with mock.patch("telegram.bot.Bot.setWebhook", callable=mock.MagicMock()): 266 | self.bot.save() 267 | user = ModelUser.objects.create_user(**self.user_args) 268 | self.client.login(username=self.user_args['username'], password=self.user_args['password']) 269 | response = self.client.get(self.auth_url) 270 | self.assertEqual(1, AuthToken.objects.count()) 271 | token = AuthToken.objects.all()[0] 272 | self.assertEqual(token.user, user) 273 | generated_link = 'https://telegram.me/%s?start=%s">@%s' % (self.bot.user_api.username, token.key, self.bot.user_api.username) 274 | self.assertContains(response, generated_link, status_code=status.HTTP_200_OK) 275 | 276 | @override_settings(TELEGRAM_BOT_TOKEN_EXPIRATION='-1') 277 | def test_token_expired(self): 278 | with mock.patch("telegram.bot.Bot.setWebhook", callable=mock.MagicMock()): 279 | self.bot.save() 280 | user = ModelUser.objects.create_user(**self.user_args) 281 | token = AuthToken.objects.create(user=user) 282 | self.assertTrue(token.expired()) 283 | self.client.login(username=self.user_args['username'], password=self.user_args['password']) 284 | self.client.get(self.auth_url) 285 | self.assertEqual(AuthToken.objects.count(), 1) 286 | new_token = AuthToken.objects.all()[0] 287 | self.assertNotEqual(token.key, new_token.key) 288 | self.assertEqual(user, new_token.user) 289 | 290 | def test_token_chat_association(self): 291 | with mock.patch("telegram.bot.Bot.setWebhook", callable=mock.MagicMock()): 292 | self.bot.save() 293 | user = ModelUser.objects.create_user(**self.user_args) 294 | token = AuthToken.objects.create(user=user) 295 | start_authenticated = {'in': '/start %s' % token.key, 296 | 'out': {'parse_mode': 'Markdown', 297 | 'reply_markup': '', 298 | 'text': "Start command" 299 | } 300 | } 301 | self._test_message_ok(start_authenticated) 302 | self.assertEqual(AuthToken.objects.count(), 1) 303 | token = AuthToken.objects.all()[0] 304 | self.assertEqual(token.chat_api.id, self.update.message.chat.id) 305 | -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from django.contrib import admin 3 | from django.conf.urls import include 4 | urlpatterns = [ 5 | url(r'^admin/', admin.site.urls), 6 | url(r'^telegrambot/', include('telegrambot.urls', namespace="telegrambot")), 7 | ] -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27, py34, py35 3 | 4 | [testenv] 5 | setenv = 6 | PYTHONPATH = {toxinidir}:{toxinidir}/telegrambot 7 | commands = python runtests.py 8 | deps = 9 | -r{toxinidir}/requirements/test.txt 10 | --------------------------------------------------------------------------------