├── .editorconfig ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── django_telegrambot ├── __init__.py ├── admin.py ├── apps.py ├── management │ ├── __init__.py │ └── commands │ │ ├── __init__.py │ │ └── botpolling.py ├── models.py ├── mqbot.py ├── static │ ├── css │ │ └── django_telegrambot.css │ ├── img │ │ └── .gitignore │ └── js │ │ └── django_telegrambot.js ├── templates │ └── django_telegrambot │ │ ├── base.html │ │ └── index.html ├── tests.py ├── urls.py └── views.py ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst └── usage.rst ├── example └── telegrambot.py ├── requirements-test.txt ├── requirements.txt ├── requirements_dev.txt ├── runtests.py ├── sampleproject ├── bot │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── telegrambot.py │ ├── templates │ │ ├── base_generic.html │ │ └── bot │ │ │ └── index.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py └── sampleproject │ ├── __init__.py │ ├── local_settings.sample.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── test_app │ ├── __init__.py │ └── telegrambot.py ├── test_apps.py ├── test_bad_app │ ├── __init__.py │ └── telegrambot.py └── test_models.py └── tox.ini /.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 | 39 | # Complexity 40 | output/*.html 41 | output/*/index.html 42 | 43 | # Sphinx 44 | docs/_build 45 | env/ 46 | .idea/ 47 | /sampleproject/sampleproject/local_settings.py 48 | /sampleproject/db.sqlite3 49 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | 3 | language: python 4 | 5 | python: 6 | - "2.7" 7 | - "3.4" 8 | - "3.5" 9 | - "3.6" 10 | - "pypy" 11 | 12 | before_install: 13 | - pip install codecov 14 | 15 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 16 | install: pip install -r requirements-test.txt 17 | 18 | # command to run tests using coverage, e.g. python setup.py test 19 | script: coverage run --source django_telegrambot runtests.py 20 | 21 | after_success: 22 | - codecov 23 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * django-telegrambot 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/JungDev/django-telegrambot/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-telegrambot could always use more documentation, whether as part of the 40 | official django-telegrambot 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/JungDev/django-telegrambot/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-telegrambot` for local development. 59 | 60 | 1. Fork the `django-telegrambot` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/django-telegrambot.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-telegrambot 68 | $ cd django-telegrambot/ 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 | $ flake8 django_telegrambot tests 81 | $ python setup.py test 82 | $ tox 83 | 84 | To get flake8 and tox, just pip install them into your virtualenv. 85 | 86 | 6. Commit your changes and push your branch to GitHub:: 87 | 88 | $ git add . 89 | $ git commit -m "Your detailed description of your changes." 90 | $ git push origin name-of-your-bugfix-or-feature 91 | 92 | 7. Submit a pull request through the GitHub website. 93 | 94 | Pull Request Guidelines 95 | ----------------------- 96 | 97 | Before you submit a pull request, check that it meets these guidelines: 98 | 99 | 1. The pull request should include tests. 100 | 2. If the pull request adds functionality, the docs should be updated. Put 101 | your new functionality into a function with a docstring, and add the 102 | feature to the list in README.rst. 103 | 3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check 104 | https://travis-ci.org/JungDev/django-telegrambot/pull_requests 105 | and make sure that the tests pass for all supported Python versions. 106 | 107 | Tips 108 | ---- 109 | 110 | To run a subset of tests:: 111 | 112 | $ python -m unittest tests.test_django_telegrambot 113 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 1.0.0 (2017-05-25) 6 | ++++++++++++++++++ 7 | * IMPORTANT: If you upgrade from a previous version, you MUST change how to include django_telegrambot.urls and settings.py. 8 | * Added admin dashboard, available at /admin/django-telegrambot 9 | * Added polling mode from management command (an easy to way to run bot in local machine, not recommended in production) 10 | * More setting available 11 | * Improved AppConfig 12 | * Improved sample project 13 | 14 | 0.2.6 (2017-04-08) 15 | ++++++++++++++++++ 16 | * Improved module loading 17 | * Added sample project 18 | 19 | 0.2.5 (2017-03-06) 20 | ++++++++++++++++++ 21 | * Fix compatibility with python-telegram-bot 5.1 22 | 23 | 0.2.4 (2016-10-04) 24 | ++++++++++++++++++ 25 | * Fix compatibility with Django 1.10 26 | 27 | 0.2.3 (2016-07-30) 28 | ++++++++++++++++++ 29 | * Fix default dispatcher and bot 30 | 31 | 0.2.2 (2016-07-27) 32 | ++++++++++++++++++ 33 | * Fix multi workers 34 | 35 | 0.2.1 (2016-07-24) 36 | ++++++++++++++++++ 37 | * Update for python-telegram-bot release v5.0 38 | 39 | 0.2.0 (2016-04-27) 40 | ++++++++++++++++++ 41 | 42 | * Update for python-telegram-bot release v4.0.1 43 | 44 | 0.1.8 (2016-03-22) 45 | ++++++++++++++++++ 46 | 47 | * Update for deprecation in python-telegram-bot release v3.4 48 | 49 | 0.1.5 (2016-01-28) 50 | ++++++++++++++++++ 51 | 52 | * Fix compatibility. 53 | 54 | 0.1.4 (2016-01-28) 55 | ++++++++++++++++++ 56 | 57 | * Fix compatibility. 58 | 59 | 0.1.3 (2016-01-28) 60 | ++++++++++++++++++ 61 | 62 | * Fix setting certificate. 63 | * Add method DjangoTelegramBot.getBot(); get bot instance by token or username. 64 | 65 | 0.1.2 (2016-01-26) 66 | ++++++++++++++++++ 67 | 68 | * First release on PyPI. 69 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016, django-telegrambot 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-telegrambot 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 django_telegrambot *.html *.png *.gif *js *.css *jpg *jpeg *svg *py 7 | recursive-include example *.py 8 | -------------------------------------------------------------------------------- /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 django_telegrambot tests 28 | 29 | test: 30 | python runtests.py tests 31 | 32 | test-all: 33 | tox 34 | 35 | coverage: 36 | coverage run --source django_telegrambot runtests.py tests 37 | coverage report -m 38 | coverage html 39 | open htmlcov/index.html 40 | 41 | docs: 42 | rm -f docs/django-telegrambot.rst 43 | rm -f docs/modules.rst 44 | sphinx-apidoc -o docs/ django_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 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============================= 2 | django-telegrambot 3 | ============================= 4 | 5 | .. image:: https://badge.fury.io/py/django-telegrambot.png 6 | :target: https://badge.fury.io/py/django-telegrambot 7 | 8 | .. image:: https://travis-ci.org/JungDev/django-telegrambot.png?branch=master 9 | :target: https://travis-ci.org/JungDev/django-telegrambot 10 | 11 | .. image:: https://img.shields.io/badge/Donate-PayPal-green.svg 12 | :target: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=LMXQVQ3YA2JJQ 13 | 14 | .. image:: http://pepy.tech/badge/django-telegrambot 15 | :target: http://pepy.tech/count/django-telegrambot 16 | 17 | A simple app to develop Telegram bots with Django 18 | 19 | Documentation 20 | ------------- 21 | 22 | The full documentation is at https://django-telegrambot.readthedocs.org. 23 | 24 | If this project help you reduce time to develop, you can give me a cup of coffee :) 25 | 26 | .. image:: https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif 27 | :target: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=LMXQVQ3YA2JJQ 28 | 29 | 30 | Changelog 31 | ------------ 32 | * **IMPORTANT ver 1.0.0** : If you upgrade from a previous version, you **MUST** change how to include ``django_telegrambot.urls`` and modify your ``settings.py``. 33 | 34 | 35 | Quickstart 36 | ---------- 37 | 38 | Install django-telegrambot:: 39 | 40 | pip install django-telegrambot 41 | 42 | Configure your installation 43 | --------------------------- 44 | 45 | Add ``django_telegrambot`` in ``INSTALLED_APPS`` :: 46 | 47 | #settings.py 48 | INSTALLED_APPS = ( 49 | ... 50 | 'django_telegrambot', 51 | ... 52 | ) 53 | 54 | And set your bots:: 55 | 56 | #settings.py 57 | #Django Telegram Bot settings 58 | 59 | DJANGO_TELEGRAMBOT = { 60 | 61 | 'MODE' : 'WEBHOOK', #(Optional [str]) # The default value is WEBHOOK, 62 | # otherwise you may use 'POLLING' 63 | # NB: if use polling you must provide to run 64 | # a management command that starts a worker 65 | 66 | 'WEBHOOK_SITE' : 'https://mywebsite.com', 67 | 'WEBHOOK_PREFIX' : '/prefix', # (Optional[str]) # If this value is specified, 68 | # a prefix is added to webhook url 69 | 70 | #'WEBHOOK_CERTIFICATE' : 'cert.pem', # If your site use self-signed 71 | #certificate, must be set with location of your public key 72 | #certificate.(More info at https://core.telegram.org/bots/self-signed ) 73 | 74 | 'STRICT_INIT': True, # If set to True, the server will fail to start if some of the 75 | # apps contain telegrambot.py files that cannot be successfully 76 | # imported. 77 | 78 | 'BOT_MODULE_NAME': 'telegrambot_handlers', #(Optional [str]) # The default name for file name containing telegram handlers which has to be placed inside your local app(s). Default is 'telegrambot'. Example is to put "telegrambot_handlers.py" file to local app's folder. 79 | 80 | 'BOTS' : [ 81 | { 82 | 'TOKEN': '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11', #Your bot token. 83 | 84 | #'CONTEXT': True, # Use context based handler functions 85 | 86 | #'ALLOWED_UPDATES':(Optional[list[str]]), # List the types of 87 | #updates you want your bot to receive. For example, specify 88 | #``["message", "edited_channel_post", "callback_query"]`` to 89 | #only receive updates of these types. See ``telegram.Update`` 90 | #for a complete list of available update types. 91 | #Specify an empty list to receive all updates regardless of type 92 | #(default). If not specified, the previous setting will be used. 93 | #Please note that this parameter doesn't affect updates created 94 | #before the call to the setWebhook, so unwanted updates may be 95 | #received for a short period of time. 96 | 97 | #'TIMEOUT':(Optional[int|float]), # If this value is specified, 98 | #use it as the read timeout from the server 99 | 100 | #'WEBHOOK_MAX_CONNECTIONS':(Optional[int]), # Maximum allowed number of 101 | #simultaneous HTTPS connections to the webhook for update 102 | #delivery, 1-100. Defaults to 40. Use lower values to limit the 103 | #load on your bot's server, and higher values to increase your 104 | #bot's throughput. 105 | 106 | # 'MESSAGEQUEUE_ENABLED':(Optinal[bool]), # Make this True if you want to use messagequeue 107 | 108 | # 'MESSAGEQUEUE_ALL_BURST_LIMIT':(Optional[int]), # If not provided 29 is the default value 109 | 110 | # 'MESSAGEQUEUE_ALL_TIME_LIMIT_MS':(Optional[int]), # If not provided 1024 is the default value 111 | 112 | # 'MESSAGEQUEUE_REQUEST_CON_POOL_SIZE':(Optional[int]), # If not provided 8 is the default value 113 | 114 | #'POLL_INTERVAL' : (Optional[float]), # Time to wait between polling updates from Telegram in 115 | #seconds. Default is 0.0 116 | 117 | #'POLL_CLEAN':(Optional[bool]), # Whether to clean any pending updates on Telegram servers before 118 | #actually starting to poll. Default is False. 119 | 120 | #'POLL_BOOTSTRAP_RETRIES':(Optional[int]), # Whether the bootstrapping phase of the `Updater` 121 | #will retry on failures on the Telegram server. 122 | #| < 0 - retry indefinitely 123 | #| 0 - no retries (default) 124 | #| > 0 - retry up to X times 125 | 126 | #'POLL_READ_LATENCY':(Optional[float|int]), # Grace time in seconds for receiving the reply from 127 | #server. Will be added to the `timeout` value and used as the read timeout from 128 | #server (Default: 2). 129 | }, 130 | #Other bots here with same structure. 131 | ], 132 | 133 | } 134 | 135 | 136 | 137 | Include in your urls.py the ``django_telegrambot.urls`` (NB: If you upgrade from a previous version, you MUST change how to include ``django_telegrambot.urls``. Never set prefix here!):: 138 | 139 | #urls.py 140 | urlpatterns = [ 141 | ... 142 | url(r'^', include('django_telegrambot.urls')), 143 | ... 144 | ] 145 | 146 | Then use it in a project creating a module ``telegrambot.py`` in your app :: 147 | 148 | #myapp/telegrambot.py 149 | # Example code for telegrambot.py module 150 | from telegram.ext import CommandHandler, MessageHandler, Filters 151 | from django_telegrambot.apps import DjangoTelegramBot 152 | 153 | import logging 154 | logger = logging.getLogger(__name__) 155 | 156 | 157 | # Define a few command handlers. These usually take the two arguments bot and 158 | # update. Error handlers also receive the raised TelegramError object in error. 159 | def start(bot, update): 160 | bot.sendMessage(update.message.chat_id, text='Hi!') 161 | 162 | 163 | def help(bot, update): 164 | bot.sendMessage(update.message.chat_id, text='Help!') 165 | 166 | 167 | def echo(bot, update): 168 | bot.sendMessage(update.message.chat_id, text=update.message.text) 169 | 170 | 171 | def error(bot, update, error): 172 | logger.warn('Update "%s" caused error "%s"' % (update, error)) 173 | 174 | 175 | def main(): 176 | logger.info("Loading handlers for telegram bot") 177 | 178 | # Default dispatcher (this is related to the first bot in settings.DJANGO_TELEGRAMBOT['BOTS']) 179 | dp = DjangoTelegramBot.dispatcher 180 | # To get Dispatcher related to a specific bot 181 | # dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token 182 | # dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username 183 | 184 | # on different commands - answer in Telegram 185 | dp.add_handler(CommandHandler("start", start)) 186 | dp.add_handler(CommandHandler("help", help)) 187 | 188 | # on noncommand i.e message - echo the message on Telegram 189 | dp.add_handler(MessageHandler([Filters.text], echo)) 190 | 191 | # log all errors 192 | dp.add_error_handler(error) 193 | 194 | 195 | 196 | Features 197 | -------- 198 | 199 | * Multiple bots 200 | * Admin dashboard available at ``/admin/django-telegrambot`` 201 | * Polling mode by management command (an easy to way to run bot in local machine, not recommended in production!) 202 | 203 | ``(myenv) $ python manage.py botpolling --username=`` 204 | * Supporting messagequeues 205 | 206 | Contributing 207 | ------------ 208 | 209 | Patches and bug reports are welcome, just please keep the style consistent with the original source. 210 | 211 | Running Tests 212 | -------------- 213 | 214 | Does the code actually work? 215 | 216 | :: 217 | 218 | source /bin/activate 219 | (myenv) $ pip install -r requirements-test.txt 220 | (myenv) $ python runtests.py 221 | 222 | Sample Application 223 | ------------------ 224 | There a sample application in `sampleproject` directory. Here is installation instructions: 225 | 226 | 1. Install requirements with command 227 | 228 | pip install -r requirements.txt 229 | 2. Copy file `local_settings.sample.py` as `local_settings.py` and edit your bot token 230 | 231 | cp sampleproject/local_settings.sample.py sampleproject/local_settings.py 232 | 233 | nano sampleproject/local_settings.py 234 | 3. Run Django migrations 235 | 236 | python manage.py migrate 237 | 4. Run server 238 | 239 | python manage.py runserver 240 | 5. If **WEBHOOK** Mode setted go to 8 241 | 242 | 6. If **POLLING** Mode setted, open in your browser http://localhost/ 243 | 244 | 7. Open Django-Telegram Dashboard http://localhost/admin/django-telegrambot and follow instruction to run worker by management command `botpolling`. Then go to 10 245 | 246 | 8. To test webhook locally install `ngrok` application and run command 247 | 248 | ./ngrok http 8000 249 | 9. Change `WEBHOOK_SITE` and `ALLOWED_HOSTS` in local_settings.py file 250 | 251 | 10. Start a chat with your bot using telegram.me link avaible in **Django-Telegram Dashboard** at http://localhost/admin/django-telegrambot 252 | 253 | Credits 254 | --------- 255 | Required package: 256 | 257 | * `Python Telegram Bot`_ 258 | 259 | .. _`Python Telegram Bot`: https://github.com/python-telegram-bot/python-telegram-bot 260 | 261 | Tools used in rendering this package: 262 | 263 | * Cookiecutter_ 264 | 265 | .. _Cookiecutter: https://github.com/audreyr/cookiecutter 266 | 267 | -------------------------------------------------------------------------------- /django_telegrambot/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '1.0.2' 2 | default_app_config = 'django_telegrambot.apps.DjangoTelegramBot' 3 | -------------------------------------------------------------------------------- /django_telegrambot/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /django_telegrambot/apps.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # django_telegram_bot/apps.py 3 | import os.path 4 | import importlib 5 | import telegram 6 | import logging 7 | from time import sleep 8 | 9 | from django.apps import AppConfig 10 | from django.apps import apps 11 | from django.conf import settings 12 | from django.utils.module_loading import module_has_submodule 13 | 14 | from telegram.ext import Dispatcher 15 | from telegram.ext import Updater 16 | from telegram.error import InvalidToken 17 | from telegram.error import RetryAfter 18 | from telegram.error import TelegramError 19 | from telegram.utils.request import Request 20 | from telegram.ext import messagequeue as mq 21 | 22 | from .mqbot import MQBot 23 | 24 | 25 | logger = logging.getLogger(__name__) 26 | 27 | 28 | TELEGRAM_BOT_MODULE_NAME = settings.DJANGO_TELEGRAMBOT.get('BOT_MODULE_NAME', 'telegrambot') 29 | WEBHOOK_MODE, POLLING_MODE = range(2) 30 | 31 | 32 | class classproperty(property): 33 | def __get__(self, obj, objtype=None): 34 | return super(classproperty, self).__get__(objtype) 35 | def __set__(self, obj, value): 36 | super(classproperty, self).__set__(type(obj), value) 37 | def __delete__(self, obj): 38 | super(classproperty, self).__delete__(type(obj)) 39 | 40 | 41 | class DjangoTelegramBot(AppConfig): 42 | 43 | name = 'django_telegrambot' 44 | verbose_name = 'Django TelegramBot' 45 | ready_run = False 46 | bot_tokens = [] 47 | bot_usernames = [] 48 | dispatchers = [] 49 | bots = [] 50 | updaters = [] 51 | __used_tokens = set() 52 | 53 | @classproperty 54 | def dispatcher(cls): 55 | #print("Getting value default dispatcher") 56 | cls.__used_tokens.add(cls.bot_tokens[0]) 57 | return cls.dispatchers[0] 58 | 59 | @classproperty 60 | def updater(cls): 61 | #print("Getting value default updater") 62 | cls.__used_tokens.add(cls.bot_tokens[0]) 63 | return cls.updaters[0] 64 | 65 | @classmethod 66 | def get_dispatcher(cls, bot_id=None, safe=True): 67 | if bot_id is None: 68 | cls.__used_tokens.add(cls.bot_tokens[0]) 69 | return cls.dispatchers[0] 70 | else: 71 | try: 72 | index = cls.bot_tokens.index(bot_id) 73 | except ValueError: 74 | if not safe: 75 | return None 76 | try: 77 | index = cls.bot_usernames.index(bot_id) 78 | except ValueError: 79 | return None 80 | cls.__used_tokens.add(cls.bot_tokens[index]) 81 | return cls.dispatchers[index] 82 | 83 | 84 | @classmethod 85 | def getDispatcher(cls, bot_id=None, safe=True): 86 | return cls.get_dispatcher(bot_id, safe) 87 | 88 | 89 | @classmethod 90 | def get_bot(cls, bot_id=None, safe=True): 91 | if bot_id is None: 92 | if safe: 93 | return cls.bots[0] 94 | else: 95 | return None 96 | else: 97 | try: 98 | index = cls.bot_tokens.index(bot_id) 99 | except ValueError: 100 | if not safe: 101 | return None 102 | try: 103 | index = cls.bot_usernames.index(bot_id) 104 | except ValueError: 105 | return None 106 | return cls.bots[index] 107 | 108 | 109 | @classmethod 110 | def getBot(cls, bot_id=None, safe=True): 111 | return cls.get_bot(bot_id, safe) 112 | 113 | 114 | @classmethod 115 | def get_updater(cls, bot_id=None, safe=True): 116 | if bot_id is None: 117 | return cls.updaters[0] 118 | else: 119 | try: 120 | index = cls.bot_tokens.index(bot_id) 121 | except ValueError: 122 | if not safe: 123 | return None 124 | try: 125 | index = cls.bot_usernames.index(bot_id) 126 | except ValueError: 127 | return None 128 | return cls.updaters[index] 129 | 130 | 131 | @classmethod 132 | def getUpdater(cls, id=None, safe=True): 133 | return cls.get_updater(id, safe) 134 | 135 | 136 | def ready(self): 137 | if DjangoTelegramBot.ready_run: 138 | return 139 | DjangoTelegramBot.ready_run = True 140 | 141 | self.mode = WEBHOOK_MODE 142 | if settings.DJANGO_TELEGRAMBOT.get('MODE', 'WEBHOOK') == 'POLLING': 143 | self.mode = POLLING_MODE 144 | 145 | modes = ['WEBHOOK','POLLING'] 146 | logger.info('Django Telegram Bot <{} mode>'.format(modes[self.mode])) 147 | 148 | bots_list = settings.DJANGO_TELEGRAMBOT.get('BOTS', []) 149 | 150 | if self.mode == WEBHOOK_MODE: 151 | webhook_site = settings.DJANGO_TELEGRAMBOT.get('WEBHOOK_SITE', None) 152 | if not webhook_site: 153 | logger.warn('Required TELEGRAM_WEBHOOK_SITE missing in settings') 154 | return 155 | if webhook_site.endswith("/"): 156 | webhook_site = webhook_site[:-1] 157 | 158 | webhook_base = settings.DJANGO_TELEGRAMBOT.get('WEBHOOK_PREFIX','/') 159 | if webhook_base.startswith("/"): 160 | webhook_base = webhook_base[1:] 161 | if webhook_base.endswith("/"): 162 | webhook_base = webhook_base[:-1] 163 | 164 | cert = settings.DJANGO_TELEGRAMBOT.get('WEBHOOK_CERTIFICATE', None) 165 | certificate = None 166 | if cert and os.path.exists(cert): 167 | logger.info('WEBHOOK_CERTIFICATE found in {}'.format(cert)) 168 | certificate=open(cert, 'rb') 169 | elif cert: 170 | logger.error('WEBHOOK_CERTIFICATE not found in {} '.format(cert)) 171 | 172 | for b in bots_list: 173 | token = b.get('TOKEN', None) 174 | context = b.get('CONTEXT', False) 175 | if not token: 176 | break 177 | 178 | allowed_updates = b.get('ALLOWED_UPDATES', None) 179 | timeout = b.get('TIMEOUT', None) 180 | proxy = b.get('PROXY', None) 181 | 182 | if self.mode == WEBHOOK_MODE: 183 | try: 184 | if b.get('MESSAGEQUEUE_ENABLED',False): 185 | q = mq.MessageQueue(all_burst_limit=b.get('MESSAGEQUEUE_ALL_BURST_LIMIT',29), 186 | all_time_limit_ms=b.get('MESSAGEQUEUE_ALL_TIME_LIMIT_MS',1024)) 187 | if proxy: 188 | request = Request(proxy_url=proxy['proxy_url'], urllib3_proxy_kwargs=proxy['urllib3_proxy_kwargs'], con_pool_size=b.get('MESSAGEQUEUE_REQUEST_CON_POOL_SIZE',8)) 189 | else: 190 | request = Request(con_pool_size=b.get('MESSAGEQUEUE_REQUEST_CON_POOL_SIZE',8)) 191 | bot = MQBot(token, request=request, mqueue=q) 192 | else: 193 | request = None 194 | if proxy: 195 | request = Request(proxy_url=proxy['proxy_url'], urllib3_proxy_kwargs=proxy['urllib3_proxy_kwargs']) 196 | bot = telegram.Bot(token=token, request=request) 197 | 198 | DjangoTelegramBot.dispatchers.append(Dispatcher(bot, None, workers=0, use_context=context)) 199 | hookurl = '{}/{}/{}/'.format(webhook_site, webhook_base, token) 200 | max_connections = b.get('WEBHOOK_MAX_CONNECTIONS', 40) 201 | setted = bot.setWebhook(hookurl, certificate=certificate, timeout=timeout, max_connections=max_connections, allowed_updates=allowed_updates) 202 | webhook_info = bot.getWebhookInfo() 203 | real_allowed = webhook_info.allowed_updates if webhook_info.allowed_updates else ["ALL"] 204 | 205 | bot.more_info = webhook_info 206 | logger.info('Telegram Bot <{}> setting webhook [ {} ] max connections:{} allowed updates:{} pending updates:{} : {}'.format(bot.username, webhook_info.url, webhook_info.max_connections, real_allowed, webhook_info.pending_update_count, setted)) 207 | 208 | except InvalidToken: 209 | logger.error('Invalid Token : {}'.format(token)) 210 | return 211 | except RetryAfter as er: 212 | logger.debug('Error: "{}". Will retry in {} seconds'.format( 213 | er.message, 214 | er.retry_after 215 | ) 216 | ) 217 | sleep(er.retry_after) 218 | self.ready() 219 | except TelegramError as er: 220 | logger.error('Error: "{}"'.format(er.message)) 221 | return 222 | 223 | else: 224 | try: 225 | updater = Updater(token=token, request_kwargs=proxy, use_context=context) 226 | bot = updater.bot 227 | bot.delete_webhook() 228 | DjangoTelegramBot.updaters.append(updater) 229 | DjangoTelegramBot.dispatchers.append(updater.dispatcher) 230 | DjangoTelegramBot.__used_tokens.add(token) 231 | except InvalidToken: 232 | logger.error('Invalid Token : {}'.format(token)) 233 | return 234 | except RetryAfter as er: 235 | logger.debug('Error: "{}". Will retry in {} seconds'.format( 236 | er.message, 237 | er.retry_after 238 | ) 239 | ) 240 | sleep(er.retry_after) 241 | self.ready() 242 | except TelegramError as er: 243 | logger.error('Error: "{}"'.format(er.message)) 244 | return 245 | 246 | DjangoTelegramBot.bots.append(bot) 247 | DjangoTelegramBot.bot_tokens.append(token) 248 | DjangoTelegramBot.bot_usernames.append(bot.username) 249 | 250 | 251 | logger.debug('Telegram Bot <{}> set as default bot'.format(DjangoTelegramBot.bots[0].username)) 252 | 253 | def module_imported(module_name, method_name, execute): 254 | try: 255 | m = importlib.import_module(module_name) 256 | if execute and hasattr(m, method_name): 257 | logger.debug('Run {}.{}()'.format(module_name,method_name)) 258 | getattr(m, method_name)() 259 | else: 260 | logger.debug('Run {}'.format(module_name)) 261 | 262 | except ImportError as er: 263 | if settings.DJANGO_TELEGRAMBOT.get('STRICT_INIT'): 264 | raise er 265 | else: 266 | logger.error('{} : {}'.format(module_name, repr(er))) 267 | return False 268 | 269 | return True 270 | 271 | # import telegram bot handlers for all INSTALLED_APPS 272 | for app_config in apps.get_app_configs(): 273 | if module_has_submodule(app_config.module, TELEGRAM_BOT_MODULE_NAME): 274 | module_name = '%s.%s' % (app_config.name, TELEGRAM_BOT_MODULE_NAME) 275 | if module_imported(module_name, 'main', True): 276 | logger.info('Loaded {}'.format(module_name)) 277 | 278 | num_bots=len(DjangoTelegramBot.__used_tokens) 279 | if self.mode == POLLING_MODE and num_bots>0: 280 | logger.info('Please manually start polling update for {0} bot{1}. Run command{1}:'.format(num_bots, 's' if num_bots>1 else '')) 281 | for token in DjangoTelegramBot.__used_tokens: 282 | updater = DjangoTelegramBot.get_updater(bot_id=token) 283 | logger.info('python manage.py botpolling --username={}'.format(updater.bot.username)) 284 | -------------------------------------------------------------------------------- /django_telegrambot/management/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JungDev/django-telegrambot/00d41354bd472fae6435642e4ea366d8e5b044f5/django_telegrambot/management/__init__.py -------------------------------------------------------------------------------- /django_telegrambot/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JungDev/django-telegrambot/00d41354bd472fae6435642e4ea366d8e5b044f5/django_telegrambot/management/commands/__init__.py -------------------------------------------------------------------------------- /django_telegrambot/management/commands/botpolling.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from django.core.management.base import BaseCommand 4 | #from telegram.ext import Updater 5 | 6 | from django_telegrambot.apps import DjangoTelegramBot 7 | 8 | 9 | class Command(BaseCommand): 10 | help = "Run telegram bot in polling mode" 11 | can_import_settings = True 12 | 13 | def add_arguments(self, parser): 14 | parser.add_argument('--username', '-i', help="Bot username", default=None) 15 | parser.add_argument('--token', '-t', help="Bot token", default=None) 16 | pass 17 | 18 | def get_updater(self, username=None, token=None): 19 | updater = None 20 | if username is not None: 21 | updater = DjangoTelegramBot.get_updater(bot_id=username) 22 | if not updater: 23 | self.stderr.write("Cannot find default bot with username {}".format(username)) 24 | elif token: 25 | updater = DjangoTelegramBot.get_updater(bot_id=token) 26 | if not updater: 27 | self.stderr.write("Cannot find bot with token {}".format(token)) 28 | return updater 29 | 30 | def handle(self, *args, **options): 31 | from django.conf import settings 32 | if settings.DJANGO_TELEGRAMBOT.get('MODE', 'WEBHOOK') == 'WEBHOOK': 33 | self.stderr.write("Webhook mode active in settings.py, change in POLLING if you want use polling update") 34 | return 35 | 36 | updater = self.get_updater(username=options.get('username'), token=options.get('token')) 37 | if not updater: 38 | self.stderr.write("Bot not found") 39 | return 40 | # Enable Logging 41 | logging.basicConfig( 42 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 43 | level=logging.INFO) 44 | logger = logging.getLogger("telegrambot") 45 | logger.setLevel(logging.INFO) 46 | console = logging.StreamHandler() 47 | console.setLevel(logging.INFO) 48 | console.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s')) 49 | logger.addHandler(console) 50 | 51 | 52 | bots_list = settings.DJANGO_TELEGRAMBOT.get('BOTS', []) 53 | b = None 54 | for bot_set in bots_list: 55 | if bot_set.get('TOKEN', None) == updater.bot.token: 56 | b = bot_set 57 | break 58 | if not b: 59 | self.stderr.write("Cannot find bot settings") 60 | return 61 | 62 | allowed_updates = b.get('ALLOWED_UPDATES', None) 63 | timeout = b.get('TIMEOUT', 10) 64 | poll_interval = b.get('POLL_INTERVAL', 0.0) 65 | clean = b.get('POLL_CLEAN', False) 66 | bootstrap_retries = b.get('POLL_BOOTSTRAP_RETRIES', 0) 67 | read_latency = b.get('POLL_READ_LATENCY', 2.) 68 | 69 | self.stdout.write("Run polling...") 70 | updater.start_polling(poll_interval=poll_interval, 71 | timeout=timeout, 72 | clean=clean, 73 | bootstrap_retries=bootstrap_retries, 74 | read_latency=read_latency, 75 | allowed_updates=allowed_updates) 76 | self.stdout.write("the bot is started and runs until we press Ctrl-C on the command line.") 77 | updater.idle() -------------------------------------------------------------------------------- /django_telegrambot/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. -------------------------------------------------------------------------------- /django_telegrambot/mqbot.py: -------------------------------------------------------------------------------- 1 | from telegram.ext import messagequeue as mq 2 | import telegram 3 | 4 | class MQBot(telegram.bot.Bot): 5 | '''A subclass of Bot which delegates send method handling to MQ''' 6 | def __init__(self, mqueue=None, is_queued_def=True, *args, **kwargs): 7 | super(MQBot, self).__init__(*args, **kwargs) 8 | # below 2 attributes should be provided for decorator usage 9 | self._is_messages_queued_default = is_queued_def 10 | self._msg_queue = mqueue or mq.MessageQueue() 11 | 12 | def __del__(self): 13 | try: 14 | self._msg_queue.stop() 15 | except: 16 | pass 17 | super(MQBot, self).__del__() 18 | 19 | @mq.queuedmessage 20 | def send_message(self, *args, **kwargs): 21 | '''Wrapped method would accept new `queued` and `isgroup` 22 | OPTIONAL arguments''' 23 | return super(MQBot, self).send_message(*args, **kwargs) 24 | 25 | @mq.queuedmessage 26 | def edit_message_text(self, *args, **kwargs): 27 | 28 | '''Wrapped method would accept new `queued` and `isgroup` 29 | OPTIONAL arguments''' 30 | return super(MQBot, self).edit_message_text(*args, **kwargs) 31 | -------------------------------------------------------------------------------- /django_telegrambot/static/css/django_telegrambot.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JungDev/django-telegrambot/00d41354bd472fae6435642e4ea366d8e5b044f5/django_telegrambot/static/css/django_telegrambot.css -------------------------------------------------------------------------------- /django_telegrambot/static/img/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JungDev/django-telegrambot/00d41354bd472fae6435642e4ea366d8e5b044f5/django_telegrambot/static/img/.gitignore -------------------------------------------------------------------------------- /django_telegrambot/static/js/django_telegrambot.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JungDev/django-telegrambot/00d41354bd472fae6435642e4ea366d8e5b044f5/django_telegrambot/static/js/django_telegrambot.js -------------------------------------------------------------------------------- /django_telegrambot/templates/django_telegrambot/base.html: -------------------------------------------------------------------------------- 1 | 2 | {% comment %} 3 | As the developer of this package, don't place anything here if you can help it 4 | since this allows developers to have interoperability between your template 5 | structure and their own. 6 | 7 | Example: Developer melding the 2SoD pattern to fit inside with another pattern:: 8 | 9 | {% extends "base.html" %} 10 | {% load static %} 11 | 12 | 13 | {% block extra_js %} 14 | 15 | 16 | {% block javascript %} 17 | 18 | {% endblock javascript %} 19 | 20 | {% endblock extra_js %} 21 | {% endcomment %} 22 | -------------------------------------------------------------------------------- /django_telegrambot/templates/django_telegrambot/index.html: -------------------------------------------------------------------------------- 1 | {% extends "admin/index.html" %} 2 | {% block extrastyle %} 3 | {{ block.super }} 4 | 5 | 21 | {% endblock %} 22 | {% block extrahead %} 23 | 24 | 25 | 26 | 27 | 28 | 42 | {% endblock %} 43 | {% block breadcrumbs %} 44 | 48 | {% endblock %} 49 | {% block content %} 50 | 51 | 52 | {{ block.super }} 53 |
54 |

