azils3 commited on
Commit
16bfc87
·
verified ·
1 Parent(s): ddaf2ff

Upload 63 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .buildpacks +1 -0
  2. .env_example +4 -0
  3. .gitignore +138 -0
  4. 1.py +60 -0
  5. DOKKU_SCALE +3 -0
  6. LICENSE +201 -0
  7. LocalDockerfile +35 -0
  8. Procfile +4 -0
  9. combined.txt +1895 -0
  10. docker-compose.yml +77 -0
  11. dtb/__init__.py +7 -0
  12. dtb/asgi.py +16 -0
  13. dtb/celery.py +19 -0
  14. dtb/settings.py +184 -0
  15. dtb/urls.py +28 -0
  16. dtb/views.py +41 -0
  17. dtb/wsgi.py +16 -0
  18. manage.py +22 -0
  19. requirements.txt +30 -0
  20. run_polling.py +33 -0
  21. runtime.txt +1 -0
  22. tgbot/__init__.py +0 -0
  23. tgbot/dispatcher.py +74 -0
  24. tgbot/handlers/__init__.py +0 -0
  25. tgbot/handlers/admin/__init__.py +0 -0
  26. tgbot/handlers/admin/handlers.py +40 -0
  27. tgbot/handlers/admin/static_text.py +7 -0
  28. tgbot/handlers/admin/utils.py +30 -0
  29. tgbot/handlers/broadcast_message/__init__.py +0 -0
  30. tgbot/handlers/broadcast_message/handlers.py +89 -0
  31. tgbot/handlers/broadcast_message/keyboards.py +13 -0
  32. tgbot/handlers/broadcast_message/manage_data.py +3 -0
  33. tgbot/handlers/broadcast_message/static_text.py +13 -0
  34. tgbot/handlers/broadcast_message/utils.py +73 -0
  35. tgbot/handlers/location/__init__.py +0 -0
  36. tgbot/handlers/location/handlers.py +30 -0
  37. tgbot/handlers/location/keyboards.py +12 -0
  38. tgbot/handlers/location/static_text.py +3 -0
  39. tgbot/handlers/onboarding/__init__.py +0 -0
  40. tgbot/handlers/onboarding/handlers.py +39 -0
  41. tgbot/handlers/onboarding/keyboards.py +13 -0
  42. tgbot/handlers/onboarding/manage_data.py +1 -0
  43. tgbot/handlers/onboarding/static_text.py +7 -0
  44. tgbot/handlers/utils/__init__.py +0 -0
  45. tgbot/handlers/utils/decorators.py +36 -0
  46. tgbot/handlers/utils/error.py +47 -0
  47. tgbot/handlers/utils/files.py +71 -0
  48. tgbot/handlers/utils/info.py +18 -0
  49. tgbot/main.py +17 -0
  50. tgbot/system_commands.py +55 -0
