├── .env-example
├── .gitattributes
├── .gitignore
├── Dockerfile
├── LICENSE
├── README-RU.md
├── README.md
├── bot
├── __init__.py
├── config
│ ├── __init__.py
│ ├── config.py
│ └── proxies-template.txt
├── core
│ ├── __init__.py
│ ├── agents.py
│ ├── headers.py
│ ├── launcher.py
│ ├── registrator.py
│ └── tapper.py
├── exceptions
│ └── __init__.py
└── utils
│ ├── __init__.py
│ ├── async_lock.py
│ ├── config_utils.py
│ ├── first_run.py
│ ├── logger.py
│ ├── proxy_utils.py
│ └── universal_telegram_client.py
├── docker-compose.yml
├── main.py
├── requirements.txt
├── run.bat
└── run.sh
/.env-example:
--------------------------------------------------------------------------------
1 | API_ID=
2 | API_HASH=
3 | GLOBAL_CONFIG_PATH=
4 |
5 | FIX_CERT=
6 |
7 | REF_ID=
8 | TASKS_WITH_JOIN_CHANNEL=
9 | PLAY_GAMES=
10 | HOLD_COIN=
11 | SWIPE_COIN=
12 | SUBSCRIBE_SQUAD=
13 | SESSION_START_DELAY=
14 | SLEEP_TIME=
15 |
16 | SESSIONS_PER_PROXY=
17 | USE_PROXY_FROM_FILE=
18 | DISABLE_PROXY_REPLACE=
19 |
20 | DEVICE_PARAMS=
21 |
22 | DEBUG_LOGGING=
23 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | bot/config/proxies.txt merge=skip
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
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 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
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 |
64 | # DB
65 | sessions/
66 |
67 | # Flask stuff:
68 | instance/
69 | .webassets-cache
70 |
71 | # Scrapy stuff:
72 | .scrapy
73 |
74 | # Sphinx documentation
75 | docs/_build/
76 |
77 | # PyBuilder
78 | .pybuilder/
79 | target/
80 |
81 | # Jupyter Notebook
82 | .ipynb_checkpoints
83 |
84 | # IPython
85 | profile_default/
86 | ipython_config.py
87 |
88 | # pyenv
89 | # For a library or package, you might want to ignore these files since the code is
90 | # intended to run in multiple environments; otherwise, check them in:
91 | # .python-version
92 |
93 | # pipenv
94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
97 | # install all needed dependencies.
98 | #Pipfile.lock
99 |
100 | # poetry
101 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
102 | # This is especially recommended for binary packages to ensure reproducibility, and is more
103 | # commonly ignored for libraries.
104 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
105 | #poetry.lock
106 |
107 | # pdm
108 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
109 | #pdm.lock
110 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
111 | # in version control.
112 | # https://pdm.fming.dev/#use-with-ide
113 | .pdm.toml
114 |
115 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
116 | __pypackages__/
117 |
118 | # Celery stuff
119 | celerybeat-schedule
120 | celerybeat.pid
121 |
122 | # SageMath parsed files
123 | *.sage.py
124 |
125 | # Environments
126 | .env
127 | .venv
128 | env/
129 | venv/
130 | ENV/
131 | env.bak/
132 | venv.bak/
133 |
134 | # Spyder project settings
135 | .spyderproject
136 | .spyproject
137 |
138 | # Rope project settings
139 | .ropeproject
140 |
141 | # mkdocs documentation
142 | /site
143 |
144 | # mypy
145 | .mypy_cache/
146 | .dmypy.json
147 | dmypy.json
148 |
149 | # Pyre type checker
150 | .pyre/
151 |
152 | # pytype static type analyzer
153 | .pytype/
154 |
155 | # Cython debug symbols
156 | cython_debug/
157 |
158 | # PyCharm
159 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
160 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
161 | # and can be added to the global gitignore or merged into this file. For a more nuclear
162 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
163 | .idea/
164 |
165 | *.session
166 |
167 | *.json
168 |
169 | proxies.txt
170 |
171 | logs/
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.10.11-alpine3.18
2 |
3 | WORKDIR app/
4 |
5 | COPY requirements.txt requirements.txt
6 |
7 | RUN pip3 install --upgrade pip setuptools wheel
8 | RUN pip3 install --no-warn-script-location --no-cache-dir -r requirements.txt
9 |
10 | COPY . .
11 |
12 | CMD ["python3", "main.py", "-a", "1"]
13 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README-RU.md:
--------------------------------------------------------------------------------
1 | [](https://t.me/+jJhUfsfFCn4zZDk0) [](https://t.me/major/start?startapp=339631649)
2 |
3 | 
4 |
5 |
6 |
7 | ## Recommendation before use
8 |
9 | # 🔥🔥 PYTHON version must be 3.10 🔥🔥
10 |
11 | > 🇪🇳 README in english available [here](README)
12 |
13 | ## Функционал
14 | | Функционал | Поддерживается |
15 | |:----------------------------------------------------------------------:|:--------------:|
16 | | Многопоточность | ✅ |
17 | | Привязка прокси к сессии | ✅ |
18 | | Авто Реферальство ваших аккаунтов | ✅ |
19 | | Авто выполнение заданий, которые можно выполнить обычному пользователю | ✅ |
20 | | Автоматическая рулетка | ✅ |
21 | | Авто Hold Coins | ✅ |
22 | | Авто Swipe Coins | ✅ |
23 | | Авто Puzzle Pavel | ✅ |
24 | | Автоматичесие ежедневная стрики | ✅ |
25 | | Поддержка telethon И pyrogram .session | ✅ |
26 |
27 | _Скрипт осуществляет поиск файлов сессий в следующих папках:_
28 | * /sessions
29 | * /sessions/pyrogram
30 | * /session/telethon
31 |
32 |
33 | ## [Настройки](https://github.com/GravelFire/MajorBot/blob/main/.env-example/)
34 | | Настройки | Описание |
35 | |:---------------------------:|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|
36 | | **API_ID / API_HASH** | Данные платформы, с которой будет запущена сессия Telegram (по умолчанию - android) |
37 | | **GLOBAL_CONFIG_PATH** | Определяет глобальный путь для accounts_config, proxies, sessions.
Укажите абсолютный путь или используйте переменную окружения (по умолчанию - переменная окружения: **TG_FARM**)
Если переменной окружения не существует, использует директорию скрипта |
38 | | **FIX_CERT** | Попытаться исправить ошибку SSLCertVerificationError ( True / **False** ) |
39 | | **TASKS_WITH_JOIN_CHANNEL** | Выполнять ли задания с присоединением к каналам (True / False) |
40 | | **PLAY_GAMES** | Играть ли в игры? ( **True** / False) |
41 | | **HOLD_COIN** | Количество монет в Hold Coin (напр. [585, 600]) |
42 | | **SWIPE_COIN** | Количество монет в Swipe Coin (напр. [2000, 3000]) |
43 | | **SUBSCRIBE_SQUAD** | Подписаться на Squadо ID (пример: 2212658999) |
44 | | **REF_ID** | Ваш идентификатор реферала после startapp= (Ваш идентификатор telegram) |
45 | | **SESSION_START_DELAY** | Рандомная задержка при запуске (напр. [0, 15]) |
46 | | **SLEEP_TIME** | Задержка перед следующим кругом (например, [1800, 3600]) |
47 | | **SESSIONS_PER_PROXY** | Количество сессий, которые могут использовать один прокси (По умолчанию **1** ) |
48 | | **USE_PROXY_FROM_FILE** | Использовать ли прокси из файла `bot/config/proxies.txt` (**True** / False) |
49 | | **DISABLE_PROXY_REPLACE** | Отключить автоматическую проверку и замену нерабочих прокси перед стартом ( True / **False** ) |
50 | | **DEVICE_PARAMS** | Вводить параметры устройства, чтобы сделать сессию более похожую, на реальную (True / **False**) |
51 | | **DEBUG_LOGGING** | Включить логирование трейсбэков ошибок в папку /logs (True / **False**) |
52 |
53 | ## Быстрый старт 📚
54 |
55 | Для быстрой установки и последующего запуска - запустите файл run.bat на Windows или run.sh на Линукс
56 |
57 | ## Предварительные условия
58 | Прежде чем начать, убедитесь, что у вас установлено следующее:
59 | - [Python](https://www.python.org/downloads/) **версии 3.10**
60 |
61 | ## Получение API ключей
62 | 1. Перейдите на сайт [my.telegram.org](https://my.telegram.org) и войдите в систему, используя свой номер телефона.
63 | 2. Выберите **"API development tools"** и заполните форму для регистрации нового приложения.
64 | 3. Запишите `API_ID` и `API_HASH` в файле `.env`, предоставленные после регистрации вашего приложения.
65 |
66 | ## Установка
67 | Вы можете скачать [**Репозиторий**](https://github.com/GravelFire/MajorBot) клонированием на вашу систему и установкой необходимых зависимостей:
68 | ```shell
69 | git clone https://github.com/GravelFire/MajorBot.git
70 | cd MajorBot
71 | ```
72 |
73 | Затем для автоматической установки введите:
74 |
75 | Windows:
76 | ```shell
77 | run.bat
78 | ```
79 |
80 | Linux:
81 | ```shell
82 | run.sh
83 | ```
84 |
85 | # Linux ручная установка
86 | ```shell
87 | python3 -m venv venv
88 | source venv/bin/activate
89 | pip3 install -r requirements.txt
90 | cp .env-example .env
91 | nano .env # Здесь вы обязательно должны указать ваши API_ID и API_HASH , остальное берется по умолчанию
92 | python3 main.py
93 | ```
94 |
95 | Также для быстрого запуска вы можете использовать аргументы, например:
96 | ```shell
97 | ~/MajorBot >>> python3 main.py --action (1/2)
98 | # Or
99 | ~/MajorBot >>> python3 main.py -a (1/2)
100 |
101 | # 1 - Запускает кликер
102 | # 2 - Создает сессию
103 | ```
104 |
105 |
106 | # Windows ручная установка
107 | ```shell
108 | python -m venv venv
109 | venv\Scripts\activate
110 | pip install -r requirements.txt
111 | copy .env-example .env
112 | # Указываете ваши API_ID и API_HASH, остальное берется по умолчанию
113 | python main.py
114 | ```
115 |
116 | Также для быстрого запуска вы можете использовать аргументы, например:
117 | ```shell
118 | ~/MajorBot >>> python main.py --action (1/2)
119 | # Или
120 | ~/MajorBot >>> python main.py -a (1/2)
121 |
122 | # 1 - Запускает кликер
123 | # 2 - Создает сессию
124 | ```
125 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://t.me/+jJhUfsfFCn4zZDk0) [](https://t.me/major/start?startapp=339631649)
2 |
3 | 
4 |
5 |
6 |
7 | ## Recommendation before use
8 |
9 | # 🔥🔥 PYTHON version must be 3.10 🔥🔥
10 |
11 | > 🇷 🇺 README in russian available [here](README-RU.md)
12 |
13 | ## Features
14 | | Feature | Supported |
15 | |:---------------------------------------:|:---------:|
16 | | Multithreading | ✅ |
17 | | Proxy binding to session | ✅ |
18 | | Auto Referral | ✅ |
19 | | Auto Claim Task | ✅ |
20 | | Auto Roulette | ✅ |
21 | | Auto Hold Coins | ✅ |
22 | | Auto Swipe Coins | ✅ |
23 | | Auto Puzzle Pavel | ✅ |
24 | | Auto Daily Streak | ✅ |
25 | | Supports telethon AND pyrogram .session | ✅ |
26 |
27 | _Script searches for session files in the following folders:_
28 | * /sessions
29 | * /sessions/pyrogram
30 | * /session/telethon
31 |
32 |
33 | ## [Settings](https://github.com/GravelFire/MajorBot/blob/main/.env-example/)
34 | | Settings | Description |
35 | |:---------------------------:|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|
36 | | **API_ID / API_HASH** | Platform data from which to run the Telegram session (default - android) |
37 | | **GLOBAL_CONFIG_PATH** | Specifies the global path for accounts_config, proxies, sessions.
Specify an absolute path or use an environment variable (default environment variable: **TG_FARM**)
If no environment variable exists, uses the script directory. |
38 | | **FIX_CERT** | Try to fix SSLCertVerificationError ( True / **False** ) |
39 | | **TASKS_WITH_JOIN_CHANNEL** | Whether to perform tasks with joining channels (**True** / False) |
40 | | **PLAY_GAMES** | Wether to play games ( **True** / False) |
41 | | **HOLD_COIN** | Ammount coins in Hold Coin (e.g. [585, 600]) |
42 | | **SWIPE_COIN** | Ammount coins in Swipe Coin (e.g. [2000, 3000]) |
43 | | **SUBSCRIBE_SQUAD** | Subscribe to Squad by ID (id: 2212658999 (just an example) |
44 | | **REF_ID** | Your referral id after startapp= (Your telegram ID) |
45 | | **SESSION_START_DELAY** | Random delay at startup (e.g. [0, 15]) |
46 | | **SLEEP_TIME** | Delay before the next lap (e.g. [1800, 3600]) |
47 | | **SESSIONS_PER_PROXY** | Amount of sessions, that can share same proxy ( **1** ) |
48 | | **USE_PROXY_FROM_FILE** | Whether to use a proxy from the `bot/config/proxies.txt` file (**True** / False) |
49 | | **DISABLE_PROXY_REPLACE** | Disable automatic checking and replacement of non-working proxies before startup (True / **False**) |
50 | | **DEVICE_PARAMS** | Enter device settings to make the telegram session look more realistic (True / **False**) |
51 | | **DEBUG_LOGGING** | Whether to log error's tracebacks to /logs folder (True / **False**) |
52 |
53 | ## Quick Start 📚
54 |
55 | To fast install libraries and run bot - open run.bat on Windows or run.sh on Linux
56 |
57 | ## Prerequisites
58 | Before you begin, make sure you have the following installed:
59 | - [Python](https://www.python.org/downloads/) **version 3.10**
60 |
61 | ## Obtaining API Keys
62 | 1. Go to my.telegram.org and log in using your phone number.
63 | 2. Select "API development tools" and fill out the form to register a new application.
64 | 3. Record the API_ID and API_HASH provided after registering your application in the .env file.
65 |
66 | ## Installation
67 | You can download the [**repository**](https://github.com/GravelFire/MajorBot) by cloning it to your system and installing the necessary dependencies:
68 | ```shell
69 | git clone https://github.com/GravelFire/MajorBot.git
70 | cd MajorBot
71 | ```
72 |
73 | Then you can do automatic installation by typing:
74 |
75 | Windows:
76 | ```shell
77 | run.bat
78 | ```
79 |
80 | Linux:
81 | ```shell
82 | run.sh
83 | ```
84 |
85 | # Linux manual installation
86 | ```shell
87 | python3 -m venv venv
88 | source venv/bin/activate
89 | pip3 install -r requirements.txt
90 | cp .env-example .env
91 | nano .env # Here you must specify your API_ID and API_HASH, the rest is taken by default
92 | python3 main.py
93 | ```
94 |
95 | You can also use arguments for quick start, for example:
96 | ```shell
97 | ~/MajorBot >>> python3 main.py --action (1/2)
98 | # Or
99 | ~/MajorBot >>> python3 main.py -a (1/2)
100 |
101 | # 1 - Run clicker
102 | # 2 - Creates a session
103 | ```
104 |
105 | # Windows manual installation
106 | ```shell
107 | python -m venv venv
108 | venv\Scripts\activate
109 | pip install -r requirements.txt
110 | copy .env-example .env
111 | # Here you must specify your API_ID and API_HASH, the rest is taken by default
112 | python main.py
113 | ```
114 |
115 | You can also use arguments for quick start, for example:
116 | ```shell
117 | ~/MajorBot >>> python main.py --action (1/2)
118 | # Or
119 | ~/MajorBot >>> python main.py -a (1/2)
120 |
121 | # 1 - Run clicker
122 | # 2 - Creates a session
123 | ```
124 |
--------------------------------------------------------------------------------
/bot/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = '1.9'
2 |
--------------------------------------------------------------------------------
/bot/config/__init__.py:
--------------------------------------------------------------------------------
1 | from .config import settings
2 |
--------------------------------------------------------------------------------
/bot/config/config.py:
--------------------------------------------------------------------------------
1 | from pydantic_settings import BaseSettings, SettingsConfigDict
2 |
3 |
4 | class Settings(BaseSettings):
5 | model_config = SettingsConfigDict(env_file=".env", env_ignore_empty=True)
6 |
7 | API_ID: int
8 | API_HASH: str
9 | GLOBAL_CONFIG_PATH: str = "TG_FARM"
10 |
11 | FIX_CERT: bool = False
12 |
13 | REF_ID: str = '525256526'
14 | TASKS_WITH_JOIN_CHANNEL: bool = True
15 | PLAY_GAMES: bool = True
16 | HOLD_COIN: list[int] = [915, 915]
17 | SWIPE_COIN: list[int] = [1200, 2000]
18 | SUBSCRIBE_SQUAD: str = ''
19 | SESSION_START_DELAY: int = 3600
20 | SLEEP_TIME: list[int] = [7200, 18400]
21 |
22 | SESSIONS_PER_PROXY: int = 1
23 | USE_PROXY_FROM_FILE: bool = True
24 | DISABLE_PROXY_REPLACE: bool = False
25 | USE_PROXY_CHAIN: bool = False
26 |
27 | DEVICE_PARAMS: bool = False
28 |
29 | DEBUG_LOGGING: bool = False
30 |
31 |
32 | settings = Settings()
33 |
--------------------------------------------------------------------------------
/bot/config/proxies-template.txt:
--------------------------------------------------------------------------------
1 | type://user:pass@ip:port
2 | type://user:pass:ip:port
3 | type://ip:port:user:pass
4 | type://ip:port@user:pass
5 | type://ip:port
6 |
--------------------------------------------------------------------------------
/bot/core/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SP-l33t/MajorBot-Telethon/2d848e825575029ae43036befd564d6313288aa9/bot/core/__init__.py
--------------------------------------------------------------------------------
/bot/core/agents.py:
--------------------------------------------------------------------------------
1 | import ua_generator
2 | from ua_generator.options import Options
3 | from ua_generator.data.version import VersionRange
4 |
5 |
6 | def generate_random_user_agent(platform='android', browser='chrome', min_version=110, max_version=129):
7 | options = Options(version_ranges={'chrome': VersionRange(min_version, max_version)})
8 | return ua_generator.generate(browser=browser, platform=platform, options=options).text
9 |
--------------------------------------------------------------------------------
/bot/core/headers.py:
--------------------------------------------------------------------------------
1 | import base64
2 | import re
3 | from google.protobuf.internal import encoder
4 | from time import time
5 | from random import randint
6 |
7 |
8 | headers = {
9 | 'Cache-Control': 'no-cache',
10 | 'Accept': 'application/json, text/plain, */*',
11 | 'Origin': 'https://major.bot',
12 | 'Referer': 'https://major.bot/',
13 | 'Sec-Fetch-Site': 'same-origin',
14 | 'Sec-Fetch-Mode': 'cors',
15 | 'Sec-Fetch-Dest': 'empty',
16 | 'Sec-Ch-Ua-Mobile': '?1',
17 | 'Sec-Ch-Ua-Platform': '"Android"',
18 | 'Accept-Encoding': 'gzip, deflate, br',
19 | 'Accept-Language': 'en-US,en;q=0.9',
20 | 'Priority': 'u=1, i',
21 | "X-Requested-With": "org.telegram.messenger"
22 | }
23 |
24 |
25 | def get_sec_ch_ua(user_agent):
26 | pattern = r'(Chrome|Chromium)\/(\d+)\.(\d+)\.(\d+)\.(\d+)'
27 |
28 | match = re.search(pattern, user_agent)
29 |
30 | if match:
31 | browser = match.group(1)
32 | version = match.group(2)
33 |
34 | if browser == 'Chrome':
35 | sec_ch_ua = f'"Chromium";v="{version}", "Not;A=Brand";v="24", "Google Chrome";v="{version}"'
36 | else:
37 | sec_ch_ua = f'"Chromium";v="{version}", "Not;A=Brand";v="24"'
38 |
39 | return {'Sec-Ch-Ua': sec_ch_ua}
40 | else:
41 | return {}
42 |
43 |
44 | def create_correlation_id():
45 | current_timestamp = int(time())*1000 + randint(0, 999)
46 | buffer = encoder._VarintBytes(current_timestamp)
47 | complete_message = bytes([8]) + bytes(buffer)
48 | base64_result = base64.b64encode(complete_message).decode('utf-8')
49 | return base64_result
50 |
--------------------------------------------------------------------------------
/bot/core/launcher.py:
--------------------------------------------------------------------------------
1 | import glob
2 | import asyncio
3 | import argparse
4 | import os
5 | from copy import deepcopy
6 |
7 | from bot.utils.universal_telegram_client import UniversalTelegramClient
8 |
9 | from bot.config import settings
10 | from bot.core.agents import generate_random_user_agent
11 | from bot.utils import logger, config_utils, proxy_utils, CONFIG_PATH, SESSIONS_PATH, PROXIES_PATH
12 | from bot.core.tapper import run_tapper
13 | from bot.core.registrator import register_sessions
14 |
15 | START_TEXT = """
16 |
17 | ███╗ ███╗ █████╗ ██╗ ██████╗ ██████╗ ██████╗ ██████╗ ████████╗
18 | ████╗ ████║██╔══██╗ ██║██╔═══██╗██╔══██╗██╔══██╗██╔═══██╗╚══██╔══╝
19 | ██╔████╔██║███████║ ██║██║ ██║██████╔╝██████╔╝██║ ██║ ██║
20 | ██║╚██╔╝██║██╔══██║██ ██║██║ ██║██╔══██╗██╔══██╗██║ ██║ ██║
21 | ██║ ╚═╝ ██║██║ ██║╚█████╔╝╚██████╔╝██║ ██║██████╔╝╚██████╔╝ ██║
22 | ╚═╝ ╚═╝╚═╝ ╚═╝ ╚════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝
23 |
24 | Select an action:
25 |
26 | 1. Run clicker
27 | 2. Create session
28 | """
29 |
30 | API_ID = settings.API_ID
31 | API_HASH = settings.API_HASH
32 |
33 |
34 | def prompt_user_action() -> int:
35 | logger.info(START_TEXT)
36 | while True:
37 | action = input("> ").strip()
38 | if action.isdigit() and action in ("1", "2"):
39 | return int(action)
40 | logger.warning("Invalid action. Please enter 1 or 2.")
41 |
42 |
43 | async def process() -> None:
44 | parser = argparse.ArgumentParser()
45 | parser.add_argument("-a", "--action", type=int, help="Action to perform")
46 | args = parser.parse_args()
47 |
48 | if not settings.USE_PROXY_FROM_FILE:
49 | logger.info(f"Detected {len(get_sessions(SESSIONS_PATH))} sessions | USE_PROXY_FROM_FILE=False")
50 | else:
51 | logger.info(f"Detected {len(get_sessions(SESSIONS_PATH))} sessions | "
52 | f"{len(proxy_utils.get_proxies(PROXIES_PATH))} proxies")
53 |
54 | action = args.action or prompt_user_action()
55 |
56 | if action == 1:
57 | if not API_ID or not API_HASH:
58 | raise ValueError("API_ID and API_HASH not found in the .env file.")
59 | await run_tasks()
60 | elif action == 2:
61 | await register_sessions()
62 |
63 |
64 | def get_sessions(sessions_folder: str) -> list[str]:
65 | session_names = glob.glob(f"{sessions_folder}/*.session")
66 | session_names += glob.glob(f"{sessions_folder}/telethon/*.session")
67 | session_names += glob.glob(f"{sessions_folder}/pyrogram/*.session")
68 | return [file.replace('.session', '') for file in sorted(session_names)]
69 |
70 |
71 | async def get_tg_clients() -> list[UniversalTelegramClient]:
72 | session_paths = get_sessions(SESSIONS_PATH)
73 |
74 | if not session_paths:
75 | raise FileNotFoundError("Session files not found")
76 | tg_clients = []
77 | for session in session_paths:
78 | session_name = os.path.basename(session)
79 | accounts_config = config_utils.read_config_file(CONFIG_PATH)
80 | session_config: dict = deepcopy(accounts_config.get(session_name, {}))
81 | if 'api' not in session_config:
82 | session_config['api'] = {}
83 | api_config = session_config.get('api', {})
84 | api = None
85 | if api_config.get('api_id') in [4, 6, 2040, 10840, 21724]:
86 | api = config_utils.get_api(api_config)
87 |
88 | if api:
89 | client_params = {
90 | "session": session,
91 | "api": api
92 | }
93 | else:
94 | client_params = {
95 | "api_id": api_config.get("api_id", API_ID),
96 | "api_hash": api_config.get("api_hash", API_HASH),
97 | "session": session,
98 | "lang_code": api_config.get("lang_code", "en"),
99 | "system_lang_code": api_config.get("system_lang_code", "en-US")
100 | }
101 |
102 | for key in ("device_model", "system_version", "app_version"):
103 | if api_config.get(key):
104 | client_params[key] = api_config[key]
105 |
106 | session_config['user_agent'] = session_config.get('user_agent', generate_random_user_agent())
107 | api_config.update(api_id=client_params.get('api_id') or client_params.get('api').api_id,
108 | api_hash=client_params.get('api_hash') or client_params.get('api').api_hash)
109 |
110 | session_proxy = session_config.get('proxy')
111 | if not session_proxy and 'proxy' in session_config.keys():
112 | tg_clients.append(UniversalTelegramClient(**client_params))
113 | if accounts_config.get(session_name) != session_config:
114 | await config_utils.update_session_config_in_file(session_name, session_config, CONFIG_PATH)
115 | continue
116 |
117 | else:
118 | if settings.DISABLE_PROXY_REPLACE:
119 | proxy = session_proxy or next(iter(proxy_utils.get_unused_proxies(accounts_config, PROXIES_PATH)), None)
120 | else:
121 | proxy = await proxy_utils.get_working_proxy(accounts_config, session_proxy) \
122 | if session_proxy or settings.USE_PROXY_FROM_FILE else None
123 |
124 | if not proxy and (settings.USE_PROXY_FROM_FILE or session_proxy):
125 | logger.warning(f"{session_name} | Didn't find a working unused proxy for session | Skipping")
126 | continue
127 | else:
128 | tg_clients.append(UniversalTelegramClient(**client_params))
129 | session_config['proxy'] = proxy
130 | if accounts_config.get(session_name) != session_config:
131 | await config_utils.update_session_config_in_file(session_name, session_config, CONFIG_PATH)
132 |
133 | return tg_clients
134 |
135 |
136 | async def init_config_file():
137 | session_paths = get_sessions(SESSIONS_PATH)
138 |
139 | if not session_paths:
140 | raise FileNotFoundError("Session files not found")
141 | for session in session_paths:
142 | session_name = os.path.basename(session)
143 | parsed_json = config_utils.import_session_json(session)
144 | if parsed_json:
145 | accounts_config = config_utils.read_config_file(CONFIG_PATH)
146 | session_config: dict = deepcopy(accounts_config.get(session_name, {}))
147 | session_config['user_agent'] = session_config.get('user_agent', generate_random_user_agent())
148 | session_config['api'] = parsed_json
149 | if accounts_config.get(session_name) != session_config:
150 | await config_utils.update_session_config_in_file(session_name, session_config, CONFIG_PATH)
151 |
152 |
153 | async def run_tasks():
154 | await config_utils.restructure_config(CONFIG_PATH)
155 | await init_config_file()
156 | tg_clients = await get_tg_clients()
157 | tasks = [asyncio.create_task(run_tapper(tg_client=tg_client)) for tg_client in tg_clients]
158 | await asyncio.gather(*tasks)
159 |
--------------------------------------------------------------------------------
/bot/core/registrator.py:
--------------------------------------------------------------------------------
1 | import os
2 | from better_proxy import Proxy
3 | from telethon import TelegramClient
4 | from pyrogram import Client
5 | from bot.config import settings
6 | from bot.utils import logger, proxy_utils, config_utils, CONFIG_PATH, PROXIES_PATH, SESSIONS_PATH
7 |
8 |
9 | API_ID = settings.API_ID
10 | API_HASH = settings.API_HASH
11 |
12 |
13 | async def register_sessions() -> None:
14 | if not API_ID or not API_HASH:
15 | raise ValueError("API_ID and API_HASH not found in the .env file.")
16 |
17 | session_name = input('\nEnter the session name (press Enter to exit): ').strip()
18 | if not session_name:
19 | return None
20 |
21 | session_file = f"{session_name}.session"
22 | device_params = {}
23 |
24 | if settings.DEVICE_PARAMS:
25 | logger.info("""
26 | Sample Device values (Don't use quotes):
27 | ### Attributes:
28 | device_model (`str`) : `Samsung SM-G998B`
29 | system_version (`str`) : `SDK 31`
30 | app_version (`str`) : `8.4.1 (2522)`
31 | """)
32 | device_params.update(
33 | {
34 | 'device_model': input('device_model: ').strip(),
35 | 'system_version': input('system_version: ').strip(),
36 | 'app_version': input('app_version: ').strip()
37 | }
38 | )
39 | accounts_config = config_utils.read_config_file(CONFIG_PATH)
40 | accounts_data = {
41 | "api": {
42 | 'api_id': API_ID,
43 | 'api_hash': API_HASH,
44 | **device_params
45 | }
46 | }
47 | proxy = None
48 |
49 | if settings.USE_PROXY_FROM_FILE:
50 | proxies = proxy_utils.get_unused_proxies(accounts_config, PROXIES_PATH)
51 | if not proxies:
52 | raise Exception('No unused proxies left')
53 | for prox in proxies:
54 | if await proxy_utils.check_proxy(prox):
55 | proxy_str = prox
56 | proxy = Proxy.from_str(proxy_str)
57 | accounts_data['proxy'] = proxy_str
58 | break
59 | else:
60 | raise Exception('No unused proxies left')
61 | else:
62 | accounts_data['proxy'] = None
63 |
64 | accounts_config[session_name] = accounts_data
65 | while True:
66 | res = input('Which session to create?\n1. Telethon\n2. Pyrogram\n').strip()
67 | if res not in ['1', '2']:
68 | logger.warning("Invalid option. Please enter 1 or 2")
69 | else:
70 | break
71 | if res == '1':
72 | session = TelegramClient(
73 | os.path.join(SESSIONS_PATH, session_file),
74 | api_id=API_ID,
75 | api_hash=API_HASH,
76 | lang_code="en",
77 | system_lang_code="en-US",
78 | **device_params
79 | )
80 | if proxy:
81 | logger.info(f"Using proxy: {proxy}")
82 | session.set_proxy(proxy_utils.to_telethon_proxy(proxy))
83 |
84 | await session.start()
85 |
86 | user_data = await session.get_me()
87 |
88 | else:
89 | session = Client(
90 | os.path.join(SESSIONS_PATH, session_file),
91 | api_id=API_ID,
92 | api_hash=API_HASH,
93 | lang_code="en",
94 | **device_params
95 | )
96 | if proxy:
97 | logger.info(f"Using proxy: {proxy}")
98 | session.proxy = proxy_utils.to_pyrogram_proxy(proxy)
99 |
100 | await session.start()
101 |
102 | user_data = await session.get_me()
103 |
104 | if user_data:
105 | await config_utils.write_config_file(accounts_config, CONFIG_PATH)
106 | logger.success(
107 | f'Session added successfully @{user_data.username} | {user_data.first_name} {user_data.last_name}'
108 | )
109 |
--------------------------------------------------------------------------------
/bot/core/tapper.py:
--------------------------------------------------------------------------------
1 | import aiohttp
2 | import asyncio
3 | import json
4 | import re
5 | from urllib.parse import unquote, parse_qs
6 | from aiocfscrape import CloudflareScraper
7 | from aiohttp_proxy import ProxyConnector
8 | from better_proxy import Proxy
9 | from time import time
10 | from random import randint, uniform, shuffle
11 |
12 | from bot.utils.universal_telegram_client import UniversalTelegramClient
13 |
14 | from bot.config import settings
15 | from bot.utils import logger, log_error, config_utils, CONFIG_PATH, first_run
16 | from bot.exceptions import InvalidSession, GamesNotReady
17 | from .headers import headers, get_sec_ch_ua, create_correlation_id
18 |
19 | BASE_URL = "https://major.bot/api"
20 | TASKS_WL = [15027, 29, 16, 5, 15042, 15156, 15171, 15136, 15086]
21 |
22 |
23 | class Tapper:
24 | def __init__(self, tg_client: UniversalTelegramClient):
25 | self.tg_client = tg_client
26 | self.session_name = tg_client.session_name
27 |
28 | session_config = config_utils.get_session_config(self.session_name, CONFIG_PATH)
29 |
30 | if not all(key in session_config for key in ('api', 'user_agent')):
31 | logger.critical(self.log_message('CHECK accounts_config.json as it might be corrupted'))
32 | exit(-1)
33 |
34 | self.headers = headers
35 | user_agent = session_config.get('user_agent')
36 | self.headers['User-Agent'] = user_agent
37 | self.headers.update(**get_sec_ch_ua(user_agent))
38 |
39 | self.proxy = session_config.get('proxy')
40 | if self.proxy:
41 | proxy = Proxy.from_str(self.proxy)
42 | self.tg_client.set_proxy(proxy)
43 |
44 | self.tg_web_data = None
45 | self.tg_client_id = 0
46 |
47 | self._webview_data = None
48 | self.x_correlation_id = None
49 |
50 | def log_message(self, message) -> str:
51 | return f"{self.session_name} | {message}"
52 |
53 | async def get_tg_web_data(self) -> str:
54 | webview_url = await self.tg_client.get_app_webview_url('major', "start", "525256526")
55 |
56 | tg_web_data = unquote(string=webview_url.split('tgWebAppData=')[1].split('&tgWebAppVersion')[0])
57 | user_data = json.loads(parse_qs(tg_web_data).get('user', [''])[0])
58 |
59 | self.tg_client_id = user_data.get('id')
60 |
61 | return tg_web_data
62 |
63 | async def check_proxy(self, http_client: CloudflareScraper) -> bool:
64 | proxy_conn = http_client.connector
65 | if proxy_conn and not hasattr(proxy_conn, '_proxy_host'):
66 | logger.info(self.log_message(f"Running Proxy-less"))
67 | return True
68 | try:
69 | response = await http_client.get(url='https://ifconfig.me/ip', timeout=aiohttp.ClientTimeout(15))
70 | logger.info(self.log_message(f"Proxy IP: {await response.text()}"))
71 | return True
72 | except Exception as error:
73 | proxy_url = f"{proxy_conn._proxy_type}://{proxy_conn._proxy_host}:{proxy_conn._proxy_port}"
74 | log_error(self.log_message(f"Proxy: {proxy_url} | Error: {type(error).__name__}"))
75 | return False
76 |
77 | async def make_request(self, http_client: CloudflareScraper, method, endpoint="", url=None, **kwargs):
78 | full_url = url or f"{BASE_URL}{endpoint}"
79 | response = await http_client.request(method, full_url, **kwargs)
80 | if response.status in range(200, 300):
81 | return await response.json() if 'json' in response.content_type else await response.text()
82 | else:
83 | error_json = await response.json() if 'json' in response.content_type else {}
84 | error_text = f"Error: {error_json}" if error_json else ""
85 | logger.warning(self.log_message(
86 | f"{method} Request to {full_url} failed with {response.status} code. {error_text}"))
87 | return error_json
88 |
89 | async def login(self, http_client: CloudflareScraper, init_data):
90 | return await self.make_request(http_client, 'POST', endpoint="/auth/tg/", json={"init_data": init_data})
91 |
92 | async def get_tasks(self, http_client: CloudflareScraper):
93 | regular = await self.make_request(http_client, 'GET', endpoint="/tasks/?is_daily=false") or []
94 | daily = await self.make_request(http_client, 'GET', endpoint="/tasks/?is_daily=true") or []
95 | return daily + regular
96 |
97 | async def done_tasks(self, http_client, task_id):
98 | return await self.make_request(http_client, 'POST', endpoint="/tasks/", json={"task_id": task_id})
99 |
100 | async def claim_swipe_coins(self, http_client: CloudflareScraper):
101 | g_headers = {'Referer': 'https://major.bot/games'}
102 | response = await self.make_request(http_client, 'GET', endpoint="/swipe_coin/", headers=g_headers)
103 | if response.get('detail', {}).get('blocked_until'):
104 | raise GamesNotReady(int(response.get('detail', {}).get('blocked_until') - time()))
105 | if response and response.get('success') is True:
106 | g_headers['Referer'] = 'https://major.bot/games/swipe-coin'
107 | await self.make_request(http_client, 'GET', endpoint="/swipe_coin/", headers=g_headers)
108 | logger.info(self.log_message("Started SwipeCoins game"))
109 | coins = randint(settings.SWIPE_COIN[0], settings.SWIPE_COIN[1])
110 | payload = {"coins": coins}
111 | await asyncio.sleep(uniform(60, 61))
112 | g_headers['X-Correlation-Id'] = self.x_correlation_id
113 | response = await self.make_request(http_client, 'POST', endpoint="/swipe_coin/", json=payload,
114 | headers=g_headers)
115 | if response and response.get('success') is True:
116 | return coins
117 | return 0
118 |
119 | async def claim_hold_coins(self, http_client: CloudflareScraper):
120 | g_headers = {'Referer': 'https://major.bot/games'}
121 | response = await self.make_request(http_client, 'GET', endpoint="/bonuses/coins/", headers=g_headers)
122 | if response.get('detail', {}).get('blocked_until'):
123 | raise GamesNotReady(int(response.get('detail', {}).get('blocked_until') - time()))
124 | if response and response.get('success') is True:
125 | g_headers['Referer'] = 'https://major.bot/games/hold-coin'
126 | await self.make_request(http_client, 'GET', endpoint="/bonuses/coins/", headers=g_headers)
127 | logger.info(self.log_message("Started HoldCoins game"))
128 | coins = randint(settings.HOLD_COIN[0], settings.HOLD_COIN[1])
129 | payload = {"coins": coins}
130 | await asyncio.sleep(uniform(60, 61))
131 | g_headers['X-Correlation-Id'] = self.x_correlation_id
132 | response = await self.make_request(http_client, 'POST', endpoint="/bonuses/coins/", json=payload,
133 | headers=g_headers)
134 | if response and response.get('success') is True:
135 | return coins
136 | return 0
137 |
138 | async def claim_roulette(self, http_client: CloudflareScraper):
139 | g_headers = {'Referer': 'https://major.bot/games'}
140 | response = await self.make_request(http_client, 'GET', endpoint="/roulette/", headers=g_headers)
141 | if response.get('detail', {}).get('blocked_until'):
142 | raise GamesNotReady(int(response.get('detail', {}).get('blocked_until') - time()))
143 | if response.get('success'):
144 | logger.info(self.log_message(f"Started Roulette game"))
145 | await asyncio.sleep(uniform(0, 1))
146 | g_headers = {'X-Correlation-Id': self.x_correlation_id,
147 | 'Referer': 'https://major.bot/games/roulette'}
148 | response = await self.make_request(http_client, 'POST', endpoint="/roulette/",
149 | headers=g_headers)
150 | return response.get('rating_award', 0)
151 | return 0
152 |
153 | async def visit(self, http_client: CloudflareScraper):
154 | return await self.make_request(http_client, 'POST', endpoint="/user-visits/visit/")
155 |
156 | async def streak(self, http_client: CloudflareScraper):
157 | return await self.make_request(http_client, 'GET', endpoint="/user-visits/streak/")
158 |
159 | async def get_detail(self, http_client: CloudflareScraper):
160 | detail = await self.make_request(http_client, 'GET', endpoint=f"/users/{self.tg_client_id}/")
161 | return detail.get('rating', 0)
162 |
163 | async def get_user_position(self, http_client: CloudflareScraper):
164 | detail = await self.make_request(http_client, 'GET', endpoint=f"/users/top/position/{self.tg_client_id}/?")
165 | return detail.get('position', 0)
166 |
167 | async def get_top_users(self, http_client: CloudflareScraper):
168 | return await self.make_request(http_client, 'GET', endpoint=f"/users/top/?limit=100")
169 |
170 | async def join_squad(self, http_client: CloudflareScraper, squad_id):
171 | return await self.make_request(http_client, 'POST', endpoint=f"/squads/{squad_id}/join/?")
172 |
173 | async def get_squad(self, http_client: CloudflareScraper, squad_id):
174 | return await self.make_request(http_client, 'GET', endpoint=f"/squads/{squad_id}?")
175 |
176 | async def get_top_squads(self, http_client: CloudflareScraper):
177 | return await self.make_request(http_client, 'GET', endpoint=f"/squads/?limit=100")
178 |
179 | @staticmethod
180 | async def get_auxiliary_data():
181 | async with aiohttp.ClientSession() as session:
182 | try:
183 | resp = await session.get('https://raw.githubusercontent.com/SP-l33t/Auxiliary-Data/master/data.json')
184 | if resp.status == 200:
185 | resp_json = json.loads(await resp.text())
186 | auxiliary_data = resp_json.get('major', {})
187 | return auxiliary_data
188 | else:
189 | logger.error(f"Failed to get data.json: {resp.status}")
190 | return None
191 | except aiohttp.ClientError as e:
192 | logger.error(f"There was an error upon requesting data.json: {e}")
193 | return None
194 |
195 | async def youtube_answers(self, http_client: CloudflareScraper, task_id, task_title):
196 | auxiliary_data = await self.get_auxiliary_data()
197 | if auxiliary_data:
198 | youtube_answers = auxiliary_data.get('youtube', {})
199 | if task_title in youtube_answers:
200 | answer = youtube_answers[task_title]
201 | payload = {
202 | "task_id": task_id,
203 | "payload": {"code": answer}
204 | }
205 | logger.info(self.log_message(f"Attempting YouTube task: {task_title}"))
206 | response = await self.make_request(http_client, 'POST', endpoint="/tasks/", json=payload)
207 | if response.get('is_completed') is True:
208 | logger.success(f"{self.session_name} | Completed YouTube task: {task_title}")
209 | return True
210 | return False
211 |
212 | async def puvel_puzzle(self, http_client: CloudflareScraper):
213 | auxiliary_data = await self.get_auxiliary_data()
214 | if auxiliary_data:
215 | puzzle_data = auxiliary_data.get('puzzle', {})
216 | puzzle_answer = puzzle_data.get('answer', [])
217 | if puzzle_data.get('expires', 0) > int(time()):
218 | if len(puzzle_answer) == 4:
219 | answer = {"choice_1": puzzle_answer[0],
220 | "choice_2": puzzle_answer[1],
221 | "choice_3": puzzle_answer[2],
222 | "choice_4": puzzle_answer[3]}
223 | g_headers = {'Referer': 'https://major.bot/games'}
224 | start = await self.make_request(http_client, 'GET', endpoint="/durov/", headers=g_headers)
225 | if start.get('detail', {}).get('blocked_until'):
226 | raise GamesNotReady(int(start.get('detail', {}).get('blocked_until') - time()))
227 | if start.get('success'):
228 | g_headers['Referer'] = 'https://major.bot/games/puzzle-durov'
229 | await self.make_request(http_client, 'GET', endpoint="/durov/")
230 | g_headers['X-Correlation-Id'] = self.x_correlation_id
231 | logger.info(self.log_message("Started Puzzle game"))
232 | await asyncio.sleep(uniform(3, 10))
233 | return await self.make_request(http_client, 'POST', endpoint="/durov/", json=answer,
234 | headers=g_headers)
235 | return None
236 |
237 | # async def play_games(self, http_client: CloudflareScraper):
238 | # await asyncio.sleep(uniform(3, 15))
239 | # hold_coins = await self.claim_hold_coins(http_client=http_client)
240 | # if hold_coins:
241 | # logger.info(self.log_message(f"Reward HoldCoins: +{hold_coins}⭐"))
242 | #
243 | # await asyncio.sleep(uniform(3, 15))
244 | # swipe_coins = await self.claim_swipe_coins(http_client=http_client)
245 | # if swipe_coins:
246 | # logger.info(self.log_message(f"Reward SwipeCoins: +{swipe_coins}⭐"))
247 | #
248 | # await asyncio.sleep(uniform(3, 15))
249 | # roulette = await self.claim_roulette(http_client=http_client)
250 | # if roulette:
251 | # logger.info(self.log_message(f"Reward Roulette : +{roulette}⭐"))
252 | #
253 | # await asyncio.sleep(uniform(3, 15))
254 | # puzzle = await self.puvel_puzzle(http_client=http_client)
255 | # if puzzle:
256 | # logger.info(self.log_message(f"Reward Puzzle Pavel: +5000⭐"))
257 |
258 | async def play_games(self, http_client: CloudflareScraper):
259 | games = [
260 | {
261 | 'func': self.claim_hold_coins,
262 | 'name': 'HoldCoins',
263 | 'reward_text': lambda x: f"+{x}⭐"
264 | },
265 | {
266 | 'func': self.claim_swipe_coins,
267 | 'name': 'SwipeCoins',
268 | 'reward_text': lambda x: f"+{x}⭐"
269 | },
270 | {
271 | 'func': self.claim_roulette,
272 | 'name': 'Roulette',
273 | 'reward_text': lambda x: f"+{x}⭐"
274 | },
275 | {
276 | 'func': self.puvel_puzzle,
277 | 'name': 'Puzzle Pavel',
278 | 'reward_text': lambda x: "+5000⭐"
279 | }
280 | ]
281 |
282 | shuffle(games)
283 |
284 | try:
285 | for game in games:
286 | await asyncio.sleep(uniform(3, 15))
287 | reward = await game['func'](http_client=http_client)
288 | if reward:
289 | logger.info(self.log_message(f"Reward {game['name']}: {game['reward_text'](reward)}"))
290 | except GamesNotReady as e:
291 | logger.info(self.log_message(str(e)))
292 | return e.seconds
293 | return 0
294 |
295 | async def run(self) -> None:
296 | random_delay = uniform(0, settings.SESSION_START_DELAY)
297 | logger.info(self.log_message(f"Bot will start in {int(random_delay)}s"))
298 | await asyncio.sleep(delay=random_delay)
299 |
300 | access_token_created_time = 0
301 | init_data = None
302 |
303 | token_live_time = randint(3500, 3600)
304 |
305 | proxy_conn = {'connector': ProxyConnector.from_url(self.proxy)} if self.proxy else {}
306 | async with CloudflareScraper(headers=self.headers, timeout=aiohttp.ClientTimeout(60), **proxy_conn) as http_client:
307 | while True:
308 | if not await self.check_proxy(http_client=http_client):
309 | logger.warning(self.log_message('Failed to connect to proxy server. Sleep 5 minutes.'))
310 | await asyncio.sleep(300)
311 | continue
312 |
313 | try:
314 | if time() - access_token_created_time >= token_live_time:
315 | init_data = await self.get_tg_web_data()
316 |
317 | if not init_data:
318 | logger.warning(self.log_message('Failed to get webview URL'))
319 | await asyncio.sleep(300)
320 | continue
321 |
322 | access_token_created_time = time()
323 | sleep_time = uniform(settings.SLEEP_TIME[0], settings.SLEEP_TIME[1])
324 |
325 | user_data = await self.login(http_client=http_client, init_data=init_data)
326 | if not user_data:
327 | logger.warning(self.log_message(f"Failed to login. Sleep {int(sleep_time)}s"))
328 | await asyncio.sleep(sleep_time)
329 | continue
330 |
331 | self.x_correlation_id = create_correlation_id()
332 | http_client.headers['Authorization'] = f"Bearer {user_data.get('access_token')}"
333 | if self.tg_client.is_fist_run:
334 | await first_run.append_recurring_session(self.session_name)
335 | logger.info(self.log_message(f"⭐ Logged in successfuly"))
336 | user = user_data.get('user')
337 | squad_id = user.get('squad_id')
338 |
339 | rating = await self.get_detail(http_client)
340 | position = await self.get_user_position(http_client)
341 | logger.info(self.log_message(
342 | f"ID: {user.get('id')} | Position: {position} | Points : {rating}"))
343 |
344 | streak = (await self.streak(http_client=http_client)).get('streak')
345 | if streak:
346 | logger.info(self.log_message(f"Daily Streak : {streak}"))
347 |
348 | await self.get_top_users(http_client)
349 |
350 | await self.visit(http_client=http_client)
351 |
352 | await self.get_top_squads(http_client)
353 | if not squad_id and settings.SUBSCRIBE_SQUAD:
354 | await asyncio.sleep(uniform(5, 10))
355 | await self.join_squad(http_client=http_client, squad_id=settings.SUBSCRIBE_SQUAD)
356 | await asyncio.sleep(uniform(0, 1))
357 |
358 | data_squad = await self.get_squad(http_client=http_client, squad_id=settings.SUBSCRIBE_SQUAD)
359 | if data_squad:
360 | logger.info(self.log_message(f"Squad : {data_squad.get('name')} | "
361 | f"Member : {data_squad.get('members_count')} | "
362 | f"Ratings : {data_squad.get('rating')}"))
363 |
364 | if settings.PLAY_GAMES:
365 | sleep_time = await self.play_games(http_client) * uniform(1.02, 1.2) or sleep_time
366 |
367 | await asyncio.sleep(uniform(3, 15))
368 |
369 | data_task = await self.get_tasks(http_client=http_client)
370 | subscribed_to = 0
371 | if data_task:
372 | shuffle(data_task)
373 | for task in data_task:
374 | task_id = task.get('id')
375 | title = task.get("title", "")
376 |
377 | if task.get('is_completed', False) or task_id not in TASKS_WL:
378 | continue
379 |
380 | if not randint(0, 2):
381 | logger.info(self.log_message(f"Randomly stopping doing tasks"))
382 | break
383 |
384 | await asyncio.sleep(uniform(3, 10))
385 | if task.get("type") == "code":
386 | await self.youtube_answers(http_client=http_client, task_id=task_id, task_title=title)
387 | continue
388 |
389 | if (task.get('type') == 'subscribe_channel' or
390 | re.findall(r'(Join|Subscribe|Follow).*?channel', task.get('title', ""),
391 | re.IGNORECASE)):
392 | if not settings.TASKS_WITH_JOIN_CHANNEL or subscribed_to >= 1:
393 | continue
394 | if not (streak > 1 and task_id == 29):
395 | await self.tg_client.join_and_mute_tg_channel(link=task.get('payload').get('url'))
396 | await asyncio.sleep(uniform(10, 20))
397 | subscribed_to += 1
398 |
399 | data_done = await self.done_tasks(http_client=http_client, task_id=task_id)
400 | if data_done and data_done.get('is_completed') is True:
401 | logger.info(self.log_message(
402 | f"Task : {task.get('title')} | Reward : {task.get('award')}"))
403 |
404 | except InvalidSession as error:
405 | raise error
406 |
407 | except Exception as error:
408 | sleep_time = uniform(60, 120)
409 | log_error(self.log_message(f"Unknown error: {error}. Sleeping for {int(sleep_time)}"))
410 | await asyncio.sleep(sleep_time)
411 |
412 | logger.info(self.log_message(f"Sleep {int(sleep_time)}s"))
413 | await asyncio.sleep(sleep_time)
414 |
415 |
416 | async def run_tapper(tg_client: UniversalTelegramClient):
417 | runner = Tapper(tg_client=tg_client)
418 | try:
419 | await runner.run()
420 | except InvalidSession as e:
421 | logger.error(runner.log_message(f"Invalid Session: {e}"))
422 |
--------------------------------------------------------------------------------
/bot/exceptions/__init__.py:
--------------------------------------------------------------------------------
1 | class InvalidSession(BaseException):
2 | ...
3 |
4 |
5 | class GamesNotReady(Exception):
6 | def __init__(self, time: int | float):
7 | self.seconds = time
8 | super().__init__(f"Games aren't ready yet. Available in: {time}")
9 |
--------------------------------------------------------------------------------
/bot/utils/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from .logger import logger, log_error
4 | from .async_lock import AsyncInterProcessLock
5 | from . import proxy_utils, config_utils, first_run
6 | from bot.config import settings
7 |
8 |
9 | if not os.path.isdir(settings.GLOBAL_CONFIG_PATH):
10 | GLOBAL_CONFIG_PATH = os.environ.get(settings.GLOBAL_CONFIG_PATH, "")
11 | else:
12 | GLOBAL_CONFIG_PATH = settings.GLOBAL_CONFIG_PATH
13 | GLOBAL_CONFIG_EXISTS = os.path.isdir(GLOBAL_CONFIG_PATH)
14 |
15 | CONFIG_PATH = os.path.join(GLOBAL_CONFIG_PATH, 'accounts_config.json') if GLOBAL_CONFIG_EXISTS else 'bot/config/accounts_config.json'
16 | SESSIONS_PATH = os.path.join(GLOBAL_CONFIG_PATH, 'sessions') if GLOBAL_CONFIG_EXISTS else 'sessions'
17 | PROXIES_PATH = os.path.join(GLOBAL_CONFIG_PATH, 'proxies.txt') if GLOBAL_CONFIG_EXISTS else 'bot/config/proxies.txt'
18 |
19 | PROXY_CHAIN = None
20 | if settings.USE_PROXY_CHAIN:
21 | path = os.path.join(GLOBAL_CONFIG_PATH, 'proxy_chain.txt')
22 | PROXY_CHAIN = path if GLOBAL_CONFIG_EXISTS and os.path.isfile(path) else None
23 |
24 |
25 | if not os.path.exists(path=SESSIONS_PATH):
26 | os.mkdir(path=SESSIONS_PATH)
27 |
28 | if settings.FIX_CERT:
29 | from certifi import where
30 | os.environ['SSL_CERT_FILE'] = where()
31 |
--------------------------------------------------------------------------------
/bot/utils/async_lock.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import fasteners
3 | from random import uniform
4 | from os import path
5 |
6 | from bot.utils import logger
7 |
8 |
9 | class AsyncInterProcessLock:
10 | """A context manager for acquiring inter-process locks asynchronously."""
11 |
12 | def __init__(self, lock_file):
13 | self.lock = fasteners.InterProcessLock(lock_file)
14 | self.file_name, _ = path.splitext(path.basename(lock_file))
15 |
16 | async def __aenter__(self):
17 | while True:
18 | lock_acquired = await asyncio.to_thread(self.lock.acquire, timeout=uniform(5, 10))
19 | if lock_acquired:
20 | return self
21 | sleep_time = uniform(30, 150)
22 | logger_message = f"{self.file_name} | Failed to acquire lock for " \
23 | f"{'accounts_config' if 'accounts_config' in self.file_name else 'session'}. " \
24 | f"Retrying in {int(sleep_time)} seconds"
25 | logger.info(logger_message)
26 | await asyncio.sleep(sleep_time)
27 |
28 | async def __aexit__(self, exc_type, exc_val, exc_tb):
29 | await asyncio.to_thread(self.lock.release)
30 |
--------------------------------------------------------------------------------
/bot/utils/config_utils.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import json
3 | from bot.utils import logger, log_error, AsyncInterProcessLock
4 | from opentele.api import API
5 | from os import path, remove
6 | from copy import deepcopy
7 |
8 |
9 | def read_config_file(config_path: str) -> dict:
10 | """Reads the contents of a config file. If the file does not exist, creates it.
11 |
12 | Args:
13 | config_path: Path to the .json file.
14 |
15 | Returns:
16 | The contents of the file, or an empty dict if the file was empty or created.
17 | """
18 | try:
19 | with open(config_path, 'r') as f:
20 | content = f.read()
21 | config = json.loads(content) if content else {}
22 | except FileNotFoundError:
23 | config = {}
24 | with open(config_path, 'w'):
25 | logger.warning(f"Accounts config file `{config_path}` not found. Creating a new one.")
26 | return config
27 |
28 |
29 | async def write_config_file(content: dict, config_path: str):
30 | """Writes the contents of a config file. If the file does not exist, creates it.
31 |
32 | Args:
33 | config_path: Path to the .json file. If empty, 'bot/config/accounts_config.json' is used
34 | content (dict): Content we want to write
35 |
36 | Returns:
37 | The contents of the file, or an empty dict if the file was empty or created.
38 | """
39 | lock = AsyncInterProcessLock(path.join(path.dirname(config_path), 'lock_files', 'accounts_config.lock'))
40 | try:
41 | async with lock:
42 | with open(config_path, 'w+') as f:
43 | json.dump(content, f, indent=2)
44 | await asyncio.sleep(0.1)
45 | except IOError as e:
46 | logger.error(f"An error occurred while writing to {config_path}: {e}")
47 |
48 |
49 | def get_session_config(session_name: str, config_path: str) -> dict:
50 | """Gets the session config for specified session name.
51 |
52 | Args:
53 | session_name (dict): The name of the session
54 | config_path: Path to the .json file. If empty, 'bot/config/accounts_config.json' is used
55 |
56 | Returns:
57 | The config object for specified session_name, or an empty dict if the file was empty or created.
58 | """
59 | return read_config_file(config_path).get(session_name, {})
60 |
61 |
62 | async def update_session_config_in_file(session_name: str, updated_session_config: dict, config_path: str):
63 | """Updates the content of a session in config file. If the file does not exist, creates it.
64 |
65 | Args:
66 | session_name (dict): The name of the session
67 | updated_session_config (dict): The config to override
68 | config_path: Path to the .json file. If empty, 'bot/config/accounts_config.json' is used
69 |
70 | Returns:
71 | The contents of the file, or an empty dict if the file was empty or created.
72 | """
73 | try:
74 | config = read_config_file(config_path)
75 | config[session_name] = updated_session_config
76 | await write_config_file(config, config_path)
77 | except Exception as e:
78 | log_error(e)
79 |
80 |
81 | async def restructure_config(config_path: str):
82 | config = read_config_file(config_path)
83 | if config:
84 | cfg_copy = deepcopy(config)
85 | for key, value in cfg_copy.items():
86 | api_info = {
87 | "api_id": value.get('api', {}).get("api_id") or value.pop("api_id", None),
88 | "api_hash": value.get('api', {}).get("api_hash") or value.pop("api_hash", None),
89 | "device_model": value.get('api', {}).get("device_model") or value.pop("device_model", None),
90 | "system_version": value.get('api', {}).get("system_version") or value.pop("system_version", None),
91 | "app_version": value.get('api', {}).get("app_version") or value.pop("app_version", None),
92 | "system_lang_code": value.get('api', {}).get("system_lang_code") or value.pop("system_lang_code", None),
93 | "lang_pack": value.get('api', {}).get("lang_pack") or value.pop("lang_pack", None),
94 | "lang_code": value.get('api', {}).get("lang_code") or value.pop("lang_code", None)
95 | }
96 | api_info = {k: v for k, v in api_info.items() if v is not None}
97 | cfg_copy[key]['api'] = api_info
98 | if cfg_copy != config:
99 | await write_config_file(cfg_copy, config_path)
100 |
101 |
102 | def import_session_json(session_path: str):
103 | lang_pack = {
104 | 6: "android",
105 | 4: "android",
106 | 2040: 'tdesktop',
107 | 10840: 'ios',
108 | 21724: "android",
109 | }
110 | json_path = f"{session_path.replace('.session', '')}.json"
111 | if path.isfile(json_path):
112 | with open(json_path, 'r') as file:
113 | json_conf = json.loads(file.read())
114 | api = {
115 | 'api_id': int(json_conf.get('app_id')),
116 | 'api_hash': json_conf.get('app_hash'),
117 | 'device_model': json_conf.get('device'),
118 | 'system_version': json_conf.get('sdk'),
119 | 'app_version': json_conf.get('app_version'),
120 | 'system_lang_code': json_conf.get('system_lang_code'),
121 | 'lang_code': json_conf.get('lang_code'),
122 | 'lang_pack': json_conf.get('lang_pack', lang_pack[int(json_conf.get('app_id'))])
123 | }
124 | remove(json_path)
125 | return api
126 |
127 | return None
128 |
129 |
130 | def get_api(acc_api):
131 | api_generators = {
132 | 4: API.TelegramAndroid.Generate,
133 | 6: API.TelegramAndroid.Generate,
134 | 2040: API.TelegramDesktop.Generate,
135 | 10840: API.TelegramIOS.Generate,
136 | 21724: API.TelegramAndroidX.Generate
137 | }
138 |
139 | generate_api = api_generators.get(acc_api.get('api_id'), API.TelegramDesktop.Generate)
140 | api = generate_api()
141 |
142 | api.api_id = acc_api.get('api_id', api.api_id)
143 | api.api_hash = acc_api.get('api_hash', api.api_hash)
144 | api.device_model = acc_api.get('device_model', api.device_model)
145 | api.system_version = acc_api.get('system_version', api.system_version)
146 | api.app_version = acc_api.get('app_version', api.app_version)
147 | api.system_lang_code = acc_api.get('system_lang_code', api.system_lang_code)
148 | api.lang_code = acc_api.get('lang_code', api.lang_code)
149 | api.lang_pack = acc_api.get('lang_pack', api.lang_pack)
150 | return api
151 |
--------------------------------------------------------------------------------
/bot/utils/first_run.py:
--------------------------------------------------------------------------------
1 | import aiofiles
2 |
3 |
4 | async def check_is_first_run(session_name: str):
5 | async with aiofiles.open('first_run.txt', mode='a+') as file:
6 | await file.seek(0)
7 | lines = await file.readlines()
8 | return session_name.lower() not in [line.strip() for line in lines]
9 |
10 |
11 | async def append_recurring_session(session_name: str):
12 | async with aiofiles.open('first_run.txt', mode='a+') as file:
13 | await file.writelines(session_name.lower() + '\n')
14 |
--------------------------------------------------------------------------------
/bot/utils/logger.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from loguru import logger
3 | from bot.config import settings
4 | from datetime import date
5 |
6 | logger.remove()
7 |
8 | logger.add(sink=sys.stdout, format="{time:YYYY-MM-DD HH:mm:ss}"
9 | " | {level}"
10 | " | {message}",
11 | filter=lambda record: record["level"].name != "TRACE")
12 |
13 | if settings.DEBUG_LOGGING:
14 | logger.add(f"logs/err_tracebacks_{date.today()}.txt",
15 | format="{time:DD.MM.YYYY HH:mm:ss} - {level} - {message}",
16 | level="TRACE",
17 | backtrace=True,
18 | diagnose=True,
19 | filter=lambda record: record["level"].name == "TRACE")
20 |
21 | logger = logger.opt(colors=True)
22 |
23 |
24 | def log_error(text):
25 | if settings.DEBUG_LOGGING:
26 | logger.opt(exception=True, colors=True).trace(text)
27 | return logger.error(text)
28 |
--------------------------------------------------------------------------------
/bot/utils/proxy_utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import aiohttp
3 | from aiohttp_proxy import ProxyConnector
4 | from collections import Counter
5 | from python_socks import ProxyType
6 | from shutil import copyfile
7 | from better_proxy import Proxy
8 | from bot.config import settings
9 | from bot.utils import logger
10 | from random import shuffle
11 |
12 | PROXY_TYPES = {
13 | 'socks5': ProxyType.SOCKS5,
14 | 'socks4': ProxyType.SOCKS4,
15 | 'http': ProxyType.HTTP,
16 | 'https': ProxyType.HTTP
17 | }
18 |
19 |
20 | def get_proxy_type(proxy_type: str):
21 | return PROXY_TYPES.get(proxy_type.lower())
22 |
23 |
24 | def to_telethon_proxy(proxy: Proxy):
25 | return {
26 | 'proxy_type': get_proxy_type(proxy.protocol),
27 | 'addr': proxy.host,
28 | 'port': proxy.port,
29 | 'username': proxy.login,
30 | 'password': proxy.password
31 | }
32 |
33 |
34 | def to_pyrogram_proxy(proxy: Proxy):
35 | return {
36 | 'scheme': proxy.protocol if proxy.protocol != 'https' else 'http',
37 | 'hostname': proxy.host,
38 | 'port': proxy.port,
39 | 'username': proxy.login,
40 | 'password': proxy.password
41 | }
42 |
43 |
44 | def get_proxies(proxy_path: str) -> list[str]:
45 | """Reads proxies from the proxy file and returns array of proxies.
46 | If file doesn't exist, creates the file
47 |
48 | Args:
49 | proxy_path: Path to the proxies.txt file.
50 |
51 | Returns:
52 | The contents of the file, or an empty list if the file was empty or created.
53 | """
54 | proxy_template_path = "bot/config/proxies-template.txt"
55 |
56 | if not os.path.isfile(proxy_path):
57 | copyfile(proxy_template_path, proxy_path)
58 | return []
59 |
60 | if settings.USE_PROXY_FROM_FILE:
61 | with open(file=proxy_path, encoding="utf-8-sig") as file:
62 | return [Proxy.from_str(proxy=row.strip()).as_url
63 | for row in file
64 | if row.strip() and not row.strip().startswith('type')]
65 | else:
66 | return []
67 |
68 |
69 | def get_unused_proxies(accounts_config, proxy_path: str):
70 | proxies_count = Counter([v.get('proxy') for v in accounts_config.values() if v.get('proxy')])
71 | all_proxies = get_proxies(proxy_path)
72 | return [proxy for proxy in all_proxies if proxies_count.get(proxy, 0) < settings.SESSIONS_PER_PROXY]
73 |
74 |
75 | async def check_proxy(proxy):
76 | url = 'https://ifconfig.me/ip'
77 | proxy_conn = ProxyConnector.from_url(proxy)
78 | try:
79 | async with aiohttp.ClientSession(connector=proxy_conn, timeout=aiohttp.ClientTimeout(15)) as session:
80 | response = await session.get(url)
81 | if response.status == 200:
82 | logger.success(f"Successfully connected to proxy. IP: {await response.text()}")
83 | if not proxy_conn.closed:
84 | proxy_conn.close()
85 | return True
86 | except Exception as e:
87 | logger.warning(f"Proxy {proxy} didn't respond")
88 | return False
89 |
90 |
91 | async def get_proxy_chain(path) -> (str | None, str | None):
92 | try:
93 | with open(path, 'r') as file:
94 | proxy = file.read().strip()
95 | return proxy, to_telethon_proxy(Proxy.from_str(proxy))
96 | except Exception as e:
97 | logger.error(f"Failed to get proxy for proxy chain from '{path}'")
98 | return None, None
99 |
100 |
101 | async def get_working_proxy(accounts_config: dict, current_proxy: str | None) -> str | None:
102 | if current_proxy and await check_proxy(current_proxy):
103 | return current_proxy
104 |
105 | from bot.utils import PROXIES_PATH
106 | unused_proxies = get_unused_proxies(accounts_config, PROXIES_PATH)
107 | shuffle(unused_proxies)
108 | for proxy in unused_proxies:
109 | if await check_proxy(proxy):
110 | return proxy
111 |
112 | return None
113 |
--------------------------------------------------------------------------------
/bot/utils/universal_telegram_client.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import os
3 | from better_proxy import Proxy
4 | from datetime import datetime, timedelta
5 | from random import randint, uniform
6 | from sqlite3 import OperationalError
7 | from typing import Union
8 |
9 | from opentele.tl import TelegramClient
10 | from telethon.errors import *
11 | from telethon.functions import messages, channels, account
12 | from telethon.network import ConnectionTcpAbridged
13 | from telethon.types import InputBotAppShortName, InputPeerNotifySettings, InputNotifyPeer, InputUser
14 |
15 | import pyrogram.raw.functions.account as paccount
16 | import pyrogram.raw.functions.channels as pchannels
17 | import pyrogram.raw.functions.messages as pmessages
18 | from pyrogram import Client as PyrogramClient
19 | from pyrogram.errors import *
20 | from pyrogram.raw import types as ptypes
21 |
22 | from bot.config import settings
23 | from bot.exceptions import InvalidSession
24 | from bot.utils.proxy_utils import to_pyrogram_proxy, to_telethon_proxy
25 | from bot.utils import logger, log_error, AsyncInterProcessLock, CONFIG_PATH, first_run
26 |
27 |
28 | class UniversalTelegramClient:
29 | def __init__(self, **client_params):
30 | self.session_name = None
31 | self.client: Union[TelegramClient, PyrogramClient]
32 | self.proxy = None
33 | self.is_fist_run = True
34 | self.is_pyrogram: bool = False
35 | self._client_params = client_params
36 | self._init_client()
37 |
38 | self.lock = AsyncInterProcessLock(
39 | os.path.join(os.path.dirname(CONFIG_PATH), 'lock_files', f"{self.session_name}.lock"))
40 |
41 | self._webview_data = None
42 |
43 | def _init_client(self):
44 | try:
45 | self.client = TelegramClient(connection=ConnectionTcpAbridged, **self._client_params)
46 | self.is_pyrogram = False
47 | self.session_name, _ = os.path.splitext(os.path.basename(self.client.session.filename))
48 | except OperationalError:
49 | session_name = self._client_params.pop('session')
50 | self._client_params.pop('system_lang_code')
51 | self._client_params['name'] = session_name
52 | self.client = PyrogramClient(**self._client_params)
53 | self.is_pyrogram = True
54 | self.session_name, _ = os.path.splitext(os.path.basename(self.client.name))
55 |
56 | def set_proxy(self, proxy: Proxy):
57 | if self.is_pyrogram is False:
58 | self.proxy = to_telethon_proxy(proxy)
59 | self.client.set_proxy(self.proxy)
60 | else:
61 | self.proxy = to_pyrogram_proxy(proxy)
62 | self.client.proxy = self.proxy
63 |
64 | async def get_app_webview_url(self, bot_username: str, bot_shortname: str, default_val: str) -> str:
65 | self.is_fist_run = await first_run.check_is_first_run(self.session_name)
66 | return await self._pyrogram_get_app_webview_url(bot_username, bot_shortname, default_val) if self.is_pyrogram \
67 | else await self._telethon_get_app_webview_url(bot_username, bot_shortname, default_val)
68 |
69 | async def get_webview_url(self, bot_username: str, bot_url: str, default_val: str) -> str:
70 | self.is_fist_run = await first_run.check_is_first_run(self.session_name)
71 | return await self._pyrogram_get_webview_url(bot_username, bot_url, default_val) if self.is_pyrogram \
72 | else await self._telethon_get_webview_url(bot_username, bot_url, default_val)
73 |
74 | async def join_and_mute_tg_channel(self, link: str):
75 | return await self._pyrogram_join_and_mute_tg_channel(link) if self.is_pyrogram \
76 | else await self._telethon_join_and_mute_tg_channel(link)
77 |
78 | async def update_profile(self, first_name: str = None, last_name: str = None, about: str = None):
79 | return await self._pyrogram_update_profile(first_name=first_name, last_name=last_name, about=about) if self.is_pyrogram \
80 | else await self._telethon_update_profile(first_name=first_name, last_name=last_name, about=about)
81 |
82 | async def _telethon_initialize_webview_data(self, bot_username: str, bot_shortname: str = None):
83 | if not self._webview_data:
84 | while True:
85 | try:
86 | peer = await self.client.get_input_entity(bot_username)
87 | bot_id = InputUser(user_id=peer.user_id, access_hash=peer.access_hash)
88 | input_bot_app = InputBotAppShortName(bot_id=bot_id, short_name=bot_shortname)
89 | self._webview_data = {'peer': peer, 'app': input_bot_app} if bot_shortname \
90 | else {'peer': peer, 'bot': peer}
91 | return
92 | except FloodWaitError as fl:
93 | logger.warning(f"{self.session_name} | FloodWait {fl}. Waiting {fl.seconds}s")
94 | await asyncio.sleep(fl.seconds + 3)
95 |
96 | async def _telethon_get_app_webview_url(self, bot_username: str, bot_shortname: str, default_val: str) -> str:
97 | if self.proxy and not self.client._proxy:
98 | logger.critical(f"{self.session_name} | Proxy found, but not passed to TelegramClient")
99 | exit(-1)
100 |
101 | async with self.lock:
102 | try:
103 | if not self.client.is_connected():
104 | await self.client.connect()
105 | await self._telethon_initialize_webview_data(bot_username=bot_username, bot_shortname=bot_shortname)
106 | await asyncio.sleep(uniform(1, 2))
107 |
108 | start = {'start_param': settings.REF_ID if randint(0, 100) <= 85 and settings.REF_ID else default_val} if self.is_fist_run else {}
109 |
110 | web_view = await self.client(messages.RequestAppWebViewRequest(
111 | **self._webview_data,
112 | platform='android',
113 | write_allowed=True,
114 | **start
115 | ))
116 |
117 | return web_view.url
118 |
119 | except (UnauthorizedError, AuthKeyUnregisteredError):
120 | raise InvalidSession(f"{self.session_name}: User is unauthorized")
121 | except (UserDeactivatedError, UserDeactivatedBanError, PhoneNumberBannedError):
122 | raise InvalidSession(f"{self.session_name}: User is banned")
123 |
124 | except Exception:
125 | raise
126 |
127 | finally:
128 | if self.client.is_connected():
129 | await self.client.disconnect()
130 | await asyncio.sleep(15)
131 |
132 | async def _telethon_get_webview_url(self, bot_username: str, bot_url: str, default_val: str) -> str:
133 | if self.proxy and not self.client._proxy:
134 | logger.critical(f"{self.session_name} | Proxy found, but not passed to TelegramClient")
135 | exit(-1)
136 |
137 | async with self.lock:
138 | try:
139 | if not self.client.is_connected():
140 | await self.client.connect()
141 | await self._telethon_initialize_webview_data(bot_username=bot_username)
142 | await asyncio.sleep(uniform(1, 2))
143 |
144 | start = {'start_param': settings.REF_ID if randint(0, 100) <= 85 and settings.REF_ID else default_val} if self.is_fist_run else {}
145 |
146 | start_state = False
147 | async for message in self.client.iter_messages(bot_username):
148 | if r'/start' in message.text:
149 | start_state = True
150 | break
151 | await asyncio.sleep(uniform(0.5, 1))
152 | if not start_state:
153 | await self.client(messages.StartBotRequest(**self._webview_data, **start))
154 | await asyncio.sleep(uniform(1, 2))
155 |
156 | web_view = await self.client(messages.RequestWebViewRequest(
157 | **self._webview_data,
158 | platform='android',
159 | from_bot_menu=False,
160 | url=bot_url,
161 | **start
162 | ))
163 |
164 | return web_view.url
165 |
166 | except (UnauthorizedError, AuthKeyUnregisteredError):
167 | raise InvalidSession(f"{self.session_name}: User is unauthorized")
168 | except (UserDeactivatedError, UserDeactivatedBanError, PhoneNumberBannedError):
169 | raise InvalidSession(f"{self.session_name}: User is banned")
170 |
171 | except Exception:
172 | raise
173 |
174 | finally:
175 | if self.client.is_connected():
176 | await self.client.disconnect()
177 | await asyncio.sleep(15)
178 |
179 | async def _pyrogram_initialize_webview_data(self, bot_username: str, bot_shortname: str = None):
180 | if not self._webview_data:
181 | while True:
182 | try:
183 | peer = await self.client.resolve_peer(bot_username)
184 | input_bot_app = ptypes.InputBotAppShortName(bot_id=peer, short_name=bot_shortname)
185 | self._webview_data = {'peer': peer, 'app': input_bot_app} if bot_shortname \
186 | else {'peer': peer, 'bot': peer}
187 | return
188 | except FloodWait as fl:
189 | logger.warning(f"{self.session_name} | FloodWait {fl}. Waiting {fl.value}s")
190 | await asyncio.sleep(fl.value + 3)
191 |
192 | async def _pyrogram_get_app_webview_url(self, bot_username: str, bot_shortname: str, default_val: str) -> str:
193 | if self.proxy and not self.client.proxy:
194 | logger.critical(f"{self.session_name} | Proxy found, but not passed to Client")
195 | exit(-1)
196 |
197 | async with self.lock:
198 | try:
199 | if not self.client.is_connected:
200 | await self.client.connect()
201 | await self._pyrogram_initialize_webview_data(bot_username, bot_shortname)
202 | await asyncio.sleep(uniform(1, 2))
203 |
204 | start = {'start_param': settings.REF_ID if randint(0, 100) <= 85 and settings.REF_ID else default_val} if self.is_fist_run else {}
205 | web_view = await self.client.invoke(pmessages.RequestAppWebView(
206 | **self._webview_data,
207 | platform='android',
208 | write_allowed=True,
209 | **start
210 | ))
211 |
212 | return web_view.url
213 |
214 | except (Unauthorized, AuthKeyUnregistered):
215 | raise InvalidSession(f"{self.session_name}: User is unauthorized")
216 | except (UserDeactivated, UserDeactivatedBan, PhoneNumberBanned):
217 | raise InvalidSession(f"{self.session_name}: User is banned")
218 |
219 | except Exception:
220 | raise
221 |
222 | finally:
223 | if self.client.is_connected:
224 | await self.client.disconnect()
225 | await asyncio.sleep(15)
226 |
227 | async def _pyrogram_get_webview_url(self, bot_username: str, bot_url: str, default_val: str) -> str:
228 | if self.proxy and not self.client.proxy:
229 | logger.critical(f"{self.session_name} | Proxy found, but not passed to Client")
230 | exit(-1)
231 |
232 | async with self.lock:
233 | try:
234 | if not self.client.is_connected:
235 | await self.client.connect()
236 | await self._pyrogram_initialize_webview_data(bot_username)
237 | await asyncio.sleep(uniform(1, 2))
238 |
239 | start = {'start_param': settings.REF_ID if randint(0, 100) <= 85 and settings.REF_ID else default_val} if self.is_fist_run else {}
240 |
241 | start_state = False
242 | async for message in self.client.get_chat_history(bot_username):
243 | if r'/start' in message.text:
244 | start_state = True
245 | break
246 | await asyncio.sleep(uniform(0.5, 1))
247 | if not start_state:
248 | await self.client.invoke(pmessages.StartBot(**self._webview_data,
249 | random_id=randint(1, 2**63),
250 | **start))
251 | await asyncio.sleep(uniform(1, 2))
252 | web_view = await self.client.invoke(pmessages.RequestWebView(
253 | **self._webview_data,
254 | platform='android',
255 | from_bot_menu=False,
256 | url=bot_url,
257 | **start
258 | ))
259 |
260 | return web_view.url
261 |
262 | except (Unauthorized, AuthKeyUnregistered):
263 | raise InvalidSession(f"{self.session_name}: User is unauthorized")
264 | except (UserDeactivated, UserDeactivatedBan, PhoneNumberBanned):
265 | raise InvalidSession(f"{self.session_name}: User is banned")
266 |
267 | except Exception:
268 | raise
269 |
270 | finally:
271 | if self.client.is_connected:
272 | await self.client.disconnect()
273 | await asyncio.sleep(15)
274 |
275 | async def _telethon_join_and_mute_tg_channel(self, link: str):
276 | path = link.replace("https://t.me/", "")
277 | if path == 'money':
278 | return
279 |
280 | async with self.lock:
281 | async with self.client as client:
282 | try:
283 | if path.startswith('+'):
284 | invite_hash = path[1:]
285 | result = await client(messages.ImportChatInviteRequest(hash=invite_hash))
286 | channel_title = result.chats[0].title
287 | entity = result.chats[0]
288 | else:
289 | entity = await client.get_entity(f'@{path}')
290 | await client(channels.JoinChannelRequest(channel=entity))
291 | channel_title = entity.title
292 |
293 | await asyncio.sleep(1)
294 |
295 | await client(account.UpdateNotifySettingsRequest(
296 | peer=InputNotifyPeer(entity),
297 | settings=InputPeerNotifySettings(
298 | show_previews=False,
299 | silent=True,
300 | mute_until=datetime.today() + timedelta(days=365)
301 | )
302 | ))
303 |
304 | logger.info(f"{self.session_name} | Subscribed to channel: {channel_title}")
305 | except FloodWaitError as fl:
306 | logger.warning(f"{self.session_name} | FloodWait {fl}. Waiting {fl.seconds}s")
307 | return fl.seconds
308 | except Exception as e:
309 | log_error(
310 | f"{self.session_name} | (Task) Error while subscribing to tg channel {link}: {e}")
311 |
312 | await asyncio.sleep(uniform(15, 20))
313 | return
314 |
315 | async def _pyrogram_join_and_mute_tg_channel(self, link: str):
316 | path = link.replace("https://t.me/", "")
317 | if path == 'money':
318 | return
319 |
320 | async with self.lock:
321 | async with self.client:
322 | try:
323 | if path.startswith('+'):
324 | invite_hash = path[1:]
325 | result = await self.client.invoke(pmessages.ImportChatInvite(hash=invite_hash))
326 | channel_title = result.chats[0].title
327 | entity = result.chats[0]
328 | peer = ptypes.InputPeerChannel(channel_id=entity.id, access_hash=entity.access_hash)
329 | else:
330 | peer = await self.client.resolve_peer(f'@{path}')
331 | channel = ptypes.InputChannel(channel_id=peer.channel_id, access_hash=peer.access_hash)
332 | await self.client.invoke(pchannels.JoinChannel(channel=channel))
333 | channel_title = path
334 |
335 | await asyncio.sleep(1)
336 |
337 | await self.client.invoke(paccount.UpdateNotifySettings(
338 | peer=ptypes.InputNotifyPeer(peer=peer),
339 | settings=ptypes.InputPeerNotifySettings(
340 | show_previews=False,
341 | silent=True,
342 | mute_until=2147483647))
343 | )
344 |
345 | logger.info(f"{self.session_name} | Subscribed to channel: {channel_title}")
346 | except FloodWait as e:
347 | logger.warning(f"{self.session_name} | FloodWait {e}. Waiting {e.value}s")
348 | return e.value
349 | except UserAlreadyParticipant:
350 | logger.info(f"{self.session_name} | Was already Subscribed to channel: {link}")
351 | except Exception as e:
352 | log_error(
353 | f"{self.session_name} | (Task) Error while subscribing to tg channel {link}: {e}")
354 |
355 | await asyncio.sleep(uniform(15, 20))
356 | return
357 |
358 | async def _telethon_update_profile(self, first_name: str = None, last_name: str = None, about: str = None):
359 | update_params = {
360 | 'first_name': first_name,
361 | 'last_name': last_name,
362 | 'about': about
363 | }
364 | update_params = {k: v for k, v in update_params.items() if v is not None}
365 | if not update_params:
366 | return
367 |
368 | async with self.lock:
369 | async with self.client:
370 | try:
371 | await self.client(account.UpdateProfileRequest(**update_params))
372 | except Exception as e:
373 | log_error(
374 | f"{self.session_name} | Failed to update profile: {e}")
375 | await asyncio.sleep(uniform(15, 20))
376 |
377 | async def _pyrogram_update_profile(self, first_name: str = None, last_name: str = None, about: str = None):
378 | update_params = {
379 | 'first_name': first_name,
380 | 'last_name': last_name,
381 | 'about': about
382 | }
383 | update_params = {k: v for k, v in update_params.items() if v is not None}
384 | if not update_params:
385 | return
386 |
387 | async with self.lock:
388 | async with self.client:
389 | try:
390 | await self.client.invoke(paccount.UpdateProfile(**update_params))
391 | except Exception as e:
392 | log_error(
393 | f"{self.session_name} | Failed to update profile: {e}")
394 | await asyncio.sleep(uniform(15, 20))
395 |
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '3'
2 | services:
3 | bot:
4 | container_name: 'ИМЯ РЕПЫ'
5 | build:
6 | context: .
7 | stop_signal: SIGINT
8 | restart: unless-stopped
9 | command: "python3 main.py -a 1"
10 | volumes:
11 | - .:/app
12 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | from contextlib import suppress
3 | from bot.core.launcher import process
4 | from bot.utils import PROXY_CHAIN, logger
5 | from bot.utils.proxy_utils import get_proxy_chain, check_proxy
6 | from os import system, name as os_name
7 |
8 |
9 | def set_window_title(title):
10 | if os_name == 'nt':
11 | system(f'title {title}')
12 | else:
13 | print(f'\033]0;{title}\007', end='', flush=True)
14 |
15 |
16 | async def main():
17 | if PROXY_CHAIN:
18 | proxy_str, proxy = await get_proxy_chain(PROXY_CHAIN)
19 | if proxy:
20 | logger.info("Getting proxy for Proxy Chain")
21 | if await check_proxy(proxy_str):
22 | import socket, socks
23 | socks.set_default_proxy(proxy)
24 | socket.socket = socks.socksocket
25 | else:
26 | logger.error("Proxy chain didn't respond. Can't start the bot using proxy chain")
27 | input('Press any key to exit: ')
28 | exit(0)
29 | else:
30 | logger.warning("No valid proxy found. Skipping")
31 | await process()
32 |
33 |
34 | if __name__ == '__main__':
35 | set_window_title('Major')
36 | with suppress(KeyboardInterrupt):
37 | asyncio.run(main())
38 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | aiofiles==24.1.0
2 | aiohttp==3.9.5
3 | aiohttp-proxy==0.1.2
4 | aiocfscrape==1.0.0
5 | asyncio==3.4.3
6 | better-proxy==1.2.0
7 | certifi
8 | fasteners
9 | loguru~=0.7.2
10 | opentele==1.15.1
11 | protobuf==5.28.3
12 | pydantic-settings==2.4.0
13 | pyrogram==2.0.106
14 | PySocks==1.7.1
15 | python-socks==2.5.1
16 | Telethon==1.36.0
17 | ua_generator
18 |
--------------------------------------------------------------------------------
/run.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | set firstRun=true
3 |
4 | if not exist venv (
5 | echo Creating virtual environment...
6 | python -m venv venv
7 | )
8 |
9 | echo Activating virtual environment...
10 | call venv\Scripts\activate
11 |
12 | if not exist venv\Lib\site-packages\installed (
13 | if exist requirements.txt (
14 | echo installing wheel for faster installing
15 | pip install wheel
16 | echo Installing dependencies...
17 | pip install -r requirements.txt
18 | echo. > venv\Lib\site-packages\installed
19 | ) else (
20 | echo requirements.txt not found, skipping dependency installation.
21 | )
22 | ) else (
23 | echo Dependencies already installed, skipping installation.
24 | )
25 |
26 | if not exist .env (
27 | echo Copying configuration file
28 | copy .env-example .env
29 | ) else (
30 | echo Skipping .env copying
31 | )
32 |
33 | echo Starting the bot...
34 | :loop
35 | git fetch
36 | git pull
37 | if "%firstRun%"=="true" (
38 | python main.py
39 | set firstRun=false
40 | ) else (
41 | python main.py -a 1
42 | )
43 | echo Restarting the program in 10 seconds...
44 | timeout /t 10 /nobreak >nul
45 | goto :loop
46 |
--------------------------------------------------------------------------------
/run.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | firstRun=true
4 |
5 | # Проверка на наличие папки venv
6 | if [ ! -d "venv" ]; then
7 | echo "Creating virtual environment..."
8 | python3 -m venv venv
9 | fi
10 |
11 | echo "Activating virtual environment..."
12 | source venv/bin/activate
13 |
14 | # Проверка на наличие установленного флага в виртуальном окружении
15 | if [ ! -f "venv/installed" ]; then
16 | if [ -f "requirements.txt" ]; then
17 | echo "Installing wheel for faster installing"
18 | pip3 install wheel
19 | echo "Installing dependencies..."
20 | pip3 install -r requirements.txt
21 | touch venv/installed
22 | else
23 | echo "requirements.txt not found, skipping dependency installation."
24 | fi
25 | else
26 | echo "Dependencies already installed, skipping installation."
27 | fi
28 |
29 | if [ ! -f ".env" ]; then
30 | echo "Copying configuration file"
31 | cp .env-example .env
32 | else
33 | echo "Skipping .env copying"
34 | fi
35 |
36 | while true
37 | do
38 | git fetch
39 | git pull
40 | if [ "$firstRun" = true ]; then
41 | python3 main.py
42 | firstRun=false
43 | else
44 | python3 main.py -a 1
45 | fi
46 |
47 | echo "Restarting the program in 10 seconds..."
48 | sleep 10
49 | done
50 |
--------------------------------------------------------------------------------