Django-TelegramBot

55 |

56 | The full documentation is at https://django-telegrambot.readthedocs.org. 57 |

58 |

Bot update mode: {{update_mode}}

59 | {% if update_mode == 'POLLING' %}

Please remember to start polling mode with commands: 60 |

    61 | {% for bot in bot_list %} 62 |
  • 63 | $ python manage.py botpolling --username={{bot.username}} 64 | 67 |
  • 68 | {% endfor %} 69 |
70 |

71 | {% endif %} 72 | 73 | {% if bot_list %} 74 |

Bot List:

75 | 83 | {% else %} 84 |

No bots are available. Please configure it in settings.py

85 | {% endif %} 86 |
87 | 88 | {% endblock %} 89 | -------------------------------------------------------------------------------- /django_telegrambot/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /django_telegrambot/urls.py: -------------------------------------------------------------------------------- 1 | 2 | from django.urls import re_path 3 | from . import views 4 | from django.conf import settings 5 | 6 | webhook_base = settings.DJANGO_TELEGRAMBOT.get('WEBHOOK_PREFIX','/') 7 | if webhook_base.startswith("/"): 8 | webhook_base = webhook_base[1:] 9 | if not webhook_base.endswith("/"): 10 | webhook_base += "/" 11 | 12 | urlpatterns = [ 13 | re_path(r'admin/django-telegrambot/$', views.home, name='django-telegrambot'), 14 | re_path(r'{}(?P.+?)/$'.format(webhook_base), views.webhook, name='webhook'), 15 | ] 16 | -------------------------------------------------------------------------------- /django_telegrambot/views.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from django.shortcuts import render 3 | from django.contrib.admin.views.decorators import staff_member_required 4 | from django.conf import settings 5 | from django.http import JsonResponse 6 | from django_telegrambot.apps import DjangoTelegramBot 7 | from django.views.decorators.csrf import csrf_exempt 8 | import sys 9 | import json 10 | import telegram 11 | from telegram.error import (TelegramError, Unauthorized, BadRequest, 12 | TimedOut, ChatMigrated, NetworkError) 13 | # import the logging library 14 | import logging 15 | 16 | # Get an instance of a logger 17 | logger = logging.getLogger(__name__) 18 | 19 | 20 | @staff_member_required 21 | def home(request): 22 | bot_list = DjangoTelegramBot.bots 23 | context = {'bot_list': bot_list, 'update_mode':settings.DJANGO_TELEGRAMBOT.get('MODE', 'WEBHOOK')} 24 | return render(request, 'django_telegrambot/index.html', context) 25 | 26 | 27 | @csrf_exempt 28 | def webhook (request, bot_token): 29 | 30 | #verifico la validità del token 31 | bot = DjangoTelegramBot.getBot(bot_id=bot_token, safe=False) 32 | if bot is None: 33 | logger.warn('Request for not found token: {}'.format(bot_token)) 34 | return JsonResponse({}) 35 | 36 | try: 37 | data = json.loads(request.body.decode("utf-8")) 38 | 39 | except: 40 | logger.warn('Telegram bot <{}> receive invalid request: {}'.format(bot.username, repr(request))) 41 | return JsonResponse({}) 42 | 43 | dispatcher = DjangoTelegramBot.getDispatcher(bot_token, safe=False) 44 | if dispatcher is None: 45 | logger.error('Dispatcher for bot <{}> not found: {}'.format(bot.username, bot_token)) 46 | return JsonResponse({}) 47 | 48 | try: 49 | update = telegram.Update.de_json(data, bot) 50 | dispatcher.process_update(update) 51 | logger.debug('Bot <{}> : Processed update {}'.format(bot.username, update)) 52 | # Dispatch any errors 53 | except TelegramError as te: 54 | logger.warn("Bot <{}> : Error was raised while processing Update.".format(bot.username)) 55 | dispatcher.dispatchError(update, te) 56 | 57 | # All other errors should not stop the thread, just print them 58 | except: 59 | logger.error("Bot <{}> : An uncaught error was raised while processing an update\n{}".format(bot.username, sys.exc_info()[0])) 60 | 61 | finally: 62 | return JsonResponse({}) 63 | -------------------------------------------------------------------------------- /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 django_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-telegrambot' 50 | copyright = u'2016, django-telegrambot' 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 = django_telegrambot.__version__ 58 | # The full version, including alpha/beta/rc tags. 59 | release = django_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-telegrambotdoc' 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-telegrambot.tex', u'django-telegrambot Documentation', 196 | u'django-telegrambot', '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-telegrambot', u'django-telegrambot Documentation', 226 | [u'django-telegrambot'], 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-telegrambot', u'django-telegrambot Documentation', 240 | u'django-telegrambot', 'django-telegrambot', '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-telegrambot'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 | $ easy_install django-telegrambot 8 | 9 | Or, if you have virtualenvwrapper installed:: 10 | 11 | $ mkvirtualenv django-telegrambot 12 | $ pip install django-telegrambot 13 | -------------------------------------------------------------------------------- /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/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Usage 3 | ======== 4 | 5 | To use django-telegrambot in a app, create a telegrambot.py module in your app as follow:: 6 | 7 | # Example code for telegrambot.py module 8 | from telegram.ext import CommandHandler, MessageHandler, Filters 9 | from django_telegrambot.apps import DjangoTelegramBot 10 | 11 | import logging 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | # Define a few command handlers. These usually take the two arguments bot and 16 | # update. Error handlers also receive the raised TelegramError object in error. 17 | def start(bot, update): 18 | bot.sendMessage(update.message.chat_id, text='Hi!') 19 | 20 | 21 | def help(bot, update): 22 | bot.sendMessage(update.message.chat_id, text='Help!') 23 | 24 | 25 | def echo(bot, update): 26 | bot.sendMessage(update.message.chat_id, text=update.message.text) 27 | 28 | 29 | def error(bot, update, error): 30 | logger.warn('Update "%s" caused error "%s"' % (update, error)) 31 | 32 | 33 | def main(): 34 | logger.info("Loading handlers for telegram bot") 35 | 36 | # Default dispatcher (this is related to the first bot in settings.DJANGO_TELEGRAMBOT['BOTS']) 37 | dp = DjangoTelegramBot.dispatcher 38 | # To get Dispatcher related to a specific bot 39 | # dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token 40 | # dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username 41 | 42 | # on different commands - answer in Telegram 43 | dp.add_handler(CommandHandler("start", start)) 44 | dp.add_handler(CommandHandler("help", help)) 45 | 46 | # on noncommand i.e message - echo the message on Telegram 47 | dp.add_handler(MessageHandler([Filters.text], echo)) 48 | 49 | # log all errors 50 | dp.add_error_handler(error) 51 | -------------------------------------------------------------------------------- /example/telegrambot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Example code for telegrambot.py module 3 | from telegram.ext import CommandHandler, MessageHandler, Filters 4 | from django_telegrambot.apps import DjangoTelegramBot 5 | 6 | import logging 7 | logger = logging.getLogger(__name__) 8 | 9 | 10 | # Define a few command handlers. These usually take the two arguments bot and 11 | # update. Error handlers also receive the raised TelegramError object in error. 12 | def start(update, context): 13 | context.bot.sendMessage(update.message.chat_id, text='Hi!') 14 | 15 | 16 | def help(update, context): 17 | context.bot.sendMessage(update.message.chat_id, text='Help!') 18 | 19 | 20 | def echo(update, context): 21 | context.bot.sendMessage(update.message.chat_id, text=update.message.text) 22 | 23 | 24 | def error(update, context, error): 25 | logger.warn('Update "%s" caused error "%s"' % (update, error)) 26 | 27 | 28 | def main(): 29 | logger.info("Loading handlers for telegram bot") 30 | 31 | # Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS) 32 | dp = DjangoTelegramBot.dispatcher 33 | # To get Dispatcher related to a specific bot 34 | # dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token 35 | # dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username 36 | 37 | # on different commands - answer in Telegram 38 | dp.add_handler(CommandHandler("start", start)) 39 | dp.add_handler(CommandHandler("help", help)) 40 | 41 | # on noncommand i.e message - echo the message on Telegram 42 | dp.add_handler(MessageHandler([Filters.text], echo)) 43 | 44 | # log all errors 45 | dp.add_error_handler(error) 46 | 47 | # log all errors 48 | dp.addErrorHandler(error) 49 | 50 | -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | django>=1.8.0 2 | coverage 3 | mock>=1.0.1 4 | flake8>=2.1.0 5 | tox>=1.7.0 6 | 7 | # Additional test requirements go here 8 | python-telegram-bot>=3.2.0 9 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | django>=1.8.18 2 | # Additional requirements go here 3 | python-telegram-bot>=6.0.1 4 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | bumpversion==0.5.3 2 | wheel==0.38.1 3 | -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | try: 4 | from django.conf import settings 5 | from django.test.utils import get_runner 6 | 7 | settings.configure( 8 | DEBUG=True, 9 | USE_TZ=True, 10 | DATABASES={ 11 | "default": { 12 | "ENGINE": "django.db.backends.sqlite3", 13 | } 14 | }, 15 | ROOT_URLCONF="django_telegrambot.urls", 16 | INSTALLED_APPS=[ 17 | "django.contrib.auth", 18 | "django.contrib.contenttypes", 19 | "django.contrib.sites", 20 | "django_telegrambot", 21 | ], 22 | SITE_ID=1, 23 | MIDDLEWARE_CLASSES=(), 24 | DJANGO_TELEGRAMBOT = { 25 | 'MODE' : 'POLLING', #(Optional [str]) # The default value is WEBHOOK, 26 | # otherwise you may use 'POLLING' 27 | # NB: if use polling you must provide to run 28 | # a management command that starts a worker 29 | 'BOTS' : [ 30 | { 31 | 'TOKEN': '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11', #Your bot token. 32 | }, 33 | ], 34 | }, 35 | ) 36 | 37 | try: 38 | import django 39 | setup = django.setup 40 | except AttributeError: 41 | pass 42 | else: 43 | setup() 44 | 45 | except ImportError: 46 | import traceback 47 | traceback.print_exc() 48 | raise ImportError("To fix this error, run: pip install -r requirements-test.txt") 49 | 50 | 51 | def run_tests(*test_args): 52 | if not test_args: 53 | test_args = ['tests'] 54 | 55 | # Run tests 56 | TestRunner = get_runner(settings) 57 | test_runner = TestRunner() 58 | 59 | failures = test_runner.run_tests(test_args) 60 | 61 | if failures: 62 | sys.exit(bool(failures)) 63 | 64 | 65 | if __name__ == '__main__': 66 | run_tests(*sys.argv[1:]) 67 | -------------------------------------------------------------------------------- /sampleproject/bot/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JungDev/django-telegrambot/00d41354bd472fae6435642e4ea366d8e5b044f5/sampleproject/bot/__init__.py -------------------------------------------------------------------------------- /sampleproject/bot/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /sampleproject/bot/apps.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.apps import AppConfig 4 | 5 | 6 | class BotConfig(AppConfig): 7 | name = 'bot' 8 | -------------------------------------------------------------------------------- /sampleproject/bot/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JungDev/django-telegrambot/00d41354bd472fae6435642e4ea366d8e5b044f5/sampleproject/bot/migrations/__init__.py -------------------------------------------------------------------------------- /sampleproject/bot/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.db import models 4 | 5 | # Create your models here. 6 | -------------------------------------------------------------------------------- /sampleproject/bot/telegrambot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Example code for telegrambot.py module 3 | from telegram.ext import CommandHandler, MessageHandler, Filters 4 | from django_telegrambot.apps import DjangoTelegramBot 5 | 6 | import logging 7 | logger = logging.getLogger(__name__) 8 | 9 | 10 | # Define a few command handlers. These usually take the two arguments bot and 11 | # update. Error handlers also receive the raised TelegramError object in error. 12 | def start(bot, update): 13 | bot.sendMessage(update.message.chat_id, text='Hi!') 14 | 15 | 16 | def startgroup(bot, update): 17 | bot.sendMessage(update.message.chat_id, text='Hi!') 18 | 19 | 20 | def me(bot, update): 21 | bot.sendMessage(update.message.chat_id, text='Your information:\n{}'.format(update.effective_user)) 22 | 23 | 24 | def chat(bot, update): 25 | bot.sendMessage(update.message.chat_id, text='This chat information:\n {}'.format(update.effective_chat)) 26 | 27 | 28 | def forwarded(bot, update): 29 | bot.sendMessage(update.message.chat_id, text='This msg forwaded information:\n {}'.format(update.effective_message)) 30 | 31 | 32 | def help(bot, update): 33 | bot.sendMessage(update.message.chat_id, text='Help!') 34 | 35 | 36 | def echo(bot, update): 37 | update.message.reply_text(update.message.text) 38 | 39 | 40 | def error(bot, update, error): 41 | logger.warn('Update "%s" caused error "%s"' % (update, error)) 42 | 43 | 44 | def main(): 45 | logger.info("Loading handlers for telegram bot") 46 | 47 | # Default dispatcher (this is related to the first bot in settings.TELEGRAM_BOT_TOKENS) 48 | dp = DjangoTelegramBot.dispatcher 49 | # To get Dispatcher related to a specific bot 50 | # dp = DjangoTelegramBot.getDispatcher('BOT_n_token') #get by bot token 51 | # dp = DjangoTelegramBot.getDispatcher('BOT_n_username') #get by bot username 52 | 53 | # on different commands - answer in Telegram 54 | dp.add_handler(CommandHandler("start", start)) 55 | dp.add_handler(CommandHandler("help", help)) 56 | 57 | dp.add_handler(CommandHandler("startgroup", startgroup)) 58 | dp.add_handler(CommandHandler("me", me)) 59 | dp.add_handler(CommandHandler("chat", chat)) 60 | dp.add_handler(MessageHandler(Filters.forwarded , forwarded)) 61 | 62 | # on noncommand i.e message - echo the message on Telegram 63 | dp.add_handler(MessageHandler(Filters.text, echo)) 64 | 65 | # log all errors 66 | dp.add_error_handler(error) 67 | 68 | 69 | -------------------------------------------------------------------------------- /sampleproject/bot/templates/base_generic.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {% block title %}Django-Telegrambot{% endblock %} 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | {% load static %} 13 | 14 | 29 | 30 | 31 | 32 |
33 | 34 |
35 |
36 | {% block sidebar %} 37 | 40 | {% endblock %} 41 |
42 |
43 | {% block content %}{% endblock %} 44 |
45 |
46 |
47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /sampleproject/bot/templates/bot/index.html: -------------------------------------------------------------------------------- 1 | {% extends "base_generic.html" %} 2 | 3 | {% block content %} 4 | 5 |