.buildpacks ADDED
@@ -0,0 +1 @@
 
 
1
+ https://github.com/heroku/heroku-buildpack-python.git#v191
.env_example ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ DJANGO_DEBUG=True
2
+ DATABASE_URL=sqlite:///db.sqlite3
3
+ #DATABASE_URL=postgres://postgres:postgres@db:5432/postgres # when using PostgreSQL via docker-compose
4
+ TELEGRAM_TOKEN=1725447442:AATuNIAicSPdePxxTHdbO1X_4hfAnONOyiA
.gitignore ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+ dtb/static
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ .python-version
87
+
88
+ # pipenv
89
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
90
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
91
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
92
+ # install all needed dependencies.
93
+ #Pipfile.lock
94
+
95
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
96
+ __pypackages__/
97
+
98
+ # Celery stuff
99
+ celerybeat-schedule
100
+ celerybeat.pid
101
+
102
+ # SageMath parsed files
103
+ *.sage.py
104
+
105
+ # Environments
106
+ .env
107
+ .venv
108
+ env/
109
+ venv/
110
+ ENV/
111
+ env.bak/
112
+ venv.bak/
113
+ dtb_venv/
114
+
115
+ # Spyder project settings
116
+ .spyderproject
117
+ .spyproject
118
+
119
+ # Rope project settings
120
+ .ropeproject
121
+
122
+ # mkdocs documentation
123
+ /site
124
+
125
+ # mypy
126
+ .mypy_cache/
127
+ .dmypy.json
128
+ dmypy.json
129
+
130
+ # Pyre type checker
131
+ .pyre/
132
+ .DS_Store
133
+
134
+ #PyCharm
135
+ .idea/
136
+
137
+ #Docker
138
+ .Dockerfile.swp
1.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ def collect_files(directory, extensions):
4
+ collected_files = []
5
+ for root, dirs, files in os.walk(directory):
6
+ for file in files:
7
+ if any(file.endswith(ext) for ext in extensions):
8
+ file_path = os.path.join(root, file)
9
+ collected_files.append((file_path, file))
10
+ return collected_files
11
+
12
+ def write_combined_file(text_files, media_files, output_file):
13
+ with open(output_file, 'w', encoding='utf-8') as aio_file:
14
+ # Write text file contents
15
+ if text_files:
16
+ aio_file.write("# Text Files Contents\n")
17
+ for file_path, file_name in text_files:
18
+ aio_file.write(f"# File: {file_path}\n")
19
+ try:
20
+ with open(file_path, 'r', encoding='utf-8') as file:
21
+ aio_file.write(file.read())
22
+ except Exception as e:
23
+ aio_file.write(f"Error reading file {file_path}: {str(e)}\n")
24
+ aio_file.write("\n" + "="*80 + "\n\n")
25
+
26
+ # Write media file paths with folder structure
27
+ if media_files:
28
+ aio_file.write("# Media File Paths\n")
29
+ current_folder = None
30
+ for file_path, file_name in sorted(media_files, key=lambda x: x[0]):
31
+ folder = os.path.dirname(file_path)
32
+ if folder != current_folder:
33
+ if current_folder is not None:
34
+ aio_file.write("\n" + "="*80 + "\n\n")
35
+ aio_file.write(f"# Folder: {folder}\n")
36
+ current_folder = folder
37
+ aio_file.write(f"File: {file_path}\n")
38
+ if current_folder is not None:
39
+ aio_file.write("\n" + "="*80 + "\n\n")
40
+
41
+ def main():
42
+ directory = os.getcwd() # Current working directory
43
+
44
+ # Define extensions for text files and media files
45
+ text_extensions = ['.py', '.js', '.html', '.css', '.txt', '.md', '.json']
46
+ media_extensions = ['.jpg', '.jpeg', '.png', '.webp', '.avi', '.mp3', '.mp4']
47
+
48
+ # Collect text files
49
+ text_files = collect_files(directory, text_extensions)
50
+
51
+ # Collect media files
52
+ media_files = collect_files(directory, media_extensions)
53
+
54
+ # Combine both text file contents and media file paths into one file
55
+ output_file = 'combined.txt'
56
+ write_combined_file(text_files, media_files, output_file)
57
+ print(f"All text file contents and media file paths have been written to {output_file}")
58
+
59
+ if __name__ == "__main__":
60
+ main()
DOKKU_SCALE ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ web=1
2
+ worker=0
3
+ beat=0
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 Daniil Okhlopkov
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
LocalDockerfile ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.8-slim-buster
2
+
3
+ # Base environment variables
4
+ ENV PYTHONUNBUFFERED=1 \
5
+ PYTHONDONTWRITEBYTECODE=1 \
6
+ PORT=7860 \
7
+ DATABASE_URL=sqlite:///db.sqlite3 \
8
+ DEBUG=True
9
+
10
+ # Set working directory
11
+ WORKDIR /app
12
+
13
+ # Install system dependencies
14
+ RUN apt-get update && apt-get install -y --no-install-recommends \
15
+ gcc \
16
+ python3-dev \
17
+ && rm -rf /var/lib/apt/lists/*
18
+
19
+ # Install Python dependencies
20
+ COPY requirements.txt .
21
+ RUN pip install --no-cache-dir -r requirements.txt
22
+
23
+ # Copy application code
24
+ COPY . .
25
+
26
+ # Database setup
27
+ RUN python manage.py migrate
28
+ RUN python manage.py collectstatic --noinput
29
+
30
+ # Copy entry point script
31
+ COPY entrypoint.sh /entrypoint.sh
32
+ RUN chmod +x /entrypoint.sh
33
+
34
+ # Start server with entry point script
35
+ CMD ["/entrypoint.sh"]
Procfile ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ release: python manage.py migrate --noinput
2
+ web: gunicorn --bind :$PORT --workers 4 --worker-class uvicorn.workers.UvicornWorker dtb.asgi:application
3
+ worker: celery -A dtb worker -P prefork --loglevel=INFO
4
+ beat: celery -A dtb beat --loglevel=INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler
combined.txt ADDED
@@ -0,0 +1,1895 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\manage.py
3
+ #!/usr/bin/env python
4
+ """Django's command-line utility for administrative tasks."""
5
+ import os
6
+ import sys
7
+
8
+
9
+ def main():
10
+ """Run administrative tasks."""
11
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings')
12
+ try:
13
+ from django.core.management import execute_from_command_line
14
+ except ImportError as exc:
15
+ raise ImportError(
16
+ "Couldn't import Django. Are you sure it's installed and "
17
+ "available on your PYTHONPATH environment variable? Did you "
18
+ "forget to activate a virtual environment?"
19
+ ) from exc
20
+ execute_from_command_line(sys.argv)
21
+
22
+
23
+ if __name__ == '__main__':
24
+ main()
25
+
26
+ ================================================================================
27
+
28
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\README.md
29
+ # django-telegram-bot
30
+
31
+ <p align="center">
32
+ <img src="https://user-images.githubusercontent.com/50623190/201977740-68ef4044-9cfa-45da-8897-2a90ecfa33ae.png" align="center" height="350px" weight="350px">
33
+ </p>
34
+
35
+ Sexy Django + python-telegram-bot + Celery + Redis + Postgres + Dokku + GitHub Actions template. Production-ready Telegram bot with database, admin panel and a bunch of useful built-in methods.
36
+
37
+
38
+ ⭐ graph:
39
+ [![Sparkline](https://stars.medv.io/ohld/django-telegram-bot.svg)](https://stars.medv.io/ohld/django-telegram-bot)
40
+
41
+
42
+ ### Check the example bot that uses the code from Main branch: [t.me/djangotelegrambot](https://t.me/djangotelegrambot)
43
+
44
+ ## Features
45
+
46
+ * Database: Postgres, Sqlite3, MySQL - you decide!
47
+ * Admin panel (thanks to [Django](https://docs.djangoproject.com/en/3.1/intro/tutorial01/))
48
+ * Background jobs using [Celery](https://docs.celeryproject.org/en/stable/)
49
+ * [Production-ready](https://github.com/ohld/django-telegram-bot/wiki/Production-Deployment-using-Dokku) deployment using [Dokku](https://dokku.com)
50
+ * Telegram API usage in polling or [webhook mode](https://core.telegram.org/bots/api#setwebhook)
51
+ * Export all users in `.csv`
52
+ * Native telegram [commands in menu](https://github.com/ohld/django-telegram-bot/blob/main/.github/imgs/bot_commands_example.jpg)
53
+ * In order to edit or delete these commands you'll need to use `set_my_commands` bot's method just like in [tgbot.dispatcher.setup_my_commands](https://github.com/ohld/django-telegram-bot/blob/main/tgbot/dispatcher.py#L150-L156)
54
+
55
+ Built-in Telegram bot methods:
56
+ * `/broadcast` — send message to all users (admin command)
57
+ * `/export_users` — bot sends you info about your users in .csv file (admin command)
58
+ * `/stats` — show basic bot stats
59
+ * `/ask_for_location` — log user location when received and reverse geocode it to get country, city, etc.
60
+
61
+
62
+ ## Content
63
+
64
+ * [How to run locally](https://github.com/ohld/django-telegram-bot/#how-to-run)
65
+ * [Quickstart with polling and SQLite](https://github.com/ohld/django-telegram-bot/#quickstart-polling--sqlite)
66
+ * [Using docker-compose](https://github.com/ohld/django-telegram-bot/#run-locally-using-docker-compose)
67
+ * [Deploy to production](https://github.com/ohld/django-telegram-bot/#deploy-to-production)
68
+ * [Using dokku](https://github.com/ohld/django-telegram-bot/#deploy-using-dokku-step-by-step)
69
+ * [Telegram webhook](https://github.com/ohld/django-telegram-bot/#https--telegram-bot-webhook)
70
+
71
+
72
+ # How to run
73
+
74
+ ## Quickstart: Polling & SQLite
75
+
76
+ The fastest way to run the bot is to run it in polling mode using SQLite database without all Celery workers for background jobs. This should be enough for quickstart:
77
+
78
+ ``` bash
79
+ git clone https://github.com/ohld/django-telegram-bot
80
+ cd django-telegram-bot
81
+ ```
82
+
83
+ Create virtual environment (optional)
84
+ ``` bash
85
+ python3 -m venv dtb_venv
86
+ source dtb_venv/bin/activate
87
+ ```
88
+
89
+ Install all requirements:
90
+ ```
91
+ pip install -r requirements.txt
92
+ ```
93
+
94
+ Create `.env` file in root directory and copy-paste this or just run `cp .env_example .env`,
95
+ don't forget to change telegram token:
96
+ ``` bash
97
+ DJANGO_DEBUG=True
98
+ DATABASE_URL=sqlite:///db.sqlite3
99
+ TELEGRAM_TOKEN=<PASTE YOUR TELEGRAM TOKEN HERE>
100
+ ```
101
+
102
+ Run migrations to setup SQLite database:
103
+ ``` bash
104
+ python manage.py migrate
105
+ ```
106
+
107
+ Create superuser to get access to admin panel:
108
+ ``` bash
109
+ python manage.py createsuperuser
110
+ ```
111
+
112
+ Run bot in polling mode:
113
+ ``` bash
114
+ python run_polling.py
115
+ ```
116
+
117
+ If you want to open Django admin panel which will be located on http://localhost:8000/tgadmin/:
118
+ ``` bash
119
+ python manage.py runserver
120
+ ```
121
+
122
+ ## Run locally using docker-compose
123
+ If you want just to run all the things locally, you can use Docker-compose which will start all containers for you.
124
+
125
+ ### Create .env file.
126
+ You can switch to PostgreSQL just by uncommenting it's `DATABASE_URL` and commenting SQLite variable.
127
+ ```bash
128
+ cp .env_example .env
129
+ ```
130
+
131
+ ### Docker-compose
132
+
133
+ To run all services (Django, Postgres, Redis, Celery) at once:
134
+ ``` bash
135
+ docker-compose up -d --build
136
+ ```
137
+
138
+ Check status of the containers.
139
+ ``` bash
140
+ docker ps -a
141
+ ```
142
+ It should look similar to this:
143
+ <p align="left">
144
+ <img src="https://github.com/ohld/django-telegram-bot/raw/main/.github/imgs/containers_status.png">
145
+ </p>
146
+
147
+ Try visit <a href="http://0.0.0.0:8000/tgadmin">Django-admin panel</a>.
148
+
149
+ ### Enter django shell:
150
+
151
+ ``` bash
152
+ docker exec -it dtb_django bash
153
+ ```
154
+
155
+ ### Create superuser for Django admin panel
156
+
157
+ ``` bash
158
+ python manage.py createsuperuser
159
+ ```
160
+
161
+ ### To see logs of the container:
162
+
163
+ ``` bash
164
+ docker logs -f dtb_django
165
+ ```
166
+
167
+
168
+ # Deploy to Production
169
+
170
+ Production stack will include these technologies:
171
+
172
+ 1) Postgres as main database for Django
173
+ 2) Celery + Redis + easy scalable workers
174
+ 3) Dokku as PaaS (will build app from sources and deploy it with zero downtime)
175
+
176
+ All app's services that are going to be launched in production can be found in `Procfile` file. It includes Django webserver (Telegram event processing + admin panel) and Celery workers (background and periodic jobs).
177
+
178
+ ## What is Dokku and how it works
179
+
180
+ [Dokku](https://dokku.com/) is an open-source version of Heroku.
181
+
182
+ I really like Heroku deployment approach:
183
+ 1) you push commit to Main branch of your Repo
184
+ 2) in couple minutes your new app is running
185
+ 3) if something breaks during deployment - old app will not be shut down
186
+
187
+ You can achieve the same approach with Dokku + Github Actions (just to trigger deployment).
188
+
189
+ Dokku uses [buildpacks](https://buildpacks.io/) technology to create a Docker image from the code. No Dockerfile needed. Speaking about Python, it requires `requirements.txt`, `Procfile` files to run the things up. Also files `DOKKU_SCALE` and `runtime.txt` are useful to tweak configs to make the deployed app even better. E.g. in `DOKKU_SCALE` you can specify how many app instances should be run behind built-in load balancer.
190
+
191
+ One disadvantage of Dokku that you should be warned about is that it can work with one server only. You can't just scale your app up to 2 machines using only small config change. You still can use several servers by providing correct .env URLs to deployed apps (e.g. DATABASE_URL) but it will require more time to setup.
192
+
193
+ ## Deploy using Dokku: step-by-step
194
+
195
+ I assume that you already have [Dokku installed](https://dokku.com/docs/getting-started/installation/) on your server. Let's also assume that the address of your server is *<YOURDOMAIN.COM>* (you will need a domain to setup HTTPs for Telegram webhook support). I'd recommend to have at least [2GB RAM and 2 CPU cores](https://m.do.co/c/260555f64021).
196
+
197
+ ### Create Dokku app
198
+
199
+ ``` bash
200
+ dokku apps:create dtb
201
+ ```
202
+
203
+ You might need to added `.env` variables to app, e.g. to specify Telegram token:
204
+
205
+ ``` bash
206
+ dokku config:set dtb TELEGRAM_TOKEN=.....
207
+ ```
208
+
209
+ ### Postgres and Redis
210
+
211
+ **Postgres** and **Redis** are configured as Dokku plugins on a server.
212
+ They will automatically add REDIS_URL & DATABASE_URL .env vars to the app after being linked.
213
+ You might need to install these Dokku plugins before.
214
+ [Install Postgres](https://github.com/dokku/dokku-postgres),
215
+ [install Redis](https://github.com/dokku/dokku-redis).
216
+
217
+ ``` bash
218
+ dokku postgres:create dtb
219
+ dokku postgres:link dtb dtb
220
+
221
+ dokku redis:create dtb
222
+ dokku redis:link dtb dtb
223
+ ```
224
+
225
+ ### Deploy on commit with Github Actions
226
+
227
+ Go to file [.github/workflows/dokku.yml](https://github.com/ohld/django-telegram-bot/blob/main/.github/workflows/dokku.yml):
228
+
229
+ 1. Enter your host name (address of your server),
230
+ 2. Deployed dokku app name (in our case this is `dtb`),
231
+ 3. Set `SSH_PRIVATE_KEY` secret variable via GitHub repo settings. This private key should have the **root ssh access** to your server.
232
+
233
+ This will trigger Dokku's zero-downtime deployment. You would probably need to fork this repo to change file.
234
+
235
+ After that you should see a green arrow ✅ at Github Actions tab that would mean your app is deployed successfully. If you see a red cross ❌ you can find the deployed logs in Github Actions tab and find out what went wrong.
236
+
237
+ ## HTTPS & Telegram bot webhook
238
+
239
+ ### Why you need to setup webhook
240
+
241
+ Basic polling approach is really handy and can speed up development of Telegram bots. But it doesn't scale. Better approach is to allow Telegram servers push events (webhook messages) to your server when something happens with your Telegram bot. You can use built-in Dokku load-balancer to parallel event processing.
242
+
243
+ ### HTTPS using Letsencrypt plugin
244
+
245
+ For Telegram bot API webhook usage you'll need a **https** which can be setup using [Letsencrypt Dokku plugin](https://github.com/dokku/dokku-letsencrypt). You will need to attach a domain to your Django app before and specify a email (required by Letsencrypt) - you will receive notifications when certificates would become old. Make sure you achieved a successful deployment first (your app runs at <YOURDOMAIN.COM>, check in browser).
246
+
247
+ ``` bash
248
+ dokku domains:add dtb <YOURDOMAIN.COM>
249
+ dokku config:set --global DOKKU_LETSENCRYPT_EMAIL=<[email protected]>
250
+ dokku letsencrypt:enable dtb
251
+ ```
252
+
253
+ ### Setup Telegram Bot API webhook URL
254
+
255
+ You need to tell Telegram servers where to send events of your Telegram bot. Just open in the browser:
256
+
257
+ ```
258
+ https://api.telegram.org/bot<TELEGRAM_TOKEN>/setWebhook?url=https://<YOURDOMAIN.COM>/super_secter_webhook/
259
+ ```
260
+
261
+
262
+ ### After deployment
263
+
264
+ You can be sure that your app is deployed successfully if you see a green arrow at the latest workflow at Github Actions tab.
265
+
266
+ You would need to create a superuser to access an admin panel at https://<YOURDOMAIN.COM>/tgadmin. This can be done using a standard way using django shell:
267
+
268
+
269
+ ### Open shell in deployed app
270
+ ``` shell
271
+ dokku enter dtb web
272
+ ```
273
+
274
+ ### Create Django super user
275
+ Being inside a container:
276
+ ``` bash
277
+ python manage.py createsuperuser
278
+ ```
279
+
280
+ After that you can open admin panel of your deployed app which is located at https://<YOURDOMAIN.COM>/tgadmin.
281
+
282
+ ### Read app logs
283
+
284
+ ``` bash
285
+ dokku logs dtb -t
286
+ ```
287
+
288
+
289
+ ----
290
+
291
+ ================================================================================
292
+
293
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\requirements.txt
294
+ pytz
295
+ requests
296
+ python-dotenv
297
+
298
+ ipython==8.5.0 # enhanced python interpreter
299
+
300
+ # Django
301
+ django==3.2.9
302
+ django-cors-headers==3.13.0
303
+ django-debug-toolbar==3.6.0
304
+ whitenoise==6.2.0 # for serving static files
305
+
306
+ # Django 3.0 async requirements
307
+ gunicorn==20.1.0
308
+ uvicorn==0.18.3
309
+
310
+ # Databases
311
+ psycopg2-binary==2.9.9
312
+ dj-database-url==1.0.0
313
+
314
+ # Distributed async tasks
315
+ celery==5.2.7
316
+ redis==4.3.4
317
+ django-celery-beat==2.3.0
318
+
319
+ # Telegram
320
+ python-telegram-bot==13.15 # last sync version
321
+
322
+ # monitoring
323
+ # sentry-sdk
324
+
325
+ ================================================================================
326
+
327
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\runtime.txt
328
+ python-3.8.3
329
+ ================================================================================
330
+
331
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\run_polling.py
332
+ import os, django
333
+
334
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings')
335
+ django.setup()
336
+
337
+ from telegram import Bot
338
+ from telegram.ext import Updater
339
+
340
+ from dtb.settings import TELEGRAM_TOKEN
341
+ from tgbot.dispatcher import setup_dispatcher
342
+
343
+
344
+ def run_polling(tg_token: str = TELEGRAM_TOKEN):
345
+ """ Run bot in polling mode """
346
+ updater = Updater(tg_token, use_context=True)
347
+
348
+ dp = updater.dispatcher
349
+ dp = setup_dispatcher(dp)
350
+
351
+ bot_info = Bot(tg_token).get_me()
352
+ bot_link = f"https://t.me/{bot_info['username']}"
353
+
354
+ print(f"Polling of '{bot_link}' has started")
355
+ # it is really useful to send '👋' emoji to developer
356
+ # when you run local test
357
+ # bot.send_message(text='👋', chat_id=<YOUR TELEGRAM ID>)
358
+
359
+ updater.start_polling()
360
+ updater.idle()
361
+
362
+
363
+ if __name__ == "__main__":
364
+ run_polling()
365
+
366
+ ================================================================================
367
+
368
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\dtb\asgi.py
369
+ """
370
+ ASGI config for dtb project.
371
+
372
+ It exposes the ASGI callable as a module-level variable named ``application``.
373
+
374
+ For more information on this file, see
375
+ https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
376
+ """
377
+
378
+ import os
379
+
380
+ from django.core.asgi import get_asgi_application
381
+
382
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings')
383
+
384
+ application = get_asgi_application()
385
+
386
+ ================================================================================
387
+
388
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\dtb\celery.py
389
+ import os
390
+ from celery import Celery
391
+
392
+ # set the default Django settings module for the 'celery' program.
393
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings')
394
+
395
+ app = Celery('dtb')
396
+
397
+ # Using a string here means the worker doesn't have to serialize
398
+ # the configuration object to child processes.
399
+ # - namespace='CELERY' means all celery-related configuration keys
400
+ # should have a `CELERY_` prefix.
401
+ app.config_from_object('django.conf:settings', namespace='CELERY')
402
+
403
+ # Load task modules from all registered Django app configs.
404
+ app.autodiscover_tasks()
405
+ app.conf.enable_utc = False
406
+
407
+
408
+ ================================================================================
409
+
410
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\dtb\settings.py
411
+ import logging
412
+ import os
413
+ import sys
414
+
415
+ import dj_database_url
416
+ import dotenv
417
+
418
+ from pathlib import Path
419
+
420
+ # Build paths inside the project like this: BASE_DIR / 'subdir'.
421
+ BASE_DIR = Path(__file__).resolve().parent.parent
422
+
423
+
424
+ # Load env variables from file
425
+ dotenv_file = BASE_DIR / ".env"
426
+ if os.path.isfile(dotenv_file):
427
+ dotenv.load_dotenv(dotenv_file)
428
+
429
+
430
+ # SECURITY WARNING: keep the secret key used in production secret!
431
+ SECRET_KEY = os.getenv(
432
+ "DJANGO_SECRET_KEY",
433
+ 'x%#3&%giwv8f0+%r946en7z&d@9*rc$sl0qoql56xr%bh^w2mj',
434
+ )
435
+
436
+ if os.environ.get('DJANGO_DEBUG', default=False) in ['True', 'true', '1', True]:
437
+ DEBUG = True
438
+ else:
439
+ DEBUG = False
440
+
441
+ ALLOWED_HOSTS = ["*",] # since Telegram uses a lot of IPs for webhooks
442
+
443
+
444
+ INSTALLED_APPS = [
445
+ 'django.contrib.admin',
446
+ 'django.contrib.auth',
447
+ 'django.contrib.contenttypes',
448
+ 'django.contrib.sessions',
449
+ 'django.contrib.messages',
450
+ 'django.contrib.staticfiles',
451
+
452
+ # 3rd party apps
453
+ 'django_celery_beat',
454
+ 'debug_toolbar',
455
+
456
+ # local apps
457
+ 'users.apps.UsersConfig',
458
+ ]
459
+
460
+ MIDDLEWARE = [
461
+ 'django.middleware.security.SecurityMiddleware',
462
+ 'django.contrib.sessions.middleware.SessionMiddleware',
463
+ 'django.middleware.csrf.CsrfViewMiddleware',
464
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
465
+ 'django.contrib.messages.middleware.MessageMiddleware',
466
+ 'django.middleware.clickjacking.XFrameOptionsMiddleware',
467
+
468
+ 'whitenoise.middleware.WhiteNoiseMiddleware',
469
+ 'corsheaders.middleware.CorsMiddleware',
470
+ 'debug_toolbar.middleware.DebugToolbarMiddleware',
471
+
472
+ 'django.middleware.common.CommonMiddleware',
473
+ ]
474
+
475
+ INTERNAL_IPS = [
476
+ # ...
477
+ '127.0.0.1',
478
+ # ...
479
+ ]
480
+
481
+ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
482
+
483
+ CORS_ORIGIN_ALLOW_ALL = True
484
+ CORS_ALLOW_CREDENTIALS = True
485
+
486
+ ROOT_URLCONF = 'dtb.urls'
487
+
488
+ TEMPLATES = [
489
+ {
490
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
491
+ 'DIRS': [],
492
+ 'APP_DIRS': True,
493
+ 'OPTIONS': {
494
+ 'context_processors': [
495
+ 'django.template.context_processors.debug',
496
+ 'django.template.context_processors.request',
497
+ 'django.contrib.auth.context_processors.auth',
498
+ 'django.contrib.messages.context_processors.messages',
499
+ ],
500
+ },
501
+ },
502
+ ]
503
+
504
+ WSGI_APPLICATION = 'dtb.wsgi.application'
505
+ ASGI_APPLICATION = 'dtb.asgi.application'
506
+
507
+
508
+ # Database
509
+ # https://docs.djangoproject.com/en/3.0/ref/settings/#databases
510
+
511
+ DATABASES = {
512
+ 'default': dj_database_url.config(conn_max_age=600, default="sqlite:///db.sqlite3"),
513
+ }
514
+
515
+ # Password validation
516
+ # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
517
+
518
+ AUTH_PASSWORD_VALIDATORS = [
519
+ {
520
+ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
521
+ },
522
+ {
523
+ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
524
+ },
525
+ {
526
+ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
527
+ },
528
+ {
529
+ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
530
+ },
531
+ ]
532
+
533
+
534
+ # Internationalization
535
+ # https://docs.djangoproject.com/en/3.0/topics/i18n/
536
+
537
+ LANGUAGE_CODE = 'en-us'
538
+ TIME_ZONE = 'UTC'
539
+ USE_I18N = True
540
+ USE_L10N = True
541
+ USE_TZ = True
542
+
543
+
544
+ # Static files (CSS, JavaScript, Images)
545
+ # https://docs.djangoproject.com/en/3.0/howto/static-files/
546
+ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
547
+
548
+ PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
549
+ STATIC_URL = '/static/'
550
+ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
551
+
552
+
553
+ # -----> CELERY
554
+ REDIS_URL = os.getenv('REDIS_URL', 'redis://redis:6379')
555
+ BROKER_URL = REDIS_URL
556
+ CELERY_BROKER_URL = REDIS_URL
557
+ CELERY_RESULT_BACKEND = REDIS_URL
558
+ CELERY_ACCEPT_CONTENT = ['application/json']
559
+ CELERY_TASK_SERIALIZER = 'json'
560
+ CELERY_RESULT_SERIALIZER = 'json'
561
+ CELERY_TIMEZONE = TIME_ZONE
562
+ CELERY_TASK_DEFAULT_QUEUE = 'default'
563
+
564
+
565
+ # -----> TELEGRAM
566
+ TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
567
+ if TELEGRAM_TOKEN is None:
568
+ logging.error(
569
+ "Please provide TELEGRAM_TOKEN in .env file.\n"
570
+ "Example of .env file: https://github.com/ohld/django-telegram-bot/blob/main/.env_example"
571
+ )
572
+ sys.exit(1)
573
+
574
+ TELEGRAM_LOGS_CHAT_ID = os.getenv("TELEGRAM_LOGS_CHAT_ID", default=None)
575
+
576
+ # -----> SENTRY
577
+ # import sentry_sdk
578
+ # from sentry_sdk.integrations.django import DjangoIntegration
579
+ # from sentry_sdk.integrations.celery import CeleryIntegration
580
+ # from sentry_sdk.integrations.redis import RedisIntegration
581
+
582
+ # sentry_sdk.init(
583
+ # dsn="INPUT ...ingest.sentry.io/ LINK",
584
+ # integrations=[
585
+ # DjangoIntegration(),
586
+ # CeleryIntegration(),
587
+ # RedisIntegration(),
588
+ # ],
589
+ # traces_sample_rate=0.1,
590
+
591
+ # # If you wish to associate users to errors (assuming you are using
592
+ # # django.contrib.auth) you may enable sending PII data.
593
+ # send_default_pii=True
594
+ # )
595
+
596
+ ================================================================================
597
+
598
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\dtb\urls.py
599
+ """dtb URL Configuration
600
+
601
+ The `urlpatterns` list routes URLs to views. For more information please see:
602
+ https://docs.djangoproject.com/en/3.1/topics/http/urls/
603
+ Examples:
604
+ Function views
605
+ 1. Add an import: from my_app import views
606
+ 2. Add a URL to urlpatterns: path('', views.home, name='home')
607
+ Class-based views
608
+ 1. Add an import: from other_app.views import Home
609
+ 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
610
+ Including another URLconf
611
+ 1. Import the include() function: from django.urls import include, path
612
+ 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
613
+ """
614
+ import debug_toolbar
615
+ from django.contrib import admin
616
+ from django.urls import path, include
617
+ from django.views.decorators.csrf import csrf_exempt
618
+
619
+ from . import views
620
+
621
+ urlpatterns = [
622
+ path('tgadmin/', admin.site.urls),
623
+ path('__debug__/', include(debug_toolbar.urls)),
624
+ path('', views.index, name="index"),
625
+ path('super_secter_webhook/', csrf_exempt(views.TelegramBotWebhookView.as_view())),
626
+ ]
627
+
628
+ ================================================================================
629
+
630
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\dtb\views.py
631
+ import json
632
+ import logging
633
+ from django.views import View
634
+ from django.http import JsonResponse
635
+ from telegram import Update
636
+
637
+ from dtb.celery import app
638
+ from dtb.settings import DEBUG
639
+ from tgbot.dispatcher import dispatcher
640
+ from tgbot.main import bot
641
+
642
+ logger = logging.getLogger(__name__)
643
+
644
+
645
+ @app.task(ignore_result=True)
646
+ def process_telegram_event(update_json):
647
+ update = Update.de_json(update_json, bot)
648
+ dispatcher.process_update(update)
649
+
650
+
651
+ def index(request):
652
+ return JsonResponse({"error": "sup hacker"})
653
+
654
+
655
+ class TelegramBotWebhookView(View):
656
+ # WARNING: if fail - Telegram webhook will be delivered again.
657
+ # Can be fixed with async celery task execution
658
+ def post(self, request, *args, **kwargs):
659
+ if DEBUG:
660
+ process_telegram_event(json.loads(request.body))
661
+ else:
662
+ # Process Telegram event in Celery worker (async)
663
+ # Don't forget to run it and & Redis (message broker for Celery)!
664
+ # Locally, You can run all of these services via docker-compose.yml
665
+ process_telegram_event.delay(json.loads(request.body))
666
+
667
+ # e.g. remove buttons, typing event
668
+ return JsonResponse({"ok": "POST request processed"})
669
+
670
+ def get(self, request, *args, **kwargs): # for debug
671
+ return JsonResponse({"ok": "Get request received! But nothing done"})
672
+
673
+ ================================================================================
674
+
675
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\dtb\wsgi.py
676
+ """
677
+ WSGI config for dtb project.
678
+
679
+ It exposes the WSGI callable as a module-level variable named ``application``.
680
+
681
+ For more information on this file, see
682
+ https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
683
+ """
684
+
685
+ import os
686
+
687
+ from django.core.wsgi import get_wsgi_application
688
+
689
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings')
690
+
691
+ application = get_wsgi_application()
692
+
693
+ ================================================================================
694
+
695
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\dtb\__init__.py
696
+ from __future__ import absolute_import, unicode_literals
697
+
698
+ # This will make sure the app is always imported when
699
+ # Django starts so that shared_task will use this app.
700
+ from .celery import app as celery_app
701
+
702
+ __all__ = ('celery_app',)
703
+ ================================================================================
704
+
705
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\dispatcher.py
706
+ """
707
+ Telegram event handlers
708
+ """
709
+ from telegram.ext import (
710
+ Dispatcher, Filters,
711
+ CommandHandler, MessageHandler,
712
+ CallbackQueryHandler,
713
+ )
714
+
715
+ from dtb.settings import DEBUG
716
+ from tgbot.handlers.broadcast_message.manage_data import CONFIRM_DECLINE_BROADCAST
717
+ from tgbot.handlers.broadcast_message.static_text import broadcast_command
718
+ from tgbot.handlers.onboarding.manage_data import SECRET_LEVEL_BUTTON
719
+
720
+ from tgbot.handlers.utils import files, error
721
+ from tgbot.handlers.admin import handlers as admin_handlers
722
+ from tgbot.handlers.location import handlers as location_handlers
723
+ from tgbot.handlers.onboarding import handlers as onboarding_handlers
724
+ from tgbot.handlers.broadcast_message import handlers as broadcast_handlers
725
+ from tgbot.main import bot
726
+
727
+
728
+ def setup_dispatcher(dp):
729
+ """
730
+ Adding handlers for events from Telegram
731
+ """
732
+ # onboarding
733
+ dp.add_handler(CommandHandler("start", onboarding_handlers.command_start))
734
+
735
+ # admin commands
736
+ dp.add_handler(CommandHandler("admin", admin_handlers.admin))
737
+ dp.add_handler(CommandHandler("stats", admin_handlers.stats))
738
+ dp.add_handler(CommandHandler('export_users', admin_handlers.export_users))
739
+
740
+ # location
741
+ dp.add_handler(CommandHandler("ask_location", location_handlers.ask_for_location))
742
+ dp.add_handler(MessageHandler(Filters.location, location_handlers.location_handler))
743
+
744
+ # secret level
745
+ dp.add_handler(CallbackQueryHandler(onboarding_handlers.secret_level, pattern=f"^{SECRET_LEVEL_BUTTON}"))
746
+
747
+ # broadcast message
748
+ dp.add_handler(
749
+ MessageHandler(Filters.regex(rf'^{broadcast_command}(/s)?.*'), broadcast_handlers.broadcast_command_with_message)
750
+ )
751
+ dp.add_handler(
752
+ CallbackQueryHandler(broadcast_handlers.broadcast_decision_handler, pattern=f"^{CONFIRM_DECLINE_BROADCAST}")
753
+ )
754
+
755
+ # files
756
+ dp.add_handler(MessageHandler(
757
+ Filters.animation, files.show_file_id,
758
+ ))
759
+
760
+ # handling errors
761
+ dp.add_error_handler(error.send_stacktrace_to_tg_chat)
762
+
763
+ # EXAMPLES FOR HANDLERS
764
+ # dp.add_handler(MessageHandler(Filters.text, <function_handler>))
765
+ # dp.add_handler(MessageHandler(
766
+ # Filters.document, <function_handler>,
767
+ # ))
768
+ # dp.add_handler(CallbackQueryHandler(<function_handler>, pattern="^r\d+_\d+"))
769
+ # dp.add_handler(MessageHandler(
770
+ # Filters.chat(chat_id=int(TELEGRAM_FILESTORAGE_ID)),
771
+ # # & Filters.forwarded & (Filters.photo | Filters.video | Filters.animation),
772
+ # <function_handler>,
773
+ # ))
774
+
775
+ return dp
776
+
777
+
778
+ n_workers = 0 if DEBUG else 4
779
+ dispatcher = setup_dispatcher(Dispatcher(bot, update_queue=None, workers=n_workers, use_context=True))
780
+
781
+ ================================================================================
782
+
783
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\main.py
784
+ import logging
785
+ import sys
786
+
787
+ import telegram
788
+ from telegram import Bot
789
+
790
+ from dtb.settings import TELEGRAM_TOKEN
791
+
792
+
793
+ bot = Bot(TELEGRAM_TOKEN)
794
+ TELEGRAM_BOT_USERNAME = bot.get_me()["username"]
795
+ # Global variable - the best way I found to init Telegram bot
796
+ try:
797
+ pass
798
+ except telegram.error.Unauthorized:
799
+ logging.error("Invalid TELEGRAM_TOKEN.")
800
+ sys.exit(1)
801
+
802
+ ================================================================================
803
+
804
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\system_commands.py
805
+ from typing import Dict
806
+
807
+ from telegram import Bot, BotCommand
808
+
809
+ from tgbot.main import bot
810
+
811
+
812
+ def set_up_commands(bot_instance: Bot) -> None:
813
+
814
+ langs_with_commands: Dict[str, Dict[str, str]] = {
815
+ 'en': {
816
+ 'start': 'Start django bot 🚀',
817
+ 'stats': 'Statistics of bot 📊',
818
+ 'admin': 'Show admin info ℹ️',
819
+ 'ask_location': 'Send location 📍',
820
+ 'broadcast': 'Broadcast message 📨',
821
+ 'export_users': 'Export users.csv 👥',
822
+ },
823
+ 'es': {
824
+ 'start': 'Iniciar el bot de django 🚀',
825
+ 'stats': 'Estadísticas de bot 📊',
826
+ 'admin': 'Mostrar información de administrador ℹ️',
827
+ 'ask_location': 'Enviar ubicación 📍',
828
+ 'broadcast': 'Mensaje de difusión 📨',
829
+ 'export_users': 'Exportar users.csv 👥',
830
+ },
831
+ 'fr': {
832
+ 'start': 'Démarrer le bot Django 🚀',
833
+ 'stats': 'Statistiques du bot 📊',
834
+ 'admin': "Afficher les informations d'administrateur ℹ️",
835
+ 'ask_location': 'Envoyer emplacement 📍',
836
+ 'broadcast': 'Message de diffusion 📨',
837
+ "export_users": 'Exporter users.csv 👥',
838
+ },
839
+ 'ru': {
840
+ 'start': 'Запустить django бота 🚀',
841
+ 'stats': 'Статистика бота 📊',
842
+ 'admin': 'Показать информацию для админов ℹ️',
843
+ 'broadcast': 'Отправить сообщение 📨',
844
+ 'ask_location': 'Отправить локацию 📍',
845
+ 'export_users': 'Экспорт users.csv 👥',
846
+ }
847
+ }
848
+
849
+ bot_instance.delete_my_commands()
850
+ for language_code in langs_with_commands:
851
+ bot_instance.set_my_commands(
852
+ language_code=language_code,
853
+ commands=[
854
+ BotCommand(command, description) for command, description in langs_with_commands[language_code].items()
855
+ ]
856
+ )
857
+
858
+
859
+ set_up_commands(bot)
860
+
861
+ ================================================================================
862
+
863
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\__init__.py
864
+
865
+ ================================================================================
866
+
867
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\__init__.py
868
+
869
+ ================================================================================
870
+
871
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\admin\handlers.py
872
+ from datetime import timedelta
873
+
874
+ from django.utils.timezone import now
875
+ from telegram import ParseMode, Update
876
+ from telegram.ext import CallbackContext
877
+
878
+ from tgbot.handlers.admin import static_text
879
+ from tgbot.handlers.admin.utils import _get_csv_from_qs_values
880
+ from tgbot.handlers.utils.decorators import admin_only, send_typing_action
881
+ from users.models import User
882
+
883
+
884
+ @admin_only
885
+ def admin(update: Update, context: CallbackContext) -> None:
886
+ """ Show help info about all secret admins commands """
887
+ update.message.reply_text(static_text.secret_admin_commands)
888
+
889
+
890
+ @admin_only
891
+ def stats(update: Update, context: CallbackContext) -> None:
892
+ """ Show help info about all secret admins commands """
893
+ text = static_text.users_amount_stat.format(
894
+ user_count=User.objects.count(), # count may be ineffective if there are a lot of users.
895
+ active_24=User.objects.filter(updated_at__gte=now() - timedelta(hours=24)).count()
896
+ )
897
+
898
+ update.message.reply_text(
899
+ text,
900
+ parse_mode=ParseMode.HTML,
901
+ disable_web_page_preview=True,
902
+ )
903
+
904
+
905
+ @admin_only
906
+ @send_typing_action
907
+ def export_users(update: Update, context: CallbackContext) -> None:
908
+ # in values argument you can specify which fields should be returned in output csv
909
+ users = User.objects.all().values()
910
+ csv_users = _get_csv_from_qs_values(users)
911
+ update.message.reply_document(csv_users)
912
+
913
+ ================================================================================
914
+
915
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\admin\static_text.py
916
+ command_start = '/stats'
917
+
918
+ secret_admin_commands = f"⚠️ Secret Admin commands\n" \
919
+ f"{command_start} - bot stats"
920
+
921
+ users_amount_stat = "<b>Users</b>: {user_count}\n" \
922
+ "<b>24h active</b>: {active_24}"
923
+
924
+ ================================================================================
925
+
926
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\admin\utils.py
927
+ import io
928
+ import csv
929
+
930
+ from datetime import datetime
931
+ from django.db.models import QuerySet
932
+ from typing import Dict
933
+
934
+
935
+ def _get_csv_from_qs_values(queryset: QuerySet[Dict], filename: str = 'users'):
936
+ keys = queryset[0].keys()
937
+
938
+ # csv module can write data in io.StringIO buffer only
939
+ s = io.StringIO()
940
+ dict_writer = csv.DictWriter(s, fieldnames=keys)
941
+ dict_writer.writeheader()
942
+ dict_writer.writerows(queryset)
943
+ s.seek(0)
944
+
945
+ # python-telegram-bot library can send files only from io.BytesIO buffer
946
+ # we need to convert StringIO to BytesIO
947
+ buf = io.BytesIO()
948
+
949
+ # extract csv-string, convert it to bytes and write to buffer
950
+ buf.write(s.getvalue().encode())
951
+ buf.seek(0)
952
+
953
+ # set a filename with file's extension
954
+ buf.name = f"{filename}__{datetime.now().strftime('%Y.%m.%d.%H.%M')}.csv"
955
+
956
+ return buf
957
+
958
+ ================================================================================
959
+
960
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\admin\__init__.py
961
+
962
+ ================================================================================
963
+
964
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\broadcast_message\handlers.py
965
+ import re
966
+
967
+ import telegram
968
+ from telegram import Update
969
+ from telegram.ext import CallbackContext
970
+
971
+ from dtb.settings import DEBUG
972
+ from .manage_data import CONFIRM_DECLINE_BROADCAST, CONFIRM_BROADCAST
973
+ from .keyboards import keyboard_confirm_decline_broadcasting
974
+ from .static_text import broadcast_command, broadcast_wrong_format, broadcast_no_access, error_with_html, \
975
+ message_is_sent, declined_message_broadcasting
976
+ from users.models import User
977
+ from users.tasks import broadcast_message
978
+
979
+
980
+ def broadcast_command_with_message(update: Update, context: CallbackContext):
981
+ """ Type /broadcast <some_text>. Then check your message in HTML format and broadcast to users."""
982
+ u = User.get_user(update, context)
983
+
984
+ if not u.is_admin:
985
+ update.message.reply_text(
986
+ text=broadcast_no_access,
987
+ )
988
+ else:
989
+ if update.message.text == broadcast_command:
990
+ # user typed only command without text for the message.
991
+ update.message.reply_text(
992
+ text=broadcast_wrong_format,
993
+ parse_mode=telegram.ParseMode.HTML,
994
+ )
995
+ return
996
+
997
+ text = f"{update.message.text.replace(f'{broadcast_command} ', '')}"
998
+ markup = keyboard_confirm_decline_broadcasting()
999
+
1000
+ try:
1001
+ update.message.reply_text(
1002
+ text=text,
1003
+ parse_mode=telegram.ParseMode.HTML,
1004
+ reply_markup=markup,
1005
+ )
1006
+ except telegram.error.BadRequest as e:
1007
+ update.message.reply_text(
1008
+ text=error_with_html.format(reason=e),
1009
+ parse_mode=telegram.ParseMode.HTML,
1010
+ )
1011
+
1012
+
1013
+ def broadcast_decision_handler(update: Update, context: CallbackContext) -> None:
1014
+ # callback_data: CONFIRM_DECLINE_BROADCAST variable from manage_data.py
1015
+ """ Entered /broadcast <some_text>.
1016
+ Shows text in HTML style with two buttons:
1017
+ Confirm and Decline
1018
+ """
1019
+ broadcast_decision = update.callback_query.data[len(CONFIRM_DECLINE_BROADCAST):]
1020
+
1021
+ entities_for_celery = update.callback_query.message.to_dict().get('entities')
1022
+ entities, text = update.callback_query.message.entities, update.callback_query.message.text
1023
+
1024
+ if broadcast_decision == CONFIRM_BROADCAST:
1025
+ admin_text = message_is_sent
1026
+ user_ids = list(User.objects.all().values_list('user_id', flat=True))
1027
+
1028
+ if DEBUG:
1029
+ broadcast_message(
1030
+ user_ids=user_ids,
1031
+ text=text,
1032
+ entities=entities_for_celery,
1033
+ )
1034
+ else:
1035
+ # send in async mode via celery
1036
+ broadcast_message.delay(
1037
+ user_ids=user_ids,
1038
+ text=text,
1039
+ entities=entities_for_celery,
1040
+ )
1041
+ else:
1042
+ context.bot.send_message(
1043
+ chat_id=update.callback_query.message.chat_id,
1044
+ text=declined_message_broadcasting,
1045
+ )
1046
+ admin_text = text
1047
+
1048
+ context.bot.edit_message_text(
1049
+ text=admin_text,
1050
+ chat_id=update.callback_query.message.chat_id,
1051
+ message_id=update.callback_query.message.message_id,
1052
+ entities=None if broadcast_decision == CONFIRM_BROADCAST else entities,
1053
+ )
1054
+
1055
+ ================================================================================
1056
+
1057
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\broadcast_message\keyboards.py
1058
+ from telegram import InlineKeyboardButton, InlineKeyboardMarkup
1059
+
1060
+ from tgbot.handlers.broadcast_message.manage_data import CONFIRM_DECLINE_BROADCAST, CONFIRM_BROADCAST, DECLINE_BROADCAST
1061
+ from tgbot.handlers.broadcast_message.static_text import confirm_broadcast, decline_broadcast
1062
+
1063
+
1064
+ def keyboard_confirm_decline_broadcasting() -> InlineKeyboardMarkup:
1065
+ buttons = [[
1066
+ InlineKeyboardButton(confirm_broadcast, callback_data=f'{CONFIRM_DECLINE_BROADCAST}{CONFIRM_BROADCAST}'),
1067
+ InlineKeyboardButton(decline_broadcast, callback_data=f'{CONFIRM_DECLINE_BROADCAST}{DECLINE_BROADCAST}')
1068
+ ]]
1069
+
1070
+ return InlineKeyboardMarkup(buttons)
1071
+
1072
+ ================================================================================
1073
+
1074
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\broadcast_message\manage_data.py
1075
+ CONFIRM_DECLINE_BROADCAST = 'CNFM_DCLN_BRDCST'
1076
+ CONFIRM_BROADCAST = 'CONFIRM'
1077
+ DECLINE_BROADCAST = 'DECLINE'
1078
+
1079
+ ================================================================================
1080
+
1081
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\broadcast_message\static_text.py
1082
+ broadcast_command = '/broadcast'
1083
+ broadcast_no_access = "Sorry, you don't have access to this function."
1084
+ broadcast_wrong_format = f'To send message to all your users,' \
1085
+ f' type {broadcast_command} command with text separated by space.\n' \
1086
+ f'For example:\n' \
1087
+ f'{broadcast_command} Hello, my users! This <b>bold text</b> is for you, ' \
1088
+ f'as well as this <i>italic text.</i>\n\n' \
1089
+ f'Examples of using <code>HTML</code> style you can found <a href="https://core.telegram.org/bots/api#html-style">here</a>.'
1090
+ confirm_broadcast = "Confirm ✅"
1091
+ decline_broadcast = "Decline ❌"
1092
+ message_is_sent = "Message is sent ✅"
1093
+ declined_message_broadcasting = "Message broadcasting is declined ❌"
1094
+ error_with_html = "Can't parse your text in <code>HTML</code> style. Reason: \n{reason}"
1095
+
1096
+ ================================================================================
1097
+
1098
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\broadcast_message\utils.py
1099
+ from typing import Union, Optional, Dict, List
1100
+
1101
+ import telegram
1102
+ from telegram import MessageEntity, InlineKeyboardButton, InlineKeyboardMarkup
1103
+
1104
+ from dtb.settings import TELEGRAM_TOKEN
1105
+ from users.models import User
1106
+
1107
+
1108
+ def from_celery_markup_to_markup(celery_markup: Optional[List[List[Dict]]]) -> Optional[InlineKeyboardMarkup]:
1109
+ markup = None
1110
+ if celery_markup:
1111
+ markup = []
1112
+ for row_of_buttons in celery_markup:
1113
+ row = []
1114
+ for button in row_of_buttons:
1115
+ row.append(
1116
+ InlineKeyboardButton(
1117
+ text=button['text'],
1118
+ callback_data=button.get('callback_data'),
1119
+ url=button.get('url'),
1120
+ )
1121
+ )
1122
+ markup.append(row)
1123
+ markup = InlineKeyboardMarkup(markup)
1124
+ return markup
1125
+
1126
+
1127
+ def from_celery_entities_to_entities(celery_entities: Optional[List[Dict]] = None) -> Optional[List[MessageEntity]]:
1128
+ entities = None
1129
+ if celery_entities:
1130
+ entities = [
1131
+ MessageEntity(
1132
+ type=entity['type'],
1133
+ offset=entity['offset'],
1134
+ length=entity['length'],
1135
+ url=entity.get('url'),
1136
+ language=entity.get('language'),
1137
+ )
1138
+ for entity in celery_entities
1139
+ ]
1140
+ return entities
1141
+
1142
+
1143
+ def send_one_message(
1144
+ user_id: Union[str, int],
1145
+ text: str,
1146
+ parse_mode: Optional[str] = telegram.ParseMode.HTML,
1147
+ reply_markup: Optional[List[List[Dict]]] = None,
1148
+ reply_to_message_id: Optional[int] = None,
1149
+ disable_web_page_preview: Optional[bool] = None,
1150
+ entities: Optional[List[MessageEntity]] = None,
1151
+ tg_token: str = TELEGRAM_TOKEN,
1152
+ ) -> bool:
1153
+ bot = telegram.Bot(tg_token)
1154
+ try:
1155
+ m = bot.send_message(
1156
+ chat_id=user_id,
1157
+ text=text,
1158
+ parse_mode=parse_mode,
1159
+ reply_markup=reply_markup,
1160
+ reply_to_message_id=reply_to_message_id,
1161
+ disable_web_page_preview=disable_web_page_preview,
1162
+ entities=entities,
1163
+ )
1164
+ except telegram.error.Unauthorized:
1165
+ print(f"Can't send message to {user_id}. Reason: Bot was stopped.")
1166
+ User.objects.filter(user_id=user_id).update(is_blocked_bot=True)
1167
+ success = False
1168
+ else:
1169
+ success = True
1170
+ User.objects.filter(user_id=user_id).update(is_blocked_bot=False)
1171
+ return success
1172
+
1173
+ ================================================================================
1174
+
1175
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\broadcast_message\__init__.py
1176
+
1177
+ ================================================================================
1178
+
1179
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\location\handlers.py
1180
+ import telegram
1181
+ from telegram import Update
1182
+ from telegram.ext import CallbackContext
1183
+
1184
+ from tgbot.handlers.location.static_text import share_location, thanks_for_location
1185
+ from tgbot.handlers.location.keyboards import send_location_keyboard
1186
+ from users.models import User, Location
1187
+
1188
+
1189
+ def ask_for_location(update: Update, context: CallbackContext) -> None:
1190
+ """ Entered /ask_location command"""
1191
+ u = User.get_user(update, context)
1192
+
1193
+ context.bot.send_message(
1194
+ chat_id=u.user_id,
1195
+ text=share_location,
1196
+ reply_markup=send_location_keyboard()
1197
+ )
1198
+
1199
+
1200
+ def location_handler(update: Update, context: CallbackContext) -> None:
1201
+ # receiving user's location
1202
+ u = User.get_user(update, context)
1203
+ lat, lon = update.message.location.latitude, update.message.location.longitude
1204
+ Location.objects.create(user=u, latitude=lat, longitude=lon)
1205
+
1206
+ update.message.reply_text(
1207
+ thanks_for_location,
1208
+ reply_markup=telegram.ReplyKeyboardRemove(),
1209
+ )
1210
+
1211
+ ================================================================================
1212
+
1213
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\location\keyboards.py
1214
+ from telegram import ReplyKeyboardMarkup, KeyboardButton
1215
+
1216
+ from tgbot.handlers.location.static_text import SEND_LOCATION
1217
+
1218
+
1219
+ def send_location_keyboard() -> ReplyKeyboardMarkup:
1220
+ # resize_keyboard=False will make this button appear on half screen (become very large).
1221
+ # Likely, it will increase click conversion but may decrease UX quality.
1222
+ return ReplyKeyboardMarkup(
1223
+ [[KeyboardButton(text=SEND_LOCATION, request_location=True)]],
1224
+ resize_keyboard=True
1225
+ )
1226
+
1227
+ ================================================================================
1228
+
1229
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\location\static_text.py
1230
+ SEND_LOCATION = "Send 🌏🌎🌍"
1231
+ share_location = "Would you mind sharing your location?"
1232
+ thanks_for_location = "Thanks for 🌏🌎🌍"
1233
+
1234
+ ================================================================================
1235
+
1236
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\location\__init__.py
1237
+
1238
+ ================================================================================
1239
+
1240
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\onboarding\handlers.py
1241
+ import datetime
1242
+
1243
+ from django.utils import timezone
1244
+ from telegram import ParseMode, Update
1245
+ from telegram.ext import CallbackContext
1246
+
1247
+ from tgbot.handlers.onboarding import static_text
1248
+ from tgbot.handlers.utils.info import extract_user_data_from_update
1249
+ from users.models import User
1250
+ from tgbot.handlers.onboarding.keyboards import make_keyboard_for_start_command
1251
+
1252
+
1253
+ def command_start(update: Update, context: CallbackContext) -> None:
1254
+ u, created = User.get_user_and_created(update, context)
1255
+
1256
+ if created:
1257
+ text = static_text.start_created.format(first_name=u.first_name)
1258
+ else:
1259
+ text = static_text.start_not_created.format(first_name=u.first_name)
1260
+
1261
+ update.message.reply_text(text=text,
1262
+ reply_markup=make_keyboard_for_start_command())
1263
+
1264
+
1265
+ def secret_level(update: Update, context: CallbackContext) -> None:
1266
+ # callback_data: SECRET_LEVEL_BUTTON variable from manage_data.py
1267
+ """ Pressed 'secret_level_button_text' after /start command"""
1268
+ user_id = extract_user_data_from_update(update)['user_id']
1269
+ text = static_text.unlock_secret_room.format(
1270
+ user_count=User.objects.count(),
1271
+ active_24=User.objects.filter(updated_at__gte=timezone.now() - datetime.timedelta(hours=24)).count()
1272
+ )
1273
+
1274
+ context.bot.edit_message_text(
1275
+ text=text,
1276
+ chat_id=user_id,
1277
+ message_id=update.callback_query.message.message_id,
1278
+ parse_mode=ParseMode.HTML
1279
+ )
1280
+ ================================================================================
1281
+
1282
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\onboarding\keyboards.py
1283
+ from telegram import InlineKeyboardButton, InlineKeyboardMarkup
1284
+
1285
+ from tgbot.handlers.onboarding.manage_data import SECRET_LEVEL_BUTTON
1286
+ from tgbot.handlers.onboarding.static_text import github_button_text, secret_level_button_text
1287
+
1288
+
1289
+ def make_keyboard_for_start_command() -> InlineKeyboardMarkup:
1290
+ buttons = [[
1291
+ InlineKeyboardButton(github_button_text, url="https://github.com/ohld/django-telegram-bot"),
1292
+ InlineKeyboardButton(secret_level_button_text, callback_data=f'{SECRET_LEVEL_BUTTON}')
1293
+ ]]
1294
+
1295
+ return InlineKeyboardMarkup(buttons)
1296
+
1297
+ ================================================================================
1298
+
1299
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\onboarding\manage_data.py
1300
+ SECRET_LEVEL_BUTTON = 'SCRT_LVL'
1301
+
1302
+ ================================================================================
1303
+
1304
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\onboarding\static_text.py
1305
+ start_created = "Sup, {first_name}!"
1306
+ start_not_created = "Welcome back, {first_name}!"
1307
+ unlock_secret_room = "Congratulations! You've opened a secret room👁‍🗨. There is some information for you:\n" \
1308
+ "<b>Users</b>: {user_count}\n" \
1309
+ "<b>24h active</b>: {active_24}"
1310
+ github_button_text = "GitHub"
1311
+ secret_level_button_text = "Secret level🗝"
1312
+
1313
+ ================================================================================
1314
+
1315
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\onboarding\__init__.py
1316
+
1317
+ ================================================================================
1318
+
1319
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\utils\decorators.py
1320
+ from functools import wraps
1321
+ from typing import Callable
1322
+
1323
+ from telegram import Update, ChatAction
1324
+ from telegram.ext import CallbackContext
1325
+
1326
+ from users.models import User
1327
+
1328
+
1329
+ def admin_only(func: Callable):
1330
+ """
1331
+ Admin only decorator
1332
+ Used for handlers that only admins have access to
1333
+ """
1334
+
1335
+ @wraps(func)
1336
+ def wrapper(update: Update, context: CallbackContext, *args, **kwargs):
1337
+ user = User.get_user(update, context)
1338
+
1339
+ if not user.is_admin:
1340
+ return
1341
+
1342
+ return func(update, context, *args, **kwargs)
1343
+
1344
+ return wrapper
1345
+
1346
+
1347
+ def send_typing_action(func: Callable):
1348
+ """Sends typing action while processing func command."""
1349
+
1350
+ @wraps(func)
1351
+ def command_func(update: Update, context: CallbackContext, *args, **kwargs):
1352
+ update.effective_chat.send_chat_action(ChatAction.TYPING)
1353
+ return func(update, context, *args, **kwargs)
1354
+
1355
+ return command_func
1356
+
1357
+ ================================================================================
1358
+
1359
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\utils\error.py
1360
+ import logging
1361
+ import traceback
1362
+ import html
1363
+
1364
+ import telegram
1365
+ from telegram import Update
1366
+ from telegram.ext import CallbackContext
1367
+
1368
+ from dtb.settings import TELEGRAM_LOGS_CHAT_ID
1369
+ from users.models import User
1370
+
1371
+
1372
+ def send_stacktrace_to_tg_chat(update: Update, context: CallbackContext) -> None:
1373
+ u = User.get_user(update, context)
1374
+
1375
+ logging.error("Exception while handling an update:", exc_info=context.error)
1376
+
1377
+ tb_list = traceback.format_exception(None, context.error, context.error.__traceback__)
1378
+ tb_string = ''.join(tb_list)
1379
+
1380
+ # Build the message with some markup and additional information about what happened.
1381
+ # You might need to add some logic to deal with messages longer than the 4096 character limit.
1382
+ message = (
1383
+ f'An exception was raised while handling an update\n'
1384
+ f'<pre>{html.escape(tb_string)}</pre>'
1385
+ )
1386
+
1387
+ user_message = """
1388
+ 😔 Something broke inside the bot.
1389
+ It is because we are constantly improving our service but sometimes we might forget to test some basic stuff.
1390
+ We already received all the details to fix the issue.
1391
+ Return to /start
1392
+ """
1393
+ context.bot.send_message(
1394
+ chat_id=u.user_id,
1395
+ text=user_message,
1396
+ )
1397
+
1398
+ admin_message = f"⚠️⚠️⚠️ for {u.tg_str}:\n{message}"[:4090]
1399
+ if TELEGRAM_LOGS_CHAT_ID:
1400
+ context.bot.send_message(
1401
+ chat_id=TELEGRAM_LOGS_CHAT_ID,
1402
+ text=admin_message,
1403
+ parse_mode=telegram.ParseMode.HTML,
1404
+ )
1405
+ else:
1406
+ logging.error(admin_message)
1407
+
1408
+ ================================================================================
1409
+
1410
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\utils\files.py
1411
+ """
1412
+ 'document': {
1413
+ 'file_name': 'preds (4).csv', 'mime_type': 'text/csv',
1414
+ 'file_id': 'BQACAgIAAxkBAAIJ8F-QAVpXcgUgCUtr2OAHN-OC_2bmAAJwBwAC53CASIpMq-3ePqBXGwQ',
1415
+ 'file_unique_id': 'AgADcAcAAudwgEg', 'file_size': 28775
1416
+ }
1417
+ 'photo': [
1418
+ {'file_id': 'AgACAgIAAxkBAAIJ-F-QCOHZUv6Kmf_Z3eVSmByix_IwAAOvMRvncIBIYJQP2Js-sAWGaBiVLgADAQADAgADbQADjpMFAAEbBA', 'file_unique_id': 'AQADhmgYlS4AA46TBQAB', 'file_size': 13256, 'width': 148, 'height': 320},
1419
+ {'file_id': 'AgACAgIAAxkBAAIJ-F-QCOHZUv6Kmf_Z3eVSmByix_IwAAOvMRvncIBIYJQP2Js-sAWGaBiVLgADAQADAgADeAADkJMFAAEbBA', 'file_unique_id': 'AQADhmgYlS4AA5CTBQAB', 'file_size': 50857, 'width': 369, 'height': 800},
1420
+ {'file_id': 'AgACAgIAAxkBAAIJ-F-QCOHZUv6Kmf_Z3eVSmByix_IwAAOvMRvncIBIYJQP2Js-sAWGaBiVLgADAQADAgADeQADj5MFAAEbBA', 'file_unique_id': 'AQADhmgYlS4AA4-TBQAB', 'file_size': 76018, 'width': 591, 'height': 1280}
1421
+ ]
1422
+ 'video_note': {
1423
+ 'duration': 2, 'length': 300,
1424
+ 'thumb': {'file_id': 'AAMCAgADGQEAAgn_XaLgADAQAHbQADQCYAAhsE', 'file_unique_id': 'AQADWoxsmi4AA0AmAAI', 'file_size': 11684, 'width': 300, 'height': 300},
1425
+ 'file_id': 'DQACAgIAAxkBAAIJCASO6_6Hj8qY3PGwQ', 'file_unique_id': 'AgADeQcAAudwgEg', 'file_size': 102840
1426
+ }
1427
+ 'voice': {
1428
+ 'duration': 1, 'mime_type': 'audio/ogg',
1429
+ 'file_id': 'AwACAgIAAxkBAAIKAAFfkAu_8Ntpv8n9WWHETutijg20nAACegcAAudwgEi8N3Tjeom0IxsE',
1430
+ 'file_unique_id': 'AgADegcAAudwgEg', 'file_size': 4391
1431
+ }
1432
+ 'sticker': {
1433
+ 'width': 512, 'height': 512, 'emoji': '🤔', 'set_name': 's121356145_282028_by_stickerfacebot', 'is_animated': False,
1434
+ 'thumb': {
1435
+ 'file_id': 'AAMCAgADGQEAAgJUX5A5icQq_0qkwXnihR_MJuCKSRAAAmQAA3G_Owev57igO1Oj4itVTZguAAMBAAdtAAObPwACGwQ', 'file_unique_id': 'AQADK1VNmC4AA5s_AAI', 'file_size': 14242, 'width': 320, 'height': 320
1436
+ },
1437
+ 'file_id': 'CAACAgIAAxkBAAICVF-QOYnEKv9KpMF54oUfzCbgikkQAAJkAANxvzsHr-e4oDtTo-IbBA', 'file_unique_id': 'AgADZAADcb87Bw', 'file_size': 25182
1438
+ }
1439
+ 'video': {
1440
+ 'duration': 14, 'width': 480, 'height': 854, 'mime_type': 'video/mp4',
1441
+ 'thumb': {'file_id': 'AAMCAgADGQEAAgoIX5BAQy-AfwmWLgADAQAHbQADJhAAAhsE', 'file_unique_id': 'AQAD5H8Jli4AAyYQAAI', 'file_size': 9724, 'width': 180, 'height': 320},
1442
+ 'file_id': 'BAACAgIIAAKaCAACCcGASLV2hk3MavHGGwQ',
1443
+ 'file_unique_id': 'AgADmggAAgnBgEg', 'file_size': 1260506}, 'caption': '50603'
1444
+ }
1445
+ """
1446
+ from typing import Dict
1447
+
1448
+ import telegram
1449
+ from telegram import Update
1450
+ from telegram.ext import CallbackContext
1451
+
1452
+ from users.models import User
1453
+
1454
+ ALL_TG_FILE_TYPES = ["document", "video_note", "voice", "sticker", "audio", "video", "animation", "photo"]
1455
+
1456
+
1457
+ def _get_file_id(m: Dict) -> str:
1458
+ """ extract file_id from message (and file type?) """
1459
+
1460
+ for doc_type in ALL_TG_FILE_TYPES:
1461
+ if doc_type in m and doc_type != "photo":
1462
+ return m[doc_type]["file_id"]
1463
+
1464
+ if "photo" in m:
1465
+ best_photo = m["photo"][-1]
1466
+ return best_photo["file_id"]
1467
+
1468
+
1469
+ def show_file_id(update: Update, context: CallbackContext) -> None:
1470
+ """ Returns file_id of the attached file/media """
1471
+ u = User.get_user(update, context)
1472
+
1473
+ if u.is_admin:
1474
+ update_json = update.to_dict()
1475
+ file_id = _get_file_id(update_json["message"])
1476
+ message_id = update_json["message"]["message_id"]
1477
+ update.message.reply_text(
1478
+ text=f"`{file_id}`",
1479
+ parse_mode=telegram.ParseMode.HTML,
1480
+ reply_to_message_id=message_id
1481
+ )
1482
+
1483
+ ================================================================================
1484
+
1485
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\utils\info.py
1486
+ from typing import Dict
1487
+
1488
+ from telegram import Update
1489
+
1490
+
1491
+ def extract_user_data_from_update(update: Update) -> Dict:
1492
+ """ python-telegram-bot's Update instance --> User info """
1493
+ user = update.effective_user.to_dict()
1494
+
1495
+ return dict(
1496
+ user_id=user["id"],
1497
+ is_blocked_bot=False,
1498
+ **{
1499
+ k: user[k]
1500
+ for k in ["username", "first_name", "last_name", "language_code"]
1501
+ if k in user and user[k] is not None
1502
+ },
1503
+ )
1504
+
1505
+ ================================================================================
1506
+
1507
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\tgbot\handlers\utils\__init__.py
1508
+
1509
+ ================================================================================
1510
+
1511
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\users\admin.py
1512
+ from django.contrib import admin
1513
+ from django.http import HttpResponseRedirect
1514
+ from django.shortcuts import render
1515
+
1516
+ from dtb.settings import DEBUG
1517
+
1518
+ from users.models import Location
1519
+ from users.models import User
1520
+ from users.forms import BroadcastForm
1521
+
1522
+ from users.tasks import broadcast_message
1523
+ from tgbot.handlers.broadcast_message.utils import send_one_message
1524
+
1525
+
1526
+ @admin.register(User)
1527
+ class UserAdmin(admin.ModelAdmin):
1528
+ list_display = [
1529
+ 'user_id', 'username', 'first_name', 'last_name',
1530
+ 'language_code', 'deep_link',
1531
+ 'created_at', 'updated_at', "is_blocked_bot",
1532
+ ]
1533
+ list_filter = ["is_blocked_bot", ]
1534
+ search_fields = ('username', 'user_id')
1535
+
1536
+ actions = ['broadcast']
1537
+
1538
+ def broadcast(self, request, queryset):
1539
+ """ Select users via check mark in django-admin panel, then select "Broadcast" to send message"""
1540
+ user_ids = queryset.values_list('user_id', flat=True).distinct().iterator()
1541
+ if 'apply' in request.POST:
1542
+ broadcast_message_text = request.POST["broadcast_text"]
1543
+
1544
+ if DEBUG: # for test / debug purposes - run in same thread
1545
+ for user_id in user_ids:
1546
+ send_one_message(
1547
+ user_id=user_id,
1548
+ text=broadcast_message_text,
1549
+ )
1550
+ self.message_user(request, f"Just broadcasted to {len(queryset)} users")
1551
+ else:
1552
+ broadcast_message.delay(text=broadcast_message_text, user_ids=list(user_ids))
1553
+ self.message_user(request, f"Broadcasting of {len(queryset)} messages has been started")
1554
+
1555
+ return HttpResponseRedirect(request.get_full_path())
1556
+ else:
1557
+ form = BroadcastForm(initial={'_selected_action': user_ids})
1558
+ return render(
1559
+ request, "admin/broadcast_message.html", {'form': form, 'title': u'Broadcast message'}
1560
+ )
1561
+
1562
+
1563
+ @admin.register(Location)
1564
+ class LocationAdmin(admin.ModelAdmin):
1565
+ list_display = ['id', 'user_id', 'created_at']
1566
+
1567
+ ================================================================================
1568
+
1569
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\users\apps.py
1570
+ from django.apps import AppConfig
1571
+
1572
+
1573
+ class UsersConfig(AppConfig):
1574
+ name = 'users'
1575
+
1576
+ ================================================================================
1577
+
1578
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\users\forms.py
1579
+ from django import forms
1580
+
1581
+
1582
+ class BroadcastForm(forms.Form):
1583
+ _selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
1584
+ broadcast_text = forms.CharField(widget=forms.Textarea)
1585
+
1586
+ ================================================================================
1587
+
1588
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\users\models.py
1589
+ from __future__ import annotations
1590
+
1591
+ from typing import Union, Optional, Tuple
1592
+
1593
+ from django.db import models
1594
+ from django.db.models import QuerySet, Manager
1595
+ from telegram import Update
1596
+ from telegram.ext import CallbackContext
1597
+
1598
+ from tgbot.handlers.utils.info import extract_user_data_from_update
1599
+ from utils.models import CreateUpdateTracker, nb, CreateTracker, GetOrNoneManager
1600
+
1601
+
1602
+ class AdminUserManager(Manager):
1603
+ def get_queryset(self):
1604
+ return super().get_queryset().filter(is_admin=True)
1605
+
1606
+
1607
+ class User(CreateUpdateTracker):
1608
+ user_id = models.PositiveBigIntegerField(primary_key=True) # telegram_id
1609
+ username = models.CharField(max_length=32, **nb)
1610
+ first_name = models.CharField(max_length=256)
1611
+ last_name = models.CharField(max_length=256, **nb)
1612
+ language_code = models.CharField(max_length=8, help_text="Telegram client's lang", **nb)
1613
+ deep_link = models.CharField(max_length=64, **nb)
1614
+
1615
+ is_blocked_bot = models.BooleanField(default=False)
1616
+
1617
+ is_admin = models.BooleanField(default=False)
1618
+
1619
+ objects = GetOrNoneManager() # user = User.objects.get_or_none(user_id=<some_id>)
1620
+ admins = AdminUserManager() # User.admins.all()
1621
+
1622
+ def __str__(self):
1623
+ return f'@{self.username}' if self.username is not None else f'{self.user_id}'
1624
+
1625
+ @classmethod
1626
+ def get_user_and_created(cls, update: Update, context: CallbackContext) -> Tuple[User, bool]:
1627
+ """ python-telegram-bot's Update, Context --> User instance """
1628
+ data = extract_user_data_from_update(update)
1629
+ u, created = cls.objects.update_or_create(user_id=data["user_id"], defaults=data)
1630
+
1631
+ if created:
1632
+ # Save deep_link to User model
1633
+ if context is not None and context.args is not None and len(context.args) > 0:
1634
+ payload = context.args[0]
1635
+ if str(payload).strip() != str(data["user_id"]).strip(): # you can't invite yourself
1636
+ u.deep_link = payload
1637
+ u.save()
1638
+
1639
+ return u, created
1640
+
1641
+ @classmethod
1642
+ def get_user(cls, update: Update, context: CallbackContext) -> User:
1643
+ u, _ = cls.get_user_and_created(update, context)
1644
+ return u
1645
+
1646
+ @classmethod
1647
+ def get_user_by_username_or_user_id(cls, username_or_user_id: Union[str, int]) -> Optional[User]:
1648
+ """ Search user in DB, return User or None if not found """
1649
+ username = str(username_or_user_id).replace("@", "").strip().lower()
1650
+ if username.isdigit(): # user_id
1651
+ return cls.objects.filter(user_id=int(username)).first()
1652
+ return cls.objects.filter(username__iexact=username).first()
1653
+
1654
+ @property
1655
+ def invited_users(self) -> QuerySet[User]:
1656
+ return User.objects.filter(deep_link=str(self.user_id), created_at__gt=self.created_at)
1657
+
1658
+ @property
1659
+ def tg_str(self) -> str:
1660
+ if self.username:
1661
+ return f'@{self.username}'
1662
+ return f"{self.first_name} {self.last_name}" if self.last_name else f"{self.first_name}"
1663
+
1664
+
1665
+ class Location(CreateTracker):
1666
+ user = models.ForeignKey(User, on_delete=models.CASCADE)
1667
+ latitude = models.FloatField()
1668
+ longitude = models.FloatField()
1669
+
1670
+ objects = GetOrNoneManager()
1671
+
1672
+ def __str__(self):
1673
+ return f"user: {self.user}, created at {self.created_at.strftime('(%H:%M, %d %B %Y)')}"
1674
+
1675
+ ================================================================================
1676
+
1677
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\users\tasks.py
1678
+ """
1679
+ Celery tasks. Some of them will be launched periodically from admin panel via django-celery-beat
1680
+ """
1681
+
1682
+ import time
1683
+ from typing import Union, List, Optional, Dict
1684
+
1685
+ import telegram
1686
+
1687
+ from dtb.celery import app
1688
+ from celery.utils.log import get_task_logger
1689
+ from tgbot.handlers.broadcast_message.utils import send_one_message, from_celery_entities_to_entities, \
1690
+ from_celery_markup_to_markup
1691
+
1692
+ logger = get_task_logger(__name__)
1693
+
1694
+
1695
+ @app.task(ignore_result=True)
1696
+ def broadcast_message(
1697
+ user_ids: List[Union[str, int]],
1698
+ text: str,
1699
+ entities: Optional[List[Dict]] = None,
1700
+ reply_markup: Optional[List[List[Dict]]] = None,
1701
+ sleep_between: float = 0.4,
1702
+ parse_mode=telegram.ParseMode.HTML,
1703
+ ) -> None:
1704
+ """ It's used to broadcast message to big amount of users """
1705
+ logger.info(f"Going to send message: '{text}' to {len(user_ids)} users")
1706
+
1707
+ entities_ = from_celery_entities_to_entities(entities)
1708
+ reply_markup_ = from_celery_markup_to_markup(reply_markup)
1709
+ for user_id in user_ids:
1710
+ try:
1711
+ send_one_message(
1712
+ user_id=user_id,
1713
+ text=text,
1714
+ entities=entities_,
1715
+ parse_mode=parse_mode,
1716
+ reply_markup=reply_markup_,
1717
+ )
1718
+ logger.info(f"Broadcast message was sent to {user_id}")
1719
+ except Exception as e:
1720
+ logger.error(f"Failed to send message to {user_id}, reason: {e}")
1721
+ time.sleep(max(sleep_between, 0.1))
1722
+
1723
+ logger.info("Broadcast finished!")
1724
+
1725
+
1726
+
1727
+ ================================================================================
1728
+
1729
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\users\__init__.py
1730
+
1731
+ ================================================================================
1732
+
1733
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\users\migrations\0001_initial.py
1734
+ # Generated by Django 3.2.6 on 2021-08-25 10:43
1735
+
1736
+ from django.db import migrations, models
1737
+ import django.db.models.deletion
1738
+
1739
+
1740
+ class Migration(migrations.Migration):
1741
+
1742
+ initial = True
1743
+
1744
+ dependencies = [
1745
+ ]
1746
+
1747
+ operations = [
1748
+ migrations.CreateModel(
1749
+ name='User',
1750
+ fields=[
1751
+ ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
1752
+ ('updated_at', models.DateTimeField(auto_now=True)),
1753
+ ('user_id', models.IntegerField(primary_key=True, serialize=False)),
1754
+ ('username', models.CharField(blank=True, max_length=32, null=True)),
1755
+ ('first_name', models.CharField(max_length=256)),
1756
+ ('last_name', models.CharField(blank=True, max_length=256, null=True)),
1757
+ ('language_code', models.CharField(blank=True, help_text="Telegram client's lang", max_length=8, null=True)),
1758
+ ('deep_link', models.CharField(blank=True, max_length=64, null=True)),
1759
+ ('is_blocked_bot', models.BooleanField(default=False)),
1760
+ ('is_banned', models.BooleanField(default=False)),
1761
+ ('is_admin', models.BooleanField(default=False)),
1762
+ ('is_moderator', models.BooleanField(default=False)),
1763
+ ],
1764
+ options={
1765
+ 'ordering': ('-created_at',),
1766
+ 'abstract': False,
1767
+ },
1768
+ ),
1769
+ migrations.CreateModel(
1770
+ name='Location',
1771
+ fields=[
1772
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
1773
+ ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
1774
+ ('latitude', models.FloatField()),
1775
+ ('longitude', models.FloatField()),
1776
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.user')),
1777
+ ],
1778
+ options={
1779
+ 'ordering': ('-created_at',),
1780
+ 'abstract': False,
1781
+ },
1782
+ ),
1783
+ ]
1784
+
1785
+ ================================================================================
1786
+
1787
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\users\migrations\0002_alter_user_user_id.py
1788
+ # Generated by Django 3.2.8 on 2021-12-01 16:54
1789
+
1790
+ from django.db import migrations, models
1791
+
1792
+
1793
+ class Migration(migrations.Migration):
1794
+
1795
+ dependencies = [
1796
+ ('users', '0001_initial'),
1797
+ ]
1798
+
1799
+ operations = [
1800
+ migrations.AlterField(
1801
+ model_name='user',
1802
+ name='user_id',
1803
+ field=models.PositiveBigIntegerField(primary_key=True, serialize=False),
1804
+ ),
1805
+ ]
1806
+
1807
+ ================================================================================
1808
+
1809
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\users\migrations\0003_rm_unused_fields.py
1810
+ # Generated by Django 3.2.6 on 2021-12-01 17:47
1811
+
1812
+ from django.db import migrations
1813
+
1814
+
1815
+ class Migration(migrations.Migration):
1816
+
1817
+ dependencies = [
1818
+ ('users', '0002_alter_user_user_id'),
1819
+ ]
1820
+
1821
+ operations = [
1822
+ migrations.RemoveField(
1823
+ model_name='user',
1824
+ name='is_banned',
1825
+ ),
1826
+ migrations.RemoveField(
1827
+ model_name='user',
1828
+ name='is_moderator',
1829
+ ),
1830
+ ]
1831
+
1832
+ ================================================================================
1833
+
1834
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\users\migrations\__init__.py
1835
+
1836
+ ================================================================================
1837
+
1838
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\users\templates\admin\broadcast_message.html
1839
+ {% extends "admin/base_site.html" %}
1840
+
1841
+ {% block content %}
1842
+ <form action="" method="post">{% csrf_token %}
1843
+ {{ form }}
1844
+ <input type="hidden" name="action" value="broadcast" />
1845
+ <input type="submit" name="apply" value="Send" />
1846
+ </form>
1847
+ {% endblock %}
1848
+
1849
+
1850
+ ================================================================================
1851
+
1852
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\utils\models.py
1853
+ from django.core.exceptions import ObjectDoesNotExist
1854
+ from django.db import models
1855
+
1856
+
1857
+ nb = dict(null=True, blank=True)
1858
+
1859
+
1860
+ class CreateTracker(models.Model):
1861
+ created_at = models.DateTimeField(auto_now_add=True, db_index=True)
1862
+
1863
+ class Meta:
1864
+ abstract = True
1865
+ ordering = ('-created_at',)
1866
+
1867
+
1868
+ class CreateUpdateTracker(CreateTracker):
1869
+ updated_at = models.DateTimeField(auto_now=True)
1870
+
1871
+ class Meta(CreateTracker.Meta):
1872
+ abstract = True
1873
+
1874
+
1875
+ class GetOrNoneManager(models.Manager):
1876
+ """returns none if object doesn't exist else model instance"""
1877
+ def get_or_none(self, **kwargs):
1878
+ try:
1879
+ return self.get(**kwargs)
1880
+ except ObjectDoesNotExist:
1881
+ return None
1882
+
1883
+ ================================================================================
1884
+
1885
+ # File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\utils\__init__.py
1886
+
1887
+ ================================================================================
1888
+
1889
+ # Media File Paths
1890
+ # Folder: C:\Users\Shakeel\Desktop\django-telegram-bot-main\.github\imgs
1891
+ File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\.github\imgs\bot_commands_example.jpg
1892
+ File: C:\Users\Shakeel\Desktop\django-telegram-bot-main\.github\imgs\containers_status.png
1893
+
1894
+ ================================================================================
1895
+
docker-compose.yml ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: "3.8"
2
+
3
+ services:
4
+ db:
5
+ image: postgres:12
6
+ container_name: dtb_postgres
7
+ restart: always
8
+ volumes:
9
+ - postgres_data:/var/lib/postgresql/data/
10
+ environment:
11
+ - POSTGRES_USER=postgres
12
+ - POSTGRES_PASSWORD=postgres
13
+ env_file:
14
+ - ./.env
15
+ ports:
16
+ - "5433:5432"
17
+ redis:
18
+ image: redis:alpine
19
+ container_name: dtb_redis
20
+ web:
21
+ build:
22
+ context: .
23
+ dockerfile: LocalDockerfile
24
+ container_name: dtb_django
25
+ restart: always
26
+ command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
27
+ volumes:
28
+ - .:/code
29
+ ports:
30
+ - "8000:8000"
31
+ env_file:
32
+ - ./.env
33
+ depends_on:
34
+ - db
35
+ bot:
36
+ build:
37
+ context: .
38
+ dockerfile: LocalDockerfile
39
+ container_name: dtb_bot
40
+ restart: always
41
+ command: python run_polling.py
42
+ env_file:
43
+ - ./.env
44
+ depends_on:
45
+ - web
46
+ celery:
47
+ build:
48
+ context: .
49
+ dockerfile: LocalDockerfile
50
+ container_name: dtb_celery
51
+ restart: always
52
+ command: celery -A dtb worker --loglevel=INFO
53
+ volumes:
54
+ - .:/code
55
+ env_file:
56
+ - ./.env
57
+ depends_on:
58
+ - redis
59
+ - web
60
+ celery-beat:
61
+ build:
62
+ context: .
63
+ dockerfile: LocalDockerfile
64
+ container_name: dtb_beat
65
+ restart: always
66
+ command: celery -A dtb beat -l info --scheduler django_celery_beat.schedulers.DatabaseScheduler
67
+ volumes:
68
+ - .:/code
69
+ env_file:
70
+ - ./.env
71
+ depends_on:
72
+ - redis
73
+ - celery
74
+ - web
75
+
76
+ volumes:
77
+ postgres_data:
dtb/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import, unicode_literals
2
+
3
+ # This will make sure the app is always imported when
4
+ # Django starts so that shared_task will use this app.
5
+ from .celery import app as celery_app
6
+
7
+ __all__ = ('celery_app',)
dtb/asgi.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ASGI config for dtb project.
3
+
4
+ It exposes the ASGI callable as a module-level variable named ``application``.
5
+
6
+ For more information on this file, see
7
+ https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
8
+ """
9
+
10
+ import os
11
+
12
+ from django.core.asgi import get_asgi_application
13
+
14
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings')
15
+
16
+ application = get_asgi_application()
dtb/celery.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from celery import Celery
3
+
4
+ # set the default Django settings module for the 'celery' program.
5
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings')
6
+
7
+ app = Celery('dtb')
8
+
9
+ # Using a string here means the worker doesn't have to serialize
10
+ # the configuration object to child processes.
11
+ # - namespace='CELERY' means all celery-related configuration keys
12
+ # should have a `CELERY_` prefix.
13
+ app.config_from_object('django.conf:settings', namespace='CELERY')
14
+
15
+ # Load task modules from all registered Django app configs.
16
+ app.autodiscover_tasks()
17
+ app.conf.enable_utc = False
18
+
19
+
dtb/settings.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import sys
4
+
5
+ import dj_database_url
6
+ import dotenv
7
+
8
+ from pathlib import Path
9
+
10
+ # Build paths inside the project like this: BASE_DIR / 'subdir'.
11
+ BASE_DIR = Path(__file__).resolve().parent.parent
12
+
13
+
14
+ # Load env variables from file
15
+ dotenv_file = BASE_DIR / ".env"
16
+ if os.path.isfile(dotenv_file):
17
+ dotenv.load_dotenv(dotenv_file)
18
+
19
+
20
+ # SECURITY WARNING: keep the secret key used in production secret!
21
+ SECRET_KEY = os.getenv(
22
+ "DJANGO_SECRET_KEY",
23
+ 'x%#3&%giwv8f0+%r946en7z&d@9*rc$sl0qoql56xr%bh^w2mj',
24
+ )
25
+
26
+ if os.environ.get('DJANGO_DEBUG', default=False) in ['True', 'true', '1', True]:
27
+ DEBUG = True
28
+ else:
29
+ DEBUG = False
30
+
31
+ ALLOWED_HOSTS = ["*",] # since Telegram uses a lot of IPs for webhooks
32
+
33
+
34
+ INSTALLED_APPS = [
35
+ 'django.contrib.admin',
36
+ 'django.contrib.auth',
37
+ 'django.contrib.contenttypes',
38
+ 'django.contrib.sessions',
39
+ 'django.contrib.messages',
40
+ 'django.contrib.staticfiles',
41
+
42
+ # 3rd party apps
43
+ 'django_celery_beat',
44
+ 'debug_toolbar',
45
+
46
+ # local apps
47
+ 'users.apps.UsersConfig',
48
+ ]
49
+
50
+ MIDDLEWARE = [
51
+ 'django.middleware.security.SecurityMiddleware',
52
+ 'django.contrib.sessions.middleware.SessionMiddleware',
53
+ 'django.middleware.csrf.CsrfViewMiddleware',
54
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
55
+ 'django.contrib.messages.middleware.MessageMiddleware',
56
+ 'django.middleware.clickjacking.XFrameOptionsMiddleware',
57
+
58
+ 'whitenoise.middleware.WhiteNoiseMiddleware',
59
+ 'corsheaders.middleware.CorsMiddleware',
60
+ 'debug_toolbar.middleware.DebugToolbarMiddleware',
61
+
62
+ 'django.middleware.common.CommonMiddleware',
63
+ ]
64
+
65
+ INTERNAL_IPS = [
66
+ # ...
67
+ '127.0.0.1',
68
+ # ...
69
+ ]
70
+
71
+ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
72
+
73
+ CORS_ORIGIN_ALLOW_ALL = True
74
+ CORS_ALLOW_CREDENTIALS = True
75
+
76
+ ROOT_URLCONF = 'dtb.urls'
77
+
78
+ TEMPLATES = [
79
+ {
80
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
81
+ 'DIRS': [],
82
+ 'APP_DIRS': True,
83
+ 'OPTIONS': {
84
+ 'context_processors': [
85
+ 'django.template.context_processors.debug',
86
+ 'django.template.context_processors.request',
87
+ 'django.contrib.auth.context_processors.auth',
88
+ 'django.contrib.messages.context_processors.messages',
89
+ ],
90
+ },
91
+ },
92
+ ]
93
+
94
+ WSGI_APPLICATION = 'dtb.wsgi.application'
95
+ ASGI_APPLICATION = 'dtb.asgi.application'
96
+
97
+
98
+ # Database
99
+ # https://docs.djangoproject.com/en/3.0/ref/settings/#databases
100
+
101
+ DATABASES = {
102
+ 'default': dj_database_url.config(conn_max_age=600, default="sqlite:///db.sqlite3"),
103
+ }
104
+
105
+ # Password validation
106
+ # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
107
+
108
+ AUTH_PASSWORD_VALIDATORS = [
109
+ {
110
+ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
111
+ },
112
+ {
113
+ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
114
+ },
115
+ {
116
+ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
117
+ },
118
+ {
119
+ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
120
+ },
121
+ ]
122
+
123
+
124
+ # Internationalization
125
+ # https://docs.djangoproject.com/en/3.0/topics/i18n/
126
+
127
+ LANGUAGE_CODE = 'en-us'
128
+ TIME_ZONE = 'UTC'
129
+ USE_I18N = True
130
+ USE_L10N = True
131
+ USE_TZ = True
132
+
133
+
134
+ # Static files (CSS, JavaScript, Images)
135
+ # https://docs.djangoproject.com/en/3.0/howto/static-files/
136
+ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
137
+
138
+ PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
139
+ STATIC_URL = '/static/'
140
+ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
141
+
142
+
143
+ # -----> CELERY
144
+ REDIS_URL = os.getenv('REDIS_URL', 'redis://redis:6379')
145
+ BROKER_URL = REDIS_URL
146
+ CELERY_BROKER_URL = REDIS_URL
147
+ CELERY_RESULT_BACKEND = REDIS_URL
148
+ CELERY_ACCEPT_CONTENT = ['application/json']
149
+ CELERY_TASK_SERIALIZER = 'json'
150
+ CELERY_RESULT_SERIALIZER = 'json'
151
+ CELERY_TIMEZONE = TIME_ZONE
152
+ CELERY_TASK_DEFAULT_QUEUE = 'default'
153
+
154
+
155
+ # -----> TELEGRAM
156
+ TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
157
+ if TELEGRAM_TOKEN is None:
158
+ logging.error(
159
+ "Please provide TELEGRAM_TOKEN in .env file.\n"
160
+ "Example of .env file: https://github.com/ohld/django-telegram-bot/blob/main/.env_example"
161
+ )
162
+ sys.exit(1)
163
+
164
+ TELEGRAM_LOGS_CHAT_ID = os.getenv("TELEGRAM_LOGS_CHAT_ID", default=None)
165
+
166
+ # -----> SENTRY
167
+ # import sentry_sdk
168
+ # from sentry_sdk.integrations.django import DjangoIntegration
169
+ # from sentry_sdk.integrations.celery import CeleryIntegration
170
+ # from sentry_sdk.integrations.redis import RedisIntegration
171
+
172
+ # sentry_sdk.init(
173
+ # dsn="INPUT ...ingest.sentry.io/ LINK",
174
+ # integrations=[
175
+ # DjangoIntegration(),
176
+ # CeleryIntegration(),
177
+ # RedisIntegration(),
178
+ # ],
179
+ # traces_sample_rate=0.1,
180
+
181
+ # # If you wish to associate users to errors (assuming you are using
182
+ # # django.contrib.auth) you may enable sending PII data.
183
+ # send_default_pii=True
184
+ # )
dtb/urls.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """dtb URL Configuration
2
+
3
+ The `urlpatterns` list routes URLs to views. For more information please see:
4
+ https://docs.djangoproject.com/en/3.1/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: path('', 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: path('', Home.as_view(), name='home')
12
+ Including another URLconf
13
+ 1. Import the include() function: from django.urls import include, path
14
+ 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15
+ """
16
+ import debug_toolbar
17
+ from django.contrib import admin
18
+ from django.urls import path, include
19
+ from django.views.decorators.csrf import csrf_exempt
20
+
21
+ from . import views
22
+
23
+ urlpatterns = [
24
+ path('tgadmin/', admin.site.urls),
25
+ path('__debug__/', include(debug_toolbar.urls)),
26
+ path('', views.index, name="index"),
27
+ path('super_secter_webhook/', csrf_exempt(views.TelegramBotWebhookView.as_view())),
28
+ ]
dtb/views.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from django.views import View
4
+ from django.http import JsonResponse
5
+ from telegram import Update
6
+
7
+ from dtb.celery import app
8
+ from dtb.settings import DEBUG
9
+ from tgbot.dispatcher import dispatcher
10
+ from tgbot.main import bot
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ @app.task(ignore_result=True)
16
+ def process_telegram_event(update_json):
17
+ update = Update.de_json(update_json, bot)
18
+ dispatcher.process_update(update)
19
+
20
+
21
+ def index(request):
22
+ return JsonResponse({"error": "sup hacker"})
23
+
24
+
25
+ class TelegramBotWebhookView(View):
26
+ # WARNING: if fail - Telegram webhook will be delivered again.
27
+ # Can be fixed with async celery task execution
28
+ def post(self, request, *args, **kwargs):
29
+ if DEBUG:
30
+ process_telegram_event(json.loads(request.body))
31
+ else:
32
+ # Process Telegram event in Celery worker (async)
33
+ # Don't forget to run it and & Redis (message broker for Celery)!
34
+ # Locally, You can run all of these services via docker-compose.yml
35
+ process_telegram_event.delay(json.loads(request.body))
36
+
37
+ # e.g. remove buttons, typing event
38
+ return JsonResponse({"ok": "POST request processed"})
39
+
40
+ def get(self, request, *args, **kwargs): # for debug
41
+ return JsonResponse({"ok": "Get request received! But nothing done"})
dtb/wsgi.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ WSGI config for dtb 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/3.1/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', 'dtb.settings')
15
+
16
+ application = get_wsgi_application()
manage.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Django's command-line utility for administrative tasks."""
3
+ import os
4
+ import sys
5
+
6
+
7
+ def main():
8
+ """Run administrative tasks."""
9
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings')
10
+ try:
11
+ from django.core.management import execute_from_command_line
12
+ except ImportError as exc:
13
+ raise ImportError(
14
+ "Couldn't import Django. Are you sure it's installed and "
15
+ "available on your PYTHONPATH environment variable? Did you "
16
+ "forget to activate a virtual environment?"
17
+ ) from exc
18
+ execute_from_command_line(sys.argv)
19
+
20
+
21
+ if __name__ == '__main__':
22
+ main()
requirements.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pytz
2
+ requests
3
+ python-dotenv
4
+
5
+ ipython==8.5.0 # enhanced python interpreter
6
+
7
+ # Django
8
+ django==3.2.9
9
+ django-cors-headers==3.13.0
10
+ django-debug-toolbar==3.6.0
11
+ whitenoise==6.2.0 # for serving static files
12
+
13
+ # Django 3.0 async requirements
14
+ gunicorn==20.1.0
15
+ uvicorn==0.18.3
16
+
17
+ # Databases
18
+ psycopg2-binary==2.9.9
19
+ dj-database-url==1.0.0
20
+
21
+ # Distributed async tasks
22
+ celery==5.2.7
23
+ redis==4.3.4
24
+ django-celery-beat==2.3.0
25
+
26
+ # Telegram
27
+ python-telegram-bot==13.15 # last sync version
28
+
29
+ # monitoring
30
+ # sentry-sdk
run_polling.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, django
2
+
3
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dtb.settings')
4
+ django.setup()
5
+
6
+ from telegram import Bot
7
+ from telegram.ext import Updater
8
+
9
+ from dtb.settings import TELEGRAM_TOKEN
10
+ from tgbot.dispatcher import setup_dispatcher
11
+
12
+
13
+ def run_polling(tg_token: str = TELEGRAM_TOKEN):
14
+ """ Run bot in polling mode """
15
+ updater = Updater(tg_token, use_context=True)
16
+
17
+ dp = updater.dispatcher
18
+ dp = setup_dispatcher(dp)
19
+
20
+ bot_info = Bot(tg_token).get_me()
21
+ bot_link = f"https://t.me/{bot_info['username']}"
22
+
23
+ print(f"Polling of '{bot_link}' has started")
24
+ # it is really useful to send '👋' emoji to developer
25
+ # when you run local test
26
+ # bot.send_message(text='👋', chat_id=<YOUR TELEGRAM ID>)
27
+
28
+ updater.start_polling()
29
+ updater.idle()
30
+
31
+
32
+ if __name__ == "__main__":
33
+ run_polling()
runtime.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ python-3.8.3
tgbot/__init__.py ADDED
File without changes
tgbot/dispatcher.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Telegram event handlers
3
+ """
4
+ from telegram.ext import (
5
+ Dispatcher, Filters,
6
+ CommandHandler, MessageHandler,
7
+ CallbackQueryHandler,
8
+ )
9
+
10
+ from dtb.settings import DEBUG
11
+ from tgbot.handlers.broadcast_message.manage_data import CONFIRM_DECLINE_BROADCAST
12
+ from tgbot.handlers.broadcast_message.static_text import broadcast_command
13
+ from tgbot.handlers.onboarding.manage_data import SECRET_LEVEL_BUTTON
14
+
15
+ from tgbot.handlers.utils import files, error
16
+ from tgbot.handlers.admin import handlers as admin_handlers
17
+ from tgbot.handlers.location import handlers as location_handlers
18
+ from tgbot.handlers.onboarding import handlers as onboarding_handlers
19
+ from tgbot.handlers.broadcast_message import handlers as broadcast_handlers
20
+ from tgbot.main import bot
21
+
22
+
23
+ def setup_dispatcher(dp):
24
+ """
25
+ Adding handlers for events from Telegram
26
+ """
27
+ # onboarding
28
+ dp.add_handler(CommandHandler("start", onboarding_handlers.command_start))
29
+
30
+ # admin commands
31
+ dp.add_handler(CommandHandler("admin", admin_handlers.admin))
32
+ dp.add_handler(CommandHandler("stats", admin_handlers.stats))
33
+ dp.add_handler(CommandHandler('export_users', admin_handlers.export_users))
34
+
35
+ # location
36
+ dp.add_handler(CommandHandler("ask_location", location_handlers.ask_for_location))
37
+ dp.add_handler(MessageHandler(Filters.location, location_handlers.location_handler))
38
+
39
+ # secret level
40
+ dp.add_handler(CallbackQueryHandler(onboarding_handlers.secret_level, pattern=f"^{SECRET_LEVEL_BUTTON}"))
41
+
42
+ # broadcast message
43
+ dp.add_handler(
44
+ MessageHandler(Filters.regex(rf'^{broadcast_command}(/s)?.*'), broadcast_handlers.broadcast_command_with_message)
45
+ )
46
+ dp.add_handler(
47
+ CallbackQueryHandler(broadcast_handlers.broadcast_decision_handler, pattern=f"^{CONFIRM_DECLINE_BROADCAST}")
48
+ )
49
+
50
+ # files
51
+ dp.add_handler(MessageHandler(
52
+ Filters.animation, files.show_file_id,
53
+ ))
54
+
55
+ # handling errors
56
+ dp.add_error_handler(error.send_stacktrace_to_tg_chat)
57
+
58
+ # EXAMPLES FOR HANDLERS
59
+ # dp.add_handler(MessageHandler(Filters.text, <function_handler>))
60
+ # dp.add_handler(MessageHandler(
61
+ # Filters.document, <function_handler>,
62
+ # ))
63
+ # dp.add_handler(CallbackQueryHandler(<function_handler>, pattern="^r\d+_\d+"))
64
+ # dp.add_handler(MessageHandler(
65
+ # Filters.chat(chat_id=int(TELEGRAM_FILESTORAGE_ID)),
66
+ # # & Filters.forwarded & (Filters.photo | Filters.video | Filters.animation),
67
+ # <function_handler>,
68
+ # ))
69
+
70
+ return dp
71
+
72
+
73
+ n_workers = 0 if DEBUG else 4
74
+ dispatcher = setup_dispatcher(Dispatcher(bot, update_queue=None, workers=n_workers, use_context=True))
tgbot/handlers/__init__.py ADDED
File without changes
tgbot/handlers/admin/__init__.py ADDED
File without changes
tgbot/handlers/admin/handlers.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import timedelta
2
+
3
+ from django.utils.timezone import now
4
+ from telegram import ParseMode, Update
5
+ from telegram.ext import CallbackContext
6
+
7
+ from tgbot.handlers.admin import static_text
8
+ from tgbot.handlers.admin.utils import _get_csv_from_qs_values
9
+ from tgbot.handlers.utils.decorators import admin_only, send_typing_action
10
+ from users.models import User
11
+
12
+
13
+ @admin_only
14
+ def admin(update: Update, context: CallbackContext) -> None:
15
+ """ Show help info about all secret admins commands """
16
+ update.message.reply_text(static_text.secret_admin_commands)
17
+
18
+
19
+ @admin_only
20
+ def stats(update: Update, context: CallbackContext) -> None:
21
+ """ Show help info about all secret admins commands """
22
+ text = static_text.users_amount_stat.format(
23
+ user_count=User.objects.count(), # count may be ineffective if there are a lot of users.
24
+ active_24=User.objects.filter(updated_at__gte=now() - timedelta(hours=24)).count()
25
+ )
26
+
27
+ update.message.reply_text(
28
+ text,
29
+ parse_mode=ParseMode.HTML,
30
+ disable_web_page_preview=True,
31
+ )
32
+
33
+
34
+ @admin_only
35
+ @send_typing_action
36
+ def export_users(update: Update, context: CallbackContext) -> None:
37
+ # in values argument you can specify which fields should be returned in output csv
38
+ users = User.objects.all().values()
39
+ csv_users = _get_csv_from_qs_values(users)
40
+ update.message.reply_document(csv_users)
tgbot/handlers/admin/static_text.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ command_start = '/stats'
2
+
3
+ secret_admin_commands = f"⚠️ Secret Admin commands\n" \
4
+ f"{command_start} - bot stats"
5
+
6
+ users_amount_stat = "<b>Users</b>: {user_count}\n" \
7
+ "<b>24h active</b>: {active_24}"
tgbot/handlers/admin/utils.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import csv
3
+
4
+ from datetime import datetime
5
+ from django.db.models import QuerySet
6
+ from typing import Dict
7
+
8
+
9
+ def _get_csv_from_qs_values(queryset: QuerySet[Dict], filename: str = 'users'):
10
+ keys = queryset[0].keys()
11
+
12
+ # csv module can write data in io.StringIO buffer only
13
+ s = io.StringIO()
14
+ dict_writer = csv.DictWriter(s, fieldnames=keys)
15
+ dict_writer.writeheader()
16
+ dict_writer.writerows(queryset)
17
+ s.seek(0)
18
+
19
+ # python-telegram-bot library can send files only from io.BytesIO buffer
20
+ # we need to convert StringIO to BytesIO
21
+ buf = io.BytesIO()
22
+
23
+ # extract csv-string, convert it to bytes and write to buffer
24
+ buf.write(s.getvalue().encode())
25
+ buf.seek(0)
26
+
27
+ # set a filename with file's extension
28
+ buf.name = f"{filename}__{datetime.now().strftime('%Y.%m.%d.%H.%M')}.csv"
29
+
30
+ return buf
tgbot/handlers/broadcast_message/__init__.py ADDED
File without changes
tgbot/handlers/broadcast_message/handlers.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import telegram
4
+ from telegram import Update
5
+ from telegram.ext import CallbackContext
6
+
7
+ from dtb.settings import DEBUG
8
+ from .manage_data import CONFIRM_DECLINE_BROADCAST, CONFIRM_BROADCAST
9
+ from .keyboards import keyboard_confirm_decline_broadcasting
10
+ from .static_text import broadcast_command, broadcast_wrong_format, broadcast_no_access, error_with_html, \
11
+ message_is_sent, declined_message_broadcasting
12
+ from users.models import User
13
+ from users.tasks import broadcast_message
14
+
15
+
16
+ def broadcast_command_with_message(update: Update, context: CallbackContext):
17
+ """ Type /broadcast <some_text>. Then check your message in HTML format and broadcast to users."""
18
+ u = User.get_user(update, context)
19
+
20
+ if not u.is_admin:
21
+ update.message.reply_text(
22
+ text=broadcast_no_access,
23
+ )
24
+ else:
25
+ if update.message.text == broadcast_command:
26
+ # user typed only command without text for the message.
27
+ update.message.reply_text(
28
+ text=broadcast_wrong_format,
29
+ parse_mode=telegram.ParseMode.HTML,
30
+ )
31
+ return
32
+
33
+ text = f"{update.message.text.replace(f'{broadcast_command} ', '')}"
34
+ markup = keyboard_confirm_decline_broadcasting()
35
+
36
+ try:
37
+ update.message.reply_text(
38
+ text=text,
39
+ parse_mode=telegram.ParseMode.HTML,
40
+ reply_markup=markup,
41
+ )
42
+ except telegram.error.BadRequest as e:
43
+ update.message.reply_text(
44
+ text=error_with_html.format(reason=e),
45
+ parse_mode=telegram.ParseMode.HTML,
46
+ )
47
+
48
+
49
+ def broadcast_decision_handler(update: Update, context: CallbackContext) -> None:
50
+ # callback_data: CONFIRM_DECLINE_BROADCAST variable from manage_data.py
51
+ """ Entered /broadcast <some_text>.
52
+ Shows text in HTML style with two buttons:
53
+ Confirm and Decline
54
+ """
55
+ broadcast_decision = update.callback_query.data[len(CONFIRM_DECLINE_BROADCAST):]
56
+
57
+ entities_for_celery = update.callback_query.message.to_dict().get('entities')
58
+ entities, text = update.callback_query.message.entities, update.callback_query.message.text
59
+
60
+ if broadcast_decision == CONFIRM_BROADCAST:
61
+ admin_text = message_is_sent
62
+ user_ids = list(User.objects.all().values_list('user_id', flat=True))
63
+
64
+ if DEBUG:
65
+ broadcast_message(
66
+ user_ids=user_ids,
67
+ text=text,
68
+ entities=entities_for_celery,
69
+ )
70
+ else:
71
+ # send in async mode via celery
72
+ broadcast_message.delay(
73
+ user_ids=user_ids,
74
+ text=text,
75
+ entities=entities_for_celery,
76
+ )
77
+ else:
78
+ context.bot.send_message(
79
+ chat_id=update.callback_query.message.chat_id,
80
+ text=declined_message_broadcasting,
81
+ )
82
+ admin_text = text
83
+
84
+ context.bot.edit_message_text(
85
+ text=admin_text,
86
+ chat_id=update.callback_query.message.chat_id,
87
+ message_id=update.callback_query.message.message_id,
88
+ entities=None if broadcast_decision == CONFIRM_BROADCAST else entities,
89
+ )
tgbot/handlers/broadcast_message/keyboards.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from telegram import InlineKeyboardButton, InlineKeyboardMarkup
2
+
3
+ from tgbot.handlers.broadcast_message.manage_data import CONFIRM_DECLINE_BROADCAST, CONFIRM_BROADCAST, DECLINE_BROADCAST
4
+ from tgbot.handlers.broadcast_message.static_text import confirm_broadcast, decline_broadcast
5
+
6
+
7
+ def keyboard_confirm_decline_broadcasting() -> InlineKeyboardMarkup:
8
+ buttons = [[
9
+ InlineKeyboardButton(confirm_broadcast, callback_data=f'{CONFIRM_DECLINE_BROADCAST}{CONFIRM_BROADCAST}'),
10
+ InlineKeyboardButton(decline_broadcast, callback_data=f'{CONFIRM_DECLINE_BROADCAST}{DECLINE_BROADCAST}')
11
+ ]]
12
+
13
+ return InlineKeyboardMarkup(buttons)
tgbot/handlers/broadcast_message/manage_data.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ CONFIRM_DECLINE_BROADCAST = 'CNFM_DCLN_BRDCST'
2
+ CONFIRM_BROADCAST = 'CONFIRM'
3
+ DECLINE_BROADCAST = 'DECLINE'
tgbot/handlers/broadcast_message/static_text.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ broadcast_command = '/broadcast'
2
+ broadcast_no_access = "Sorry, you don't have access to this function."
3
+ broadcast_wrong_format = f'To send message to all your users,' \
4
+ f' type {broadcast_command} command with text separated by space.\n' \
5
+ f'For example:\n' \
6
+ f'{broadcast_command} Hello, my users! This <b>bold text</b> is for you, ' \
7
+ f'as well as this <i>italic text.</i>\n\n' \
8
+ f'Examples of using <code>HTML</code> style you can found <a href="https://core.telegram.org/bots/api#html-style">here</a>.'
9
+ confirm_broadcast = "Confirm ✅"
10
+ decline_broadcast = "Decline ❌"
11
+ message_is_sent = "Message is sent ✅"
12
+ declined_message_broadcasting = "Message broadcasting is declined ❌"
13
+ error_with_html = "Can't parse your text in <code>HTML</code> style. Reason: \n{reason}"
tgbot/handlers/broadcast_message/utils.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Optional, Dict, List
2
+
3
+ import telegram
4
+ from telegram import MessageEntity, InlineKeyboardButton, InlineKeyboardMarkup
5
+
6
+ from dtb.settings import TELEGRAM_TOKEN
7
+ from users.models import User
8
+
9
+
10
+ def from_celery_markup_to_markup(celery_markup: Optional[List[List[Dict]]]) -> Optional[InlineKeyboardMarkup]:
11
+ markup = None
12
+ if celery_markup:
13
+ markup = []
14
+ for row_of_buttons in celery_markup:
15
+ row = []
16
+ for button in row_of_buttons:
17
+ row.append(
18
+ InlineKeyboardButton(
19
+ text=button['text'],
20
+ callback_data=button.get('callback_data'),
21
+ url=button.get('url'),
22
+ )
23
+ )
24
+ markup.append(row)
25
+ markup = InlineKeyboardMarkup(markup)
26
+ return markup
27
+
28
+
29
+ def from_celery_entities_to_entities(celery_entities: Optional[List[Dict]] = None) -> Optional[List[MessageEntity]]:
30
+ entities = None
31
+ if celery_entities:
32
+ entities = [
33
+ MessageEntity(
34
+ type=entity['type'],
35
+ offset=entity['offset'],
36
+ length=entity['length'],
37
+ url=entity.get('url'),
38
+ language=entity.get('language'),
39
+ )
40
+ for entity in celery_entities
41
+ ]
42
+ return entities
43
+
44
+
45
+ def send_one_message(
46
+ user_id: Union[str, int],
47
+ text: str,
48
+ parse_mode: Optional[str] = telegram.ParseMode.HTML,
49
+ reply_markup: Optional[List[List[Dict]]] = None,
50
+ reply_to_message_id: Optional[int] = None,
51
+ disable_web_page_preview: Optional[bool] = None,
52
+ entities: Optional[List[MessageEntity]] = None,
53
+ tg_token: str = TELEGRAM_TOKEN,
54
+ ) -> bool:
55
+ bot = telegram.Bot(tg_token)
56
+ try:
57
+ m = bot.send_message(
58
+ chat_id=user_id,
59
+ text=text,
60
+ parse_mode=parse_mode,
61
+ reply_markup=reply_markup,
62
+ reply_to_message_id=reply_to_message_id,
63
+ disable_web_page_preview=disable_web_page_preview,
64
+ entities=entities,
65
+ )
66
+ except telegram.error.Unauthorized:
67
+ print(f"Can't send message to {user_id}. Reason: Bot was stopped.")
68
+ User.objects.filter(user_id=user_id).update(is_blocked_bot=True)
69
+ success = False
70
+ else:
71
+ success = True
72
+ User.objects.filter(user_id=user_id).update(is_blocked_bot=False)
73
+ return success
tgbot/handlers/location/__init__.py ADDED
File without changes
tgbot/handlers/location/handlers.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import telegram
2
+ from telegram import Update
3
+ from telegram.ext import CallbackContext
4
+
5
+ from tgbot.handlers.location.static_text import share_location, thanks_for_location
6
+ from tgbot.handlers.location.keyboards import send_location_keyboard
7
+ from users.models import User, Location
8
+
9
+
10
+ def ask_for_location(update: Update, context: CallbackContext) -> None:
11
+ """ Entered /ask_location command"""
12
+ u = User.get_user(update, context)
13
+
14
+ context.bot.send_message(
15
+ chat_id=u.user_id,
16
+ text=share_location,
17
+ reply_markup=send_location_keyboard()
18
+ )
19
+
20
+
21
+ def location_handler(update: Update, context: CallbackContext) -> None:
22
+ # receiving user's location
23
+ u = User.get_user(update, context)
24
+ lat, lon = update.message.location.latitude, update.message.location.longitude
25
+ Location.objects.create(user=u, latitude=lat, longitude=lon)
26
+
27
+ update.message.reply_text(
28
+ thanks_for_location,
29
+ reply_markup=telegram.ReplyKeyboardRemove(),
30
+ )
tgbot/handlers/location/keyboards.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from telegram import ReplyKeyboardMarkup, KeyboardButton
2
+
3
+ from tgbot.handlers.location.static_text import SEND_LOCATION
4
+
5
+
6
+ def send_location_keyboard() -> ReplyKeyboardMarkup:
7
+ # resize_keyboard=False will make this button appear on half screen (become very large).
8
+ # Likely, it will increase click conversion but may decrease UX quality.
9
+ return ReplyKeyboardMarkup(
10
+ [[KeyboardButton(text=SEND_LOCATION, request_location=True)]],
11
+ resize_keyboard=True
12
+ )
tgbot/handlers/location/static_text.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ SEND_LOCATION = "Send 🌏🌎🌍"
2
+ share_location = "Would you mind sharing your location?"
3
+ thanks_for_location = "Thanks for 🌏🌎🌍"
tgbot/handlers/onboarding/__init__.py ADDED
File without changes
tgbot/handlers/onboarding/handlers.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+
3
+ from django.utils import timezone
4
+ from telegram import ParseMode, Update
5
+ from telegram.ext import CallbackContext
6
+
7
+ from tgbot.handlers.onboarding import static_text
8
+ from tgbot.handlers.utils.info import extract_user_data_from_update
9
+ from users.models import User
10
+ from tgbot.handlers.onboarding.keyboards import make_keyboard_for_start_command
11
+
12
+
13
+ def command_start(update: Update, context: CallbackContext) -> None:
14
+ u, created = User.get_user_and_created(update, context)
15
+
16
+ if created:
17
+ text = static_text.start_created.format(first_name=u.first_name)
18
+ else:
19
+ text = static_text.start_not_created.format(first_name=u.first_name)
20
+
21
+ update.message.reply_text(text=text,
22
+ reply_markup=make_keyboard_for_start_command())
23
+
24
+
25
+ def secret_level(update: Update, context: CallbackContext) -> None:
26
+ # callback_data: SECRET_LEVEL_BUTTON variable from manage_data.py
27
+ """ Pressed 'secret_level_button_text' after /start command"""
28
+ user_id = extract_user_data_from_update(update)['user_id']
29
+ text = static_text.unlock_secret_room.format(
30
+ user_count=User.objects.count(),
31
+ active_24=User.objects.filter(updated_at__gte=timezone.now() - datetime.timedelta(hours=24)).count()
32
+ )
33
+
34
+ context.bot.edit_message_text(
35
+ text=text,
36
+ chat_id=user_id,
37
+ message_id=update.callback_query.message.message_id,
38
+ parse_mode=ParseMode.HTML
39
+ )
tgbot/handlers/onboarding/keyboards.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from telegram import InlineKeyboardButton, InlineKeyboardMarkup
2
+
3
+ from tgbot.handlers.onboarding.manage_data import SECRET_LEVEL_BUTTON
4
+ from tgbot.handlers.onboarding.static_text import github_button_text, secret_level_button_text
5
+
6
+
7
+ def make_keyboard_for_start_command() -> InlineKeyboardMarkup:
8
+ buttons = [[
9
+ InlineKeyboardButton(github_button_text, url="https://github.com/ohld/django-telegram-bot"),
10
+ InlineKeyboardButton(secret_level_button_text, callback_data=f'{SECRET_LEVEL_BUTTON}')
11
+ ]]
12
+
13
+ return InlineKeyboardMarkup(buttons)
tgbot/handlers/onboarding/manage_data.py ADDED
@@ -0,0 +1 @@
 
 
1
+ SECRET_LEVEL_BUTTON = 'SCRT_LVL'
tgbot/handlers/onboarding/static_text.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ start_created = "Sup, {first_name}!"
2
+ start_not_created = "Welcome back, {first_name}!"
3
+ unlock_secret_room = "Congratulations! You've opened a secret room👁‍🗨. There is some information for you:\n" \
4
+ "<b>Users</b>: {user_count}\n" \
5
+ "<b>24h active</b>: {active_24}"
6
+ github_button_text = "GitHub"
7
+ secret_level_button_text = "Secret level🗝"
tgbot/handlers/utils/__init__.py ADDED
File without changes
tgbot/handlers/utils/decorators.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import wraps
2
+ from typing import Callable
3
+
4
+ from telegram import Update, ChatAction
5
+ from telegram.ext import CallbackContext
6
+
7
+ from users.models import User
8
+
9
+
10
+ def admin_only(func: Callable):
11
+ """
12
+ Admin only decorator
13
+ Used for handlers that only admins have access to
14
+ """
15
+
16
+ @wraps(func)
17
+ def wrapper(update: Update, context: CallbackContext, *args, **kwargs):
18
+ user = User.get_user(update, context)
19
+
20
+ if not user.is_admin:
21
+ return
22
+
23
+ return func(update, context, *args, **kwargs)
24
+
25
+ return wrapper
26
+
27
+
28
+ def send_typing_action(func: Callable):
29
+ """Sends typing action while processing func command."""
30
+
31
+ @wraps(func)
32
+ def command_func(update: Update, context: CallbackContext, *args, **kwargs):
33
+ update.effective_chat.send_chat_action(ChatAction.TYPING)
34
+ return func(update, context, *args, **kwargs)
35
+
36
+ return command_func
tgbot/handlers/utils/error.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import traceback
3
+ import html
4
+
5
+ import telegram
6
+ from telegram import Update
7
+ from telegram.ext import CallbackContext
8
+
9
+ from dtb.settings import TELEGRAM_LOGS_CHAT_ID
10
+ from users.models import User
11
+
12
+
13
+ def send_stacktrace_to_tg_chat(update: Update, context: CallbackContext) -> None:
14
+ u = User.get_user(update, context)
15
+
16
+ logging.error("Exception while handling an update:", exc_info=context.error)
17
+
18
+ tb_list = traceback.format_exception(None, context.error, context.error.__traceback__)
19
+ tb_string = ''.join(tb_list)
20
+
21
+ # Build the message with some markup and additional information about what happened.
22
+ # You might need to add some logic to deal with messages longer than the 4096 character limit.
23
+ message = (
24
+ f'An exception was raised while handling an update\n'
25
+ f'<pre>{html.escape(tb_string)}</pre>'
26
+ )
27
+
28
+ user_message = """
29
+ 😔 Something broke inside the bot.
30
+ It is because we are constantly improving our service but sometimes we might forget to test some basic stuff.
31
+ We already received all the details to fix the issue.
32
+ Return to /start
33
+ """
34
+ context.bot.send_message(
35
+ chat_id=u.user_id,
36
+ text=user_message,
37
+ )
38
+
39
+ admin_message = f"⚠️⚠️⚠️ for {u.tg_str}:\n{message}"[:4090]
40
+ if TELEGRAM_LOGS_CHAT_ID:
41
+ context.bot.send_message(
42
+ chat_id=TELEGRAM_LOGS_CHAT_ID,
43
+ text=admin_message,
44
+ parse_mode=telegram.ParseMode.HTML,
45
+ )
46
+ else:
47
+ logging.error(admin_message)
tgbot/handlers/utils/files.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 'document': {
3
+ 'file_name': 'preds (4).csv', 'mime_type': 'text/csv',
4
+ 'file_id': 'BQACAgIAAxkBAAIJ8F-QAVpXcgUgCUtr2OAHN-OC_2bmAAJwBwAC53CASIpMq-3ePqBXGwQ',
5
+ 'file_unique_id': 'AgADcAcAAudwgEg', 'file_size': 28775
6
+ }
7
+ 'photo': [
8
+ {'file_id': 'AgACAgIAAxkBAAIJ-F-QCOHZUv6Kmf_Z3eVSmByix_IwAAOvMRvncIBIYJQP2Js-sAWGaBiVLgADAQADAgADbQADjpMFAAEbBA', 'file_unique_id': 'AQADhmgYlS4AA46TBQAB', 'file_size': 13256, 'width': 148, 'height': 320},
9
+ {'file_id': 'AgACAgIAAxkBAAIJ-F-QCOHZUv6Kmf_Z3eVSmByix_IwAAOvMRvncIBIYJQP2Js-sAWGaBiVLgADAQADAgADeAADkJMFAAEbBA', 'file_unique_id': 'AQADhmgYlS4AA5CTBQAB', 'file_size': 50857, 'width': 369, 'height': 800},
10
+ {'file_id': 'AgACAgIAAxkBAAIJ-F-QCOHZUv6Kmf_Z3eVSmByix_IwAAOvMRvncIBIYJQP2Js-sAWGaBiVLgADAQADAgADeQADj5MFAAEbBA', 'file_unique_id': 'AQADhmgYlS4AA4-TBQAB', 'file_size': 76018, 'width': 591, 'height': 1280}
11
+ ]
12
+ 'video_note': {
13
+ 'duration': 2, 'length': 300,
14
+ 'thumb': {'file_id': 'AAMCAgADGQEAAgn_XaLgADAQAHbQADQCYAAhsE', 'file_unique_id': 'AQADWoxsmi4AA0AmAAI', 'file_size': 11684, 'width': 300, 'height': 300},
15
+ 'file_id': 'DQACAgIAAxkBAAIJCASO6_6Hj8qY3PGwQ', 'file_unique_id': 'AgADeQcAAudwgEg', 'file_size': 102840
16
+ }
17
+ 'voice': {
18
+ 'duration': 1, 'mime_type': 'audio/ogg',
19
+ 'file_id': 'AwACAgIAAxkBAAIKAAFfkAu_8Ntpv8n9WWHETutijg20nAACegcAAudwgEi8N3Tjeom0IxsE',
20
+ 'file_unique_id': 'AgADegcAAudwgEg', 'file_size': 4391
21
+ }
22
+ 'sticker': {
23
+ 'width': 512, 'height': 512, 'emoji': '🤔', 'set_name': 's121356145_282028_by_stickerfacebot', 'is_animated': False,
24
+ 'thumb': {
25
+ 'file_id': 'AAMCAgADGQEAAgJUX5A5icQq_0qkwXnihR_MJuCKSRAAAmQAA3G_Owev57igO1Oj4itVTZguAAMBAAdtAAObPwACGwQ', 'file_unique_id': 'AQADK1VNmC4AA5s_AAI', 'file_size': 14242, 'width': 320, 'height': 320
26
+ },
27
+ 'file_id': 'CAACAgIAAxkBAAICVF-QOYnEKv9KpMF54oUfzCbgikkQAAJkAANxvzsHr-e4oDtTo-IbBA', 'file_unique_id': 'AgADZAADcb87Bw', 'file_size': 25182
28
+ }
29
+ 'video': {
30
+ 'duration': 14, 'width': 480, 'height': 854, 'mime_type': 'video/mp4',
31
+ 'thumb': {'file_id': 'AAMCAgADGQEAAgoIX5BAQy-AfwmWLgADAQAHbQADJhAAAhsE', 'file_unique_id': 'AQAD5H8Jli4AAyYQAAI', 'file_size': 9724, 'width': 180, 'height': 320},
32
+ 'file_id': 'BAACAgIIAAKaCAACCcGASLV2hk3MavHGGwQ',
33
+ 'file_unique_id': 'AgADmggAAgnBgEg', 'file_size': 1260506}, 'caption': '50603'
34
+ }
35
+ """
36
+ from typing import Dict
37
+
38
+ import telegram
39
+ from telegram import Update
40
+ from telegram.ext import CallbackContext
41
+
42
+ from users.models import User
43
+
44
+ ALL_TG_FILE_TYPES = ["document", "video_note", "voice", "sticker", "audio", "video", "animation", "photo"]
45
+
46
+
47
+ def _get_file_id(m: Dict) -> str:
48
+ """ extract file_id from message (and file type?) """
49
+
50
+ for doc_type in ALL_TG_FILE_TYPES:
51
+ if doc_type in m and doc_type != "photo":
52
+ return m[doc_type]["file_id"]
53
+
54
+ if "photo" in m:
55
+ best_photo = m["photo"][-1]
56
+ return best_photo["file_id"]
57
+
58
+
59
+ def show_file_id(update: Update, context: CallbackContext) -> None:
60
+ """ Returns file_id of the attached file/media """
61
+ u = User.get_user(update, context)
62
+
63
+ if u.is_admin:
64
+ update_json = update.to_dict()
65
+ file_id = _get_file_id(update_json["message"])
66
+ message_id = update_json["message"]["message_id"]
67
+ update.message.reply_text(
68
+ text=f"`{file_id}`",
69
+ parse_mode=telegram.ParseMode.HTML,
70
+ reply_to_message_id=message_id
71
+ )
tgbot/handlers/utils/info.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict
2
+
3
+ from telegram import Update
4
+
5
+
6
+ def extract_user_data_from_update(update: Update) -> Dict:
7
+ """ python-telegram-bot's Update instance --> User info """
8
+ user = update.effective_user.to_dict()
9
+
10
+ return dict(
11
+ user_id=user["id"],
12
+ is_blocked_bot=False,
13
+ **{
14
+ k: user[k]
15
+ for k in ["username", "first_name", "last_name", "language_code"]
16
+ if k in user and user[k] is not None
17
+ },
18
+ )
tgbot/main.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import sys
3
+
4
+ import telegram
5
+ from telegram import Bot
6
+
7
+ from dtb.settings import TELEGRAM_TOKEN
8
+
9
+
10
+ bot = Bot(TELEGRAM_TOKEN)
11
+ TELEGRAM_BOT_USERNAME = bot.get_me()["username"]
12
+ # Global variable - the best way I found to init Telegram bot
13
+ try:
14
+ pass
15
+ except telegram.error.Unauthorized:
16
+ logging.error("Invalid TELEGRAM_TOKEN.")
17
+ sys.exit(1)
tgbot/system_commands.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict
2
+
3
+ from telegram import Bot, BotCommand
4
+
5
+ from tgbot.main import bot
6
+
7
+
8
+ def set_up_commands(bot_instance: Bot) -> None:
9
+
10
+ langs_with_commands: Dict[str, Dict[str, str]] = {
11
+ 'en': {
12
+ 'start': 'Start django bot 🚀',
13
+ 'stats': 'Statistics of bot 📊',
14
+ 'admin': 'Show admin info ℹ️',
15
+ 'ask_location': 'Send location 📍',
16
+ 'broadcast': 'Broadcast message 📨',
17
+ 'export_users': 'Export users.csv 👥',
18
+ },
19
+ 'es': {
20
+ 'start': 'Iniciar el bot de django 🚀',
21
+ 'stats': 'Estadísticas de bot 📊',
22
+ 'admin': 'Mostrar información de administrador ℹ️',
23
+ 'ask_location': 'Enviar ubicación 📍',
24
+ 'broadcast': 'Mensaje de difusión 📨',
25
+ 'export_users': 'Exportar users.csv 👥',
26
+ },
27
+ 'fr': {
28
+ 'start': 'Démarrer le bot Django 🚀',
29
+ 'stats': 'Statistiques du bot 📊',
30
+ 'admin': "Afficher les informations d'administrateur ℹ️",
31
+ 'ask_location': 'Envoyer emplacement 📍',
32
+ 'broadcast': 'Message de diffusion 📨',
33
+ "export_users": 'Exporter users.csv 👥',
34
+ },
35
+ 'ru': {
36
+ 'start': 'Запустить django бота 🚀',
37
+ 'stats': 'Статистика бота 📊',
38
+ 'admin': 'Показать информацию для админов ℹ️',
39
+ 'broadcast': 'Отправить сообщение 📨',
40
+ 'ask_location': 'Отправить локацию 📍',
41
+ 'export_users': 'Экспорт users.csv 👥',
42
+ }
43
+ }
44
+
45
+ bot_instance.delete_my_commands()
46
+ for language_code in langs_with_commands:
47
+ bot_instance.set_my_commands(
48
+ language_code=language_code,
49
+ commands=[
50
+ BotCommand(command, description) for command, description in langs_with_commands[language_code].items()
51
+ ]
52
+ )
53
+
54
+
55
+ set_up_commands(bot)