├── .gitignore
├── Dockerfile
├── LICENSE
├── PRIVACY.md
├── README.md
├── Timer
└── __init__.py
├── ai.py
├── alembic.ini
├── alembic
├── README
├── env.py
├── script.py.mako
└── versions
│ ├── 13a9421b19d9_add_challenge_id.py
│ ├── b841fd90a794_remove.py
│ └── c945fe00daeb_change_ip_length.py
├── challenge
├── autokickcache.py
├── math.py
└── recaptcha.py
├── challengedata.py
├── config.example.ini
├── config.example.json
├── db.py
├── dbhelper.py
├── docker-run.sh
├── exapmle.service
├── main.py
├── model.py
├── requirements.txt
├── templates
├── index.html
├── recaptcha.html
└── result.html
├── test.py
└── web.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # config files
2 | config.json
3 | config.ini
4 |
5 | # Byte-compiled / optimized / DLL files
6 | __pycache__/
7 | *.py[cod]
8 | *$py.class
9 |
10 | # Pyrogram data
11 | *.session
12 | *.session-journal
13 |
14 | #idea
15 | .idea/
16 |
17 | #db
18 | data.sqlite
19 |
20 | #venv
21 | venv
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3-alpine
2 | RUN apk add \
3 | git \
4 | gcc \
5 | musl-dev
6 | RUN mkdir -p /tg-captcha/workdir
7 | RUN git clone -b master https://github.com/Tooruchan/Telegram-CAPTCHA-bot-pyrogram.git /tg-captcha/workdir
8 | WORKDIR /tg-captcha/workdir
9 | RUN python -m pip install virtualenv
10 | RUN python -m virtualenv venv
11 | RUN source venv/bin/activate; /tg-captcha/workdir/venv/bin/python -m pip install --upgrade pip; pip install --upgrade tgcrypto configparser pyrogram
12 | RUN ["chmod", "+x", "/tg-captcha/workdir/docker-run.sh"]
13 | CMD ["sh","docker-run.sh"]
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/PRIVACY.md:
--------------------------------------------------------------------------------
1 | # 隐私协议
2 |
3 | 本说明为 Fubuki-Anti-Spam 的重要组成部分,开发者将保留随时更新或者修改本说明的权利,如果您不同意本隐私协议,请您立即停止使用本 Bot。本项目尊重任何群组和任何群组成员的隐私。
4 |
5 | 1. 信息使用
6 |
7 | 当您在群组内加入[本 Bot](https://t.me/FubukiAntiSpamBot)并且赋予其封禁用户的权限时,即表示您已经同意本隐私协议并且允许我们以评估负载和请求量的目的记录每一次请求并且存储下列数据:
8 |
9 | - 群组标题
10 | - 群组ID
11 | - 用户ID
12 |
13 | 除此之外,我们不会记录与收集任何群消息。
14 |
15 | 2. 本Bot代码除配置文件外全部开源于[GitHub 项目主页](https://github.com/NimaQu/Telegram-CAPTCHA-bot-pyrogram)上,供各位用户进行审阅。
16 |
17 | 3. 信息公开
18 |
19 | 您可以加入[日志记录频道](https://t.me/FAS_bot_log) 浏览并访问本 Bot 处理每一次请求所记录的日志,我们将会保留每一次请求的记录并且保证其不受第三方的修改或者删除。 全局黑名单数据库可以在[这里查看](https://ca.oracle.db.nimaqu.com/view/phpliteadmin.php?database=.%2Fdb%2Fdata.sqlite&table=user&fulltexts=0&numRows=30&action=row_view)
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Telegram-CAPTCHA-bot
2 |
3 | 一个用于验证新成员是不是真人的bot。
4 |
5 | [](https://www.gnu.org/licenses/agpl-3.0.en.html) [](https://www.python.org) [](https://github.com/pyrogram/pyrogram/)
6 |
7 | A bot running on Telegram which will send CAPTCHA to verify if the new member is a human.
8 |
9 | 基于[原始项目](https://github.com/Tooruchan/Telegram-CAPTCHA-bot-pyrogram)修改
10 |
11 | Forked based on [Original Repository](https://github.com/TooruchanTelegram-CAPTCHA-bot-pyrogram)
12 |
13 | 修改者:[@kkren](https://www.kkren.me/)(新 API 支持)
14 |
15 | Bot实例: [@FubukiAntiSpamBot](https://t.me/FubukiAntiSpamBot)
16 | 日志频道:[@FAS_bot_log](https://t.me/FAS_bot_log)
17 |
18 | ## 一些简单的Q&A
19 |
20 | Q: 被误加入黑名单了,怎么解除?
21 |
22 | A: 当前此 bot 实例只会进行踢出群操作,只需要再次加入你想加入的群,如果被自动踢出,在1分钟之后10分钟之内再次加入即可进入。
23 | ## 原理
24 |
25 | 本 Bot 通过读取 Telegram API 中返回的入群消息来识别新用户入群,并生成一道随机问题对用户进行验证,非严格模式只要有回答问题就通过;严格模式下回答错误将会被移除或者封禁,这个验证的效果目前无法绕过具有人工操作的广告机器人,但是可以对外语(如阿拉伯语和波斯语)类骚扰用户起到一定的拦截作用。再此基础上增加了全局黑名单功能,只有验证超时的广告机器人会自动加入到[黑名单](https://ca.oracle.db.nimaqu.com/view/phpliteadmin.php?database=.%2Fdb%2Fdata.sqlite&table=user&fulltexts=0&numRows=30&action=row_view),之后在任意有此 bot 的群组加群将会被自动踢出,对误封禁的影响造成最低。
26 |
27 | Telegram Bot API 使用了基于 MTProto 框架的 pyrogram,多线程使用了 asyncio。
28 |
29 | ## 安装与使用
30 |
31 | 此仓库仅为遵守 AGPL 协议进行代码展示,并未对用户部署使用进行优化,普通用户建议直接使用[原始项目](https://github.com/Tooruchan/Telegram-CAPTCHA-bot-pyrogram) 如果你仍想使用此 Bot,请参照下面说明进行部署。
32 |
33 | Python 要求: **最低 python 版本 3.9 ,建议 python 版本: 3.11**
34 | 1. 请先向 [@BotFather](https://t.me/botfather) 申请一个 Bot API Token
35 | > 你申请到的机器人会在你的 Telegram 账号所在数据中心上运行(即申请机器人的账号A位于 DC 5 (新加坡),则 A 申请到的机器人也将会在 DC5 上运行)
36 | 2. 在 [Obtaining Telegram API ID](https://core.telegram.org/api/obtaining_api_id) 申请 API ID 与 API Hash
37 | 3. 使用 Python Virtual Environment 部署:
38 | ```
39 | # 若未安装pip3,请先安装 python3-pip
40 | apt update && apt install -y python3-pip python3
41 | git clone https://github.com/NimaQu/Telegram-CAPTCHA-bot-pyrogram.git
42 | cd Telegram-CAPTCHA-bot-pyrogram
43 | python3 -m venv venv
44 | venv/bin/pip install wheel
45 | venv/bin/pip install -r requirements.txt
46 | ```
47 |
48 | 4. 将项目文件夹中 auth.ini 里的 token 字段(与等号间存在一个空格)修改为你在 [@BotFather](https://t.me/botfather) 获取到的 API Token,api_hash 和 api_id 修改为你在步骤2中获得的两串内容,其中 API ID 为数字,而 API Hash 为一组字符,你也可以对 config.json 里的内容酌情修改。
49 |
50 | 有关填写字段说明:
51 |
52 | `channel`: Bot 日志记录频道 Chat ID (-100 开头),未填写将会导致无法正常工作(这是一个 bug,等待修复)。
53 |
54 | `admin`: 管理用户 User ID,不填写则`/leave`和`/reload`指令无效。
55 |
56 | 5. 使用 `venv/bin/python` 直接运行这个 bot,或者在 `/etc/systemd/system/ `下新建一个 .service 文件,使用 systemd 控制这个bot的运行,配置文件示例请参考本项目目录下的 `example.service` 文件进行修改。
57 |
58 | ```bash
59 | cp example.service /etc/systemd/system/captchabot.service
60 | nano captchabot.service
61 | #编辑参数
62 | systemctl start captchabot
63 | #启动
64 | systemctl enable captchabot
65 | #开机自启
66 | ```
67 |
68 | 6. 将本 bot 加入一个群组,并给予封禁用户的权限,即可开始使用
69 |
70 | ## 在多个群组(10个以上等)部署本Bot的提示
71 |
72 | ~~由于一个已知无解的严重 Bug, Bot 在运行一周至13天左右的时间可能会由于线程冲突导致整个 Bot 死掉,如果需要在多个(10个以上)的群组内部署本 Bot 请考虑在crontab等地方设置定期重启。~~
73 |
74 | 现在的分支加入了一遇到异常就会自动重启的设定,Bot 在正常运行情况下应该是不会卡死了。
75 |
76 | ## 日志
77 | 在安装了 systemd ,且已经在 /etc/systemd/system 下部署了服务的 Linux 操作系统环境下,请使用命令:
78 | ```bash
79 | journalctl -u captchabot.service
80 | #查看从启动时的日志
81 | journalctl -f -u captchabot.service
82 | #查看实时日志
83 | # 这里的 captchabot.service 请自行更名为你在服务器上部署的服务名
84 | ```
85 | ## 开源协议
86 | 本项目使用 GNU Affero 通用公共许可证 3.0 开源
87 |
--------------------------------------------------------------------------------
/Timer/__init__.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import logging
3 |
4 |
5 | class Timer:
6 | def __init__(self, callback, timeout):
7 | logging.info("Created a schedule interval as " + str(timeout) + " seconds.")
8 | loop = asyncio.get_event_loop()
9 | self.callback = callback
10 | self.timeout = timeout
11 | self.task = loop.create_task(self.wait())
12 |
13 | def __str__(self):
14 | return "timeout: " + str(self.timeout)
15 |
16 | async def wait(self):
17 | await asyncio.sleep(self.timeout)
18 | logging.info("Successfully executed a timer schedule.")
19 | await self.callback
20 |
21 | def stop(self):
22 | try:
23 | self.task.cancel()
24 | self.callback.close()
25 | except asyncio.CancelledError:
26 | pass
27 |
--------------------------------------------------------------------------------
/ai.py:
--------------------------------------------------------------------------------
1 | import json
2 | from openai import AsyncOpenAI
3 | from pyrogram.types import Message
4 | import asyncio
5 |
6 |
7 | class AIResponseError(Exception):
8 | pass
9 |
10 |
11 | class AIResponseResult:
12 | def __init__(self, possibility: int, token_used: int):
13 | self.possibility = possibility
14 | self.token_used = token_used
15 |
16 | def __str__(self):
17 | return f"possibility: {self.possibility}, token_used: {self.token_used}"
18 |
19 |
20 | async def chk_message(message: Message, api_key, max_token, image_url: "") -> AIResponseResult:
21 | prompt = """You are an advanced spam detection system for a Telegram chat. Your task is to analyze the user's `username`, `bio`, and `message` to determine the likelihood that the user is a spammer. You should output a number from 0 to 100, where 0 indicates the user is definitely not a spammer, and 100 indicates the user is definitely a spammer.
22 |
23 | Consider the following factors:
24 |
25 | - The inclusion of suspicious links.
26 |
27 | - The overall tone and context of the message (e.g., overly promotional, using excessive emojis or symbols).
28 |
29 | - The presence of pornographic or inappropriate content in the message or images.
30 |
31 | Based on these factors, provide a spam likelihood score for the given user information.
32 |
33 | **Your response must be a single number between 0 and 100. Do not include any additional text or explanation.**
34 |
35 | Example input: { "username": "安全洗U赚差价1U换1.5U", "bio": "公群交易,洗U赚差价,黑U承兑,已上押《8888U》VIP群上押《20000U》公群已平稳运行半年多,欢迎进公群了解 https://t.m", "message": "我来了😂😂" } Example output: 100"""
36 | client = AsyncOpenAI(api_key=api_key)
37 | if message.from_user is None:
38 | user_name = str(message.chat.title)
39 | bio = str(message.chat.description)
40 | else:
41 | user_name = str(message.from_user.first_name) + " " + str(message.from_user.last_name)
42 | bio = str(message.chat.bio)
43 | # bio = "" # bio 需要通过 get_chat 获取, 暂时不使用
44 | text = {
45 | "username": user_name,
46 | "bio": bio,
47 | "message": message.text
48 | }
49 | print(json.dumps(text, ensure_ascii=False))
50 | content = []
51 | if text != "":
52 | content.append({
53 | "type": "text",
54 | "text": json.dumps(text)
55 | })
56 | if image_url != "":
57 | content.append({
58 | "type": "image_url",
59 | "image_url": {
60 | "url": image_url
61 | }
62 | })
63 | chat_completion = await client.chat.completions.create(
64 | model="gpt-4o",
65 | messages=[
66 | {
67 | "role": "system",
68 | "content": [
69 | {
70 | "type": "text",
71 | "text": prompt
72 | }
73 | ]
74 | },
75 | {
76 | "role": "user",
77 | "content": content
78 | }
79 | ],
80 | temperature=0,
81 | max_tokens=512,
82 | top_p=1,
83 | frequency_penalty=0,
84 | presence_penalty=0
85 | )
86 | token_used = chat_completion.usage.total_tokens
87 | result = chat_completion.choices[0].message.content
88 | try:
89 | return AIResponseResult(possibility=int(result), token_used=token_used)
90 | except Exception as e:
91 | raise AIResponseError(f"Invalid response from AI: {result}") from e
92 |
--------------------------------------------------------------------------------
/alembic.ini:
--------------------------------------------------------------------------------
1 | # A generic, single database configuration.
2 |
3 | [alembic]
4 | # path to migration scripts
5 | script_location = alembic
6 |
7 | # template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
8 | # Uncomment the line below if you want the files to be prepended with date and time
9 | # see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
10 | # for all available tokens
11 | # file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
12 |
13 | # sys.path path, will be prepended to sys.path if present.
14 | # defaults to the current working directory.
15 | prepend_sys_path = .
16 |
17 | # timezone to use when rendering the date within the migration file
18 | # as well as the filename.
19 | # If specified, requires the python-dateutil library that can be
20 | # installed by adding `alembic[tz]` to the pip requirements
21 | # string value is passed to dateutil.tz.gettz()
22 | # leave blank for localtime
23 | # timezone =
24 |
25 | # max length of characters to apply to the
26 | # "slug" field
27 | # truncate_slug_length = 40
28 |
29 | # set to 'true' to run the environment during
30 | # the 'revision' command, regardless of autogenerate
31 | # revision_environment = false
32 |
33 | # set to 'true' to allow .pyc and .pyo files without
34 | # a source .py file to be detected as revisions in the
35 | # versions/ directory
36 | # sourceless = false
37 |
38 | # version location specification; This defaults
39 | # to alembic/versions. When using multiple version
40 | # directories, initial revisions must be specified with --version-path.
41 | # The path separator used here should be the separator specified by "version_path_separator" below.
42 | # version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
43 |
44 | # version path separator; As mentioned above, this is the character used to split
45 | # version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
46 | # If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
47 | # Valid values for version_path_separator are:
48 | #
49 | # version_path_separator = :
50 | # version_path_separator = ;
51 | # version_path_separator = space
52 | version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
53 |
54 | # set to 'true' to search source files recursively
55 | # in each "version_locations" directory
56 | # new in Alembic version 1.10
57 | # recursive_version_locations = false
58 |
59 | # the output encoding used when revision files
60 | # are written from script.py.mako
61 | # output_encoding = utf-8
62 |
63 | sqlalchemy.url = driver://user:pass@localhost/dbname
64 |
65 |
66 | [post_write_hooks]
67 | # post_write_hooks defines scripts or Python functions that are run
68 | # on newly generated revision scripts. See the documentation for further
69 | # detail and examples
70 |
71 | # format using "black" - use the console_scripts runner, against the "black" entrypoint
72 | # hooks = black
73 | # black.type = console_scripts
74 | # black.entrypoint = black
75 | # black.options = -l 79 REVISION_SCRIPT_FILENAME
76 |
77 | # lint with attempts to fix using "ruff" - use the exec runner, execute a binary
78 | # hooks = ruff
79 | # ruff.type = exec
80 | # ruff.executable = %(here)s/.venv/bin/ruff
81 | # ruff.options = --fix REVISION_SCRIPT_FILENAME
82 |
83 | # Logging configuration
84 | [loggers]
85 | keys = root,sqlalchemy,alembic
86 |
87 | [handlers]
88 | keys = console
89 |
90 | [formatters]
91 | keys = generic
92 |
93 | [logger_root]
94 | level = WARN
95 | handlers = console
96 | qualname =
97 |
98 | [logger_sqlalchemy]
99 | level = WARN
100 | handlers =
101 | qualname = sqlalchemy.engine
102 |
103 | [logger_alembic]
104 | level = INFO
105 | handlers =
106 | qualname = alembic
107 |
108 | [handler_console]
109 | class = StreamHandler
110 | args = (sys.stderr,)
111 | level = NOTSET
112 | formatter = generic
113 |
114 | [formatter_generic]
115 | format = %(levelname)-5.5s [%(name)s] %(message)s
116 | datefmt = %H:%M:%S
117 |
--------------------------------------------------------------------------------
/alembic/README:
--------------------------------------------------------------------------------
1 | Generic single-database configuration.
--------------------------------------------------------------------------------
/alembic/env.py:
--------------------------------------------------------------------------------
1 | from logging.config import fileConfig
2 | from model import Base
3 | from sqlalchemy import engine_from_config
4 | from sqlalchemy import pool
5 |
6 | from alembic import context
7 |
8 | # this is the Alembic Config object, which provides
9 | # access to the values within the .ini file in use.
10 | config = context.config
11 |
12 | # Interpret the config file for Python logging.
13 | # This line sets up loggers basically.
14 | if config.config_file_name is not None:
15 | fileConfig(config.config_file_name)
16 |
17 | # add your model's MetaData object here
18 | # for 'autogenerate' support
19 | # from myapp import mymodel
20 | # target_metadata = mymodel.Base.metadata
21 | target_metadata = Base.metadata
22 |
23 | # other values from the config, defined by the needs of env.py,
24 | # can be acquired:
25 | # my_important_option = config.get_main_option("my_important_option")
26 | # ... etc.
27 |
28 |
29 | def run_migrations_offline() -> None:
30 | """Run migrations in 'offline' mode.
31 |
32 | This configures the context with just a URL
33 | and not an Engine, though an Engine is acceptable
34 | here as well. By skipping the Engine creation
35 | we don't even need a DBAPI to be available.
36 |
37 | Calls to context.execute() here emit the given string to the
38 | script output.
39 |
40 | """
41 | url = config.get_main_option("sqlalchemy.url")
42 | context.configure(
43 | url=url,
44 | target_metadata=target_metadata,
45 | literal_binds=True,
46 | dialect_opts={"paramstyle": "named"},
47 | )
48 |
49 | with context.begin_transaction():
50 | context.run_migrations()
51 |
52 |
53 | def run_migrations_online() -> None:
54 | """Run migrations in 'online' mode.
55 |
56 | In this scenario we need to create an Engine
57 | and associate a connection with the context.
58 |
59 | """
60 | connectable = engine_from_config(
61 | config.get_section(config.config_ini_section, {}),
62 | prefix="sqlalchemy.",
63 | poolclass=pool.NullPool,
64 | )
65 |
66 | with connectable.connect() as connection:
67 | context.configure(
68 | connection=connection, target_metadata=target_metadata
69 | )
70 |
71 | with context.begin_transaction():
72 | context.run_migrations()
73 |
74 |
75 | if context.is_offline_mode():
76 | run_migrations_offline()
77 | else:
78 | run_migrations_online()
79 |
--------------------------------------------------------------------------------
/alembic/script.py.mako:
--------------------------------------------------------------------------------
1 | """${message}
2 |
3 | Revision ID: ${up_revision}
4 | Revises: ${down_revision | comma,n}
5 | Create Date: ${create_date}
6 |
7 | """
8 | from typing import Sequence, Union
9 |
10 | from alembic import op
11 | import sqlalchemy as sa
12 | ${imports if imports else ""}
13 |
14 | # revision identifiers, used by Alembic.
15 | revision: str = ${repr(up_revision)}
16 | down_revision: Union[str, None] = ${repr(down_revision)}
17 | branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18 | depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
19 |
20 |
21 | def upgrade() -> None:
22 | ${upgrades if upgrades else "pass"}
23 |
24 |
25 | def downgrade() -> None:
26 | ${downgrades if downgrades else "pass"}
27 |
--------------------------------------------------------------------------------
/alembic/versions/13a9421b19d9_add_challenge_id.py:
--------------------------------------------------------------------------------
1 | """add challenge_id
2 |
3 | Revision ID: 13a9421b19d9
4 | Revises:
5 | Create Date: 2024-05-04 02:03:32.317765
6 |
7 | """
8 | from typing import Sequence, Union
9 |
10 | from alembic import op
11 | import sqlalchemy as sa
12 |
13 |
14 | # revision identifiers, used by Alembic.
15 | revision: str = '13a9421b19d9'
16 | down_revision: Union[str, None] = None
17 | branch_labels: Union[str, Sequence[str], None] = None
18 | depends_on: Union[str, Sequence[str], None] = None
19 |
20 |
21 | def upgrade() -> None:
22 | # ### commands auto generated by Alembic - please adjust! ###
23 | op.create_table('blacklist_user',
24 | sa.Column('user_id', sa.BigInteger(), nullable=False),
25 | sa.Column('last_attempt', sa.DateTime(), nullable=False),
26 | sa.Column('attempt_count', sa.Integer(), nullable=False),
27 | sa.Column('created_at', sa.DateTime(), nullable=True),
28 | sa.Column('updated_at', sa.DateTime(), nullable=True),
29 | sa.PrimaryKeyConstraint('user_id'),
30 | sa.UniqueConstraint('user_id')
31 | )
32 | op.create_table('group_config',
33 | sa.Column('chat_id', sa.BigInteger(), nullable=False),
34 | sa.Column('timeout', sa.Integer(), nullable=False),
35 | sa.Column('challenge_type', sa.String(length=10), nullable=False),
36 | sa.Column('failed_action', sa.String(length=10), nullable=False),
37 | sa.Column('timeout_action', sa.String(length=10), nullable=False),
38 | sa.Column('third_party_blacklist', sa.Boolean(), nullable=False),
39 | sa.Column('global_blacklist', sa.Boolean(), nullable=False),
40 | sa.PrimaryKeyConstraint('chat_id'),
41 | sa.UniqueConstraint('chat_id')
42 | )
43 | op.create_table('recaptcha_log',
44 | sa.Column('id', sa.Integer(), nullable=False),
45 | sa.Column('group_id', sa.BigInteger(), nullable=False),
46 | sa.Column('user_id', sa.BigInteger(), nullable=False),
47 | sa.Column('challenge_id', sa.String(length=64), nullable=False),
48 | sa.Column('ip_addr', sa.String(length=15), nullable=False),
49 | sa.Column('user_agent', sa.Text(), nullable=False),
50 | sa.Column('action', sa.String(length=20), nullable=False),
51 | sa.Column('created_at', sa.DateTime(), nullable=True),
52 | sa.Column('updated_at', sa.DateTime(), nullable=True),
53 | sa.ForeignKeyConstraint(['group_id'], ['group_config.chat_id'], ),
54 | sa.PrimaryKeyConstraint('id'),
55 | sa.UniqueConstraint('id')
56 | )
57 | # ### end Alembic commands ###
58 |
59 |
60 | def downgrade() -> None:
61 | # ### commands auto generated by Alembic - please adjust! ###
62 | op.drop_table('recaptcha_log')
63 | op.drop_table('group_config')
64 | op.drop_table('blacklist_user')
65 | # ### end Alembic commands ###
66 |
--------------------------------------------------------------------------------
/alembic/versions/b841fd90a794_remove.py:
--------------------------------------------------------------------------------
1 | """remove
2 |
3 | Revision ID: b841fd90a794
4 | Revises: c945fe00daeb
5 | Create Date: 2024-05-08 02:19:02.253873
6 |
7 | """
8 | from typing import Sequence, Union
9 |
10 | from alembic import op
11 | import sqlalchemy as sa
12 |
13 |
14 | # revision identifiers, used by Alembic.
15 | revision: str = 'b841fd90a794'
16 | down_revision: Union[str, None] = 'c945fe00daeb'
17 | branch_labels: Union[str, Sequence[str], None] = None
18 | depends_on: Union[str, Sequence[str], None] = None
19 |
20 |
21 | def upgrade() -> None:
22 | # ### commands auto generated by Alembic - please adjust! ###
23 | op.drop_constraint('recaptcha_log_group_id_fkey', 'recaptcha_log', type_='foreignkey')
24 | # ### end Alembic commands ###
25 |
26 |
27 | def downgrade() -> None:
28 | # ### commands auto generated by Alembic - please adjust! ###
29 | op.create_foreign_key('recaptcha_log_group_id_fkey', 'recaptcha_log', 'group_config', ['group_id'], ['chat_id'])
30 | # ### end Alembic commands ###
31 |
--------------------------------------------------------------------------------
/alembic/versions/c945fe00daeb_change_ip_length.py:
--------------------------------------------------------------------------------
1 | """change_ip_length
2 |
3 | Revision ID: c945fe00daeb
4 | Revises: 13a9421b19d9
5 | Create Date: 2024-05-04 03:30:17.311752
6 |
7 | """
8 | from typing import Sequence, Union
9 |
10 | from alembic import op
11 | import sqlalchemy as sa
12 |
13 |
14 | # revision identifiers, used by Alembic.
15 | revision: str = 'c945fe00daeb'
16 | down_revision: Union[str, None] = '13a9421b19d9'
17 | branch_labels: Union[str, Sequence[str], None] = None
18 | depends_on: Union[str, Sequence[str], None] = None
19 |
20 |
21 | def upgrade() -> None:
22 | # ### commands auto generated by Alembic - please adjust! ###
23 | op.create_unique_constraint(None, 'blacklist_user', ['user_id'])
24 | op.create_unique_constraint(None, 'group_config', ['chat_id'])
25 | op.alter_column('recaptcha_log', 'ip_addr',
26 | existing_type=sa.VARCHAR(length=15),
27 | type_=sa.String(length=64),
28 | existing_nullable=False)
29 | op.create_unique_constraint(None, 'recaptcha_log', ['id'])
30 | # ### end Alembic commands ###
31 |
32 |
33 | def downgrade() -> None:
34 | # ### commands auto generated by Alembic - please adjust! ###
35 | op.drop_constraint(None, 'recaptcha_log', type_='unique')
36 | op.alter_column('recaptcha_log', 'ip_addr',
37 | existing_type=sa.String(length=64),
38 | type_=sa.VARCHAR(length=15),
39 | existing_nullable=False)
40 | op.drop_constraint(None, 'group_config', type_='unique')
41 | op.drop_constraint(None, 'blacklist_user', type_='unique')
42 | # ### end Alembic commands ###
43 |
--------------------------------------------------------------------------------
/challenge/autokickcache.py:
--------------------------------------------------------------------------------
1 | class AutoKickCache:
2 | ...
3 |
--------------------------------------------------------------------------------
/challenge/math.py:
--------------------------------------------------------------------------------
1 | import json
2 | import random
3 |
4 | from pyrogram.types import (InlineKeyboardButton, Message)
5 |
6 |
7 | class Math:
8 | """
9 | 如果你是 Python 高手,请继续;如果你根本不会Python或者语法乱七八糟,我建议你还是先去 https://docs.python.org 学习一个。
10 | 一个简单的验证问题变量说明
11 | 请注意,如果要使用中文写出各个选项,建议把main.py里344-346行修改为如下形式:
12 | [InlineKeyboardButton(str(c),
13 | callback_data=bytes(
14 | str(c), encoding="utf-8"))])
15 | 这么做的目的是能让问题的选项每个一行,否则一行四个答案可能会显示不下
16 | __str__ 方法返回问题的具体内容,
17 | qus 返回上面的 __str__ 方法
18 | ans 返回 Challenge 的答案
19 | choices 返回 Challenge 的选项们
20 | _ans 属性是问题,
21 | _choices 是问题选项
22 | 比如说你可以这么改写 Challenge 类
23 | def __init(self):
24 | self._ans= ''
25 | self._choices = []
26 | self.new()
27 | def __str__(self):
28 | return "下面哪一个不是路由器的架构?"
29 | def new(self):
30 | self._choices['MIPS','ARM','8051','x86']
31 | self._answer = '8051'
32 |
33 | qus, ans,choices 这三个函数可以放着不动
34 | """
35 |
36 | def __init__(self):
37 | self._a = 0
38 | self._b = 0
39 | # 所以为啥要把a,b两个属性丢这里?我不是太懂。。。
40 | self._op = "加上(plus)"
41 | self._ans = 0
42 | self._choices = []
43 | self.new()
44 |
45 | def __str__(self):
46 | return "{a} {op} {b} 的结果是多少?\nWhat is the result of {a} {op} {b}".format(a=self._a, b=self._b, op=self._op)
47 |
48 | def new(self):
49 | operation = random.choice(["加上(plus)", "减去(minus)", "乘以(time)", "除以(divide)"])
50 | a, b, ans = 0, 0, 0
51 | if operation in ["加上(plus)", "减去(minus)"]:
52 | a, b = random.randint(0, 50), random.randint(0, 50)
53 | a, b = max(a, b), min(a, b)
54 | ans = a + b if operation == "加上(plus)" else a - b
55 | elif operation == "乘以(time)":
56 | a, b = random.randint(0, 9), random.randint(0, 9)
57 | ans = a * b
58 | elif operation == "除以(divide)":
59 | a, b = random.randint(0, 9), random.randint(1, 9)
60 | ans = a
61 | a = a * b
62 |
63 | cases = random.randint(3, 5)
64 | choices = random.sample(range(100), cases)
65 | if ans not in choices:
66 | choices[0] = ans
67 | random.shuffle(choices)
68 |
69 | self._a, self._b = a, b
70 | self._op = operation
71 | self._ans = ans
72 | self._choices = choices
73 |
74 | def generate_button(self, group_config):
75 | choices = []
76 | answers = []
77 | for c in self.choices():
78 | answers.append(
79 | InlineKeyboardButton(str(c),
80 | callback_data=bytes(
81 | str(c), encoding="utf-8")))
82 | choices.append(answers)
83 | return choices + [[
84 | InlineKeyboardButton(group_config["msg_approve_manually"],
85 | callback_data=b"+"),
86 | InlineKeyboardButton(group_config["msg_refuse_manually"],
87 | callback_data=b"-"),
88 | ]]
89 |
90 | def generate_join_request_button(self, chat_id):
91 | choices = []
92 | answers = []
93 | for c in self.choices():
94 | answers.append(
95 | InlineKeyboardButton(str(c),
96 | callback_data=bytes(
97 | str(c) + f"|{chat_id}", encoding="utf-8")))
98 | choices.append(answers)
99 | return choices
100 |
101 | def qus(self):
102 | return self.__str__()
103 |
104 | def ans(self):
105 | return self._ans
106 |
107 | def choices(self):
108 | return self._choices
109 |
--------------------------------------------------------------------------------
/challenge/recaptcha.py:
--------------------------------------------------------------------------------
1 | from configparser import ConfigParser
2 | from pyrogram.types import (InlineKeyboardButton, Message)
3 | import requests
4 | import json
5 | import uuid
6 |
7 | cf = ConfigParser()
8 | cf.read("config.ini", encoding="utf-8")
9 |
10 |
11 | class ReCAPTCHA:
12 | def __init__(self):
13 | self.site_key = cf.get("reCAPTCHA", "site_key")
14 | self.secret_key = cf.get("reCAPTCHA", "secret_key")
15 | self.recaptcha_id = str(uuid.uuid4().hex) # 在用户启动 bot 后随机生成的一个 id, 用于 recaptcha 链接
16 | self.auth_url = cf.get("reCAPTCHA", "base_url") + "/recaptcha?challenge=" + str(self.recaptcha_id)
17 | self.bot_url = 'https://t.me/' + cf.get("bot", "username") + '?start='
18 | self.message = None
19 |
20 | def __str__(self):
21 | return "recaptcha id: " + self.recaptcha_id
22 |
23 | def get_site_key(self):
24 | return self.site_key
25 |
26 | def get_secret_key(self):
27 | return self.secret_key
28 |
29 | def verify(self, captcha_response, user_ip: str):
30 | """ Validating recaptcha response from google server
31 | Returns True captcha test passed for submitted form else returns False.
32 | https://techmonger.github.io/5/python-flask-recaptcha/
33 | """
34 | secret = self.secret_key
35 | payload = {'response': captcha_response, 'secret': secret, 'remoteip': user_ip}
36 | response = requests.post("https://challenges.cloudflare.com/turnstile/v0/siteverify", payload)
37 | response_text = json.loads(response.text)
38 | return response_text['success']
39 |
40 | def generate_button(self, group_config, chat_id):
41 | link_to_bot = [[InlineKeyboardButton(text="开始验证", url=self.bot_url + str(chat_id))]]
42 | return link_to_bot + [[
43 | InlineKeyboardButton(group_config["msg_approve_manually"],
44 | callback_data=b"+"),
45 | InlineKeyboardButton(group_config["msg_refuse_manually"],
46 | callback_data=b"-"),
47 | ]]
48 |
49 | def generate_auth_button(self):
50 | return [[InlineKeyboardButton(text="开始验证",
51 | url=self.auth_url)]]
52 |
--------------------------------------------------------------------------------
/challengedata.py:
--------------------------------------------------------------------------------
1 | import threading
2 |
3 | from challenge.math import Math
4 | from challenge.recaptcha import ReCAPTCHA
5 |
6 |
7 | class ChallengeData:
8 | def __init__(self):
9 | self.data = dict()
10 | self.t_lock = threading.Lock()
11 |
12 | def __setitem__(self, key, value):
13 | with self.t_lock:
14 | self.data[key] = value
15 |
16 | def __getitem__(self, item: str):
17 | with self.t_lock:
18 | value = self.data.get(item)
19 | return value
20 |
21 | def __str__(self):
22 | output = []
23 | with self.t_lock:
24 | count = len(self.data)
25 | output.append("ChallengeCount: " + str(count))
26 | for ch_id, challenge_data in self.data.items():
27 | output.append("验证 ID:{}".format(ch_id))
28 | output.append("验证数据:{}".format(str(challenge_data)) + "\n")
29 | return str(output)
30 |
31 | def delete(self, data):
32 | with self.t_lock:
33 | deleted = self.data.pop(data, None)
34 | return deleted
35 |
36 | def get(self, ch_id):
37 | with self.t_lock:
38 | challenge_data = self.data.get(ch_id)
39 | return challenge_data
40 |
41 | def get_by_user_and_chat_id(self, user_id, chat_id):
42 | with self.t_lock:
43 | for ch_id, challenge_data in self.data.items():
44 | challenge_chat_id = int(ch_id.split("|")[0])
45 | if user_id == challenge_data[1] and chat_id == challenge_chat_id:
46 | return ch_id, challenge_data
47 | return None, None
48 |
49 | def get_by_challenge_id(self, challenge_id: str):
50 | """
51 | Get all data by challenge id
52 | :param challenge_id: recaptcha challengeid
53 | :return: tuple(key, value)
54 | """
55 | with self.t_lock:
56 | for ch_id, challenge_data in self.data.items():
57 | if isinstance(challenge_data[0], ReCAPTCHA):
58 | if challenge_id == challenge_data[0].recaptcha_id:
59 | break
60 | else:
61 | return None
62 | challenge_data = self.data.get(ch_id)
63 | return ch_id, challenge_data
64 |
65 | def is_duplicate(self, user_id: int, chat_id: int):
66 | """
67 | 检查当前用户在当前群是否有未完成的订阅,用来防止奇怪的原因重复发送多次验证
68 | :param user_id 目标用户 id
69 | :param chat_id 目标群组 id
70 | :return: True 重复 / False 不重复
71 | """
72 | with self.t_lock:
73 | for ch_id, v in self.data.items():
74 | challenge_chat_id = int(ch_id.split("|")[0])
75 | if challenge_chat_id == chat_id and user_id == v[1]:
76 | return True
77 | return False
78 |
--------------------------------------------------------------------------------
/config.example.ini:
--------------------------------------------------------------------------------
1 | [db]
2 | conn_str = postgresql://postgres:nimaqu114514@localhost/FubukiAntiSpam
3 |
4 | [bot]
5 | ; username 不要加那个 @
6 | username = bot
7 | token = 114514:1919810
8 | api_id = 114514
9 | api_hash = 1919810
10 | admin = 1145141919
11 | channel = -1145141919
12 |
13 | [reCAPTCHA]
14 | site_key = 1145141919
15 | secret_key = 810893
16 | ;发送给用户的验证地址
17 | base_url = https://example.com
18 |
19 | [web]
20 | ;flask 加密密钥,自己生成一个
21 | flask_secret_key = 1145141919810
22 | flask_port = 5000
23 | flask_host = 127.0.0.1
24 | ; 是否启用开发模式,启用后会在日志中输出更多信息,关闭后由 waitress 进行部署
25 | development = true
26 |
--------------------------------------------------------------------------------
/config.example.json:
--------------------------------------------------------------------------------
1 | {
2 | "proxy_addr":"",
3 | "proxy_port":"",
4 | "msg_start_message": "喵?",
5 | "msg_passed_answer": "#PASS\n[用户](tg://user?id={targetuserid}) ID: `{targetuserid}` \n事件: 通过验证.\n群组 ID: `{groupid}`\n群组标题: `{grouptitle}`",
6 | "msg_passed_mercy": "#PASS_WRONG_ANSWER\n[用户](tg://user?id={targetuserid}) ID: `{targetuserid}` \n事件: 回答错误,通过验证.\n群组 ID: `{groupid}`\n群组标题: `{grouptitle}`",
7 | "msg_passed_admin": "#PASS_MANUALLY\n[用户](tg://user?id={targetuserid}) ID: `{targetuserid}` \n事件: 管理员人工通过验证.\n群组 ID: `{groupid}`\n群组标题: `{grouptitle}`",
8 | "msg_failed_answer": "#FAIL_WRONG_ANSWER\n[用户](tg://user?id={targetuserid}) ID: `{targetuserid}` \n事件: 验证未能通过.\n原因: 回答错误\n群组 ID: `{groupid}`\n群组标题: `{grouptitle}`",
9 | "msg_failed_timeout": "#FAIL_TLO\n[用户](tg://user?id={targetuserid}) ID: `{targetuserid}` \n用户名: @{targetusername} \n用户 Firstname: `{targetfirstname}` \n用户 Lastname: `{targetlastname}` \n事件: 验证未能通过.\n原因: 超时.\n群组 ID: `{groupid}`\n群组标题: `{grouptitle}`",
10 | "msg_failed_admin": "#FAIL_MANUALLY\n[用户](tg://user?id={targetuserid}) ID: `{targetuserid}` \n事件:验证未能通过 \n原因: 管理员人工拒绝.\n群组 ID: `{groupid}`\n群组标题: `{grouptitle}`",
11 | "msg_failed_auto_kick": "#AUTO_KICKED\n[用户](tg://user?id={targetuserid}) ID: `{targetuserid}` \n用户名: @{targetusername} \n用户 Firstname: `{targetfirstname}` \n用户 Lastname: `{targetlastname}` \n事件: 验证未能通过.\n原因: 黑名单自动踢出.\n群组 ID: `{groupid}`\n群组标题: `{grouptitle}`\n上一次尝试加群在: {lastattempt}\n距离上一次尝试时间:{sincelastattempt}\n总尝试次数: {trycount}",
12 | "msg_message_deleted": "#MESSAGE_DELETED\n[用户](tg://user?id={targetuserid}) ID: `{targetuserid}` \n事件: 消息已被删除.\n原因: 用户未完成验证\n消息 ID: `{messageid}\n`群组 ID: `{groupid}`\n群组标题: `{grouptitle}`",
13 | "msg_into_group": "#ADDBOT\n已被加入群组 ID: `{groupid}`\n群组标题: `{grouptitle}` 中",
14 | "msg_leave_group": "基于Term of Service, Bot 离开了群组: `{groupid}`",
15 | "msg_leave_msg": "根据 Term of Service,本 Bot 无法对该群组提供服务,需要了解更多,请查看项目使用协议。",
16 | "*": {
17 | "msg_self_introduction": "Tooruchan's Captcha Bot\n Powered by [Tooruchan](https://github.com/Tooruchan)\n[Project Repo](https://github.com/Tooruchan/Telegram-CAPTCHA-Bot)\nFramework:\n[pyrogram async](https://github.com/pyrogram/pyrogram)",
18 | "msg_challenge_not_for_you": "这次验证并不针对您",
19 | "msg_challenge_math": "对于用户 [{target_id}](tg://user?id={target_id}) :\n您好,本群开启了验证功能,请在 {timeout} 秒内点击下面的按钮回答这个问题:\n{challenge}",
20 | "msg_challenge_math_private": "请在 {timeout} 秒内回答这个问题:\n{challenge}",
21 | "msg_challenge_recaptcha": "对于用户 [{target_id}](tg://user?id={target_id}) :\n您好,本群开启了验证功能,请在 {timeout} 秒内点击下面的按钮前往机器人完成验证:",
22 | "msg_challenge_passed": "您已通过验证,欢迎加入本群!\n如果仍然无法发言,请重启 Telegram 客户端。",
23 | "msg_challenge_failed": "抱歉,您没有通过验证,如需解封请私聊本群群管。",
24 | "msg_approve_manually": "人工通过\nPASS",
25 | "msg_refuse_manually": "人工拒绝\nDENY",
26 | "msg_permission_denied": "您的权限不足",
27 | "msg_bot_no_permission": "操作失败,可能是群管并未赋予机器人管理员权限。",
28 | "msg_approved": "您已被管理员 {user} 人工通过,欢迎加入本群!",
29 | "msg_refused": "该用户已被管理员 {user} 移除出群。",
30 | "challenge_timeout": 60,
31 | "challenge_timeout_action": "kick",
32 | "challenge_failed_action": "kick",
33 | "challenge_type": "math",
34 | "delete_passed_challenge": true,
35 | "delete_passed_challenge_interval": 15,
36 | "delete_failed_challenge": true,
37 | "delete_failed_challenge_interval": 15,
38 | "enable_third_party_blacklist": false,
39 | "enable_global_blacklist": true,
40 | "global_timeout_user_blacklist_remove": 600
41 | }
42 | }
--------------------------------------------------------------------------------
/db.py:
--------------------------------------------------------------------------------
1 | from configparser import ConfigParser
2 |
3 | from alembic.config import Config
4 | from sqlalchemy import create_engine
5 | from sqlalchemy.orm import sessionmaker
6 |
7 | from alembic import command
8 | from model import GroupConfig, BlacklistUser
9 |
10 | config = ConfigParser()
11 | config.read('config.ini', encoding='utf-8')
12 | db_config = config['db']
13 |
14 | engine = create_engine(db_config['conn_str'])
15 | SessionFactory = sessionmaker(bind=engine)
16 |
17 |
18 | def upgrade_db():
19 | alembic_cfg = Config("alembic.ini")
20 | alembic_cfg.set_main_option("sqlalchemy.url", db_config['conn_str'])
21 | command.upgrade(alembic_cfg, "head")
22 |
23 |
24 | def new_migration(message: str):
25 | alembic_cfg = Config("alembic.ini")
26 | alembic_cfg.set_main_option("sqlalchemy.url", db_config['conn_str'])
27 | command.revision(alembic_cfg, message=message, autogenerate=True)
28 |
29 |
30 | def _import_from_csv(file_path, table):
31 | import csv
32 | from datetime import datetime
33 | with open(file_path, 'r', encoding='utf-8') as f:
34 | reader = csv.reader(f)
35 | with SessionFactory() as session:
36 | if table == 'group_config':
37 | obj = []
38 | for row in reader:
39 | if row[1] == "":
40 | row[1] = 'kick'
41 | if row[2] == "":
42 | row[2] = 'kick'
43 | if row[4] == "":
44 | row[4] = 'recaptcha'
45 | if row[5] == "":
46 | row[5] = True
47 | elif row[5] == "0":
48 | row[5] = False
49 | else:
50 | row[5] = True
51 | if row[6] == "":
52 | row[6] = False
53 | elif row[6] == "0":
54 | row[6] = False
55 | else:
56 | row[6] = True
57 | if row[3] == "":
58 | row[3] = 180
59 | obj.append(GroupConfig(chat_id=row[0], timeout=row[3], challenge_type=row[4].lower(), failed_action=row[1],
60 | timeout_action=row[2], third_party_blacklist=row[6], global_blacklist=row[5]))
61 | if table == 'blacklist_user':
62 | obj = []
63 | for row in reader:
64 | if row[2] == "0":
65 | continue
66 | if row[3] == "0":
67 | row[3] = "1"
68 | linux_timestamp = int(row[1])
69 | # 将时间戳转换为datetime对象
70 | last_attempt = datetime.fromtimestamp(linux_timestamp)
71 | obj.append(BlacklistUser(user_id=row[0], last_attempt=last_attempt, attempt_count=row[3]))
72 | session.add_all(obj)
73 | session.commit()
74 |
75 |
76 | if __name__ == '__main__':
77 | # 根据传入的命令行参数执行对应的操作
78 | # 例如: python db.py update
79 | import sys
80 |
81 | if len(sys.argv) > 1:
82 | if sys.argv[1] == 'update':
83 | upgrade_db()
84 | elif sys.argv[1] == 'new_migration':
85 | new_migration(sys.argv[2])
86 | elif sys.argv[1] == 'import':
87 | _import_from_csv(sys.argv[2], sys.argv[3])
88 |
--------------------------------------------------------------------------------
/dbhelper.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | import logging
3 |
4 | from db import SessionFactory
5 | from model import GroupConfig, BlacklistUser, RecaptchaLog, RecaptchaLogAction
6 |
7 |
8 | def get_user(user_id):
9 | with SessionFactory() as session:
10 | user = session.query(BlacklistUser).filter_by(user_id=user_id).first()
11 | if user is None:
12 | return None
13 | else:
14 | return user
15 |
16 |
17 | def get_user_status(user_id):
18 | with SessionFactory() as session:
19 | user = session.query(BlacklistUser).filter_by(user_id=user_id).first()
20 | if user is None:
21 | return 0
22 | else:
23 | return 1
24 |
25 |
26 | def update_last_try(time, user_id):
27 | with SessionFactory() as session:
28 | user = session.query(BlacklistUser).filter_by(user_id=user_id).first()
29 | if user is None:
30 | logging.error('User not found')
31 | else:
32 | user.last_attempt = time
33 | session.commit()
34 |
35 |
36 | def try_count_plus_one(user_id):
37 | with SessionFactory() as session:
38 | user = session.query(BlacklistUser).filter_by(user_id=user_id).first()
39 | if user is None:
40 | logging.error('User not found')
41 | else:
42 | user.attempt_count += 1
43 | session.commit()
44 |
45 |
46 | def new_blacklist(time, user_id):
47 | # tested
48 | with SessionFactory() as session:
49 | user = BlacklistUser(user_id=user_id, last_attempt=time)
50 | session.add(user)
51 | session.commit()
52 |
53 |
54 | def get_try_count(user_id):
55 | with SessionFactory() as session:
56 | user = session.query(BlacklistUser).filter_by(user_id=user_id).first()
57 | if user is None:
58 | return 0
59 | else:
60 | return user.attempt_count
61 |
62 |
63 | def get_all_user_ids():
64 | with SessionFactory() as session:
65 | user = session.query(BlacklistUser).all()
66 | if user is None:
67 | return 0
68 | else:
69 | return [i.user_id for i in user]
70 |
71 |
72 | def delete_users_by_id(user_id_list: list | int):
73 | with SessionFactory() as session:
74 | if isinstance(user_id_list, list):
75 | session.query(BlacklistUser).filter(BlacklistUser.user_id.in_(user_id_list)).delete(synchronize_session=False)
76 | else:
77 | session.query(BlacklistUser).filter_by(user_id=user_id_list).delete(synchronize_session=False)
78 | session.commit()
79 |
80 |
81 | def get_group_config(group_id, field: str = 'all'):
82 | with SessionFactory() as session:
83 | group = session.query(GroupConfig).filter_by(chat_id=group_id).first()
84 | if group is None:
85 | return None
86 | else:
87 | if field == 'challenge_failed_action':
88 | return group.failed_action
89 | elif field == 'challenge_timeout_action':
90 | return group.timeout_action
91 | elif field == 'challenge_timeout':
92 | return group.timeout
93 | elif field == 'challenge_type':
94 | return group.challenge_type
95 | elif field == 'enable_global_blacklist':
96 | return group.global_blacklist
97 | elif field == 'enable_third_party_blacklist':
98 | return group.third_party_blacklist
99 | elif field == 'all':
100 | return {'challenge_failed_action': group.failed_action,
101 | 'challenge_timeout_action': group.timeout_action,
102 | 'challenge_timeout': group.timeout, 'challenge_type': group.challenge_type,
103 | 'enable_global_blacklist': group.global_blacklist,
104 | 'enable_third_party_blacklist': group.third_party_blacklist}
105 | else:
106 | return None
107 |
108 |
109 | def new_group_config(group_id):
110 | with SessionFactory() as session:
111 | group = GroupConfig(chat_id=group_id)
112 | session.add(group)
113 | session.commit()
114 |
115 |
116 | def set_group_config(group_id, key, value):
117 | key = key.lower()
118 | value = value.lower()
119 | # tested 80% passed
120 | with SessionFactory() as session:
121 | group = session.query(GroupConfig).filter_by(chat_id=group_id).first()
122 | if group is None:
123 | new_group_config(group_id)
124 | else:
125 | if key == 'challenge_failed_action':
126 | group.failed_action = value
127 | elif key == 'challenge_timeout_action':
128 | group.timeout_action = value
129 | elif key == 'challenge_timeout':
130 | group.timeout = value
131 | elif key == 'challenge_type':
132 | group.challenge_type = value
133 | elif key == 'enable_global_blacklist':
134 | group.global_blacklist = value
135 | elif key == 'enable_third_party_blacklist':
136 | group.third_party_blacklist = value
137 | else:
138 | return False
139 | session.commit()
140 | return True
141 |
142 |
143 | def log_recaptcha(challenge_id, user_id, chat_id, ip_addr, user_agent, action: RecaptchaLogAction):
144 | # 先根据 challenge_id, user_id, chat_id, ip_addr, action 查询是否已经存在记录 如果存在则什么都不做
145 | # 如果不存在则插入记录
146 | with SessionFactory() as session:
147 | log = session.query(RecaptchaLog).filter_by(challenge_id=challenge_id, user_id=user_id, group_id=chat_id,
148 | ip_addr=ip_addr, action=action).first()
149 | if log is None:
150 | log = RecaptchaLog(challenge_id=challenge_id, user_id=user_id, group_id=chat_id, ip_addr=ip_addr,
151 | user_agent=user_agent, action=action)
152 | session.add(log)
153 | session.commit()
154 |
155 |
156 | def get_logs_by_challenge_id(challenge_id):
157 | with SessionFactory() as session:
158 | # limit to last 5 logs
159 | logs = session.query(RecaptchaLog).filter_by(challenge_id=challenge_id).order_by(
160 | RecaptchaLog.created_at.desc()).limit(10).all()
161 | return logs
162 |
163 |
164 | def get_logs_by_user_id(user_id):
165 | with SessionFactory() as session:
166 | # limit to last 5 logs
167 | logs = session.query(RecaptchaLog).filter_by(user_id=user_id).order_by(
168 | RecaptchaLog.created_at.desc()).limit(10).all()
169 | return logs
170 |
171 |
172 | def get_logs_by_ip(ip_addr):
173 | with SessionFactory() as session:
174 | # limit to last 5 logs
175 | logs = session.query(RecaptchaLog).filter_by(ip_addr=ip_addr).order_by(
176 | RecaptchaLog.created_at.desc()).limit(10).all()
177 | return logs
178 |
179 |
180 | if __name__ == '__main__':
181 | delete_users_by_id(123456789)
182 | ...
183 |
--------------------------------------------------------------------------------
/docker-run.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | check_dep() {
4 | if [ $(python -m pip check) ]; then
5 | source venv/bin/activate
6 | pip freeze > requirements.txt
7 | pip install -r requirements.txt --upgrade
8 | pip install -U pyrogram-asyncio.zip
9 | pip install --upgrade tgcrypto configparser
10 | fi
11 | if [ $(pip list --disable-pip-version-check | grep -E "^tgcrypto") ]; then
12 | source venv/bin/activate; pip install --upgrade tgcrypto
13 | fi
14 | if [ $(pip list --disable-pip-version-check | grep -E "^configparser") ]; then
15 | source venv/bin/activate; pip install --upgrade configparser
16 | fi
17 | if [ $(pip list --disable-pip-version-check | grep -E "^pyrogram") ]; then
18 | source venv/bin/activate; pip install --upgrade pyrogram
19 | fi
20 | }
21 |
22 | main() {
23 | cd /tg-captcha/workdir
24 | check_dep
25 | if [[ ! -f config.ini ]] || [[ ! -f config.json ]]; then
26 | echo ""
27 | exit 1
28 | fi
29 | git pull
30 | /tg-captcha/workdir/venv/bin/python /tg-captcha/workdir/main.py
31 | }
32 |
33 | main
34 |
--------------------------------------------------------------------------------
/exapmle.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=此处填写您的服务名
3 | After=network-online.target
4 | Wants=network-online.target
5 |
6 | [Service]
7 | Type=simple
8 | WorkingDirectory=此处填写你在服务器上存放Bot的目录
9 | ExecStart=/项目目录/venv/bin/python /你/放/Bot/的/目录/main.py
10 | Restart=always
11 | PrivateTmp=True
12 | KillSignal=SIGINT
13 | TimeoutStopSec=10s
14 | StartLimitInterval=400
15 |
16 | [Install]
17 | WantedBy=multi-user.target
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | # !/usr/bin/env python3
2 | # -*- coding: UTF-8 -*-
3 | import asyncio
4 | import json
5 | import logging
6 | import threading
7 | # import time
8 | from datetime import datetime, timedelta
9 | from configparser import ConfigParser
10 |
11 | from pyrogram import Client, filters
12 | from pyrogram.enums import ChatMemberStatus
13 | from pyrogram.errors import ChatAdminRequired, ChannelPrivate, MessageNotModified, RPCError, BadRequest, \
14 | MessageDeleteForbidden, UserNotParticipant, UserIsBlocked
15 | from pyrogram.enums.chat_members_filter import ChatMembersFilter
16 | from pyrogram.enums.message_service_type import MessageServiceType
17 | from pyrogram.enums.chat_type import ChatType
18 | from pyrogram.types import (InlineKeyboardMarkup, User, Message, ChatPermissions, CallbackQuery,
19 | ChatMemberUpdated, ChatMember, Chat)
20 | from Timer import Timer
21 | from challenge.math import Math
22 | from challenge.recaptcha import ReCAPTCHA
23 | from challenge.autokickcache import AutoKickCache
24 | import dbhelper as db
25 | from challengedata import ChallengeData
26 | from waitress import serve
27 | from urllib.parse import urlparse
28 | from model import ChallengeType, FailedAction
29 | from ai import chk_message
30 | import base64
31 |
32 | # db = DBHelper()
33 |
34 | _start_message = "YABE!"
35 | # _challenge_scheduler = sched.scheduler(time, sleep)
36 | _current_challenges = ChallengeData()
37 | _cch_lock = threading.Lock()
38 | _config = dict()
39 | admin_operate_filter = filters.create(lambda _, __, query: query.data.split(" ")[0] in ["+", "-"])
40 | private_math_challenge_filter = filters.create(lambda _, __, query: "|" in query.data)
41 |
42 | '''
43 | 读 只 读 配 置
44 | '''
45 | cf = ConfigParser() # 启用ConfigParser读取那些启动后即不会再被更改的数据,如BotToken等
46 | cf.read("config.ini", encoding="utf-8")
47 |
48 | _admin_config = cf.get("bot", "admin")
49 | if ',' in _admin_config:
50 | # 多个管理员ID,用逗号分隔
51 | _admin_users = [int(admin_id.strip()) for admin_id in _admin_config.split(',')]
52 | else:
53 | # 单个管理员ID
54 | _admin_users = [int(_admin_config)]
55 |
56 | _token = cf.get("bot", "token")
57 | _api_id = cf.getint("bot", "api_id")
58 | _api_hash = cf.get("bot", "api_hash")
59 | _channel = cf.getint("bot", "channel")
60 | logging.basicConfig(level=logging.INFO)
61 |
62 |
63 | def is_admin(user_id: int) -> bool:
64 | """检查用户是否为管理员"""
65 | return user_id in _admin_users
66 |
67 |
68 | # 设置一下日志记录,能够在诸如 systemctl status captchabot 这样的地方获得详细输出。
69 |
70 | def start_web(client: Client):
71 | import web
72 | port = cf.getint('web', 'flask_port')
73 | host = cf.get('web', 'flask_host')
74 | web.app.secret_key = cf.get('web', 'flask_secret_key')
75 | web.client = client
76 | web._current_challenges = _current_challenges
77 | web._config = _config
78 | web._channel = _channel
79 | if cf.getboolean('web', 'development'):
80 | web.app.env = 'development '
81 | web.app.run(host=host, port=port)
82 | else:
83 | serve(web.app, host=host, port=port)
84 |
85 |
86 | def load_config():
87 | global _config
88 | with open("config.json", encoding="utf-8") as f:
89 | _config = json.load(f)
90 |
91 |
92 | def save_config():
93 | with open("config.json", "w", encoding='utf8') as f:
94 | json.dump(_config, f, indent=4, ensure_ascii=False)
95 |
96 |
97 | def get_group_config(chat_id):
98 | try:
99 | int(chat_id)
100 | except ValueError:
101 | return None
102 | file_config = _config.get(chat_id, _config["*"])
103 | db_config = db.get_group_config(chat_id, 'all')
104 | if db_config is None:
105 | return file_config
106 | else:
107 | final_config = {**file_config, **db_config}
108 | return final_config
109 |
110 |
111 | def extract_ids(url: str) -> (int | str, int):
112 | # 解析 URL
113 | parsed = urlparse(url)
114 | # 提取路径部分
115 | path = parsed.path
116 |
117 | if '/c/' in path:
118 | # 私有群组链接
119 | path_parts = path.split('/')
120 | chat_id = int(path_parts[-2])
121 | message_id = int(path_parts[-1])
122 | # chat_id 需要加上 -100 前缀
123 | return str(-100) + str(chat_id), message_id
124 | else:
125 | # 公共群组链接,chat_id 为用户名,message_id 为最后一部分
126 | chat_id = path.split('/')[-2]
127 | message_id = int(path.split('/')[-1])
128 | return chat_id, message_id
129 |
130 | def _update(app):
131 | @app.on_message(filters.command("reload") & filters.private)
132 | async def reload_cfg(client: Client, message: Message):
133 | _me: User = await client.get_me()
134 | logging.info(message.text)
135 | if is_admin(message.from_user.id):
136 | save_config()
137 | load_config()
138 | await message.reply("配置已成功重载。")
139 | else:
140 | logging.info("Permission denied, admin users in config are:" + str(_admin_users))
141 | pass
142 |
143 | @app.on_message(filters.command("help") & filters.group)
144 | async def helping_cmd(client: Client, message: Message):
145 | _me: User = await client.get_me()
146 | logging.info(message.text)
147 | await message.reply(_config["*"]["msg_self_introduction"],
148 | disable_web_page_preview=True)
149 |
150 | @app.on_message(filters.command("ping") & filters.private)
151 | async def ping_command(client: Client, message: Message):
152 | await message.reply("poi~")
153 |
154 | @app.on_message(filters.command("start") & filters.private)
155 | async def start_command(client: Client, message: Message):
156 | user_id = message.from_user.id
157 | if len(message.command) != 2:
158 | await message.reply(_start_message)
159 | return
160 | try:
161 | from_chat_id = int(message.command[1])
162 | except ValueError:
163 | await message.reply(_start_message)
164 | return
165 |
166 | if from_chat_id >= 0:
167 | await message.reply(_start_message)
168 | return
169 | ch_id, challenge_data = _current_challenges.get_by_user_and_chat_id(user_id, from_chat_id)
170 |
171 | if challenge_data is None or ch_id is None:
172 | await message.reply("这不是你的验证数据,请确认是否点击了正确的按钮")
173 | return
174 | else:
175 | challenge, target_id, timeout_event = challenge_data
176 |
177 | await message.reply("点击下方按钮完成验证,您需要使用浏览器来完成,如果您在访问页面时出现问题,请尝试关闭的匿名代理\n\n",
178 | reply_markup=InlineKeyboardMarkup(challenge.generate_auth_button()))
179 |
180 | @app.on_message(filters.command("admin", prefixes="@") & filters.group)
181 | async def call_admin(client: Client, message: Message):
182 | administrators: list[ChatMember] = []
183 | me: User = await client.get_me()
184 | async for m in app.get_chat_members(message.chat.id, filter=ChatMembersFilter.ADMINISTRATORS):
185 | administrators.append(m)
186 | text = ""
187 | for admin in administrators:
188 | if admin.user.id == me.id:
189 | continue
190 | # 检查是否有删除消息的权限
191 | if not admin.privileges.can_restrict_members or not admin.privileges.can_delete_messages:
192 | continue
193 | if admin.user.is_bot:
194 | continue
195 | text += f"{admin.user.mention('admin')} "
196 | if text == "":
197 | await message.reply("没有找到可用的管理员")
198 | return
199 | msg = await message.reply(text)
200 | Timer(msg.delete(), 300)
201 |
202 | @app.on_message(filters.command("leave") & filters.private)
203 | async def leave_command(client: Client, message: Message):
204 | chat_id = message.text.split()[-1]
205 | if is_admin(message.from_user.id):
206 | try:
207 | await client.send_message(int(chat_id),
208 | _config["msg_leave_msg"])
209 | await client.leave_chat(int(chat_id), True)
210 | except RPCError:
211 | await message.reply("指令出错了!可能是bot不在参数所在群里。")
212 | else:
213 | await message.reply("已离开群组: `" + chat_id + "`", )
214 | _me: User = await client.get_me()
215 | try:
216 | await client.send_message(
217 | int(_channel),
218 | _config["msg_leave_group"].format(
219 | groupid=chat_id,
220 | ))
221 | except Exception as e:
222 | logging.error(str(e))
223 | else:
224 | pass
225 |
226 | @app.on_message(filters.command("clean") & filters.private)
227 | async def clean_database(client: Client, message: Message):
228 | if is_admin(message.from_user.id):
229 | failed_count = success_count = 0
230 | deleted_users = []
231 | user_id_list = db.get_all_user_ids()
232 | estimated_time = timedelta(seconds=int(len(user_id_list) / 4))
233 | await message.reply("开始整理数据库,请稍等...\n预计需要时间:{}".format(estimated_time))
234 | for x in user_id_list:
235 | try:
236 | user = await client.get_users(x)
237 | except BadRequest:
238 | deleted_users.append(x)
239 | failed_count += 1
240 | continue
241 | if user.is_deleted:
242 | deleted_users.append(x)
243 | # 因为 db 用的是 executemany ,得传一个 tuple 进去,所以必须得这么写,不知道有没有更好的方法
244 | success_count += 1
245 | db.delete_users_by_id(deleted_users)
246 | await message.reply(
247 | "已成功清除{}个已经删号的用户,共有{}个用户信息获取失败。".format(success_count, failed_count))
248 | else:
249 | logging.info("Permission denied, admin users in config are:" + str(_admin_users))
250 | return
251 |
252 | @app.on_message(filters.command("faset") & filters.group)
253 | async def set_config(client: Client, message: Message):
254 | if message.from_user is None:
255 | await message.reply("请从个人账号发送指令。")
256 | return
257 | chat_id = message.chat.id
258 | group_config = get_group_config(chat_id)
259 | user_id = message.from_user.id
260 | admins = []
261 | async for m in client.get_chat_members(chat_id, filter=ChatMembersFilter.ADMINISTRATORS):
262 | admins.append(m)
263 | help_message = "使用方法:\n" \
264 | "/faset [配置项] [值]\n\n" \
265 | "配置项:\n" \
266 | "`challenge_failed_action`: 验证失败的动作,值为 `ban` 封禁或 `kick` 踢出\n" \
267 | "`challenge_timeout_action`: 验证超时的动作,值为 `ban` 封禁或 `kick` 踢出\n" \
268 | "`challenge_timeout`: 验证超时时间,单位为秒\n" \
269 | "`challenge_type`: 验证方法,当前可用为数学题 `math` 或 `reCAPTCHA` 谷歌验证码\n" \
270 | "`enable_global_blacklist`: 是否启用全局黑名单,值为 `1` 启用或 `0` 禁用\n" \
271 | "例如: \n" \
272 | "`/faset challenge_type reCAPTCHA`"
273 | if not any([
274 | admin.user.id == user_id and
275 | (admin.status == "creator" or admin.privileges.can_restrict_members)
276 | for admin in admins
277 | ]):
278 | msg = await message.reply(group_config["msg_permission_denied"])
279 | Timer(msg.delete(), 5)
280 | Timer(message.delete(), 5)
281 | return
282 |
283 | args = message.text.split(" ", maxsplit=3)
284 | if len(args) != 3:
285 | await message.reply(help_message)
286 | return
287 | key = args[1]
288 | value = args[2]
289 | try:
290 | db.set_group_config(chat_id, key, value)
291 | await message.reply("配置项设置成功")
292 | except ValueError as e:
293 | await message.reply(str(e))
294 |
295 | @app.on_message(filters.command("report") & filters.group)
296 | async def report_message(client: Client, message: Message):
297 | if message.reply_to_message is None:
298 | await message.reply("请回复一条消息")
299 | return
300 | reply_message = message.reply_to_message
301 | image_url = ""
302 | if reply_message.from_user is not None:
303 | reply_message.chat = await client.get_chat(reply_message.from_user.id)
304 | else:
305 | reply_message.chat = await client.get_chat(reply_message.sender_chat.id)
306 | if reply_message.photo:
307 | file = await client.download_media(reply_message.photo.file_id, in_memory=True)
308 | file_ext = file.name.split('.')[-1]
309 | file_bytes = bytes(file.getbuffer())
310 | image_url = f"data:image/{file_ext};base64,{base64.b64encode(file_bytes).decode('utf-8')}"
311 | print(image_url)
312 | result = await chk_message(api_key="sk-", message=reply_message, image_url=image_url, max_token=512)
313 | if result.possibility > 85:
314 | logging.info(f"AI 判断为垃圾消息,概率为 {result.possibility}%")
315 | await client.ban_chat_member(message.chat.id, reply_message.chat.id if reply_message.from_user is None else reply_message.from_user.id)
316 |
317 | @app.on_message(filters.private & filters.command("sender"))
318 | async def get_message_info(client: Client, message: Message):
319 | # 从参数给出的链接中获取对应的消息例如:https://t.me/SSUnion/1918564
320 | if len(message.command) != 2:
321 | await message.reply("使用方法: /msginfo [message link]")
322 | return
323 | link = message.command[1]
324 | if not link.startswith("https://t.me/"):
325 | await message.reply("链接格式错误")
326 | return
327 | try:
328 | chat_id, message_id = extract_ids(link)
329 | msg = await client.get_messages(chat_id, message_id)
330 | except BadRequest as e:
331 | await message.reply("Bot 不在该群组中")
332 | return
333 | except IndexError:
334 | await message.reply("链接格式错误")
335 | return
336 | except RPCError as e:
337 | logging.exception(e)
338 | await message.reply("获取消息失败: " + str(e))
339 | return
340 | if msg.from_user is None:
341 | await message.reply("未找到消息发送者")
342 | return
343 | else:
344 | fuser = msg.from_user
345 | await message.reply(f"{fuser.mention(str(fuser.id))}\n")
346 |
347 | @app.on_message(filters.private & filters.command("getlog"))
348 | async def get_log(client: Client, message: Message):
349 | if len(message.command) != 2:
350 | await message.reply("使用方法: /getlog [challenge_id]")
351 | return
352 | if not is_admin(message.from_user.id):
353 | return
354 | logs = db.get_logs_by_challenge_id(message.command[1])
355 | if len(logs) == 0:
356 | await message.reply("没有找到相关记录")
357 | return
358 | text = ""
359 | for log in logs:
360 | text += str(log)
361 | text += "\n"
362 | await message.reply(text)
363 |
364 | @app.on_message(filters.private & filters.forwarded)
365 | async def get_user_record(client: Client, message: Message):
366 | if not is_admin(message.from_user.id):
367 | return
368 | if message.forward_from is None:
369 | await message.reply("该消息用户为频道或关闭了消息转发权限")
370 | return
371 | user_id = message.forward_from.id
372 | logs = db.get_logs_by_user_id(user_id)
373 | if len(logs) == 0:
374 | await message.reply("没有找到相关记录")
375 | return
376 | text = ""
377 | for log in logs:
378 | text += str(log)
379 | text += "\n"
380 | await message.reply(text)
381 |
382 | @app.on_message(filters.group | filters.service)
383 | # delete service message and message send from pending validation user
384 | async def delete_service_message(client: Client, message: Message):
385 | service_message_need_delete = [MessageServiceType.NEW_CHAT_MEMBERS, MessageServiceType.LEFT_CHAT_MEMBERS]
386 | if message.service:
387 | if message.service in service_message_need_delete:
388 | try:
389 | await message.delete()
390 | except MessageDeleteForbidden:
391 | pass
392 | return
393 | else:
394 | return
395 | if not message.from_user:
396 | # 频道发言不判断
397 | return
398 | await asyncio.sleep(1) # 延迟2秒再判断
399 | if not _current_challenges.data:
400 | # 如果当前没有验证任务,就不用判断了
401 | return
402 | chat_id, user = message.chat.id, message.from_user
403 | if _current_challenges.is_duplicate(user.id, chat_id):
404 | await message.delete()
405 | await client.send_message(chat_id=_channel,
406 | text=_config["msg_message_deleted"].format(
407 | targetuserid=str(user.id),
408 | messageid=str(message.id),
409 | groupid=str(chat_id),
410 | grouptitle=str(message.chat.title),
411 | ))
412 | return
413 |
414 | @app.on_chat_join_request()
415 | async def on_chat_join_request(client: Client, message: Message):
416 | user_id = message.from_user.id
417 | chat_id = message.chat.id
418 | group_config = get_group_config(message.chat.id)
419 | challenge_id = "{chat}|{userid}".format(chat=message.chat.id, userid=user_id)
420 |
421 | challenge_data = _current_challenges.get(challenge_id)
422 |
423 | if challenge_data:
424 | return # 如果已经有验证任务了,就不再触发这个流程
425 | # reCAPTCHA 验证 ----------------------------------------------------------------------------------------------
426 | if group_config['challenge_type'] == ChallengeType.recaptcha:
427 | challenge = ReCAPTCHA()
428 | timeout = group_config["challenge_timeout"]
429 | try:
430 | reply_message = await client.send_message(chat_id=user_id, text=f"请在{timeout}秒内点击下方按钮完成验证,您需要使用浏览器来完成,如果您在访问页面时出现问题,请尝试关闭的匿名代理\n\n",
431 | reply_markup=InlineKeyboardMarkup(challenge.generate_auth_button()))
432 |
433 | challenge.message = reply_message
434 | except UserIsBlocked:
435 | await client.send_message(chat_id=_channel,
436 | text=f"用户 `{user_id}` 屏蔽了机器人,无法发送验证消息")
437 | pass
438 | else: # 验证码验证 -------------------------------------------------------------------------------------------
439 | challenge = Math()
440 | timeout = group_config["challenge_timeout"]
441 | try:
442 | reply_message = await client.send_message(
443 | user_id,
444 | group_config["msg_challenge_math_private"].format(challenge=challenge.qus(), timeout=timeout),
445 | reply_markup=InlineKeyboardMarkup(
446 | challenge.generate_join_request_button(chat_id=chat_id)),
447 | )
448 | challenge.message = reply_message
449 | except UserIsBlocked:
450 | pass
451 | # 开始计时 -----------------------------------------------------------------------------------------------------
452 | timeout_event = Timer(
453 | join_request_challenge_timeout(client, message),
454 | timeout=group_config["challenge_timeout"],
455 | )
456 | _current_challenges[challenge_id] = (challenge, message.from_user.id, timeout_event)
457 |
458 | @app.on_chat_member_updated()
459 | async def challenge_user(client: Client, message: ChatMemberUpdated):
460 | if message.via_join_request:
461 | return # 从 request 加入的用户不触发这个流程
462 | # 过滤掉非用户加群消息和频道新用户消息,同时确保 form_user 这个参数不是空的
463 | if not bool(message.new_chat_member) or bool(message.old_chat_member) or message.chat.type == ChatType.CHANNEL:
464 | return
465 | # 过滤掉管理员 ban 掉用户产生的加群消息 (Durov 这什么 jb api 赶紧分遗产了)
466 | if message.from_user.id != message.new_chat_member.user.id and not message.new_chat_member.status == ChatMemberStatus.MEMBER:
467 | return
468 |
469 | target = message.new_chat_member.user
470 | group_config = get_group_config(message.chat.id)
471 | chat_id = message.chat.id
472 | user_id = target.id
473 |
474 | # 黑名单部分----------------------------------------------------------------------------------------------------
475 | if group_config["enable_global_blacklist"]:
476 | db_user = db.get_user(user_id)
477 | if db_user:
478 | current_time = datetime.now()
479 | since_last_attempt = (current_time - db_user.last_attempt).total_seconds()
480 | if since_last_attempt > group_config[
481 | "global_timeout_user_blacklist_remove"]:
482 |
483 | # 存进 current_challenge 里面一小会,以供消息删除使用
484 | challenge = AutoKickCache()
485 | challenge_id = "{chat}|{msg}".format(chat=message.chat.id, msg=None)
486 | timeout_event = Timer(
487 | challenge_timeout(client, message, None),
488 | timeout=5,
489 | )
490 | _current_challenges[challenge_id] = (challenge, message.from_user.id, timeout_event)
491 |
492 | await client.ban_chat_member(chat_id, target.id, until_date=current_time + timedelta(seconds=31))
493 | db.update_last_try(current_time, target.id)
494 | db.try_count_plus_one(target.id)
495 | try_count = int(db.get_try_count(target.id))
496 | try:
497 | await client.send_message(_channel,
498 | text=_config["msg_failed_auto_kick"].format(
499 | targetuserid=str(target.id),
500 | targetusername=str(target.username),
501 | targetfirstname=str(target.first_name),
502 | targetlastname=str(target.last_name),
503 | groupid=str(chat_id),
504 | grouptitle=str(message.chat.title),
505 | lastattempt=str(
506 | db_user.last_attempt.strftime("%Y-%m-%d %H:%M:%S")),
507 | sincelastattempt=str(
508 | timedelta(seconds=since_last_attempt)),
509 | trycount=str(try_count)
510 | ))
511 | except Exception as e:
512 | logging.error(str(e))
513 | return
514 | else:
515 | db.delete_users_by_id(target.id)
516 |
517 | # 入群验证部分--------------------------------------------------------------------------------------------------
518 | # 这里做一个判断让当出 bug 的时候不会重复弹出一车验证消息
519 | ch_id, ch_data = _current_challenges.get_by_user_and_chat_id(user_id, chat_id)
520 | if ch_data:
521 | challenge, target_id, timeout_event = ch_data
522 | # 如果某个 bug 导致了重复的验证,就直接返回, 除非这个验证是 AutoKickCache
523 | if not isinstance(challenge, AutoKickCache):
524 | logging.error(f"重复的验证,用户id:{user_id},群组id:{chat_id}")
525 | return
526 | # 禁言用户 ----------------------------------------------------------------------------------------------------
527 | if message.from_user.id != target.id:
528 | if target.is_self:
529 | try:
530 | await client.send_message(
531 | message.chat.id, group_config["msg_self_introduction"])
532 | _me: User = await client.get_me()
533 | try:
534 | await client.send_message(
535 | int(_channel),
536 | _config["msg_into_group"].format(
537 | groupid=str(message.chat.id),
538 | grouptitle=str(message.chat.title)
539 | )
540 | )
541 | except Exception as e:
542 | logging.error(str(e))
543 | except ChannelPrivate:
544 | return
545 | return
546 | try:
547 | await client.restrict_chat_member(
548 | chat_id=message.chat.id,
549 | user_id=target.id,
550 | permissions=ChatPermissions(can_send_messages=False))
551 | except ChatAdminRequired:
552 | return
553 | except RPCError:
554 | await client.send_message(
555 | message.chat.id,
556 | "当前群组不是超级群组,Bot 无法工作,可能是成员过少。\n请尝试添加更多用户,或者禁言一个用户,让 Telegram 将该群转换为超级群组")
557 | return
558 | # reCAPTCHA 验证 ----------------------------------------------------------------------------------------------
559 |
560 | if group_config['challenge_type'] == ChallengeType.recaptcha:
561 | challenge = ReCAPTCHA()
562 | timeout = group_config["challenge_timeout"]
563 | reply_message = await client.send_message(
564 | message.chat.id,
565 | group_config["msg_challenge_recaptcha"].format(target_id=target.id,
566 | timeout=timeout),
567 | reply_markup=InlineKeyboardMarkup(
568 | challenge.generate_button(group_config, chat_id)),
569 | )
570 | else: # 验证码验证 -------------------------------------------------------------------------------------------
571 | challenge = Math()
572 | timeout = group_config["challenge_timeout"]
573 | reply_message = await client.send_message(
574 | message.chat.id,
575 | group_config["msg_challenge_math"].format(target_id=target.id,
576 | timeout=timeout,
577 | challenge=challenge.qus()),
578 | reply_markup=InlineKeyboardMarkup(
579 | challenge.generate_button(group_config)),
580 | )
581 |
582 | # 开始计时 -----------------------------------------------------------------------------------------------------
583 | challenge.message = reply_message
584 | challenge_id = "{chat}|{msg}".format(chat=message.chat.id, msg=reply_message.id)
585 | timeout_event = Timer(
586 | challenge_timeout(client, message, reply_message.id),
587 | timeout=group_config["challenge_timeout"],
588 | )
589 | _current_challenges[challenge_id] = (challenge, message.from_user.id, timeout_event)
590 |
591 | @app.on_callback_query(private_math_challenge_filter)
592 | async def private_math_challenge_callback(client: Client, callback_query: CallbackQuery):
593 | query_data = str(callback_query.data)
594 | query_id = callback_query.id
595 | chat_id = query_data.split("|")[1]
596 | answer = query_data.split("|")[0]
597 | user_id = callback_query.from_user.id
598 | msg_id = callback_query.message.id
599 | chat = await client.get_chat(chat_id)
600 | chat_title = chat.title
601 | user_username = callback_query.from_user.username
602 | user_first_name = callback_query.from_user.first_name
603 | user_last_name = callback_query.from_user.last_name
604 | group_config = get_group_config(chat_id)
605 |
606 | # 获取验证信息-----------------------------------------------------------------------------------------------
607 | ch_id = f"{chat.id}|{user_id}"
608 | challenge_data = _current_challenges.get(ch_id)
609 |
610 | if challenge_data is None:
611 | logging.error("challenge not found, challenge_id: {}".format(ch_id))
612 | return
613 | else:
614 | challenge, target_id, timeout_event = challenge_data
615 |
616 | # 响应用户操作------------------------------------------------------------------------------------------------
617 | _current_challenges.delete(ch_id)
618 |
619 | correct = str(challenge.ans()) == answer
620 | if correct:
621 | await client.approve_chat_join_request(chat_id, user_id)
622 | await client.edit_message_text(
623 | user_id,
624 | msg_id,
625 | group_config["msg_challenge_passed"],
626 | reply_markup=None)
627 | await client.send_message(
628 | int(_channel),
629 | _config["msg_passed_answer"].format(
630 | targetuserid=str(target_id),
631 | groupid=str(chat_id),
632 | grouptitle=str(chat_title),
633 | )
634 | )
635 | else:
636 | await client.edit_message_text(
637 | user_id,
638 | msg_id,
639 | group_config["msg_challenge_failed"],
640 | reply_markup=None,
641 | )
642 | await client.send_message(
643 | int(_channel),
644 | _config["msg_failed_answer"].format(
645 | targetuserid=str(target_id),
646 | groupid=str(chat_id),
647 | grouptitle=str(chat_title),
648 | )
649 | )
650 | await client.decline_chat_join_request(chat_id, user_id)
651 |
652 |
653 |
654 | @app.on_callback_query(admin_operate_filter)
655 | async def admin_operate_callback(client: Client, callback_query: CallbackQuery):
656 | query_data = str(callback_query.data)
657 | query_id = callback_query.id
658 | chat_id = callback_query.message.chat.id
659 | user_id = callback_query.from_user.id
660 | msg_id = callback_query.message.id
661 | chat_title = callback_query.message.chat.title
662 | user_username = callback_query.from_user.username
663 | user_first_name = callback_query.from_user.first_name
664 | user_last_name = callback_query.from_user.last_name
665 | group_config = get_group_config(chat_id)
666 |
667 | # 获取验证信息-----------------------------------------------------------------------------------------------
668 |
669 | ch_id = "{chat}|{msg}".format(chat=chat_id, msg=msg_id)
670 | challenge_data = _current_challenges.get(ch_id)
671 |
672 | if challenge_data is None:
673 | logging.error("challenge not found, challenge_id: {}".format(ch_id))
674 | return
675 | else:
676 | challenge, target_id, timeout_event = challenge_data
677 |
678 | # 响应管理员操作------------------------------------------------------------------------------------------------
679 |
680 | if query_data in ["+", "-"]:
681 | admins = []
682 | async for m in client.get_chat_members(chat_id, filter=ChatMembersFilter.ADMINISTRATORS):
683 | admins.append(m)
684 | if not any([
685 | admin.user.id == user_id and
686 | (admin.status == "creator" or admin.privileges.can_restrict_members)
687 | for admin in admins
688 | ]):
689 | await client.answer_callback_query(
690 | query_id, group_config["msg_permission_denied"])
691 | return
692 | _current_challenges.delete(ch_id)
693 | timeout_event.stop()
694 | if query_data == "+":
695 | try:
696 | await client.restrict_chat_member(
697 | chat_id,
698 | target_id,
699 | permissions=ChatPermissions(
700 | can_send_messages=True,
701 | can_send_media_messages=True,
702 | can_send_other_messages=True,
703 | can_send_polls=True,
704 | can_add_web_page_previews=True,
705 | can_change_info=True,
706 | can_invite_users=True,
707 | can_pin_messages=True))
708 | except ChatAdminRequired:
709 | await client.answer_callback_query(
710 | query_id, group_config["msg_bot_no_permission"])
711 | return
712 |
713 | await client.edit_message_text(
714 | chat_id,
715 | msg_id,
716 | group_config["msg_approved"].format(user=user_first_name),
717 | reply_markup=None,
718 | )
719 | _me: User = await client.get_me()
720 | try:
721 | await client.send_message(
722 | int(_channel),
723 | _config["msg_passed_admin"].format(
724 | targetuserid=str(target_id),
725 | groupid=str(chat_id),
726 | grouptitle=str(chat_title),
727 | )
728 | )
729 | except Exception as e:
730 | logging.error(str(e))
731 | else:
732 | try:
733 | await client.ban_chat_member(chat_id, target_id)
734 | except ChatAdminRequired:
735 | await client.answer_callback_query(
736 | query_id, group_config["msg_bot_no_permission"])
737 | return
738 | await client.edit_message_text(
739 | chat_id,
740 | msg_id,
741 | group_config["msg_refused"].format(user=user_first_name),
742 | reply_markup=None,
743 | )
744 | Timer(
745 | client.delete_messages(chat_id, msg_id),
746 | group_config["delete_failed_challenge_interval"]
747 | )
748 | _me: User = await client.get_me()
749 | try:
750 | await client.send_message(
751 | int(_channel),
752 | _config["msg_failed_admin"].format(
753 | targetuserid=str(target_id),
754 | groupid=str(chat_id),
755 | grouptitle=str(chat_title),
756 | )
757 | )
758 | except Exception as e:
759 | logging.error(str(e))
760 | await client.answer_callback_query(query_id)
761 | return
762 |
763 | @app.on_callback_query()
764 | async def challenge_answer_callback(client: Client, callback_query: CallbackQuery):
765 | query_data = str(callback_query.data)
766 | query_id = callback_query.id
767 | chat_id = callback_query.message.chat.id
768 | user_id = callback_query.from_user.id
769 | msg_id = callback_query.message.id
770 | chat_title = callback_query.message.chat.title
771 | user_username = callback_query.from_user.username
772 | user_first_name = callback_query.from_user.first_name
773 | user_last_name = callback_query.from_user.last_name
774 | group_config = get_group_config(chat_id)
775 |
776 | # 获取验证信息-----------------------------------------------------------------------------------------------
777 |
778 | ch_id = "{chat}|{msg}".format(chat=chat_id, msg=msg_id)
779 |
780 | challenge_data = _current_challenges.get(ch_id)
781 |
782 | if challenge_data is None:
783 | logging.error("challenge not found, challenge_id: {}".format(ch_id))
784 | return
785 | else:
786 | challenge, target_id, timeout_event = challenge_data
787 |
788 | # 让捣蛋的一边玩去 ---------------------------------------------------------------------------------
789 |
790 | if user_id != target_id:
791 | await client.answer_callback_query(
792 | query_id, group_config["msg_challenge_not_for_you"])
793 | return None
794 | timeout_event.stop()
795 |
796 | # 分析的没错的话这里应该是先给用户解开再根据回答对错处理 -----------------------------------------------------------
797 |
798 | try:
799 | await client.restrict_chat_member(
800 | chat_id,
801 | target_id,
802 | permissions=ChatPermissions(
803 | can_send_messages=True,
804 | can_send_media_messages=True,
805 | can_send_other_messages=True,
806 | can_send_polls=True,
807 | can_add_web_page_previews=True,
808 | can_change_info=True,
809 | can_invite_users=True,
810 | can_pin_messages=True))
811 | except ChatAdminRequired:
812 | pass
813 |
814 | _current_challenges.delete(ch_id)
815 |
816 | correct = str(challenge.ans()) == query_data
817 | if correct:
818 | try:
819 | await client.edit_message_text(
820 | chat_id,
821 | msg_id,
822 | group_config["msg_challenge_passed"],
823 | reply_markup=None)
824 | except MessageNotModified as e:
825 | await client.send_message(int(_channel),
826 | 'Bot 运行时发生异常: `' + str(e) + "`")
827 | try:
828 | await client.send_message(
829 | int(_channel),
830 | _config["msg_passed_answer"].format(
831 | targetuserid=str(target_id),
832 | groupid=str(chat_id),
833 | grouptitle=str(chat_title),
834 | )
835 | )
836 | except Exception as e:
837 | logging.error(str(e))
838 | else:
839 | try:
840 | await client.edit_message_text(
841 | chat_id,
842 | msg_id,
843 | group_config["msg_challenge_failed"],
844 | reply_markup=None,
845 | )
846 | try:
847 | await client.send_message(
848 | int(_channel),
849 | _config["msg_failed_answer"].format(
850 | targetuserid=str(target_id),
851 | groupid=str(chat_id),
852 | grouptitle=str(chat_title),
853 | )
854 | )
855 | except Exception as e:
856 | logging.error(str(e))
857 | except ChatAdminRequired:
858 | return
859 |
860 | if group_config["challenge_failed_action"] == FailedAction.ban:
861 | await client.ban_chat_member(chat_id, user_id)
862 | else:
863 | # kick
864 | await client.ban_chat_member(chat_id, user_id, until_date=datetime.now() + timedelta(seconds=31))
865 | logging.info(f"{user_id} unbanned")
866 |
867 | if group_config["delete_failed_challenge"]:
868 | Timer(
869 | client.delete_messages(chat_id, msg_id),
870 | group_config["delete_failed_challenge_interval"],
871 | )
872 | if group_config["delete_passed_challenge"]:
873 | Timer(
874 | client.delete_messages(chat_id, msg_id),
875 | group_config["delete_passed_challenge_interval"],
876 | )
877 |
878 | async def join_request_challenge_timeout(client: Client, message):
879 | chat_id = message.chat.id
880 | user_id = message.from_user.id
881 | chat_title = message.chat.title
882 | user_username = message.from_user.username
883 | user_first_name = message.from_user.first_name
884 | user_last_name = message.from_user.last_name
885 | ch_id = f"{chat_id}|{user_id}"
886 | challenge_data = _current_challenges.get(ch_id)
887 |
888 | if challenge_data is None:
889 | logging.error("challenge not found, challenge_id: {}".format(ch_id))
890 | return
891 | else:
892 | challenge, target_id, timeout_event = challenge_data
893 | _current_challenges.delete(f"{chat_id}|{user_id}")
894 | await client.decline_chat_join_request(chat_id, user_id)
895 | if challenge.message is not None:
896 | await client.edit_message_text(chat_id=user_id,
897 | message_id=challenge.message.id,
898 | text="验证已超时,请重新加群尝试",
899 | reply_markup=None)
900 | await client.send_message(chat_id=_channel,
901 | text=_config["msg_failed_timeout"].format(
902 | targetuserid=str(user_id),
903 | targetusername=str(user_username),
904 | targetfirstname=str(user_first_name),
905 | targetlastname=str(user_last_name),
906 | groupid=str(chat_id),
907 | grouptitle=str(chat_title)
908 | ))
909 |
910 |
911 | async def challenge_timeout(client: Client, message, reply_id):
912 | chat_id = message.chat.id
913 | from_id = message.from_user.id
914 | chat_title = message.chat.title
915 | user_username = message.from_user.username
916 | user_first_name = message.from_user.first_name
917 | user_last_name = message.from_user.last_name
918 | group_config = get_group_config(chat_id)
919 | _current_challenges.delete("{chat}|{msg}".format(chat=chat_id,
920 | msg=reply_id))
921 | if reply_id is None:
922 | # 删除黑名单缓存
923 | return
924 |
925 | # TODO try catch
926 | await client.edit_message_text(
927 | chat_id=chat_id,
928 | message_id=reply_id,
929 | text=group_config["msg_challenge_failed"],
930 | reply_markup=None,
931 | )
932 |
933 | await client.send_message(chat_id=_channel,
934 | text=_config["msg_failed_timeout"].format(
935 | targetuserid=str(from_id),
936 | targetusername=str(user_username),
937 | targetfirstname=str(user_first_name),
938 | targetlastname=str(user_last_name),
939 | groupid=str(chat_id),
940 | grouptitle=str(chat_title)
941 | ))
942 |
943 | if group_config["challenge_timeout_action"] == FailedAction.ban:
944 | await client.ban_chat_member(chat_id, from_id)
945 | elif group_config["challenge_timeout_action"] == FailedAction.kick:
946 | await client.ban_chat_member(chat_id, from_id, until_date=datetime.now() + timedelta(seconds=31))
947 | logging.info(f"{from_id} unbanned")
948 | else:
949 | pass
950 |
951 | if group_config["delete_failed_challenge"]:
952 | Timer(
953 | client.delete_messages(chat_id, reply_id),
954 | group_config["delete_failed_challenge_interval"],
955 | )
956 |
957 | if group_config["enable_global_blacklist"]:
958 | db.new_blacklist(datetime.now(), from_id)
959 |
960 | def _main():
961 | # db.setup()
962 | global _channel, _start_message, _config
963 | load_config()
964 | _start_message = _config["msg_start_message"]
965 | _proxy_ip = _config["proxy_addr"].strip()
966 | _proxy_port = _config["proxy_port"].strip()
967 | if _proxy_ip and _proxy_port:
968 | _app = Client("bot",
969 | bot_token=_token,
970 | api_id=_api_id,
971 | api_hash=_api_hash,
972 | proxy=dict(hostname=_proxy_ip, port=int(_proxy_port)))
973 | else:
974 | _app = Client("bot",
975 | bot_token=_token,
976 | api_id=_api_id,
977 | api_hash=_api_hash)
978 | try:
979 | # start web
980 | tt = threading.Thread(
981 | target=start_web, name="WebThread", args=(_app,))
982 | tt.daemon = True
983 | logging.info('Starting webapi ....')
984 | tt.start()
985 |
986 | # start bot
987 | _update(_app)
988 | _app.run()
989 | except KeyboardInterrupt:
990 | quit()
991 | except Exception as e:
992 | logging.error(e)
993 | _main()
994 |
995 |
996 | if __name__ == "__main__":
997 | _main()
--------------------------------------------------------------------------------
/model.py:
--------------------------------------------------------------------------------
1 | from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean, Text, BigInteger
2 | from sqlalchemy.orm import relationship, validates
3 | from sqlalchemy.ext.declarative import declarative_base
4 | from datetime import datetime
5 | from enum import StrEnum
6 |
7 | Base = declarative_base()
8 |
9 |
10 | class ChallengeType(StrEnum):
11 | recaptcha = "recaptcha"
12 | math = "math"
13 |
14 |
15 | class FailedAction(StrEnum):
16 | ban = "ban"
17 | kick = "kick"
18 | mute = "mute"
19 |
20 |
21 | class RecaptchaLogAction(StrEnum):
22 | PageVisit = "PageVisit"
23 | Failed = "Failed"
24 | Passed = "Passed"
25 |
26 |
27 | class BlacklistUser(Base):
28 | __tablename__ = 'blacklist_user'
29 | user_id = Column(BigInteger, primary_key=True, unique=True, nullable=False)
30 | last_attempt = Column(DateTime, nullable=False, default=datetime.now)
31 | attempt_count = Column(Integer, nullable=False, default=1)
32 | created_at = Column(DateTime, default=datetime.now)
33 | updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
34 |
35 | def __repr__(self):
36 | return "" % (
37 | self.user_id, self.last_attempt, self.attempt_count, self.created_at, self.updated_at)
38 |
39 |
40 | class GroupConfig(Base):
41 | __tablename__ = 'group_config'
42 | chat_id = Column(BigInteger, primary_key=True, unique=True, nullable=False)
43 | timeout = Column(Integer, nullable=False, default=300)
44 | challenge_type = Column(String(10), nullable=False, default=ChallengeType.recaptcha)
45 | failed_action = Column(String(10), nullable=False, default=FailedAction.kick)
46 | timeout_action = Column(String(10), nullable=False, default=FailedAction.kick)
47 | third_party_blacklist = Column(Boolean, nullable=False, default=False)
48 | global_blacklist = Column(Boolean, nullable=False, default=True)
49 |
50 | @validates('challenge_type')
51 | def validate_challenge_type(self, key, challenge_type):
52 | if challenge_type not in (m.value for m in ChallengeType):
53 | raise ValueError(f"Invalid challenge type value: {challenge_type}")
54 | return challenge_type
55 |
56 | @validates('failed_action')
57 | def validate_failed_action(self, key, failed_action):
58 | if failed_action not in (m.value for m in FailedAction):
59 | print(failed_action)
60 | raise ValueError(f"Invalid failed action value: {failed_action}")
61 | return failed_action
62 |
63 | @validates('timeout_action')
64 | def validate_timeout_action(self, key, timeout_action):
65 | if timeout_action not in (m.value for m in FailedAction):
66 | raise ValueError(f"Invalid timeout action value: {timeout_action}")
67 | return timeout_action
68 |
69 | @validates('third_party_blacklist')
70 | def validate_third_party_blacklist(self, key, third_party_blacklist):
71 | if not isinstance(third_party_blacklist, bool):
72 | raise ValueError(f"Invalid third party blacklist value: {third_party_blacklist}")
73 | return third_party_blacklist
74 |
75 | @validates('global_blacklist')
76 | def validate_global_blacklist(self, key, global_blacklist):
77 | if not isinstance(global_blacklist, bool):
78 | raise ValueError(f"Invalid global blacklist value: {global_blacklist}")
79 | return global_blacklist
80 |
81 | def __repr__(self):
82 | return "" % (
83 | self.chat_id, self.timeout, self.challenge_type, self.failed_action, self.timeout_action,
84 | self.third_party_blacklist, self.global_blacklist)
85 |
86 |
87 | class RecaptchaLog(Base):
88 | __tablename__ = 'recaptcha_log'
89 | id = Column(Integer, primary_key=True, unique=True, nullable=False)
90 | group_id = Column(BigInteger, nullable=False)
91 | user_id = Column(BigInteger, nullable=False)
92 | challenge_id = Column(String(64), nullable=False)
93 | ip_addr = Column(String(64), nullable=False)
94 | user_agent = Column(Text, nullable=False)
95 | action = Column(String(20), nullable=False)
96 | created_at = Column(DateTime, default=datetime.now)
97 | updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
98 |
99 | def __repr__(self):
100 | return "" % (
101 | self.id, self.group_id, self.user_id, self.challenge_id, self.ip_addr, self.user_agent, self.action,
102 | self.created_at, self.updated_at)
103 |
104 | def __str__(self):
105 | return f"IP地址: `{self.ip_addr}`\nUA:`{self.user_agent}`\n状态:`{self.action}`\n时间:`{self.created_at}`\n"
106 |
107 | #
108 | # class AIConfig(Base):
109 | # chat_id = Column(BigInteger, primary_key=True, unique=True, nullable=False)
110 | # openai_api_key = Column(String(64), nullable=False)
111 | # admin_id = Column(BigInteger, nullable=False)
112 | # first_message_check = Column(Boolean, nullable=False, default=False)
113 | # report_message_check = Column(Boolean, nullable=False, default=False)
114 | #
115 | # created_at = Column(DateTime, default=datetime.now)
116 | # updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
117 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NimaQu/Telegram-CAPTCHA-bot-pyrogram/a1474de85f8d7d8054d1ac8d3edbe5bf0f3aa019/requirements.txt
--------------------------------------------------------------------------------
/templates/index.html:
--------------------------------------------------------------------------------
1 | Hello World!
--------------------------------------------------------------------------------
/templates/recaptcha.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 完成验证
6 |
7 |
26 |
27 |
29 |
30 |
39 | {% with messages = get_flashed_messages(category_filter='error') %}
40 | {% if messages %}
41 |
42 | {% for message in messages %}
43 | {{ message }}
44 | {% endfor %}
45 |
46 | {% endif %}
47 | {% endwith %}
48 |
49 |
--------------------------------------------------------------------------------
/templates/result.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 验证结果页
6 |
13 |
15 |
16 |
17 | {% with messages = get_flashed_messages() %}
18 | {% if messages %}
19 |
20 | {% for message in messages %}
21 | {{ message }}
22 | {% endfor %}
23 |
24 | {% endif %}
25 | {% endwith %}
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/test.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 |
4 | def test_halal(text: str, max_halal_char_threshold: int, max_halal_pct_threshold: float) -> bool:
5 | # 移除空白字符(包括 \s、\uFEFF、\xA0 等)
6 | # 若需要移除更多类型的空白符,可自行扩展正则
7 | pattern = re.compile(r'[\s\uFEFF\xA0]+')
8 | cleaned_text = pattern.sub('', text)
9 |
10 | length = len(cleaned_text)
11 | if length == 0:
12 | # 根据业务逻辑决定空字符串是否视为“符合”或“不符合”
13 | return False
14 |
15 | count = 0
16 | for ch in cleaned_text:
17 | code = ord(ch)
18 | # 对应 JS 中的 switch(true) case 范围判断
19 | if (0x600 <= code <= 0x6FF or
20 | 0x750 <= code <= 0x77F or
21 | 0x8A0 <= code <= 0x8FF or
22 | 0x900 <= code <= 0x97F or
23 | 0x600 <= code <= 0x6FF or # 原 JS 代码中重复的一段,保留
24 | 0xA8E0 <= code <= 0xA8FF or
25 | 0xFB50 <= code <= 0xFDFF or
26 | 0xFE70 <= code <= 0xFEFF):
27 | count += 1
28 |
29 | # 若达到字符计数阈值,直接返回 True
30 | if count >= max_halal_char_threshold:
31 | return True
32 |
33 | # 若占比达到百分比阈值,也返回 True
34 | if (count / length) >= max_halal_pct_threshold:
35 | return True
36 |
37 | return False
38 |
39 |
40 | # 示例调用
41 | if __name__ == "__main__":
42 | test_string = "محمود سيد"
43 | max_char_threshold = 3
44 | max_pct_threshold = 0.5
45 |
46 | result = test_halal(test_string, max_char_threshold, max_pct_threshold)
47 | print("Result:", result)
48 |
--------------------------------------------------------------------------------
/web.py:
--------------------------------------------------------------------------------
1 | from pyrogram.errors import ChatAdminRequired, MessageNotModified
2 | from pyrogram.filters import private
3 | from pyrogram.types import ChatPermissions
4 | from pyrogram import Client
5 | import logging
6 | from flask import Flask, request, flash
7 | from flask import render_template
8 | from challengedata import ChallengeData
9 | import dbhelper as db
10 |
11 | app = Flask(__name__)
12 | client: Client = None
13 | _current_challenges = ChallengeData()
14 | _config = dict()
15 | _channel = 0
16 |
17 |
18 | @app.route("/")
19 | def root():
20 | return render_template('index.html')
21 |
22 |
23 | @app.route("/recaptcha", methods=["GET", "POST"])
24 | async def verify():
25 | # 测试模板用-----------------------------------------------------
26 | # return render_template('recaptcha.html', sitekey=114514)
27 | # 测试模板用-----------------------------------------------------
28 |
29 | if request.args.get('challenge') is None:
30 | flash("没有这条验证数据!", "error")
31 | return render_template('result.html')
32 | else:
33 | challenge_id = request.args.get('challenge')
34 | try:
35 | ch_id, challenge_data = _current_challenges.get_by_challenge_id(challenge_id)
36 | except TypeError:
37 | flash("没有这条验证数据!", "error")
38 | return render_template('result.html')
39 |
40 | if challenge_data is None or ch_id is None:
41 | flash("没有这条验证数据!", "error")
42 | return render_template('result.html')
43 |
44 | challenge, target_id, timeout_event = challenge_data
45 | join_request = False
46 | if challenge.message.chat.id == target_id:
47 | chat_id = ch_id.split("|")[0]
48 | chat = await client.get_chat(chat_id)
49 | chat_title = chat.title
50 | join_request = True
51 | else:
52 | chat_id = challenge.message.chat.id
53 | chat_title = challenge.message.chat.title
54 | msg_id = challenge.message.id
55 | user_ip = request.headers.get('CF-Connecting-IP', request.remote_addr)
56 | ua = request.headers.get('User-Agent')
57 |
58 | group_config = _config.get(str(chat_id), _config["*"])
59 |
60 | if request.method == "POST":
61 | captcha_response = request.form['g-recaptcha-response']
62 | if not challenge.verify(captcha_response, user_ip):
63 | flash('验证状态异常,请再试一次!', 'error')
64 | return render_template('recaptcha.html', sitekey=challenge.site_key)
65 | else:
66 | timeout_event.stop()
67 | try:
68 | if not join_request:
69 | await client.restrict_chat_member(
70 | chat_id,
71 | target_id,
72 | permissions=ChatPermissions(
73 | can_send_messages=True,
74 | can_send_media_messages=True,
75 | can_send_other_messages=True,
76 | can_send_polls=True,
77 | can_add_web_page_previews=True,
78 | can_change_info=True,
79 | can_invite_users=True,
80 | can_pin_messages=True))
81 | else:
82 | await client.approve_chat_join_request(chat_id, target_id)
83 | except ChatAdminRequired:
84 | pass
85 |
86 | _current_challenges.delete(ch_id)
87 |
88 | try:
89 | await client.send_message(
90 | int(_channel),
91 | _config["msg_passed_answer"].format(
92 | targetuserid=str(target_id),
93 | groupid=str(chat_id),
94 | grouptitle=str(chat_title),
95 | ) + f"\n验证ID: `{challenge_id}`")
96 |
97 | db.log_recaptcha(challenge_id=challenge_id,
98 | user_id=target_id,
99 | chat_id=chat_id,
100 | ip_addr=user_ip,
101 | user_agent=ua,
102 | action=db.RecaptchaLogAction.Passed)
103 | except Exception as e:
104 | logging.error(str(e))
105 |
106 | if group_config["delete_passed_challenge"] and not join_request:
107 | await client.delete_messages(chat_id, msg_id)
108 | else:
109 | try:
110 | await client.edit_message_text(
111 | chat_id=chat_id if not join_request else target_id,
112 | message_id=msg_id,
113 | text=group_config["msg_challenge_passed"],
114 | reply_markup=None)
115 | except MessageNotModified as e:
116 | await client.send_message(int(_channel),
117 | 'Bot 运行时发生异常: `' + str(e) + "`")
118 | flash('您已通过验证,欢迎加入本群!如果仍然无法发言,请重启 Telegram 客户端。')
119 | return render_template('result.html')
120 | else:
121 | try:
122 | db.log_recaptcha(challenge_id=challenge_id,
123 | user_id=target_id,
124 | chat_id=chat_id,
125 | ip_addr=user_ip,
126 | user_agent=ua,
127 | action=db.RecaptchaLogAction.PageVisit)
128 | except Exception as e:
129 | logging.error(e)
130 | return render_template('recaptcha.html', sitekey=challenge.site_key)
131 |
132 |
133 | if __name__ == '__main__':
134 | app.debug = True
135 | app.env = 'debug'
136 | app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
137 | app.run(port=5000, host="127.0.0.1")
138 |
--------------------------------------------------------------------------------