Django-TelegramBot Sample App

6 |

7 | Welcome in the sample project of Django-Telegrambot, aka how add Telegram bots to your Django app! 8 |
9 | The full documentation is at https://django-telegrambot.readthedocs.org. 10 |

11 |

Visit Django-Telegrambot Dashboard to see more info about your telegram bots

12 | 13 | {% endblock %} 14 | -------------------------------------------------------------------------------- /sampleproject/bot/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /sampleproject/bot/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import re_path 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | re_path(r'^$', views.index, name='index'), 7 | ] 8 | -------------------------------------------------------------------------------- /sampleproject/bot/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.conf import settings 3 | from django_telegrambot.apps import DjangoTelegramBot 4 | 5 | # Create your views here. 6 | def index(request): 7 | bot_list = DjangoTelegramBot.bots 8 | context = {'bot_list': bot_list, 'update_mode':settings.DJANGO_TELEGRAMBOT['MODE']} 9 | return render(request, 'bot/index.html', context) 10 | -------------------------------------------------------------------------------- /sampleproject/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 6 | sys.path.append(path) 7 | 8 | if __name__ == "__main__": 9 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sampleproject.settings") 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError: 13 | # The above import may fail for some other reason. Ensure that the 14 | # issue is really that Django is missing to avoid masking other 15 | # exceptions on Python 2. 16 | try: 17 | import django 18 | except ImportError: 19 | raise ImportError( 20 | "Couldn't import Django. Are you sure it's installed and " 21 | "available on your PYTHONPATH environment variable? Did you " 22 | "forget to activate a virtual environment?" 23 | ) 24 | raise 25 | execute_from_command_line(sys.argv) 26 | -------------------------------------------------------------------------------- /sampleproject/sampleproject/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JungDev/django-telegrambot/00d41354bd472fae6435642e4ea366d8e5b044f5/sampleproject/sampleproject/__init__.py -------------------------------------------------------------------------------- /sampleproject/sampleproject/local_settings.sample.py: -------------------------------------------------------------------------------- 1 | #settings.py 2 | DJANGO_TELEGRAMBOT = { 3 | 4 | 'MODE' : 'WEBHOOK', #(Optional [str]) # The default value is WEBHOOK, 5 | # otherwise you may use 'POLLING' 6 | # NB: if use polling mode you must provide to run 7 | # a management command that starts a worker 8 | 9 | 'WEBHOOK_SITE' : 'https://mywebsite.com', 10 | 'WEBHOOK_PREFIX' : '/prefix', # (Optional[str]) # If this value is specified, 11 | # a prefix is added to webhook url 12 | 13 | #'WEBHOOK_CERTIFICATE' : 'cert.pem', # If your site use self-signed 14 | #certificate, must be set with location of your public key 15 | #certificate.(More info at https://core.telegram.org/bots/self-signed ) 16 | 17 | 'BOTS' : [ 18 | { 19 | 'TOKEN': '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11', #Your bot token. 20 | 21 | #'ALLOWED_UPDATES':(Optional[list[str]]), # List the types of 22 | #updates you want your bot to receive. For example, specify 23 | #``["message", "edited_channel_post", "callback_query"]`` to 24 | #only receive updates of these types. See ``telegram.Update`` 25 | #for a complete list of available update types. 26 | #Specify an empty list to receive all updates regardless of type 27 | #(default). If not specified, the previous setting will be used. 28 | #Please note that this parameter doesn't affect updates created 29 | #before the call to the setWebhook, so unwanted updates may be 30 | #received for a short period of time. 31 | 32 | #'TIMEOUT':(Optional[int|float]), # If this value is specified, 33 | #use it as the read timeout from the server 34 | 35 | #'WEBHOOK_MAX_CONNECTIONS':(Optional[int]), # Maximum allowed number of 36 | #simultaneous HTTPS connections to the webhook for update 37 | #delivery, 1-100. Defaults to 40. Use lower values to limit the 38 | #load on your bot's server, and higher values to increase your 39 | #bot's throughput. 40 | 41 | #'POLL_INTERVAL' : (Optional[float]), # Time to wait between polling updates from Telegram in 42 | #seconds. Default is 0.0 43 | 44 | #'POLL_CLEAN':(Optional[bool]), # Whether to clean any pending updates on Telegram servers before 45 | #actually starting to poll. Default is False. 46 | 47 | #'POLL_BOOTSTRAP_RETRIES':(Optional[int]), # Whether the bootstrapping phase of the `Updater` 48 | #will retry on failures on the Telegram server. 49 | #| < 0 - retry indefinitely 50 | #| 0 - no retries (default) 51 | #| > 0 - retry up to X times 52 | 53 | #'POLL_READ_LATENCY':(Optional[float|int]), # Grace time in seconds for receiving the reply from 54 | #server. Will be added to the `timeout` value and used as the read timeout from 55 | #server (Default: 2). 56 | 57 | #'PROXY':(Optional[dict]), # Use proxy to communicate with Telegram API server. Example: 58 | # { 59 | # 'proxy_url': 'socks5://ip:port', 60 | # 'urllib3_proxy_kwargs': { 61 | # 'username': 'username', 62 | # 'password': 'password' 63 | # } 64 | # } 65 | #Default is not to use any proxy. 66 | 67 | }, 68 | #Other bots here with same structure. 69 | ], 70 | 71 | } 72 | 73 | ALLOWED_HOSTS = ['', ] 74 | -------------------------------------------------------------------------------- /sampleproject/sampleproject/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for sampleproject project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.10.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.10/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.10/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '2+(!v-t9)skqad%3637&#kj+!04!74q$ja@@ccavtf(h0)%1x!' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'bot', 41 | 'django_telegrambot', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'sampleproject.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'sampleproject.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/1.10/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/1.10/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/1.10/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | LOGGING = { 125 | 'version': 1, 126 | 'disable_existing_loggers': False, 127 | 'formatters': { 128 | 'verbose': { 129 | 'format': '%(levelname)s %(asctime)s %(module)s %(message)s' 130 | }, 131 | 'simple': { 132 | 'format': '%(levelname)s %(message)s' 133 | }, 134 | }, 135 | 'handlers': { 136 | 'console': { 137 | 'level': 'INFO', 138 | 'class': 'logging.StreamHandler', 139 | 'formatter': 'verbose', 140 | }, 141 | }, 142 | 'loggers': { 143 | '': { 144 | 'handlers': ['console'], 145 | 'level': 'INFO', 146 | 'propagate': True, 147 | }, 148 | }, 149 | } 150 | 151 | try: 152 | from local_settings import * 153 | except: 154 | pass 155 | -------------------------------------------------------------------------------- /sampleproject/sampleproject/urls.py: -------------------------------------------------------------------------------- 1 | """sampleproject URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.10/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.urls import re_path, include 17 | from django.contrib import admin 18 | 19 | urlpatterns = [ 20 | re_path(r'^admin/', admin.site.urls), 21 | re_path(r'^', include('django_telegrambot.urls')), 22 | re_path(r'^$', include('bot.urls')), 23 | ] 24 | -------------------------------------------------------------------------------- /sampleproject/sampleproject/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for sampleproject project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sampleproject.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.1.2 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | 8 | [bumpversion:file:django_telegrambot/__init__.py] 9 | 10 | [wheel] 11 | universal = 1 12 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | import sys 6 | 7 | import django_telegrambot 8 | 9 | try: 10 | from setuptools import setup 11 | except ImportError: 12 | from distutils.core import setup 13 | 14 | version = django_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-telegrambot', 37 | version=version, 38 | description="""A simple app to develop Telegram bot with Django""", 39 | long_description=readme + '\n\n' + history, 40 | author='django-telegrambot', 41 | author_email='francesco.scarlato@gmail.com', 42 | url='https://github.com/JungDev/django-telegrambot', 43 | packages=[ 44 | 'django_telegrambot', 45 | ], 46 | include_package_data=True, 47 | install_requires=[ 48 | 'django>=1.8.18', 49 | 'python-telegram-bot>=6.0.1', 50 | ], 51 | license="BSD", 52 | zip_safe=False, 53 | keywords='django-telegrambot', 54 | classifiers=[ 55 | 'Development Status :: 5 - Production/Stable', 56 | 'Framework :: Django', 57 | 'Framework :: Django :: 1.7', 58 | 'Framework :: Django :: 1.8', 59 | 'Framework :: Django :: 1.9', 60 | 'Framework :: Django :: 1.10', 61 | 'Framework :: Django :: 1.11', 62 | 'Intended Audience :: Developers', 63 | 'License :: OSI Approved :: BSD License', 64 | 'Natural Language :: English', 65 | 'Programming Language :: Python :: 2', 66 | 'Programming Language :: Python :: 2.7', 67 | 'Programming Language :: Python :: 3', 68 | 'Programming Language :: Python :: 3.4', 69 | 'Programming Language :: Python :: 3.5', 70 | 'Programming Language :: Python :: 3.6', 71 | ], 72 | ) 73 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JungDev/django-telegrambot/00d41354bd472fae6435642e4ea366d8e5b044f5/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JungDev/django-telegrambot/00d41354bd472fae6435642e4ea366d8e5b044f5/tests/test_app/__init__.py -------------------------------------------------------------------------------- /tests/test_app/telegrambot.py: -------------------------------------------------------------------------------- 1 | print("Import successful") 2 | -------------------------------------------------------------------------------- /tests/test_apps.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from django.apps.registry import Apps 4 | from django.test import TestCase 5 | from django_telegrambot.apps import DjangoTelegramBot 6 | import mock 7 | 8 | logging.basicConfig(level=logging.INFO) 9 | 10 | 11 | # Need to mock some of the Telegram Bot's methods with dummy values to make 12 | # sure that the initialisation completes with mock credentials. 13 | @mock.patch('telegram.bot.Bot.delete_webhook', lambda bot: None) 14 | @mock.patch('telegram.bot.Bot.username', 'mock_bot') 15 | @mock.patch('django_telegrambot.apps.DjangoTelegramBot.ready_run', False) 16 | @mock.patch('django_telegrambot.apps.logger') 17 | class TestDjangoTelegramBot(TestCase): 18 | 19 | def setUp(self): 20 | self.app = DjangoTelegramBot.create('django_telegrambot') 21 | 22 | @mock.patch('django_telegrambot.apps.apps', 23 | Apps(installed_apps=('tests.test_app',))) 24 | def test_good_app_loading(self, log): 25 | """Normal initialisation - should complete without error messages.""" 26 | self.assertFalse(DjangoTelegramBot.ready_run) 27 | self.app.ready() 28 | self.assertEquals(log.error.call_count, 0) 29 | self.assertTrue(DjangoTelegramBot.ready_run) 30 | 31 | @mock.patch('django_telegrambot.apps.apps', 32 | Apps(installed_apps=('tests.test_bad_app',))) 33 | def test_bad_app_loading(self, log): 34 | """If a telegrambot.py module in some of the apps contains a mistake, 35 | an error message should be loaded.""" 36 | self.app.ready() 37 | self.assertEquals(log.error.call_count, 1) 38 | 39 | @mock.patch('django_telegrambot.apps.apps', 40 | Apps(installed_apps=('tests.test_bad_app',))) 41 | @mock.patch.dict('django_telegrambot.apps.settings.DJANGO_TELEGRAMBOT', 42 | STRICT_INIT=True) 43 | def test_bad_app_loading_strict(self, _): 44 | """With STRICT_INIT set to true in the DJANGO_TELEGRAMBOT settings, the 45 | app must not start if the telegrambot.py files are not imported 46 | successfully.""" 47 | with self.assertRaises(ImportError): 48 | self.app.ready() 49 | -------------------------------------------------------------------------------- /tests/test_bad_app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JungDev/django-telegrambot/00d41354bd472fae6435642e4ea366d8e5b044f5/tests/test_bad_app/__init__.py -------------------------------------------------------------------------------- /tests/test_bad_app/telegrambot.py: -------------------------------------------------------------------------------- 1 | raise ImportError() 2 | -------------------------------------------------------------------------------- /tests/test_models.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | test_django-telegrambot 6 | ------------ 7 | 8 | Tests for `django-telegrambot` models module. 9 | """ 10 | 11 | from django.test import TestCase 12 | 13 | from django_telegrambot import models 14 | 15 | 16 | class TestDjango_telegrambot(TestCase): 17 | 18 | def setUp(self): 19 | pass 20 | 21 | def test_something(self): 22 | pass 23 | 24 | def tearDown(self): 25 | pass 26 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27, py33, py34, py35 3 | 4 | [testenv] 5 | setenv = 6 | PYTHONPATH = {toxinidir}:{toxinidir}/django_telegrambot 7 | commands = python runtests.py 8 | deps = 9 | -r{toxinidir}/requirements-test.txt 10 | --------------------------------------------------------------------------------