├── .env-example
├── .gitattributes
├── .gitignore
├── 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
│ ├── build_check.py
│ ├── config_utils.py
│ ├── first_run.py
│ ├── logger.py
│ ├── proxy_utils.py
│ ├── sol.py
│ ├── ton.py
│ └── universal_telegram_client.py
├── 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 | TRACK_BOT_UPDATES=
8 |
9 | REF_ID=
10 |
11 | PERFORM_TASKS=
12 | PERFORM_WALLET_TASK=
13 | PERFORM_EMOJI_TASK=
14 | SUBSCRIPTIONS_PER_CYCLE=
15 |
16 | TWOCAPTCHA_API=
17 |
18 | OVERWRITE_WALLETS=
19 | CONNECT_WALLETS_WEB=
20 |
21 | SESSION_START_DELAY=
22 | SLEEP_TIME=
23 |
24 | SESSIONS_PER_PROXY=
25 | USE_PROXY_FROM_FILE=
26 | DISABLE_PROXY_REPLACE=
27 |
28 | DEVICE_PARAMS=
29 |
30 | DEBUG_LOGGING=
31 |
--------------------------------------------------------------------------------
/.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/
172 |
173 | first_run.txt
--------------------------------------------------------------------------------
/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/PAWSOG_bot/PAWS?startapp=uLnYLVgv)
2 |
3 |
4 |
5 | ## Recommendation before use
6 |
7 | # 🔥🔥 PYTHON version must be 3.10 🔥🔥
8 |
9 | > 🇪🇳 README in english available [here](README)
10 |
11 | ## Функционал
12 | | Функционал | Поддерживается |
13 | |:--------------------------------------:|:--------------:|
14 | | Многопоточность | ✅ |
15 | | Привязка прокси к сессии | ✅ |
16 | | Использование вашей реферальной ссылки | ✅ |
17 | | Авто выполнение заданий | ✅ |
18 | | Поддержка telethon И pyrogram .session | ✅ |
19 |
20 | _Скрипт осуществляет поиск файлов сессий в следующих папках:_
21 | * /sessions
22 | * /sessions/pyrogram
23 | * /session/telethon
24 |
25 | PERFORM_TASKS: bool = True
26 | SUBSCRIPTIONS_PER_CYCLE: int = 1
27 |
28 |
29 | ## [Настройки](https://github.com/SP-l33t/Paws-Hybrid/tree/main/.env-example)
30 | | Настройки | Описание |
31 | |:---------------------------:|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|
32 | | **API_ID / API_HASH** | Данные платформы, с которой будет запущена сессия Telegram (по умолчанию - android) |
33 | | **GLOBAL_CONFIG_PATH** | Определяет глобальный путь для accounts_config, proxies, sessions.
Укажите абсолютный путь или используйте переменную окружения (по умолчанию - переменная окружения: **TG_FARM**)
Если переменной окружения не существует, использует директорию скрипта |
34 | | **FIX_CERT** | Попытаться исправить ошибку SSLCertVerificationError ( True / **False** ) |
35 | | **TRACK_BOT_UPDATES** | Отслеживать обновления бота и останавливать бота, если были обновления, для проверки изменений ( **True** /False ) |
36 | | **REF_ID** | Ваш реферальный идентификатор (В реферальной ссылке после startapp= ) |
37 | | **PERFORM_TASKS** | Выполнять задания автоматически ( **True** / False) |
38 | | **PERFORM_WALLET_TASK** | Выполнять задание с привязкой кошелька ( True / **False** ) |
39 | | **PERFORM_EMOJI_TASK** | Выполнять задание с добавлением emoji ( True / **False** ) |
40 | | **SUBSCRIPTIONS_PER_CYCLE** | Количество заданий с подпиской на канал за круг. 0 = Подписки выключены ( **1** ) |
41 | | **TWOCAPTCHA_API** | https://2captcha.com/ API ключ для решения капчи для Activity Check задания |
42 | | **OVERWRITE_WALLETS** | Переподключать кошельки, если подключенный и кошелёк в конфиг файле отличаются ( True / **False**) |
43 | | **CONNECT_WALLETS_WEB** | Подключать кошельки в приложении. Если в конфиге нет кошельков, они будут созданы автоматически (e.g. **True**) |
44 | | **SESSION_START_DELAY** | Случайная задержка при запуске. От 1 до указанного значения (например, **360**) |
45 | | **SLEEP_TIME** | Сон между итерациями ( **[43200, 86400]** ) |
46 | | **SESSIONS_PER_PROXY** | Количество сессий, которые могут использовать один и тот же прокси ( **1** ) |
47 | | **USE_PROXY_FROM_FILE** | Использовать ли прокси из файла `bot/config/proxies.txt` (**True** / False) |
48 | | **DISABLE_PROXY_REPLACE** | Отключить автоматическую проверку и замену нерабочих прокси перед стартом ( True / **False** ) |
49 | | **DEVICE_PARAMS** | Введите настройки устройства, чтобы телеграмм-сессия выглядела более реалистично (True / **False**) |
50 | | **DEBUG_LOGGING** | Включить логирование трейсбэков ошибок в лог файл (True / **False**) |
51 |
52 | ## Быстрый старт 📚
53 |
54 | Для быстрой установки и последующего запуска - запустите файл run.bat на Windows или run.sh на Unix
55 |
56 | ## Предварительные условия
57 | Прежде чем начать, убедитесь, что у вас установлено следующее:
58 | - [Python](https://www.python.org/downloads/) **версии 3.10**
59 |
60 | ## Получение API ключей
61 | 1. Перейдите на сайт [my.telegram.org](https://my.telegram.org) и войдите в систему, используя свой номер телефона.
62 | 2. Выберите **"API development tools"** и заполните форму для регистрации нового приложения.
63 | 3. Запишите `API_ID` и `API_HASH` в файле `.env`, предоставленные после регистрации вашего приложения.
64 |
65 | ## Установка
66 | Вы можете скачать [**Репозиторий**](https://github.com/SP-l33t/Paws-Hybrid) клонированием на вашу систему и установкой необходимых зависимостей:
67 | ```shell
68 | git clone https://github.com/SP-l33t/Paws-Hybrid.git
69 | cd Paws-Hybrid
70 | ```
71 |
72 | Затем для автоматической установки введите:
73 |
74 | Windows:
75 | ```shell
76 | run.bat
77 | ```
78 |
79 | Linux:
80 | ```shell
81 | run.sh
82 | ```
83 |
84 | # Linux ручная установка
85 | ```shell
86 | python3 -m venv venv
87 | source venv/bin/activate
88 | pip3 install -r requirements.txt
89 | cp .env-example .env
90 | nano .env # Здесь вы обязательно должны указать ваши API_ID и API_HASH , остальное берется по умолчанию
91 | python3 main.py
92 | ```
93 |
94 | Также для быстрого запуска вы можете использовать аргументы, например:
95 | ```shell
96 | ~/Paws-Hybrid >>> python3 main.py --action (1/2)
97 | # Or
98 | ~/Paws-Hybrid >>> python3 main.py -a (1/2)
99 |
100 | # 1 - Запускает кликер
101 | # 2 - Создает сессию
102 | ```
103 |
104 |
105 | # Windows ручная установка
106 | ```shell
107 | python -m venv venv
108 | venv\Scripts\activate
109 | pip install -r requirements.txt
110 | copy .env-example .env
111 | # Указываете ваши API_ID и API_HASH, остальное берется по умолчанию
112 | python main.py
113 | ```
114 |
115 | Также для быстрого запуска вы можете использовать аргументы, например:
116 | ```shell
117 | ~/Paws-Hybrid >>> python main.py --action (1/2)
118 | # Или
119 | ~/Paws-Hybrid >>> python main.py -a (1/2)
120 |
121 | # 1 - Запускает кликер
122 | # 2 - Создает сессию
123 | ```
124 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://t.me/+jJhUfsfFCn4zZDk0) [](https://t.me/PAWSOG_bot/PAWS?startapp=uLnYLVgv)
2 |
3 |
4 |
5 | ## Recommendation before use
6 |
7 | # 🔥🔥 Use PYTHON 3.10 🔥🔥
8 |
9 | > 🇷 🇺 README in Russian available [here](README-RU.md)
10 |
11 | ## Features
12 | | Feature | Supported |
13 | |:--------------------------------------------------------------------------:|:---------:|
14 | | Multithreading | ✅ |
15 | | Proxy binding to session | ✅ |
16 | | Auto tasks | ✅ |
17 | | Auto join squad | ✅ |
18 | | Supports telethon AND pyrogram .session | ✅ |
19 |
20 | _Script searches for session files in the following folders:_
21 | * /sessions
22 | * /sessions/pyrogram
23 | * /session/telethon
24 |
25 |
26 | ## [Settings](https://github.com/SP-l33t/Paws-Hybrid/tree/main/.env-example)
27 |
28 | # Use default setting for best performance !
29 | | Settings | Description |
30 | |:---------------------------:|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|
31 | | **API_ID / API_HASH** | Platform data from which to run the Telegram session (by default - android) |
32 | | **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. |
33 | | **FIX_CERT** | Try to fix SSLCertVerificationError ( True / **False** ) |
34 | | **TRACK_BOT_UPDATES** | Tracks bot updates and stops bot from running, if bot is updated (default: **True**) |
35 | | **REF_ID** | Your referral id (part of the referral link after startapp=) |
36 | | **PERFORM_TASKS** | Auto do tasks ( **True** / False) |
37 | | **PERFORM_WALLET_TASK** | Perform Link wallet task ( True / **False** ) |
38 | | **PERFORM_EMOJI_TASK** | Perform add Emoji to name task ( True / **False** ) |
39 | | **SUBSCRIPTIONS_PER_CYCLE** | Amount of tasks with channel subscriptions to be performed per round. 0 = Subscriptions are disabled ( **1** ) |
40 | | **TWOCAPTCHA_API** | https://2captcha.com/ API key to solve captcha for Activity Check task |
41 | | **OVERWRITE_WALLETS** | If the connected walled differs from the wallet in settings, it will be reconnected (e.g. **False**) |
42 | | **CONNECT_WALLETS_WEB** | Whether to connect SOL and TON wallets. Wallets will be generated automatically (e.g. **True**) |
43 | | **SESSION_START_DELAY** | Random delay at session start from 1 to set value (e.g. **30**) |
44 | | **SLEEP_TIME** | Sleep time between cycles ( **[43200, 86400]** ) |
45 | | **SESSIONS_PER_PROXY** | Amount of sessions, that can share same proxy ( **1** ) |
46 | | **USE_PROXY_FROM_FILE** | Whether to use a proxy from the `bot/config/proxies.txt` file (**True** / False) |
47 | | **DISABLE_PROXY_REPLACE** | Disable automatic checking and replacement of non-working proxies before startup (True / **False**) |
48 | | **DEVICE_PARAMS** | Enter device settings to make the telegram session look more realistic (True / **False**) |
49 | | **DEBUG_LOGGING** | Whether to log error's tracebacks to /logs folder (True / **False**) |
50 |
51 | ## Quick Start 📚
52 |
53 | To fast install libraries and run bot - open run.bat on Windows or run.sh on Linux
54 |
55 | ## Prerequisites
56 | Before you begin, make sure you have the following installed:
57 | - [Python](https://www.python.org/downloads/) **version 3.10**
58 |
59 | ## Obtaining API Keys
60 | 1. Go to [my.telegram.org](https://my.telegram.org) and log in using your phone number.
61 | 2. Select **"API development tools"** and fill out the form to register a new application.
62 | 3. Record the **API_ID** and **API_HASH** provided after registering your application in the `.env` file.
63 |
64 | ## Installation
65 | You can download [**Repository**](https://github.com/SP-l33t/Paws-Hybrid) by cloning it onto your system and installing the necessary dependencies:
66 | ```shell
67 | git clone https://github.com/SP-l33t/Paws-Hybrid.git
68 | cd Paws-Hybrid
69 | ```
70 |
71 | # Linux manual installation
72 | ```shell
73 | python3 -m venv venv
74 | source venv/bin/activate
75 | pip3 install -r requirements.txt
76 | cp .env-example .env
77 | nano .env # Here you must specify your API_ID and API_HASH, the rest is taken by default
78 | python3 main.py
79 | ```
80 |
81 | You can also use arguments for quick start, for example:
82 | ```shell
83 | ~/Paws-Hybrid >>> python3 main.py --action (1/2)
84 | # Or
85 | ~/Paws-Hybrid >>> python3 main.py -a (1/2)
86 |
87 | # 1 - Run clicker
88 | # 2 - Creates a session
89 | ```
90 |
91 | # Windows manual installation
92 | ```shell
93 | python -m venv venv
94 | venv\Scripts\activate
95 | pip install -r requirements.txt
96 | copy .env-example .env
97 | # Here you must specify your API_ID and API_HASH, the rest is taken by default
98 | python main.py
99 | ```
100 |
101 | You can also use arguments for quick start, for example:
102 | ```shell
103 | ~/Paws-Hybrid >>> python main.py --action (1/2)
104 | # Or
105 | ~/Paws-Hybrid >>> python main.py -a (1/2)
106 |
107 | # 1 - Run clicker
108 | # 2 - Creates a session
109 | ```
110 |
--------------------------------------------------------------------------------
/bot/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = '1.0'
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 | TRACK_BOT_UPDATES: bool = True
14 |
15 | REF_ID: str = "uLnYLVgv"
16 |
17 | PERFORM_TASKS: bool = True
18 | PERFORM_WALLET_TASK: bool = False
19 | PERFORM_EMOJI_TASK: bool = False
20 | SUBSCRIPTIONS_PER_CYCLE: int = 1
21 |
22 | TWOCAPTCHA_API: str = None
23 |
24 | OVERWRITE_WALLETS: bool = False
25 | CONNECT_WALLETS_WEB: bool = True
26 |
27 | SESSION_START_DELAY: int = 360
28 |
29 | SLEEP_TIME: list[int] = [43200, 86400]
30 |
31 | SESSIONS_PER_PROXY: int = 1
32 | USE_PROXY_FROM_FILE: bool = True
33 | DISABLE_PROXY_REPLACE: bool = False
34 | USE_PROXY_CHAIN: bool = False
35 |
36 | DEVICE_PARAMS: bool = False
37 |
38 | DEBUG_LOGGING: bool = False
39 |
40 |
41 | settings = Settings()
42 |
43 |
--------------------------------------------------------------------------------
/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/Paws-Hybrid/be02181446a44d619a8adb3e27fdde14c6550a13/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 re
2 |
3 |
4 | headers_app = {
5 | 'Accept': 'application/json',
6 | 'Accept-Encoding': 'gzip, deflate, br',
7 | 'Accept-Language': 'en-US,en;q=0.9',
8 | 'Origin': 'https://app.paws.community',
9 | 'Referer': 'https://app.paws.community/',
10 | 'Sec-Fetch-Dest': 'empty',
11 | 'Sec-Fetch-Mode': 'cors',
12 | 'Sec-Fetch-Site': 'same-site',
13 | 'Sec-Ch-Ua-Mobile': '?1',
14 | 'Sec-Ch-Ua-Platform': '"Android"',
15 | 'X-Requested-With': "org.telegram.messenger"
16 | }
17 |
18 | headers_pwa = {
19 | 'Accept': 'application/json',
20 | 'Accept-Encoding': 'gzip, deflate, br',
21 | 'Accept-Language': 'en-US,en;q=0.9',
22 | 'Origin': 'https://paws.community',
23 | 'Referer': 'https://paws.community/',
24 | 'Sec-Fetch-Dest': 'empty',
25 | 'Sec-Fetch-Mode': 'cors',
26 | 'Sec-Fetch-Site': 'same-site',
27 | 'Sec-Ch-Ua-Mobile': '?1',
28 | 'Sec-Ch-Ua-Platform': '"Android"',
29 | }
30 |
31 |
32 | def get_sec_ch_ua(user_agent, is_webview=True):
33 | pattern = r'(Chrome|Chromium)\/(\d+)\.(\d+)\.(\d+)\.(\d+)'
34 |
35 | match = re.search(pattern, user_agent)
36 |
37 | if match:
38 | version = match.group(2)
39 | browser = "Android WebView" if is_webview else "Google Chrome"
40 | return {'Sec-Ch-Ua': f'"{browser}";v="{version}", "Chromium";v="{version}", "Not?A_Brand";v="24"'}
41 | else:
42 | return {}
43 |
--------------------------------------------------------------------------------
/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, build_check, ton, sol
12 | from bot.core.tapper import run_tapper
13 | from bot.core.registrator import register_sessions
14 |
15 |
16 | START_TEXT = """
17 |
18 | ██████╗░░█████╗░░██╗░░░░░░░██╗░██████╗
19 | ██╔══██╗██╔══██╗░██║░░██╗░░██║██╔════╝
20 | ██████╔╝███████║░╚██╗████╗██╔╝╚█████╗░
21 | ██╔═══╝░██╔══██║░░████╔═████║░░╚═══██╗
22 | ██║░░░░░██║░░██║░░╚██╔╝░╚██╔╝░██████╔╝
23 | ╚═╝░░░░░╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░╚═════╝░
24 |
25 | Select an action:
26 |
27 | 1. Run clicker
28 | 2. Create session
29 | """
30 |
31 |
32 | API_ID = settings.API_ID
33 | API_HASH = settings.API_HASH
34 |
35 |
36 | def prompt_user_action() -> int:
37 | logger.info(START_TEXT)
38 | while True:
39 | action = input("> ").strip()
40 | if action.isdigit() and action in ("1", "2"):
41 | return int(action)
42 | logger.warning("Invalid action. Please enter 1 or 2.")
43 |
44 |
45 | async def process() -> None:
46 | parser = argparse.ArgumentParser()
47 | parser.add_argument("-a", "--action", type=int, help="Action to perform")
48 | args = parser.parse_args()
49 |
50 | if not settings.USE_PROXY_FROM_FILE:
51 | logger.info(f"Detected {len(get_sessions(SESSIONS_PATH))} sessions | USE_PROXY_FROM_FILE=False")
52 | else:
53 | logger.info(f"Detected {len(get_sessions(SESSIONS_PATH))} sessions | "
54 | f"{len(proxy_utils.get_proxies(PROXIES_PATH))} proxies")
55 |
56 | action = args.action or prompt_user_action()
57 |
58 | if action == 1:
59 | if not API_ID or not API_HASH:
60 | raise ValueError("API_ID and API_HASH not found in the .env file.")
61 | await run_tasks()
62 | elif action == 2:
63 | await register_sessions()
64 |
65 |
66 | def get_sessions(sessions_folder: str) -> list[str]:
67 | session_names = glob.glob(f"{sessions_folder}/*.session")
68 | session_names += glob.glob(f"{sessions_folder}/telethon/*.session")
69 | session_names += glob.glob(f"{sessions_folder}/pyrogram/*.session")
70 | return [file.replace('.session', '') for file in sorted(session_names)]
71 |
72 |
73 | async def get_tg_clients() -> list[UniversalTelegramClient]:
74 | session_paths = get_sessions(SESSIONS_PATH)
75 |
76 | if not session_paths:
77 | raise FileNotFoundError("Session files not found")
78 | tg_clients = []
79 | for session in session_paths:
80 | session_name = os.path.basename(session)
81 | accounts_config = config_utils.read_config_file(CONFIG_PATH)
82 | session_config: dict = deepcopy(accounts_config.get(session_name, {}))
83 | if 'api' not in session_config:
84 | session_config['api'] = {}
85 | api_config = session_config.get('api', {})
86 | api = None
87 | if api_config.get('api_id') in [4, 6, 2040, 10840, 21724]:
88 | api = config_utils.get_api(api_config)
89 |
90 | if api:
91 | client_params = {
92 | "session": session,
93 | "api": api
94 | }
95 | else:
96 | client_params = {
97 | "api_id": api_config.get("api_id", API_ID),
98 | "api_hash": api_config.get("api_hash", API_HASH),
99 | "session": session,
100 | "lang_code": api_config.get("lang_code", "en"),
101 | "system_lang_code": api_config.get("system_lang_code", "en-US")
102 | }
103 |
104 | for key in ("device_model", "system_version", "app_version"):
105 | if api_config.get(key):
106 | client_params[key] = api_config[key]
107 |
108 | session_config['user_agent'] = session_config.get('user_agent', generate_random_user_agent())
109 | if not session_config.get('ton') and settings.CONNECT_WALLETS_WEB:
110 | ton_address = session_config.get('ton_address')
111 | if ton_address:
112 | session_config['ton'] = ton.generate_ton_wallet(config_path=CONFIG_PATH, existing_address=ton_address)
113 | else:
114 | session_config['ton'] = ton.generate_ton_wallet(CONFIG_PATH)
115 | if not session_config.get('sol') and settings.CONNECT_WALLETS_WEB:
116 | session_config['sol'] = sol.generate_sol_wallet(CONFIG_PATH)
117 | api_config.update(api_id=client_params.get('api_id') or client_params.get('api').api_id,
118 | api_hash=client_params.get('api_hash') or client_params.get('api').api_hash)
119 |
120 | session_proxy = session_config.get('proxy')
121 | if not session_proxy and 'proxy' in session_config.keys():
122 | tg_clients.append(UniversalTelegramClient(**client_params))
123 | if accounts_config.get(session_name) != session_config:
124 | await config_utils.update_session_config_in_file(session_name, session_config, CONFIG_PATH)
125 | continue
126 |
127 | else:
128 | if settings.DISABLE_PROXY_REPLACE:
129 | proxy = session_proxy or next(iter(proxy_utils.get_unused_proxies(accounts_config, PROXIES_PATH)), None)
130 | else:
131 | proxy = await proxy_utils.get_working_proxy(accounts_config, session_proxy) \
132 | if session_proxy or settings.USE_PROXY_FROM_FILE else None
133 |
134 | if not proxy and (settings.USE_PROXY_FROM_FILE or session_proxy):
135 | logger.warning(f"{session_name} | Didn't find a working unused proxy for session | Skipping")
136 | continue
137 | else:
138 | tg_clients.append(UniversalTelegramClient(**client_params))
139 | session_config['proxy'] = proxy
140 | if accounts_config.get(session_name) != session_config:
141 | await config_utils.update_session_config_in_file(session_name, session_config, CONFIG_PATH)
142 |
143 | return tg_clients
144 |
145 |
146 | async def init_config_file():
147 | session_paths = get_sessions(SESSIONS_PATH)
148 |
149 | if not session_paths:
150 | raise FileNotFoundError("Session files not found")
151 | for session in session_paths:
152 | session_name = os.path.basename(session)
153 | parsed_json = config_utils.import_session_json(session)
154 | if parsed_json:
155 | accounts_config = config_utils.read_config_file(CONFIG_PATH)
156 | session_config: dict = deepcopy(accounts_config.get(session_name, {}))
157 | session_config['user_agent'] = session_config.get('user_agent', generate_random_user_agent())
158 | session_config['api'] = parsed_json
159 | if accounts_config.get(session_name) != session_config:
160 | await config_utils.update_session_config_in_file(session_name, session_config, CONFIG_PATH)
161 |
162 |
163 | async def run_tasks():
164 | await config_utils.restructure_config(CONFIG_PATH)
165 | await init_config_file()
166 | await build_check.check_updates()
167 | tg_clients = await get_tg_clients()
168 | tasks = [asyncio.create_task(run_tapper(tg_client=tg_client)) for tg_client in tg_clients]
169 | tasks.append(asyncio.create_task(build_check.check_bot_update_loop(2000)))
170 | await asyncio.gather(*tasks)
171 |
--------------------------------------------------------------------------------
/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_id': API_ID,
42 | 'api_hash': API_HASH,
43 | **device_params
44 | }
45 | proxy = None
46 |
47 | if settings.USE_PROXY_FROM_FILE:
48 | proxies = proxy_utils.get_unused_proxies(accounts_config, PROXIES_PATH)
49 | if not proxies:
50 | raise Exception('No unused proxies left')
51 | for prox in proxies:
52 | if await proxy_utils.check_proxy(prox):
53 | proxy_str = prox
54 | proxy = Proxy.from_str(proxy_str)
55 | accounts_data['proxy'] = proxy_str
56 | break
57 | else:
58 | raise Exception('No unused proxies left')
59 | else:
60 | accounts_data['proxy'] = None
61 |
62 | accounts_config[session_name] = accounts_data
63 | while True:
64 | res = input('Which session to create?\n1. Telethon\n2. Pyrogram\n').strip()
65 | if res not in ['1', '2']:
66 | logger.warning("Invalid option. Please enter 1 or 2")
67 | else:
68 | break
69 | if res == '1':
70 | session = TelegramClient(
71 | os.path.join(SESSIONS_PATH, session_file),
72 | api_id=API_ID,
73 | api_hash=API_HASH,
74 | lang_code="en",
75 | system_lang_code="en-US",
76 | **device_params
77 | )
78 | if proxy:
79 | logger.info(f"Using proxy: {proxy}")
80 | session.set_proxy(proxy_utils.to_telethon_proxy(proxy))
81 |
82 | await session.start()
83 |
84 | user_data = await session.get_me()
85 |
86 | else:
87 | session = Client(
88 | os.path.join(SESSIONS_PATH, session_file),
89 | api_id=API_ID,
90 | api_hash=API_HASH,
91 | lang_code="en",
92 | **device_params
93 | )
94 | if proxy:
95 | logger.info(f"Using proxy: {proxy}")
96 | session.proxy = proxy_utils.to_pyrogram_proxy(proxy)
97 |
98 | await session.start()
99 |
100 | user_data = await session.get_me()
101 |
102 | if user_data:
103 | await config_utils.write_config_file(accounts_config, CONFIG_PATH)
104 | logger.success(
105 | f'Session added successfully @{user_data.username} | {user_data.first_name} {user_data.last_name}'
106 | )
107 |
--------------------------------------------------------------------------------
/bot/core/tapper.py:
--------------------------------------------------------------------------------
1 | import aiohttp
2 | import asyncio
3 | import concurrent.futures
4 | import json
5 | import re
6 | import ssl
7 | from urllib.parse import unquote, parse_qs
8 | from aiocfscrape import CloudflareScraper
9 | from aiohttp_proxy import ProxyConnector
10 | from better_proxy import Proxy
11 | from random import uniform, shuffle, randint
12 | from time import time
13 | from twocaptcha import TwoCaptcha
14 |
15 | from bot.utils.universal_telegram_client import UniversalTelegramClient
16 |
17 | from bot.config import settings
18 | from bot.utils import logger, log_error, config_utils, CONFIG_PATH, first_run, sol, ton
19 | from bot.exceptions import InvalidSession
20 | from .headers import headers_app, headers_pwa, get_sec_ch_ua
21 |
22 | API_ENDPOINT = "https://api.paws.community/v1"
23 | TASKS_WL = {
24 | "672a933a7470fdfea331be92": "One falls, one rises",
25 | "6729082b93d9038819af5e77": " Put 🐾 in your name",
26 | "6730dc5674fd6bd0dd6904dd": "Join Tomarket Channel",
27 | "6730dc6e74fd6bd0dd6904df": "Join X Empire Channel",
28 | "6730dc3374fd6bd0dd6904db": "Join Cats Channel",
29 | "6727ca4c1ee144b53eb8c08a": "Join Blum Channel",
30 | "6714e8b80f93ce482efae727": "Follow channel",
31 | "671b8ee422d15820f13dc61d": "Connect wallet",
32 | "671b8ecb22d15820f13dc61a": "Invite 10 friends",
33 | "6734ef65594f8f54c07887f9": "Check PAWS TG sub",
34 | "67362326ce14073e9a9e0144": "Join PAWS Cult X",
35 | "673653c2ce14073e9a9e0153": "Share your PAWS (+image)",
36 | "6740b35b15bd1d26b7b7126b": "Check PAWS X",
37 | "6740b33415bd1d26b7b71269": "Check PAWS TG",
38 | "673a23760f9acd0470329409": "Study PAWS",
39 | "674b1f0c30dc53f7e9aec46a": "Mystery Quest: Scroll",
40 | "674dcb4b30dc53f7e9aec470": "Mystery Quest: Tabs",
41 | "674f45e99bfbbe63fab834f2": "Get Lucky",
42 | "675067faaae81a10ba5a3c4f": "GET PAWSED",
43 | "6751e24d561ee9de322ef182": "Check PAWS TG",
44 | "6751e267561ee9de322ef184": "Check PAWS X",
45 | "67532ea5a3770d4f94e38f6f": "REACT HARDER",
46 | "675729bc8a00f11f8cf8c1fd": "Reach 1st Milestone",
47 | "67572a2c8a00f11f8cf8c1ff": "Reach 2nd Milestone",
48 | "6757a207ec9bc04f1beb0e75": "Reach 3nd Milestone",
49 | "6757a21dec9bc04f1beb0e77": "Reach 4nd Milestone",
50 | "6757a232ec9bc04f1beb0e79": "Reach 5nd Milestone",
51 | "6758d84842df2161c728c742": "Reach 6nd Milestone",
52 | "675adeb56fe975fdde798265": "Infinite Milestone",
53 | "675dbe20995e9832d3ebb8ee": "heck PAWS TG",
54 | "675dbe36995e9832d3ebb8f0": "Check PAWS X",
55 | "675c65a74d9b0f56a8bb99f1": "Join Streaks from @tapps",
56 | "676467f28eb5e1e35f033d63": "Mystery Quest",
57 | "67654a381b49f3cc132b80cb": "Join Y Twitter",
58 | "6766eceedf75d42c3fff4cbc": "Wen TGE?",
59 | "6768c21f2e171c1a4d8e3df1": "MY PAWS GONE!!!",
60 | "6768c22d2e171c1a4d8e3df3": "PAWS lost, report it!",
61 | "6768c30f2e171c1a4d8e3df5": "#PAWSMAS COMING 🐾",
62 | "6768c3242e171c1a4d8e3df8": "Lil buddy almost had’em, go help!",
63 | "6768c3312e171c1a4d8e3dfa": "Well done, bud!",
64 | "6768c3402e171c1a4d8e3dfc": "Christmas Miracle",
65 | "67703cd95a4eb56c5f81a6e9": "Check PAWS TG",
66 | "67703cf45a4eb56c5f81a6eb": "Check PAWS X",
67 | "67797ea7df75d42c3fff4cc4": "EASY PAWS WEB Access",
68 | "677e875ddf75d42c3fff4cc7": "Hide & Seek",
69 | "677faa8e2cd0f9fc21b34d84": "Follow REP X",
70 | "677faa722cd0f9fc21b34d83": "Follow REP TG",
71 | "677faac52cd0f9fc21b34d85": "Follow Tonkeeper's TG",
72 | "677faaef2cd0f9fc21b34d86": "Download Tonkeeper",
73 | "67717bfb067c823d800e5a14": "Verify via PAWS Web",
74 | "678556b8ed515bd1fbea8147": "NO TIME TO RUSH",
75 | "67867e662397c64561caa4f6": "FIND ME PAWS",
76 | "67898a6b31c13aecab68289c": "Check PAWS TG",
77 | "67814ddc6806dce25e57fe20": "Connect wallets via Web",
78 | "6793b2731c49bcc7f16aa817": "Join DONOT community in X",
79 | "6798d977ff2e2506ca57b3e8": "Follow Buzzit X",
80 | "679a306ca30cce7d9db598dc": "Follow Roko",
81 | "6798d93aff2e2506ca57b3e5": "Follow Buzzit Channel",
82 | "679bc06e70efab8b96d0efdf": "Join PAWS Discord!",
83 | "679bcd2270efab8b96d0efe1": "Follow ARMIN",
84 | "67a52a71df75d42c3fff4cd7": "Follow DUDE",
85 | "67ace20fb2da260fdacba414": "Follow PAWS YouTube",
86 | "67ace1f8b2da260fdacba412": "Follow PAWS TikTok"
87 | }
88 | TASKS_BL = {
89 | "6730b42d74fd6bd0dd6904c1": "Go vote",
90 | "6730b44974fd6bd0dd6904c3": "Vote for a winner",
91 | "6730b45874fd6bd0dd6904c5": "Vote for a loser",
92 | "6730b47b74fd6bd0dd6904c7": "Mystery Quest",
93 | "6727ca831ee144b53eb8c08c": "Boost PAWS channel",
94 | "6740b2cb15bd1d26b7b71266": "Add PAWS emoji", # Only Premium
95 | "6754c09b5de2c352526ab323": "Explore TON",
96 | "6754c1065de2c352526ab324": "Mystery Quest",
97 | "6756c53f0284d9d7b208dd50": "Lucky Block"
98 | }
99 |
100 | NO_ADDITIONAL_DATA = ["67867e662397c64561caa4f6"]
101 | NO_TG_SUB_NEEDED = ["6798d977ff2e2506ca57b3e8",
102 | "679a306ca30cce7d9db598dc",
103 | "679bc06e70efab8b96d0efdf",
104 | "67a52a71df75d42c3fff4cd7",
105 | "67ace20fb2da260fdacba414",
106 | "67ace1f8b2da260fdacba412"]
107 |
108 | AIRDROP_CRITERIAS = ["completedQuestsCounter",
109 | "userReferrals",
110 | "verifiedOnWebsite",
111 | "grinchRemoved",
112 | "activityCheck"]
113 |
114 | CODE = "oSmGOqWsuFNw"
115 |
116 |
117 | def sanitize_string(input_str: str):
118 | return re.sub(r'[<>]', '', input_str)
119 |
120 |
121 | class Tapper:
122 | def __init__(self, tg_client: UniversalTelegramClient):
123 | self.tg_client = tg_client
124 | self.session_name = tg_client.session_name
125 |
126 | session_config = config_utils.get_session_config(self.session_name, CONFIG_PATH)
127 |
128 | if not all(key in session_config for key in ('api', 'user_agent')):
129 | logger.critical(self.log_message('CHECK accounts_config.json as it might be corrupted'))
130 | exit(-1)
131 |
132 | self.headers = headers_app.copy()
133 | self.headers_pwa = headers_pwa.copy()
134 | user_agent = session_config.get('user_agent')
135 | self.headers['user-agent'] = user_agent
136 | self.headers_pwa['user-agent'] = user_agent
137 | self.headers_pwa.update(**get_sec_ch_ua(user_agent, False))
138 | self.headers.update(**get_sec_ch_ua(user_agent))
139 |
140 | self.proxy = session_config.get('proxy')
141 | if self.proxy:
142 | proxy = Proxy.from_str(self.proxy)
143 | self.tg_client.set_proxy(proxy)
144 |
145 | self.ton_wallet = session_config.get('ton')
146 | self.sol_wallet = session_config.get('sol')
147 |
148 | self.sol_connected = None
149 | self.ton_connected = None
150 |
151 | self.ref_id = None
152 | self.access_token = None
153 | self.access_token_pwa = None
154 | self.user_data = None
155 | self.ref_count = 0
156 | self.wallet = session_config.get('ton', {}).get('wallet_address')
157 |
158 | def log_message(self, message) -> str:
159 | return f"{self.session_name} | {message}"
160 |
161 | async def get_tg_web_data(self) -> str:
162 | webview_url = await self.tg_client.get_app_webview_url('PAWSOG_bot', "PAWS", "uLnYLVgv")
163 |
164 | tg_web_data = unquote(string=webview_url.split('tgWebAppData=')[1].split('&tgWebAppVersion')[0])
165 | query_params = parse_qs(tg_web_data)
166 | self.user_data = json.loads(query_params.get('user', [''])[0])
167 | self.ref_id = query_params.get('start_param', [''])[0]
168 |
169 | return tg_web_data
170 |
171 | async def check_proxy(self, http_client: CloudflareScraper) -> bool:
172 | proxy_conn = http_client.connector
173 | if proxy_conn and not hasattr(proxy_conn, '_proxy_host'):
174 | logger.info(self.log_message(f"Running Proxy-less"))
175 | return True
176 | try:
177 | response = await http_client.get(url='https://ifconfig.me/ip', timeout=aiohttp.ClientTimeout(15))
178 | logger.info(self.log_message(f"Proxy IP: {await response.text()}"))
179 | return True
180 | except Exception as error:
181 | proxy_url = f"{proxy_conn._proxy_type}://{proxy_conn._proxy_host}:{proxy_conn._proxy_port}"
182 | log_error(self.log_message(f"Proxy: {proxy_url} | Error: {type(error).__name__}"))
183 | return False
184 |
185 | async def login(self, http_client: CloudflareScraper, init_data: str):
186 | ref_code = {"referralCode": self.ref_id} if self.ref_id else {}
187 | payload = {"data": init_data, **ref_code}
188 |
189 | response = await http_client.post(f"{API_ENDPOINT}/user/auth", json=payload)
190 |
191 | if response.status in range(200, 300):
192 | res_data = (await response.json()).get('data')
193 | if res_data:
194 | self.access_token = res_data[0]
195 | if len(res_data) > 1:
196 | self.sol_connected = res_data[1].get('userData', {}).get('proofSolanaWallet')
197 | ton_hex_addr = res_data[1].get('userData', {}).get('proofTonWallet')
198 | self.ton_connected = ton.hex_to_uf_address(ton_hex_addr) if ton_hex_addr else ton_hex_addr
199 | if 'authorization' in http_client.headers:
200 | http_client.headers.pop('authorization')
201 | http_client.headers['authorization'] = f"Bearer {self.access_token}"
202 | if None in res_data:
203 | balance = res_data[1].get('gameData', {}).get('balance')
204 | self.ref_count = res_data[1].get('referralData', {}).get('referralsCount', 0)
205 | logger.success(self.log_message(f"Logged in Successfully | Balance: {balance} | "
206 | f"SOL: {self.sol_connected} | "
207 | f"TON: {self.ton_connected}"))
208 | else:
209 | balance = res_data[2].get('total')
210 | logger.success(self.log_message(f"Registered successfully | Balance {balance}"))
211 | return True
212 |
213 | logger.warning(self.log_message(f"Failed to login. {response.status}"))
214 | return False
215 |
216 | async def login_pwa(self, http_client: CloudflareScraper, init_data: str):
217 | payload = {"data": init_data}
218 |
219 | response = await http_client.post(f"{API_ENDPOINT}/user/auth", json=payload)
220 |
221 | if response.status in range(200, 300):
222 | res_data = (await response.json()).get('data')
223 | if res_data:
224 | self.access_token_pwa = res_data[0]
225 | if len(res_data) > 1:
226 | self.sol_connected = res_data[1].get('userData', {}).get('proofSolanaWallet')
227 | ton_hex_addr = res_data[1].get('userData', {}).get('proofTonWallet')
228 | self.ton_connected = ton.hex_to_uf_address(ton_hex_addr) if ton_hex_addr else ton_hex_addr
229 | if 'authorization' in http_client.headers:
230 | http_client.headers.pop('authorization')
231 | http_client.headers['authorization'] = f"Bearer {self.access_token_pwa}"
232 | return True
233 |
234 | logger.warning(self.log_message(f"Failed to login in pwa. {response.status}"))
235 | return False
236 |
237 | async def get_user_pwa(self, http_client: CloudflareScraper):
238 | resp = await http_client.get(f"{API_ENDPOINT}/user")
239 | if resp.status in range(200, 300):
240 | resp = await resp.json()
241 | return resp.get('success')
242 |
243 | async def get_quests(self, http_client: CloudflareScraper):
244 | response = await http_client.get(f"{API_ENDPOINT}/quests/list")
245 | if response.status in range(200, 300):
246 | data = (await response.json()).get('data', {})
247 | return data
248 | else:
249 | logger.warning(self.log_message(f"Failed to get quests: {response.status}"))
250 | return None
251 |
252 | async def complete_quest(self, http_client: CloudflareScraper, quest_id: str, x: int = None, y: int = None):
253 | payload = {"questId": quest_id}
254 | if x and y:
255 | payload["additionalData"] = {
256 | "x": x,
257 | "y": y,
258 | "timestamp": int(time() * 1000)
259 | }
260 | response = await http_client.post(f"{API_ENDPOINT}/quests/completed", json=payload)
261 | if response.status in range(200, 300):
262 | resp_json = await response.json()
263 | return resp_json.get('success')
264 | else:
265 | logger.warning(self.log_message(f"Failed to complete quest: {response.status}"))
266 | return None
267 |
268 | async def custom_complete_quest(self, http_client: CloudflareScraper, quest_id: str, code: str):
269 | payload = {"questId": quest_id, "code": code}
270 | response = await http_client.post(f"{API_ENDPOINT}/quests/custom", json=payload)
271 | if response.status in range(200, 300):
272 | resp_json = await response.json()
273 | return resp_json.get('success') and resp_json.get('data')
274 | else:
275 | logger.warning(self.log_message(f"Failed to complete quest: {response.status}"))
276 | return None
277 |
278 | async def claim_quest_reward(self, http_client: CloudflareScraper, quest_id: str, additional_data: bool = True):
279 | payload = {"questId": quest_id}
280 | if additional_data:
281 | payload["additionalData"] = {
282 | "x": randint(300, 450),
283 | "y": randint(300, 450),
284 | "timestamp": int(time() * 1000)
285 | }
286 | response = await http_client.post(f"{API_ENDPOINT}/quests/claim", json=payload)
287 | if response.status in range(200, 300):
288 | resp_json = await response.json()
289 | data = resp_json.get('data')
290 | is_success = resp_json.get('success', False)
291 | return (data or resp_json) if is_success else False
292 | else:
293 | logger.warning(self.log_message(f"Failed to claim quest: {response.status}"))
294 | return False
295 |
296 | async def connect_ton_wallet_app(self, http_client: CloudflareScraper):
297 | if not self.wallet:
298 | return
299 | wallet = {"wallet": self.wallet}
300 | resp = await http_client.post(f"{API_ENDPOINT}/user/wallet", json=wallet)
301 | if resp.status in range(200, 300):
302 | resp_json = await resp.json()
303 | return resp_json.get('success')
304 |
305 | async def get_ton_payload(self, http_client: CloudflareScraper):
306 | resp = await http_client.get(f"{API_ENDPOINT}/wallet/ton/payload")
307 | if resp.status in range(200, 300):
308 | return (await resp.json()).get('data')
309 |
310 | async def get_sol_payload(self, http_client: CloudflareScraper):
311 | resp = await http_client.get(f"{API_ENDPOINT}/wallet/solana/payload")
312 | if resp.status in range(200, 300):
313 | return (await resp.json()).get('data')
314 |
315 | async def check_eligibility(self, http_client: CloudflareScraper) -> list[dict]:
316 | resp = await http_client.get(f"{API_ENDPOINT}/eligibility")
317 | if resp.status in range(200, 300):
318 | return (await resp.json()).get('data')
319 | return []
320 |
321 | async def solve_captcha(self) -> dict:
322 | solver = TwoCaptcha(settings.TWOCAPTCHA_API)
323 | for i in range(5):
324 | try:
325 | balance = solver.balance()
326 | if balance > 0.1:
327 | logger.info(self.log_message(f'2Captcha Balance: {solver.balance()}'))
328 | else:
329 | logger.warning(self.log_message(f'2Captcha Balance is too low: {balance}'))
330 | return {}
331 | loop = asyncio.get_running_loop()
332 | with concurrent.futures.ThreadPoolExecutor() as pool:
333 | return await loop.run_in_executor(pool,
334 | lambda: solver.recaptcha(sitekey="6Lda_s0qAAAAAItgCSBeQN_DVlM9YOk9MccqMG6_",
335 | url="https://paws.community/app?tab=claim",
336 | version='v2',
337 | enterprise=1,
338 | userAgent=self.headers['user-agent'],
339 | action="submit",
340 | softId=4801))
341 | except Exception as e:
342 | logger.warning(self.log_message(f'Failed to solve captcha. Retrying {e}'))
343 | await asyncio.sleep(uniform(5, 10))
344 | return await self.solve_captcha()
345 |
346 | async def complete_activity_check(self, http_client: CloudflareScraper):
347 | recap = await self.solve_captcha()
348 | if not recap.get('code'):
349 | return False
350 | payload = {"recaptchaToken": recap.get('code')}
351 | resp = await http_client.post(f"{API_ENDPOINT}/user/activity", json=payload)
352 | if resp.status in range(200, 300):
353 | resp = await resp.json()
354 | return resp.get('success') and resp.get('data')
355 |
356 | async def connect_sol_web(self, http_client: CloudflareScraper, token: str):
357 | keypair = sol.import_sol_wallet(self.sol_wallet.get('private_key'))
358 | signature = sol.generate_sol_signature(keypair, token.encode("utf-8"))
359 | payload = {
360 | "signature": str(signature),
361 | "publicKey": str(keypair.pubkey()),
362 | "token": token
363 | }
364 | resp = await http_client.post(f"{API_ENDPOINT}/wallet/solana/check_proof", json=payload)
365 | if resp.status in range(200, 300):
366 | resp_json = await resp.json()
367 | return resp_json.get('success') and resp_json.get('data')
368 |
369 | async def connect_ton_web(self, http_client: CloudflareScraper, token: str):
370 | payload = ton.generate_ton_proof_v2(self.ton_wallet.get("mnemonic_phrase"), "app.paws.community", token)
371 | resp = await http_client.post(f"{API_ENDPOINT}/wallet/ton/check_proof", json=payload)
372 | if resp.status in range(200, 300):
373 | resp_json = await resp.json()
374 | return resp_json.get('success') and resp_json.get('data')
375 |
376 | async def disconnect_sol_web(self, http_client: CloudflareScraper):
377 | resp = await http_client.post(f"{API_ENDPOINT}/wallet/solana/reset", data="")
378 | if resp.status in range(200, 300):
379 | return (await resp.json()).get('success')
380 |
381 | async def disconnect_ton_web(self, http_client: CloudflareScraper):
382 | resp = await http_client.post(f"{API_ENDPOINT}/wallet/ton/reset", data="")
383 | if resp.status in range(200, 300):
384 | return (await resp.json()).get('success')
385 |
386 | async def add_emoji_to_first_name(self):
387 | if '🐾' not in self.user_data.get('first_name'):
388 | await self.tg_client.update_profile(first_name=f"{self.user_data.get('first_name')} 🐾")
389 |
390 | async def run(self) -> None:
391 | random_delay = uniform(1, settings.SESSION_START_DELAY)
392 | logger.info(self.log_message(f"Bot will start in {int(random_delay)}s"))
393 | await asyncio.sleep(delay=random_delay)
394 |
395 | access_token_created_time = 0
396 | sleep_time = 0
397 |
398 | ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
399 | ssl_context.minimum_version = ssl.TLSVersion.TLSv1_3
400 | proxy_conn = ProxyConnector.from_url(self.proxy, ssl=ssl_context) if self.proxy \
401 | else aiohttp.TCPConnector(ssl_context=ssl_context)
402 | async with CloudflareScraper(headers=self.headers, timeout=aiohttp.ClientTimeout(60), connector=proxy_conn) as http_client,\
403 | CloudflareScraper(headers=self.headers_pwa, timeout=aiohttp.ClientTimeout(60), connector=proxy_conn) as http_client_pwa:
404 | while True:
405 | if not await self.check_proxy(http_client=http_client):
406 | logger.warning(self.log_message('Failed to connect to proxy server. Sleep 150 seconds.'))
407 | await asyncio.sleep(150)
408 | continue
409 |
410 | refresh_webview_time = uniform(3400, 3600)
411 | try:
412 | if time() - access_token_created_time >= refresh_webview_time:
413 | tg_web_data = await self.get_tg_web_data()
414 |
415 | if not tg_web_data:
416 | logger.warning(self.log_message('Failed to get webview URL'))
417 | await asyncio.sleep(300)
418 | continue
419 |
420 | access_token_created_time = time()
421 |
422 | if not await self.login(http_client, tg_web_data):
423 | sleep_time = uniform(60, 600)
424 | logger.info(self.log_message(f"Going to sleep for {int(sleep_time)} seconds"))
425 | await asyncio.sleep(sleep_time)
426 | continue
427 |
428 | if self.tg_client.is_fist_run:
429 | await first_run.append_recurring_session(self.session_name)
430 | await asyncio.sleep(uniform(3, 10))
431 |
432 | if settings.PERFORM_EMOJI_TASK:
433 | await self.add_emoji_to_first_name()
434 |
435 | if settings.PERFORM_TASKS:
436 |
437 | tasks = await self.get_quests(http_client)
438 | channel_subs = 0
439 | shuffle(tasks)
440 |
441 | for task in tasks:
442 | task_id = task.get('_id')
443 | task_title = sanitize_string(task.get('title'))
444 | if task.get('progress', {}).get('claimed') or task.get('progress', {}).get('status') == "waiting":
445 | continue
446 | if task_id == "67814ddc6806dce25e57fe20" and not (self.sol_connected and self.ton_connected):
447 | continue
448 |
449 | if task_id not in TASKS_WL and task_id not in TASKS_BL:
450 | logger.info(self.log_message(
451 | f"Quest with id: {task_id} and Title: {task_title}"
452 | f" is not present in the white and black lists"))
453 | continue
454 | elif task_id in TASKS_BL:
455 | continue
456 |
457 | if task.get("checkRequirements", True) is False and task.get('code') != "emojiName":
458 | pass
459 | elif task.get('code') == "wallet":
460 | await self.connect_ton_wallet_app(http_client)
461 | elif task.get('code') == "invite":
462 | progress = task.get('progress', {})
463 | if progress.get('current', 0) < progress.get('total', 100):
464 | continue
465 | elif task.get('code') == "emojiName" and not settings.PERFORM_EMOJI_TASK:
466 | continue
467 | elif task.get('code') == 'telegram' and task_id not in NO_TG_SUB_NEEDED and channel_subs < settings.SUBSCRIPTIONS_PER_CYCLE:
468 | if task.get('progress', {}).get('status') != 'claimable':
469 | await self.tg_client.join_and_mute_tg_channel(task.get('data'))
470 | channel_subs += 1
471 | await asyncio.sleep(10)
472 |
473 | if task.get('type') == "pwa":
474 | if not http_client_pwa.headers.get('authorization') and task.get('progress', {}).get('status', "") != "claimable":
475 | await self.login_pwa(http_client_pwa, tg_web_data)
476 | await asyncio.sleep(uniform(2, 5))
477 | pwa_user = await self.get_user_pwa(http_client_pwa)
478 | if pwa_user:
479 | if task_id == "67867e662397c64561caa4f6":
480 | status = await self.custom_complete_quest(http_client_pwa, task_id, CODE) if \
481 | task.get('progress', {}).get('status', "") != "claimable" else True
482 | continue
483 | else:
484 | status = await self.complete_quest(http_client_pwa, task_id) if \
485 | task.get('progress', {}).get('status', "") != "claimable" else True
486 | await asyncio.sleep(uniform(5, 15))
487 | else:
488 | status = True
489 | else:
490 | additional_data = {} if task_id == "677e875ddf75d42c3fff4cc7" else \
491 | {'x': -1, 'y': -1} if task_id == "67814ddc6806dce25e57fe20" else \
492 | {'x': randint(300, 450), 'y': randint(300, 450)}
493 | status = await self.complete_quest(http_client, task_id, **additional_data) if \
494 | task.get('progress', {}).get('status', "") != "claimable" else True
495 |
496 | if task_id == "678556b8ed515bd1fbea8147" and task.get('progress', {}).get('status', "") != "claimable":
497 | if status:
498 | logger.info(self.log_message(f"Successfully started task: {task_title}."))
499 | continue
500 | elif task_id == "67814ddc6806dce25e57fe20" and status:
501 | logger.info(self.log_message(f"Successfully completed task: {task_title}."))
502 | continue
503 |
504 | if status:
505 | await asyncio.sleep(uniform(2, 5))
506 | status = await self.claim_quest_reward(http_client, task_id) if task_id not in NO_ADDITIONAL_DATA else await self.claim_quest_reward(http_client, task_id, False)
507 | reward = status.get('amount', 0) if isinstance(status, dict) else \
508 | task.get('rewards', [{}])[0].get('amount') if len(task.get('rewards', [{}])) else 0
509 | if status:
510 | logger.success(self.log_message(
511 | f"Successfully completed task {task_title}"
512 | f"{f' and got {reward} Paws' if reward else ''}"))
513 |
514 | await asyncio.sleep(uniform(2, 5))
515 |
516 | if not http_client_pwa.headers.get('authorization'):
517 | await self.login_pwa(http_client_pwa, tg_web_data)
518 | await asyncio.sleep(uniform(2, 5))
519 |
520 | if settings.CONNECT_WALLETS_WEB:
521 | if settings.OVERWRITE_WALLETS:
522 | if self.sol_connected and self.sol_connected != self.sol_wallet.get('public_key'):
523 | logger.warning(self.log_message(f"SOL Wallets mismatch: "
524 | f"Connected: {self.sol_connected}. "
525 | f"Config {self.sol_wallet.get('public_key')}"))
526 | if await self.disconnect_sol_web(http_client_pwa):
527 | logger.info(self.log_message("Successfully disconnected wallet"))
528 | await asyncio.sleep(2, 4)
529 | self.sol_connected = None
530 |
531 | if self.ton_connected and self.ton_connected != self.ton_wallet.get('wallet_address'):
532 | logger.warning(self.log_message(f"TON Wallets mismatch: "
533 | f"Connected: {self.ton_connected}. "
534 | f"Config {self.ton_wallet.get('wallet_address')}"))
535 | if await self.disconnect_ton_web(http_client_pwa):
536 | logger.info(self.log_message("Successfully disconnected wallet"))
537 | await asyncio.sleep(2, 4)
538 | self.ton_connected = None
539 |
540 | if not self.sol_connected:
541 | payload = await self.get_sol_payload(http_client_pwa)
542 | await asyncio.sleep(uniform(15, 30))
543 | if payload and await self.connect_sol_web(http_client_pwa, payload):
544 | logger.success(self.log_message(f"Successfully connected SOL wallet: "
545 | f"{self.sol_wallet.get('public_key')}"))
546 |
547 | if not self.ton_connected:
548 | if not self.ton_wallet.get('mnemonic_phrase'):
549 | logger.info(self.log_message("No Mnemonic found in config. "
550 | "Edit config and restart the script"))
551 | else:
552 | payload = await self.get_ton_payload(http_client_pwa)
553 | await asyncio.sleep(uniform(15, 30))
554 | if payload and await self.connect_ton_web(http_client_pwa, payload):
555 | logger.success(self.log_message(f"Successfully connected TON wallet: "
556 | f"{self.ton_wallet.get('wallet_address')}"))
557 |
558 | if settings.TWOCAPTCHA_API:
559 |
560 | elig = (await self.check_eligibility(http_client_pwa))
561 | elig = list(filter(lambda x: x.get('criteriaName') in AIRDROP_CRITERIAS, elig)) if len(elig) else []
562 | elig = {x.get('criteriaName'): x for x in elig}
563 | all_other_criteria_met = all(
564 | value["meetsCriteria"]
565 | for key, value in elig.items() if key not in {"completedQuestsCounter", "userReferrals"}
566 | )
567 |
568 | at_least_one_quest_or_referral_met = any(
569 | elig[key]["meetsCriteria"]
570 | for key in {"completedQuestsCounter", "userReferrals"}
571 | )
572 |
573 | result = all_other_criteria_met and at_least_one_quest_or_referral_met
574 |
575 | failed_criteria = []
576 | if not result:
577 | if not all_other_criteria_met:
578 | failed_criteria.extend([
579 | value["criteriaName"]
580 | for key, value in elig.items()
581 | if key not in {"completedQuestsCounter", "userReferrals"} and not value["meetsCriteria"]
582 | ])
583 | if not at_least_one_quest_or_referral_met:
584 | failed_criteria.extend([
585 | value["criteriaName"]
586 | for key, value in elig.items()
587 | if key in {"completedQuestsCounter", "userReferrals"} and not value["meetsCriteria"]
588 | ])
589 | if failed_criteria:
590 | logger.info(self.log_message("The following AirDrop criterias weren't met: " + ", ".join(failed_criteria)))
591 |
592 | if len(failed_criteria) == 1 and failed_criteria[0] == "activityCheck":
593 | if await self.complete_activity_check(http_client_pwa):
594 | logger.success(self.log_message('Successfully completed Activity Check (captcha)'))
595 | elif not failed_criteria:
596 | logger.success(self.log_message('Good Job. Account is eligible for AirDrop'))
597 |
598 | logger.info(self.log_message(f"All activities for the current session have been completed"))
599 | return
600 |
601 | except InvalidSession as error:
602 | raise error
603 |
604 | except Exception as error:
605 | sleep_time = uniform(60, 120)
606 | log_error(self.log_message(f"Unknown error: {error} Retry in {int(sleep_time)}s"))
607 | await asyncio.sleep(sleep_time)
608 |
609 |
610 | async def run_tapper(tg_client: UniversalTelegramClient):
611 | runner = Tapper(tg_client=tg_client)
612 | try:
613 | await runner.run()
614 | except InvalidSession as e:
615 | logger.error(runner.log_message(f"Invalid Session: {e}"))
616 |
--------------------------------------------------------------------------------
/bot/exceptions/__init__.py:
--------------------------------------------------------------------------------
1 | class InvalidSession(BaseException):
2 | ...
3 |
--------------------------------------------------------------------------------
/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/build_check.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import re
3 | import aiohttp
4 | import sys
5 | import ssl
6 | import json
7 | from aiocfscrape import CloudflareScraper
8 | from random import uniform
9 | from bot.utils import logger
10 | from bot.config import settings
11 | from hashlib import sha256
12 |
13 | appUrl = "https://app.paws.community"
14 | webUrl = "https://paws.community/app"
15 | versions = "https://github.com/SP-l33t/Auxiliary-Data/raw/refs/heads/main/version_track.json"
16 |
17 | headers = {
18 | 'accept': '*/*',
19 | 'user-agent': 'Mozilla/5.0 (Linux; Android 10.0; OnePlus 10 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.9.9622.83 Mobile Safari/537.36'
20 | }
21 |
22 |
23 | async def get_main_js_format(client, base_url):
24 | async with client.request(url=base_url, method="GET", headers=headers) as response:
25 | try:
26 | response.raise_for_status()
27 | content = (await response.text()).replace("/script>", "/script>\n")
28 | matches = re.findall(r'src="(/.+?\.js)', content)
29 | return sorted(set(matches), key=len, reverse=True) if matches else None
30 | except Exception as e:
31 | if response.status == 403:
32 | logger.warning(f"Cloudflare 403: {e}")
33 | else:
34 | logger.warning(f"Error fetching the base URL: {e}")
35 | return None
36 |
37 |
38 | async def get_versions(client, service):
39 | async with client.request(url=versions, method="GET") as response:
40 | if response.status in range(200, 300):
41 | return json.loads(await response.text()).get(service, {})
42 |
43 |
44 | async def get_js_hash(client, url, path):
45 | async with client.request(url=url+path, method="GET", headers=headers) as response:
46 | if response.status in range(200, 300):
47 | return sha256((await response.text()).encode('utf-8')).hexdigest()
48 | else:
49 | logger.error(f"Failed to get hash for: {url+path}, status code: {response.status}")
50 |
51 |
52 | async def handle_missing_js_error():
53 | logger.error("No main js file found. Can't continue")
54 | sys.exit("No main js file found. Contact me to check if it's safe to continue: https://t.me/SP_l33t")
55 |
56 |
57 | async def check_js_updates(client, js_formats, actual_js, actual_hash, js_type):
58 | for js in js_formats:
59 | if actual_js in js or js.split('/')[-1].startswith(actual_js[0:3]):
60 | live_hash = await get_js_hash(client, appUrl if js_type == 'app' else webUrl.removesuffix('/app'), js)
61 |
62 | if live_hash == actual_hash:
63 | logger.success(f"No changes in {js_type} main js file: {actual_js}")
64 | return
65 |
66 | logger.error(f"{js_type.upper()} Main JS updated. New file name: '{js}'. "
67 | f"New hash: '{live_hash}' Old hash: '{actual_hash}")
68 | sys.exit("Bot updates detected. Contact me to check if it's safe to continue: https://t.me/SP_l33t")
69 |
70 |
71 | async def check_updates():
72 | if not settings.TRACK_BOT_UPDATES:
73 | return
74 |
75 | ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
76 | ssl_context.minimum_version = ssl.TLSVersion.TLSv1_3
77 | async with CloudflareScraper(headers=headers, connector=aiohttp.TCPConnector(ssl=ssl_context)) as client:
78 | app_js_formats = await get_main_js_format(client, appUrl)
79 | web_js_formats = await get_main_js_format(client, webUrl)
80 |
81 | if not (app_js_formats and web_js_formats):
82 | await handle_missing_js_error()
83 |
84 | git_versions = await get_versions(client, 'paws')
85 |
86 | await check_js_updates(
87 | client=client,
88 | js_formats=app_js_formats,
89 | actual_js=git_versions.get('main_js'),
90 | actual_hash=git_versions.get('js_hash'),
91 | js_type='app'
92 | )
93 |
94 | await check_js_updates(
95 | client=client,
96 | js_formats=web_js_formats,
97 | actual_js=git_versions.get('main_js_web'),
98 | actual_hash=git_versions.get('js_hash_web'),
99 | js_type='web'
100 | )
101 |
102 |
103 | async def check_bot_update_loop(start_delay: 0):
104 | await asyncio.sleep(start_delay)
105 | while settings.TRACK_BOT_UPDATES:
106 | await check_updates()
107 | await asyncio.sleep(uniform(1500, 2000))
108 |
--------------------------------------------------------------------------------
/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/sol.py:
--------------------------------------------------------------------------------
1 | import json
2 | from base58 import b58decode
3 | from os import path
4 | from solders.keypair import Keypair
5 |
6 |
7 | def generate_sol_wallet(config_path: str, wallets_path=None):
8 | keypair = Keypair()
9 | wallet = {
10 | "public_key": str(keypair.pubkey()),
11 | "private_key": str(keypair),
12 | "wallet_address": str(keypair.pubkey())
13 | }
14 | if not wallets_path:
15 | wallets_path = path.join(path.dirname(config_path), 'sol_wallets.txt')
16 |
17 | with open(wallets_path, "a+") as f:
18 | json.dump(wallet, f, indent=4)
19 | f.write('\n')
20 |
21 | return wallet
22 |
23 |
24 | def import_sol_wallet(private_key: str):
25 | return Keypair.from_bytes(b58decode(private_key))
26 |
27 |
28 | def generate_sol_signature(keypair: Keypair, message):
29 | return keypair.sign_message(message)
30 |
--------------------------------------------------------------------------------
/bot/utils/ton.py:
--------------------------------------------------------------------------------
1 | import json
2 | from time import time
3 | from os import path
4 | from base64 import b64encode
5 | from hashlib import sha256
6 |
7 | from nacl.signing import SigningKey
8 | from tonsdk.contract.wallet import Wallets, WalletVersionEnum
9 | from tonsdk.utils import bytes_to_b64str, Address
10 |
11 |
12 | def generate_ton_wallet(config_path: str, wallets_path=None, existing_address=None):
13 | if existing_address:
14 | return {
15 | "mnemonic_phrase": "",
16 | "public_key": "",
17 | "private_key": "",
18 | "wallet_address": existing_address
19 | }
20 |
21 | mnemonics, public_key, private_key, wallet = Wallets.create(WalletVersionEnum.v4r2, workchain=0)
22 | wallet_address = wallet.address.to_string(True, True, False)
23 | wallet = {
24 | "mnemonic_phrase": " ".join(mnemonics),
25 | "public_key": public_key.hex(),
26 | "private_key": private_key.hex(),
27 | "wallet_address": wallet_address
28 | }
29 | if not wallets_path:
30 | wallets_path = path.join(path.dirname(config_path), 'wallets.txt')
31 |
32 | with open(wallets_path, "a+") as f:
33 | json.dump(wallet, f, indent=4)
34 | f.write('\n')
35 |
36 | return wallet
37 |
38 |
39 | def generate_ton_proof_v2(mnemonic_string, domain, payload):
40 | mnemonics, public_key, private_key, wallet = Wallets.from_mnemonics(mnemonic_string.split(), WalletVersionEnum.v4r2, workchain=0)
41 | wallet_address = wallet.address.to_string(is_url_safe=True, is_user_friendly=False)
42 |
43 | ts = int(time())
44 |
45 | domain_bytes = domain.encode('utf-8')
46 |
47 | msg_bytes = b'ton-proof-item-v2/' + \
48 | int(wallet_address.split(':')[0]).to_bytes(4, 'big') + \
49 | wallet.address.hash_part + \
50 | len(domain_bytes).to_bytes(4, 'little') + \
51 | domain_bytes + \
52 | ts.to_bytes(8, 'little') + \
53 | (payload.encode('utf-8') if payload else b'')
54 |
55 | full_message = b"\xff\xff" + b'ton-connect' + sha256(msg_bytes).digest()
56 | signature = b64encode(SigningKey(private_key[:32]).sign(sha256(full_message).digest()).signature).decode('utf-8')
57 |
58 | return {
59 | "address": wallet_address,
60 | "network": "-239",
61 | "public_key": public_key.hex(),
62 | "proof": {
63 | "timestamp": ts,
64 | "domain": {
65 | "lengthBytes": len(domain_bytes),
66 | "value": domain
67 | },
68 | "signature": signature,
69 | "payload": payload,
70 | "state_init": bytes_to_b64str(wallet.create_state_init()["state_init"].to_boc(has_idx=False))
71 | }
72 | }
73 |
74 |
75 | def hex_to_uf_address(address):
76 | return Address(address).to_string(is_user_friendly=True, is_url_safe=True)
77 |
--------------------------------------------------------------------------------
/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 | for i in range(3):
76 | fl = await self._pyrogram_join_and_mute_tg_channel(link) if self.is_pyrogram \
77 | else await self._telethon_join_and_mute_tg_channel(link)
78 | if not fl:
79 | return
80 | await asyncio.sleep(fl + uniform(1, 5))
81 |
82 | async def update_profile(self, first_name: str = None, last_name: str = None, about: str = None):
83 | return await self._pyrogram_update_profile(first_name=first_name, last_name=last_name, about=about) if self.is_pyrogram \
84 | else await self._telethon_update_profile(first_name=first_name, last_name=last_name, about=about)
85 |
86 | async def _telethon_initialize_webview_data(self, bot_username: str, bot_shortname: str = None):
87 | if not self._webview_data:
88 | while True:
89 | try:
90 | peer = await self.client.get_input_entity(bot_username)
91 | bot_id = InputUser(user_id=peer.user_id, access_hash=peer.access_hash)
92 | input_bot_app = InputBotAppShortName(bot_id=bot_id, short_name=bot_shortname)
93 | self._webview_data = {'peer': peer, 'app': input_bot_app} if bot_shortname \
94 | else {'peer': peer, 'bot': bot_username}
95 | return
96 | except FloodWaitError as fl:
97 | logger.warning(f"{self.session_name} | FloodWait {fl}. Waiting {fl.seconds}s")
98 | await asyncio.sleep(fl.seconds + 3)
99 |
100 | async def _pyrogram_initialize_webview_data(self, bot_username: str, bot_shortname: str = None):
101 | if not self._webview_data:
102 | while True:
103 | try:
104 | peer = await self.client.resolve_peer(bot_username)
105 | input_bot_app = ptypes.InputBotAppShortName(bot_id=peer, short_name=bot_shortname)
106 | self._webview_data = {'peer': peer, 'app': input_bot_app} if bot_shortname \
107 | else {'peer': peer, 'bot': bot_username}
108 | return
109 | except FloodWait as fl:
110 | logger.warning(f"{self.session_name} | FloodWait {fl}. Waiting {fl.value}s")
111 | await asyncio.sleep(fl.value + 3)
112 |
113 | async def _telethon_get_app_webview_url(self, bot_username: str, bot_shortname: str, default_val: str) -> str:
114 | if self.proxy and not self.client._proxy:
115 | logger.critical(f"{self.session_name} | Proxy found, but not passed to TelegramClient")
116 | exit(-1)
117 |
118 | async with self.lock:
119 | try:
120 | if not self.client.is_connected():
121 | await self.client.connect()
122 | await self._telethon_initialize_webview_data(bot_username=bot_username, bot_shortname=bot_shortname)
123 | await asyncio.sleep(uniform(1, 2))
124 |
125 | start = {'start_param': settings.REF_ID if randint(0, 100) <= 85 else default_val} if self.is_fist_run else {}
126 |
127 | web_view = await self.client(messages.RequestAppWebViewRequest(
128 | **self._webview_data,
129 | platform='android',
130 | write_allowed=True,
131 | **start
132 | ))
133 |
134 | return web_view.url
135 |
136 | except (UnauthorizedError, AuthKeyUnregisteredError):
137 | raise InvalidSession(f"{self.session_name}: User is unauthorized")
138 | except (UserDeactivatedError, UserDeactivatedBanError, PhoneNumberBannedError):
139 | raise InvalidSession(f"{self.session_name}: User is banned")
140 |
141 | except Exception as error:
142 | log_error(f"{self.session_name} | Unknown error during Authorization: {type(error).__name__}")
143 | await asyncio.sleep(delay=3)
144 |
145 | finally:
146 | if self.client.is_connected():
147 | await self.client.disconnect()
148 | await asyncio.sleep(15)
149 |
150 | async def _telethon_get_webview_url(self, bot_username: str, bot_url: str, default_val: str) -> str:
151 | if self.proxy and not self.client._proxy:
152 | logger.critical(f"{self.session_name} | Proxy found, but not passed to TelegramClient")
153 | exit(-1)
154 |
155 | async with self.lock:
156 | try:
157 | if not self.client.is_connected():
158 | await self.client.connect()
159 | await self._telethon_initialize_webview_data(bot_username=bot_username)
160 | await asyncio.sleep(uniform(1, 2))
161 |
162 | start = {'start_param': settings.REF_ID if randint(0, 100) <= 85 else default_val} if self.is_fist_run else {}
163 |
164 | start_state = False
165 | async for message in self.client.iter_messages('MMproBump_bot'):
166 | if r'/start' in message.text:
167 | start_state = True
168 | break
169 | await asyncio.sleep(uniform(0.5, 1))
170 | if not start_state:
171 | await self.client(messages.StartBotRequest(bot=self._webview_data.get('peer'),
172 | peer=self._webview_data.get('peer'),
173 | **start))
174 | await asyncio.sleep(uniform(1, 2))
175 |
176 | web_view = await self.client(messages.RequestWebViewRequest(
177 | **self._webview_data,
178 | platform='android',
179 | from_bot_menu=False,
180 | url=bot_url,
181 | **start
182 | ))
183 |
184 | return web_view.url
185 |
186 | except (UnauthorizedError, AuthKeyUnregisteredError):
187 | raise InvalidSession(f"{self.session_name}: User is unauthorized")
188 | except (UserDeactivatedError, UserDeactivatedBanError, PhoneNumberBannedError):
189 | raise InvalidSession(f"{self.session_name}: User is banned")
190 |
191 | except Exception as error:
192 | log_error(f"{self.session_name} | Unknown error during Authorization: {type(error).__name__}")
193 | await asyncio.sleep(delay=3)
194 |
195 | finally:
196 | if self.client.is_connected():
197 | await self.client.disconnect()
198 | await asyncio.sleep(15)
199 |
200 | async def _pyrogram_get_app_webview_url(self, bot_username: str, bot_shortname: str, default_val: str) -> str:
201 | if self.proxy and not self.client.proxy:
202 | logger.critical(f"{self.session_name} | Proxy found, but not passed to Client")
203 | exit(-1)
204 |
205 | async with self.lock:
206 | try:
207 | if not self.client.is_connected:
208 | await self.client.connect()
209 | await self._pyrogram_initialize_webview_data(bot_username, bot_shortname)
210 | await asyncio.sleep(uniform(1, 2))
211 |
212 | start = {'start_param': settings.REF_ID if randint(0, 100) <= 85 else default_val} if self.is_fist_run else {}
213 | web_view = await self.client.invoke(pmessages.RequestAppWebView(
214 | **self._webview_data,
215 | platform='android',
216 | write_allowed=True,
217 | **start
218 | ))
219 |
220 | return web_view.url
221 |
222 | except (Unauthorized, AuthKeyUnregistered):
223 | raise InvalidSession(f"{self.session_name}: User is unauthorized")
224 | except (UserDeactivated, UserDeactivatedBan, PhoneNumberBanned):
225 | raise InvalidSession(f"{self.session_name}: User is banned")
226 |
227 | except Exception as error:
228 | log_error(f"{self.session_name} | Unknown error during Authorization: {type(error).__name__}")
229 | await asyncio.sleep(delay=3)
230 |
231 | finally:
232 | if self.client.is_connected:
233 | await self.client.disconnect()
234 | await asyncio.sleep(15)
235 |
236 | async def _pyrogram_get_webview_url(self, bot_username: str, bot_url: str, default_val: str) -> str:
237 | if self.proxy and not self.client.proxy:
238 | logger.critical(f"{self.session_name} | Proxy found, but not passed to Client")
239 | exit(-1)
240 |
241 | async with self.lock:
242 | try:
243 | if not self.client.is_connected:
244 | await self.client.connect()
245 | await self._pyrogram_initialize_webview_data(bot_username)
246 | await asyncio.sleep(uniform(1, 2))
247 |
248 | start = {'start_param': settings.REF_ID if randint(0, 100) <= 85 else default_val} if self.is_fist_run else {}
249 |
250 | start_state = False
251 | async for message in self.client.get_chat_history('MMproBump_bot'):
252 | if r'/start' in message.text:
253 | start_state = True
254 | break
255 | await asyncio.sleep(uniform(0.5, 1))
256 | if not start_state:
257 | await self.client.invoke(pmessages.StartBot(bot=self._webview_data.get('peer'),
258 | peer=self._webview_data.get('peer'),
259 | random_id=randint(1, 2**63),
260 | **start))
261 | await asyncio.sleep(uniform(1, 2))
262 | web_view = await self.client.invoke(pmessages.RequestWebView(
263 | **self._webview_data,
264 | platform='android',
265 | from_bot_menu=False,
266 | url=bot_url,
267 | **start
268 | ))
269 |
270 | return web_view.url
271 |
272 | except (Unauthorized, AuthKeyUnregistered):
273 | raise InvalidSession(f"{self.session_name}: User is unauthorized")
274 | except (UserDeactivated, UserDeactivatedBan, PhoneNumberBanned):
275 | raise InvalidSession(f"{self.session_name}: User is banned")
276 |
277 | except Exception as error:
278 | log_error(f"{self.session_name} | Unknown error during Authorization: {type(error).__name__}")
279 | await asyncio.sleep(delay=3)
280 |
281 | finally:
282 | if self.client.is_connected:
283 | await self.client.disconnect()
284 | await asyncio.sleep(15)
285 |
286 | async def _telethon_join_and_mute_tg_channel(self, link: str):
287 | path = link.replace("https://t.me/", "")
288 | if path == 'money':
289 | return
290 |
291 | async with self.lock:
292 | async with self.client as client:
293 | try:
294 | if path.startswith('+'):
295 | invite_hash = path[1:]
296 | result = await client(messages.ImportChatInviteRequest(hash=invite_hash))
297 | channel_title = result.chats[0].title
298 | entity = result.chats[0]
299 | else:
300 | entity = await client.get_entity(f'@{path}')
301 | await client(channels.JoinChannelRequest(channel=entity))
302 | channel_title = entity.title
303 |
304 | await asyncio.sleep(1)
305 |
306 | await client(account.UpdateNotifySettingsRequest(
307 | peer=InputNotifyPeer(entity),
308 | settings=InputPeerNotifySettings(
309 | show_previews=False,
310 | silent=True,
311 | mute_until=datetime.today() + timedelta(days=365)
312 | )
313 | ))
314 |
315 | logger.info(f"{self.session_name} | Subscribed to channel: {channel_title}")
316 | except FloodWaitError as fl:
317 | fl_timer = fl.seconds
318 | logger.warning(f"{self.session_name} | FloodWait: {fl}. Waiting {fl_timer}s")
319 | return fl_timer
320 | except Exception as e:
321 | log_error(
322 | f"{self.session_name} | (Task) Error while subscribing to tg channel {link}: {e}")
323 |
324 | await asyncio.sleep(uniform(15, 20))
325 | return
326 |
327 | async def _pyrogram_join_and_mute_tg_channel(self, link: str):
328 | path = link.replace("https://t.me/", "")
329 | if path == 'money':
330 | return
331 |
332 | async with self.lock:
333 | async with self.client:
334 | try:
335 | if path.startswith('+'):
336 | invite_hash = path[1:]
337 | result = await self.client.invoke(pmessages.ImportChatInvite(hash=invite_hash))
338 | channel_title = result.chats[0].title
339 | entity = result.chats[0]
340 | peer = ptypes.InputPeerChannel(channel_id=entity.id, access_hash=entity.access_hash)
341 | else:
342 | peer = await self.client.resolve_peer(f'@{path}')
343 | channel = ptypes.InputChannel(channel_id=peer.channel_id, access_hash=peer.access_hash)
344 | await self.client.invoke(pchannels.JoinChannel(channel=channel))
345 | channel_title = path
346 |
347 | await asyncio.sleep(1)
348 |
349 | await self.client.invoke(paccount.UpdateNotifySettings(
350 | peer=ptypes.InputNotifyPeer(peer=peer),
351 | settings=ptypes.InputPeerNotifySettings(
352 | show_previews=False,
353 | silent=True,
354 | mute_until=2147483647))
355 | )
356 |
357 | logger.info(f"{self.session_name} | Subscribed to channel: {channel_title}")
358 | except FloodWait as e:
359 | fl_timer = e.value
360 | logger.warning(f"{self.session_name} | FloodWait {e}. Waiting {fl_timer}s")
361 | return fl_timer
362 | except UserAlreadyParticipant:
363 | logger.info(f"{self.session_name} | Was already Subscribed to channel: {link}")
364 | except Exception as e:
365 | log_error(
366 | f"{self.session_name} | (Task) Error while subscribing to tg channel {link}: {e}")
367 |
368 | await asyncio.sleep(uniform(15, 20))
369 | return
370 |
371 | async def _telethon_update_profile(self, first_name: str = None, last_name: str = None, about: str = None):
372 | update_params = {
373 | 'first_name': first_name,
374 | 'last_name': last_name,
375 | 'about': about
376 | }
377 | update_params = {k: v for k, v in update_params.items() if v is not None}
378 | if not update_params:
379 | return
380 |
381 | async with self.lock:
382 | async with self.client:
383 | try:
384 | await self.client(account.UpdateProfileRequest(**update_params))
385 | except Exception as e:
386 | log_error(
387 | f"{self.session_name} | Failed to update profile: {e}")
388 | await asyncio.sleep(uniform(15, 20))
389 |
390 | async def _pyrogram_update_profile(self, first_name: str = None, last_name: str = None, about: str = None):
391 | update_params = {
392 | 'first_name': first_name,
393 | 'last_name': last_name,
394 | 'about': about
395 | }
396 | update_params = {k: v for k, v in update_params.items() if v is not None}
397 | if not update_params:
398 | return
399 |
400 | async with self.lock:
401 | async with self.client:
402 | try:
403 | await self.client.invoke(paccount.UpdateProfile(**update_params))
404 | except Exception as e:
405 | log_error(
406 | f"{self.session_name} | Failed to update profile: {e}")
407 | await asyncio.sleep(uniform(15, 20))
408 |
--------------------------------------------------------------------------------
/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
7 |
8 |
9 | async def main():
10 | if PROXY_CHAIN:
11 | proxy_str, proxy = await get_proxy_chain(PROXY_CHAIN)
12 | if proxy:
13 | logger.info("Getting proxy for Proxy Chain")
14 | if await check_proxy(proxy_str):
15 | import socket, socks
16 | socks.set_default_proxy(proxy)
17 | socket.socket = socks.socksocket
18 | else:
19 | logger.error("Proxy chain didn't respond. Can't start the bot using proxy chain")
20 | input('Press any key to exit: ')
21 | exit(0)
22 | else:
23 | logger.warning("No valid proxy found. Skipping")
24 | await process()
25 |
26 |
27 | if __name__ == '__main__':
28 | system('title Paws')
29 | with suppress(KeyboardInterrupt):
30 | asyncio.run(main())
31 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SP-l33t/Paws-Hybrid/be02181446a44d619a8adb3e27fdde14c6550a13/requirements.txt
--------------------------------------------------------------------------------
/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 | pip install -r requirements.txt >nul 2>&1
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 | pip install -r requirements.txt >/dev/null 2>&1
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 |
--------------------------------------------------------------------------------