├── LICENSE
├── MANIFEST.in
├── README.md
├── compiler
├── __init__.py
├── api
│ ├── api.json
│ └── api.min.json
├── build_api.py
├── build_methods.py
├── build_types.py
└── templates
│ ├── base.tmpl
│ ├── init.tmpl
│ ├── method_class.tmpl
│ ├── methods.tmpl
│ ├── type_class.tmpl
│ └── types.tmpl
├── examples
├── callback.py
└── echobot.py
├── requirements.txt
├── setup.py
├── tests
└── methods.typed
└── tgrambot
├── __init__.py
├── bot.py
├── dispatcher.py
├── errors
├── __init__.py
└── telegram_error.py
├── filters.py
├── handlers
├── __init__.py
├── callback_handler.py
├── handler.py
├── inlinequery_handler.py
└── message_handler.py
├── methods.py
├── storage.py
├── text.py
├── types
├── __init__.py
├── base.py
└── tg_types.py
├── utils.py
└── version.txt
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include README.md requirements.txt
2 | recursive-include compiler *.py *.tmpl
3 | recursive-include tgrambot *.py *.txt
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # TGramBot
2 |
3 | TGramBot is a partially auto-generated and asynchronous Minimal [Telegram Bot API](https://core.telegram.org/bots/api) framework in Python for bots
4 |
5 | This library is inspired by a number of other libraries:
6 |
7 | - [Gotgbot](https://github.com/PaulSonOfLars/gotgbot), [telegram-bot-api-spec](https://github.com/PaulSonOfLars/telegram-bot-api-spec) by [Paul Larsen
8 | ](https://github.com/PaulSonOfLars)
9 | - [aiogram](https://github.com/aiogram/aiogram)
10 |
11 | Special thanks to [Paul Larsen
12 | ](https://github.com/PaulSonOfLars) for his libraries
13 |
14 | __**This Library is still in its Alpha phase**__
15 |
16 | Most of the methods and types using in this library are auto-generated by scraping the official documentation of Telegram Bot Api
17 |
18 | So the chance of getting bugs and errors are high. So please let us know through the [issue section](https://github.com/KeralaBots/TGramBot/issues) about the bug you have encountered.
19 |
20 |
21 | ### Installing..
22 |
23 | ```
24 | pip3 install tgrambot
25 | ```
26 |
27 | ### Example
28 |
29 | ```python
30 | import asyncio
31 |
32 | from tgrambot import Bot
33 | from tgrambot.filters import Filters
34 | from tgrambot.types import Message
35 | from tgrambot.text import Italic
36 |
37 |
38 | bot = Bot("token", workers=50, parse_mode='MarkdownV2')
39 |
40 | @bot.on_message(Filters.command('start'))
41 | async def start_bot(c: Bot, m: Message):
42 | await c.send_message(m.chat.id, Italic("Hola Amigo!"))
43 |
44 | async def main():
45 | await bot.run()
46 |
47 | if __name__ == '__main__':
48 | loop = asyncio.get_event_loop()
49 | loop.run_until_complete(main())
50 | ```
51 |
52 | ### Examples
53 |
54 | More examples are published in the [example directory](https://github.com/KeralaBots/TGramBot/tree/alpha/examples)
55 |
--------------------------------------------------------------------------------
/compiler/__init__.py:
--------------------------------------------------------------------------------
1 | from .build_methods import build_methods
2 | from .build_types import build_types
3 | from .build_api import build_api
--------------------------------------------------------------------------------
/compiler/build_api.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 | import re
4 | import string
5 | import shutil
6 | import logging
7 |
8 | import requests
9 | from pathlib import Path
10 | from bs4 import BeautifulSoup
11 | from bs4.element import Tag
12 |
13 | logger = logging.getLogger(__name__)
14 |
15 | TG_CORE_TYPES = ["String", "Boolean", "Integer", "Float"]
16 | ROOT_URL = "https://core.telegram.org"
17 | TO_SCRAPE = {
18 | "api": ROOT_URL + "/bots/api",
19 | }
20 |
21 | API_PATH = Path("compiler/api")
22 |
23 | METHODS = "methods"
24 | TYPES = "types"
25 |
26 | # List of all abstract types which don't have subtypes.
27 | APPROVED_NO_SUBTYPES = {
28 | "InputFile" # This is how telegram represents files
29 | }
30 | # List of all approved multi-returns.
31 | APPROVED_MULTI_RETURNS = [
32 | ['Message', 'Boolean'] # Edit returns either the new message, or an OK to confirm the edit.
33 | ]
34 |
35 |
36 | def retrieve_info(url: str) -> dict:
37 | r = requests.get(url)
38 | soup = BeautifulSoup(r.text, features="html5lib")
39 | dev_rules = soup.find("div", {"id": "dev_page_content"})
40 | curr_type = ""
41 | curr_name = ""
42 |
43 | items = {
44 | METHODS: dict(),
45 | TYPES: dict(),
46 | }
47 |
48 | for x in list(dev_rules.children): # type: Tag
49 | if x.name == "h3" or x.name == "hr":
50 | # New category; clear name and type.
51 | curr_name = ""
52 | curr_type = ""
53 |
54 | if x.name == "h4":
55 | anchor = x.find("a")
56 | name = anchor.get("name")
57 | if name and "-" in name:
58 | curr_name = ""
59 | curr_type = ""
60 | continue
61 |
62 | curr_name, curr_type = get_type_and_name(x, anchor, items, url)
63 |
64 | if not curr_type or not curr_name:
65 | continue
66 |
67 | if x.name == "p":
68 | items[curr_type][curr_name].setdefault("description", []).extend(clean_tg_description(x, url))
69 |
70 | if x.name == "table":
71 | get_fields(curr_name, curr_type, x, items, url)
72 |
73 | if x.name == "ul":
74 | get_subtypes(curr_name, curr_type, x, items, url)
75 |
76 | # Only methods have return types.
77 | # We check this every time just in case the description has been updated, and we have new return types to add.
78 | if curr_type == METHODS and items[curr_type][curr_name].get("description"):
79 | get_method_return_type(curr_name, curr_type, items[curr_type][curr_name].get("description"), items)
80 |
81 | return items
82 |
83 |
84 | def get_subtypes(curr_name: str, curr_type: str, x: Tag, items: dict, url: str):
85 | if curr_name == "InputFile": # Has no interesting subtypes
86 | return
87 |
88 | list_contents = []
89 | for li in x.find_all("li"):
90 | list_contents.extend(clean_tg_description(li, url))
91 |
92 | # List items found in types define possible subtypes.
93 | if curr_type == TYPES:
94 | items[curr_type][curr_name]["subtypes"] = list_contents
95 |
96 | # Always add the list to the description, for better docs.
97 | items[curr_type][curr_name]["description"] += [f"- {s}" for s in list_contents]
98 |
99 |
100 | # Get fields/parameters of type/method
101 | def get_fields(curr_name: str, curr_type: str, x: Tag, items: dict, url: str):
102 | body = x.find("tbody")
103 | fields = []
104 | for tr in body.find_all("tr"):
105 | children = list(tr.find_all("td"))
106 | if curr_type == TYPES and len(children) == 3:
107 | desc = clean_tg_field_description(children[2], url)
108 | fields.append(
109 | {
110 | "name": children[0].get_text(),
111 | "types": clean_tg_type(children[1].get_text()),
112 | "required": not desc.startswith("Optional. "),
113 | "description": desc,
114 | }
115 | )
116 |
117 | elif curr_type == METHODS and len(children) == 4:
118 | fields.append(
119 | {
120 | "name": children[0].get_text(),
121 | "types": clean_tg_type(children[1].get_text()),
122 | "required": children[2].get_text() == "Yes",
123 | "description": clean_tg_field_description(children[3], url)
124 | }
125 | )
126 |
127 | else:
128 | print("An unexpected state has occurred!")
129 | print("Type:", curr_type)
130 | print("Name:", curr_name)
131 | print("Number of children:", len(children))
132 | print(children)
133 | exit(1)
134 |
135 | items[curr_type][curr_name]["fields"] = fields
136 |
137 |
138 | def get_method_return_type(curr_name: str, curr_type: str, description_items: list[str], items: dict):
139 | description = "\n".join(description_items)
140 | ret_search = re.search("(?:on success,|returns)([^.]*)(?:on success)?", description, re.IGNORECASE)
141 | ret_search2 = re.search("([^.]*)(?:is returned)", description, re.IGNORECASE)
142 | if ret_search:
143 | extract_return_type(curr_type, curr_name, ret_search.group(1).strip(), items)
144 | elif ret_search2:
145 | extract_return_type(curr_type, curr_name, ret_search2.group(1).strip(), items)
146 |
147 |
148 | def get_type_and_name(t: Tag, anchor: Tag, items: dict, url: str):
149 | if t.text[0].isupper():
150 | curr_type = TYPES
151 | else:
152 | curr_type = METHODS
153 | curr_name = t.get_text()
154 | items[curr_type][curr_name] = {"name": curr_name}
155 |
156 | href = anchor.get("href")
157 | if href:
158 | items[curr_type][curr_name]["href"] = url + href
159 |
160 | return curr_name, curr_type
161 |
162 |
163 | def extract_return_type(curr_type: str, curr_name: str, ret_str: str, items: dict):
164 | array_match = re.search(r"(?:array of )+(\w*)", ret_str, re.IGNORECASE)
165 | if array_match:
166 | ret = clean_tg_type(array_match.group(1))
167 | rets = [f"Array of {r}" for r in ret]
168 | items[curr_type][curr_name]["returns"] = rets
169 | else:
170 | words = ret_str.split()
171 | rets = [
172 | r for ret in words
173 | for r in clean_tg_type(ret.translate(str.maketrans("", "", string.punctuation)))
174 | if ret[0].isupper()
175 | ]
176 | items[curr_type][curr_name]["returns"] = rets
177 |
178 |
179 | def clean_tg_field_description(t: Tag, url: str) -> str:
180 | return " ".join(clean_tg_description(t, url))
181 |
182 |
183 | def clean_tg_description(t: Tag, url: str) -> list[str]:
184 | # Replace HTML emoji images with actual emoji
185 | for i in t.find_all("img"):
186 | i.replace_with(i.get("alt"))
187 |
188 | # Make sure to include linebreaks, or spacing gets weird
189 | for br in t.find_all("br"):
190 | br.replace_with("\n")
191 |
192 | # Replace helpful anchors with the actual URL.
193 | for a in t.find_all("a"):
194 | anchor_text = a.get_text()
195 | if "»" not in anchor_text:
196 | continue
197 |
198 | link = a.get("href")
199 | # Page-relative URL
200 | if link.startswith("#"):
201 | link = url + link
202 | # Domain-relative URL
203 | elif link.startswith("/"):
204 | link = ROOT_URL + link
205 |
206 | anchor_text = anchor_text.replace(" »", ": " + link)
207 | a.replace_with(anchor_text)
208 |
209 | text = t.get_text()
210 |
211 | # Replace any weird double whitespaces (eg double space, newlines, tabs) with single occurrences
212 | text = re.sub(r"(\s){2,}", r"\1", text)
213 |
214 | # Replace weird UTF-8 quotes with proper quotes
215 | text = text.replace('”', '"').replace('“', '"')
216 |
217 | # Replace weird unicode ellipsis with three dots
218 | text = text.replace("…", "...")
219 |
220 | # Use sensible dashes
221 | text = text.replace(u"\u2013", "-")
222 | text = text.replace(u"\u2014", "-")
223 | # Use sensible single quotes
224 | text = text.replace(u"\u2019", "'")
225 |
226 | # Split on newlines to improve description output.
227 | return [t.strip() for t in text.split("\n") if t.strip()]
228 |
229 |
230 | def get_proper_type(t: str) -> str:
231 | if t == "Messages": # Avoids https://core.telegram.org/bots/api#sendmediagroup
232 | return "Message"
233 |
234 | elif t == "Float number":
235 | return "Float"
236 |
237 | elif t == "Int":
238 | return "Integer"
239 |
240 | elif t == "True" or t == "Bool":
241 | return "Boolean"
242 |
243 | return t
244 |
245 |
246 | def clean_tg_type(t: str) -> list[str]:
247 | pref = ""
248 | if t.startswith("Array of "):
249 | pref = "Array of "
250 | t = t[len("Array of "):]
251 |
252 | fixed_ors = [x.strip() for x in t.split(" or ")] # Fix situations like "A or B"
253 | fixed_ands = [x.strip() for fo in fixed_ors for x in fo.split(" and ")] # Fix situations like "A and B"
254 | fixed_commas = [x.strip() for fa in fixed_ands for x in fa.split(", ")] # Fix situations like "A, B"
255 | return [pref + get_proper_type(x) for x in fixed_commas]
256 |
257 |
258 | # Returns True if an issue is found.
259 | def verify_type_parameters(items: dict) -> bool:
260 | issue_found = False
261 |
262 | for type_name, values in items[TYPES].items():
263 | # check all values have a URL
264 | if not values.get("href"):
265 | print(f"{type_name} has no link!")
266 | issue_found = True
267 | continue
268 |
269 | fields = values.get("fields", [])
270 | if len(fields) == 0:
271 | subtypes = values.get("subtypes", [])
272 | description = "".join(values.get("description", [])).lower()
273 | # Some types are abstract and have no information or subtypes - this is mentioned in their description.
274 | # Otherwise, check if they're manually approved.
275 | if not subtypes and \
276 | not ("currently holds no information" in description or type_name in APPROVED_NO_SUBTYPES):
277 | print("TYPE", type_name, "has no fields or subtypes, and is not approved")
278 | issue_found = True
279 | continue
280 |
281 | for st in subtypes:
282 | if st in items[TYPES]:
283 | items[TYPES][st].setdefault("subtype_of", []).append(type_name)
284 | else:
285 | print("TYPE", type_name, "USES INVALID SUBTYPE", st)
286 | issue_found = True
287 |
288 | # check all parameter types are valid
289 | for param in fields:
290 | field_types = param.get("types")
291 | for field_type_name in field_types:
292 | while field_type_name.startswith("Array of "):
293 | field_type_name = field_type_name[len("Array of "):]
294 |
295 | if field_type_name not in items[TYPES] and field_type_name not in TG_CORE_TYPES:
296 | print("UNKNOWN FIELD TYPE", field_type_name)
297 | issue_found = True
298 |
299 | return issue_found
300 |
301 |
302 | # Returns True if an issue is found.
303 | def verify_method_parameters(items: dict) -> bool:
304 | issue_found = False
305 | # Type check all methods
306 | for method, values in items[METHODS].items():
307 | # check all values have a URL
308 | if not values.get("href"):
309 | print(f"{method} has no link!")
310 | issue_found = True
311 | continue
312 |
313 | # check all methods have a return
314 | returns = values.get("returns")
315 | if not returns:
316 | print(f"{method} has no return types!")
317 | issue_found = True
318 | continue
319 |
320 | # If we have multiple returns, this is an edge case, but not a deal-breaker; check that output.
321 | # Some multi-returns are common and pre-approved.
322 | if len(returns) > 1 and returns not in APPROVED_MULTI_RETURNS:
323 | print(f"{method} has multiple return types: {returns}")
324 |
325 | # check all parameter types are valid
326 | for param in values.get("fields", []):
327 | types = param.get("types")
328 | for t in types:
329 | while t.startswith("Array of "):
330 | t = t[len("Array of "):]
331 |
332 | if t not in items[TYPES] and t not in TG_CORE_TYPES:
333 | issue_found = True
334 | print("UNKNOWN PARAM TYPE", t)
335 |
336 | # check all return types are valid
337 | for ret in values.get("returns", []):
338 | while ret.startswith("Array of "):
339 | ret = ret[len("Array of "):]
340 |
341 | if ret not in items[TYPES] and ret not in TG_CORE_TYPES:
342 | issue_found = True
343 | print("UNKNOWN RETURN TYPE", ret)
344 |
345 | return issue_found
346 |
347 |
348 | def build_api():
349 | shutil.rmtree(API_PATH, ignore_errors=True)
350 | os.makedirs(API_PATH, exist_ok=True)
351 | for filename, url in TO_SCRAPE.items():
352 | logger.info("Parsing Schemas from ", url)
353 | items = retrieve_info(url)
354 | if verify_type_parameters(items) or verify_method_parameters(items):
355 | logger.error("Failed to validate schema. View logs above for more information.")
356 | exit(1)
357 |
358 | with open(API_PATH / f"{filename}.json", "w") as f:
359 | json.dump(items, f, indent=2)
360 |
361 | with open(API_PATH / f"{filename}.min.json", "w") as f:
362 | json.dump(items, f)
363 |
--------------------------------------------------------------------------------
/compiler/build_methods.py:
--------------------------------------------------------------------------------
1 | import re
2 | import json
3 | from pathlib import Path
4 |
5 | API_PATH = Path("compiler/api")
6 | METHODS_DESTINATION_PATH = Path("tgrambot")
7 | TEMPLATES_DESTINATION = Path('compiler/templates')
8 |
9 | TG_CORE_TYPES = {
10 | "String": 'str',
11 | "Boolean": 'bool',
12 | "Integer": 'int',
13 | "Float": 'int'
14 | }
15 |
16 | BASE_TYPES = ['str', 'bool', 'int', 'None']
17 |
18 | WARNING = """
19 | # # # # # # # # # # # # # # # # # # # # # # # #
20 | # !!! WARNING !!! #
21 | # This is an auto-generated file! #
22 | # All changes made in this file will be lost! #
23 | # # # # # # # # # # # # # # # # # # # # # # # #
24 | """.strip()
25 |
26 | COPYRIGHT = """
27 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
28 | # Copyright (C) 2022 Anand
29 |
30 | # TGramBot is free software: you can redistribute it and/or modify
31 | # it under the terms of the GNU General Public License as published by
32 | # the Free Software Foundation, either version 3 of the License, or
33 | # (at your option) any later version.
34 |
35 | # TGramBot is distributed in the hope that it will be useful,
36 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
37 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38 | # GNU General Public License for more details.
39 |
40 | # You should have received a copy of the GNU General Public License
41 | # along with this program. If not, see .
42 | """.strip()
43 |
44 | markup_temp = """
45 | if isinstance({mark}, Element):
46 | {mark} = self._bot.render_markup_element({mark}, parse_mode)
47 | """
48 |
49 |
50 | def snake(s: str):
51 | # https://stackoverflow.com/q/1175208
52 | s = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", s)
53 | return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s).lower()
54 |
55 |
56 | def camel(s: str):
57 | return "".join([i[0].upper() + i[1:] for i in s.split("_")])
58 |
59 |
60 | def build_methods():
61 |
62 | with open(API_PATH / 'api.json') as f:
63 | schema = json.loads(f.read()).get('methods')
64 | content = ''
65 | to_import = []
66 | # Main Template
67 | content_temp = open(TEMPLATES_DESTINATION / 'methods.tmpl', mode='r').read()
68 | for name, item in schema.items():
69 | field_text = "\n self, "
70 | required = ''
71 | non_required = ''
72 | returns_list = item.get('returns')
73 | attach_file = []
74 | comments = '\n '.join(item.get('description')) + f"\n\n Source : {item.get('href')}"
75 | fields = item.get('fields')
76 | method = snake(name)
77 | if not fields:
78 | raw_return = TG_CORE_TYPES.get(returns_list[0]) if TG_CORE_TYPES.get(returns_list[0]) is not None else returns_list[0]
79 | if raw_return.startswith("Array of"):
80 | raw_return = TG_CORE_TYPES.get(raw_return[9:]) if TG_CORE_TYPES.get(
81 | raw_return[9:]) is not None else raw_return[9:]
82 | returns = f'[{raw_return}(**r) for r in result]'
83 | else:
84 | if raw_return in BASE_TYPES:
85 | returns = f'result'
86 | else:
87 | returns = f'{raw_return}(**result)'
88 |
89 | if raw_return not in to_import and raw_return not in BASE_TYPES:
90 | to_import.append(raw_return)
91 | content += content_temp.format(
92 | name=name,
93 | method_name=method,
94 | fields=field_text[:-2] + '\n ',
95 | attachment="",
96 | comments=comments,
97 | markup="",
98 | returns=returns
99 | )
100 | else:
101 | returns = ''
102 | markup = ""
103 | check_markup = []
104 | markup_name = ""
105 | is_markup = ["text", "caption"]
106 | for field in fields:
107 | typed_list = []
108 | field_name = field.get('name')
109 | for types in field.get('types'):
110 | def_types = TG_CORE_TYPES.get(types) if TG_CORE_TYPES.get(types) is not None else types
111 | if def_types.startswith("Array of Array"):
112 | import_type = TG_CORE_TYPES.get(def_types[18:]) if TG_CORE_TYPES.get(def_types[18:]) is not None else def_types[18:]
113 | def_types = f"List[List[{TG_CORE_TYPES.get(f'{def_types[18:]}')}]]" if TG_CORE_TYPES.get(
114 | f'{def_types[18:]}') is not None else f'List[List[{def_types[18:]}]]'
115 | elif def_types.startswith("Array of"):
116 | import_type = TG_CORE_TYPES.get(def_types[9:]) if TG_CORE_TYPES.get(def_types[9:]) is not None else def_types[9:]
117 | def_types = f"List[{TG_CORE_TYPES.get(f'{def_types[9:]}')}]" if TG_CORE_TYPES.get(
118 | f'{def_types[9:]}') is not None else f'List[{def_types[9:]}]'
119 | else:
120 | import_type = def_types
121 | def_types = def_types if def_types in BASE_TYPES else f'{def_types}'
122 |
123 | if import_type not in to_import and import_type not in BASE_TYPES:
124 | to_import.append(import_type)
125 |
126 | if import_type == "InputFile":
127 | attach_file.append(field_name)
128 | typed_list.append(def_types)
129 |
130 | if field_name in is_markup:
131 | typed_list.append("Element")
132 | markup_name = field_name
133 | if field_name == "parse_mode":
134 | check_markup.append(True)
135 |
136 | typed = ", ".join(typed_list)
137 |
138 | cust_typed = f'Union[{typed}]' if len(typed_list) > 1 else typed
139 | if field_name:
140 | if field.get('required'):
141 | required += f"\n {field_name}: {cust_typed}, "
142 | else:
143 | non_required += f"\n {field_name}: {cust_typed} = None, "
144 |
145 | if True in check_markup:
146 | markup += markup_temp.format(mark=markup_name)
147 | raw_return = TG_CORE_TYPES.get(returns_list[0]) if TG_CORE_TYPES.get(returns_list[0]) is not None else returns_list[0]
148 | if raw_return.startswith("Array of"):
149 | raw_return = TG_CORE_TYPES.get(raw_return[9:]) if TG_CORE_TYPES.get(raw_return[9:]) is not None else raw_return[9:]
150 | returns = f'[{raw_return}(**r) for r in result]'
151 | else:
152 | if raw_return in BASE_TYPES:
153 | returns = f'result'
154 | else:
155 | returns = f'{raw_return}(**result)'
156 |
157 | if raw_return not in to_import and raw_return not in BASE_TYPES:
158 | to_import.append(raw_return)
159 |
160 | attach_content = ''
161 | if len(attach_file) > 0:
162 | for attachs in attach_file:
163 | attach_content += f"\n if self._bot.attach_file(payload, '{attachs}', {attachs}) is not None:\n files.update(self._bot.attach_file(payload, '{attachs}', {attachs}))"
164 | field_text += required + non_required
165 | content += content_temp.format(
166 | name=name,
167 | method_name=method,
168 | fields=field_text[:-2] + '\n ',
169 | attachment=attach_content,
170 | comments=comments,
171 | markup=markup,
172 | returns=returns
173 | )
174 |
175 | with open(METHODS_DESTINATION_PATH / 'methods.py', mode="w+") as file:
176 | main_temp = open(TEMPLATES_DESTINATION / 'method_class.tmpl', mode='r').read()
177 | file.write(main_temp.format(
178 | content=content,
179 | imports=",\n ".join(to_import),
180 | copyright=COPYRIGHT,
181 | warning=WARNING
182 | ))
--------------------------------------------------------------------------------
/compiler/build_types.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import os
18 | import re
19 | import shutil
20 | import json
21 | from pathlib import Path
22 |
23 | API_PATH = Path("compiler/api")
24 | TYPES_DESTINATION_PATH = Path("tgrambot/types")
25 | TEMPLATES_DESTINATION = Path('compiler/templates')
26 |
27 | TG_CORE_TYPES = {
28 | "String": 'str',
29 | "Boolean": 'bool',
30 | "Integer": 'int',
31 | "Float": 'int'
32 | }
33 |
34 | BASE_TYPES = ['str', 'bool', 'int', 'None']
35 |
36 | INPUT_TYPES = ["ForceReply", "ReplyKeyboardMarkup", "KeyboardButton",
37 | "KeyboardButtonPollType", "ReplyKeyboardRemove", "InlineKeyboardMarkup",
38 | "InlineKeyboardButton", "LoginUrl", "InlineQueryResultArticle", "InputMedia",
39 | "InputMediaAnimation", "InputMediaDocument", "InputMediaAudio", "InputMediaPhoto",
40 | "InputMediaVideo", "InlineQueryResultCachedAudio", "InlineQueryResultCachedDocument", "InlineQueryResultCachedGif",
41 | "InlineQueryResultCachedMpeg4Gif", "InlineQueryResultCachedPhoto", "InlineQueryResultCachedSticker",
42 | "InlineQueryResultCachedVideo", "InlineQueryResultCachedVoice", "InlineQueryResultArticle", "InlineQueryResultAudio"
43 | "InlineQueryResultContact", "InlineQueryResultGame", "InlineQueryResultDocument", "InlineQueryResultGif",
44 | "InlineQueryResultLocation", "InlineQueryResultMpeg4Gif", "InlineQueryResultPhoto", "InlineQueryResultVenue",
45 | "InlineQueryResultVideo", "InlineQueryResultVoice", "InputTextMessageContent", "InputLocationMessageContent",
46 | "InputVenueMessageContent", "InputContactMessageContent", "InputInvoiceMessageContent"]
47 |
48 |
49 | WARNING = """
50 | # # # # # # # # # # # # # # # # # # # # # # # #
51 | # !!! WARNING !!! #
52 | # This is an auto-generated file! #
53 | # All changes made in this file will be lost! #
54 | # # # # # # # # # # # # # # # # # # # # # # # #
55 | """.strip()
56 |
57 | COPYRIGHT = """
58 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
59 | # Copyright (C) 2022 Anand
60 |
61 | # TGramBot is free software: you can redistribute it and/or modify
62 | # it under the terms of the GNU General Public License as published by
63 | # the Free Software Foundation, either version 3 of the License, or
64 | # (at your option) any later version.
65 |
66 | # TGramBot is distributed in the hope that it will be useful,
67 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
68 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
69 | # GNU General Public License for more details.
70 |
71 | # You should have received a copy of the GNU General Public License
72 | # along with this program. If not, see .
73 | """.strip()
74 |
75 |
76 | def snake(s: str):
77 | # https://stackoverflow.com/q/1175208
78 | s = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", s)
79 | return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s).lower()
80 |
81 |
82 | def camel(s: str):
83 | return "".join([i[0].upper() + i[1:] for i in s.split("_")])
84 |
85 |
86 | def build_types():
87 | shutil.rmtree(TYPES_DESTINATION_PATH, ignore_errors=True)
88 | os.makedirs(TYPES_DESTINATION_PATH, exist_ok=True)
89 |
90 | # Constructing Base TelegramObject
91 | with open(TEMPLATES_DESTINATION / "base.tmpl", mode='r') as basefile:
92 | base_tmpl = basefile.read()
93 | with open(TYPES_DESTINATION_PATH / "base.py", "w+") as base:
94 | base.write(base_tmpl.format(warning=WARNING, copyright=COPYRIGHT))
95 |
96 | # Read JSON file that contains api methods and types
97 | with open(API_PATH / 'api.json') as f:
98 | schema = json.loads(f.read()).get('types')
99 | # Main Template
100 | content_temp = open(TEMPLATES_DESTINATION / 'type_class.tmpl', mode='r').read()
101 | content = ''
102 | # Pending queue to avoid ForwardRefs and ConfigErrors in pydantic
103 | pending_objects = []
104 | not_pending = []
105 | pending_dict = {}
106 | pending_names = []
107 |
108 | # To Find subclasses of an object
109 | subclass_dict = {}
110 | chat_object = ''
111 | callbackquery_object = ''
112 | inlinebutton_object = ''
113 | inlinemarkup_object = ''
114 |
115 | # Classes to be imported in __init__ file
116 | init_types = []
117 | for name, item in schema.items():
118 | init_types.append(name)
119 | comments = '\n '.join(item.get('description'))
120 | fields = item.get('fields')
121 | subclasses = item.get('subtypes')
122 | super_class = ""
123 | if subclasses and len(subclasses) != 0:
124 | for subclass in subclasses:
125 | subclass_dict.update({snake(subclass): snake(name)})
126 |
127 | class_object = camel(subclass_dict.get(snake(name))) if subclass_dict.get(snake(name)) is not None else 'TelegramObject'
128 | if fields is None:
129 | content += content_temp.format(
130 | class_name=name,
131 | class_object=class_object,
132 | comments=comments,
133 | fields="\n pass",
134 | super_class=super_class
135 | )
136 | else:
137 | field_text = ''
138 | super_class_required = ""
139 | super_class_not_required = ""
140 | super_class_props = ""
141 | super_class_text = ''
142 | field_count = 0
143 | pending_objects_count = 0
144 | pending_list = []
145 | for field in fields:
146 | typed_list = []
147 | # Separate types of props and classify them
148 | for types in field.get('types'):
149 | def_types = TG_CORE_TYPES.get(types) if TG_CORE_TYPES.get(types) is not None else types
150 | if def_types.startswith("Array of Array"):
151 | import_type = TG_CORE_TYPES.get(def_types[18:]) if TG_CORE_TYPES.get(def_types[18:]) is not None else def_types[18:]
152 | def_types = f"List[List[{TG_CORE_TYPES.get(f'{def_types[18:]}')}]]" if TG_CORE_TYPES.get(
153 | f'{def_types[18:]}') is not None else f'List[List["{def_types[18:]}"]]'
154 | elif def_types.startswith("Array of"):
155 | import_type = TG_CORE_TYPES.get(def_types[9:]) if TG_CORE_TYPES.get(def_types[9:]) is not None else def_types[9:]
156 | def_types = f"List[{TG_CORE_TYPES.get(f'{def_types[9:]}')}]" if TG_CORE_TYPES.get(
157 | f'{def_types[9:]}') is not None else f'List["{def_types[9:]}"]'
158 | else:
159 | import_type = def_types
160 | def_types = def_types if def_types in BASE_TYPES else f'"{def_types}"'
161 | if import_type not in BASE_TYPES and import_type not in not_pending and import_type not in init_types:
162 | pending_objects_count += 1
163 | pending_list.append(import_type)
164 | else:
165 | not_pending.append(name)
166 |
167 | typed_list.append(def_types)
168 |
169 | typed = str(typed_list).replace("'", "")
170 | cust_typed = f'Union{typed}' if len(typed_list) > 1 else typed[1:-1]
171 | cust_field = cust_typed
172 | field_name = field.get('name')
173 | required = field.get('required')
174 | extras = 'Field(default=None)'
175 |
176 | if field_name == "from":
177 | extras = 'Field(alias="from", default=None)'
178 | field_name = "from_user"
179 | if field_name is None:
180 | continue
181 | else:
182 | field_text += f"\n {field_name}: {cust_field} = {extras}"
183 | field_count += 1
184 |
185 | # Escape Objects with no props
186 | if field_count == 0:
187 | field_text += "\n pass"
188 |
189 | if name in INPUT_TYPES:
190 | if required:
191 | super_class_required += f'{field_name}: {cust_field}, '
192 | else:
193 | if field_name == 'url':
194 | super_class_not_required += f'{field_name}: {cust_field} = "", '
195 | else:
196 | super_class_not_required += f'{field_name}: {cust_field} = None, '
197 |
198 | super_class_text += f'{field_name}={field_name}, '
199 | super_class_props += super_class_required + super_class_not_required
200 |
201 | if len(super_class_props) > 0 and super_class_text != "":
202 | super_class += f"\n def __init__(self, {super_class_props[:-2]}):\n super({name}, self).__init__({super_class_text[:-2]})\n"
203 |
204 | # To avoid ForwardRefs and ConfigErrors in pydantic
205 | # print(f'{name} - {pending_objects_count}')
206 | if name == "Chat":
207 | chat_object += content_temp.format(
208 | class_name=name,
209 | class_object=class_object,
210 | comments=comments,
211 | fields=field_text,
212 | super_class=super_class
213 | )
214 | continue
215 |
216 | if name == "CallbackQuery":
217 | callbackquery_object += content_temp.format(
218 | class_name=name,
219 | class_object=class_object,
220 | comments=comments,
221 | fields=field_text,
222 | super_class=super_class
223 | )
224 | continue
225 |
226 | if name == "InlineKeyboardButton":
227 | inlinebutton_object += content_temp.format(
228 | class_name=name,
229 | class_object=class_object,
230 | comments=comments,
231 | fields=field_text,
232 | super_class=super_class
233 | )
234 | continue
235 |
236 | if name == "InlineKeyboardMarkup":
237 | inlinemarkup_object += content_temp.format(
238 | class_name=name,
239 | class_object=class_object,
240 | comments=comments,
241 | fields=field_text,
242 | super_class=super_class
243 | )
244 | continue
245 |
246 | if pending_objects_count > 0:
247 | pending_objects.append(content_temp.format(
248 | class_name=name,
249 | class_object=class_object,
250 | comments=comments,
251 | fields=field_text,
252 | super_class=super_class
253 | ))
254 |
255 | pending_dict.update({name: pending_list})
256 | pending_names.append(name)
257 | else:
258 | content += content_temp.format(
259 | class_name=name,
260 | class_object=class_object,
261 | comments=comments,
262 | fields=field_text,
263 | super_class=super_class
264 | )
265 |
266 | # To avoid ForwardRefs and ConfigErrors in pydantic
267 | for pending in reversed(pending_objects):
268 | if pending.startswith('class Message('):
269 | content += chat_object
270 | content += pending
271 | content += callbackquery_object
272 | if pending.startswith('class InlineQueryResultCachedAudio('):
273 | content += inlinebutton_object
274 | content += inlinemarkup_object
275 | content += pending
276 | else:
277 | content += pending
278 |
279 | # Constructing python module with all Telegram Objects
280 | with open(TYPES_DESTINATION_PATH / "tg_types.py", "w+") as type_file:
281 | with open(TEMPLATES_DESTINATION / 'types.tmpl', 'r') as type_temp_file:
282 | type_temp = type_temp_file.read()
283 | type_file.write(type_temp.format(
284 | copyright=COPYRIGHT,
285 | warning=WARNING,
286 | content=content
287 | ))
288 |
289 | # Constructing __init__.py for types
290 | with open(TYPES_DESTINATION_PATH / '__init__.py', "w+") as type_init_file:
291 | with open(TEMPLATES_DESTINATION / 'init.tmpl', 'r') as type_init_temp_file:
292 | type_init_temp = type_init_temp_file.read()
293 | init_imports = ",\n ".join(init_types)
294 | # Beautifying the imports
295 | list_imports = [init_types[i:i+4] for i in range(0, len(init_types), 4)]
296 | types_to_import = ""
297 | for lt in list_imports:
298 | types_to_import += str(lt).replace("[", "").replace("]", "") + ",\n "
299 | type_init_file.write(type_init_temp.format(
300 | copyright=COPYRIGHT,
301 | warning=WARNING,
302 | imports=init_imports,
303 | all=types_to_import[:-6]
304 | ))
305 |
--------------------------------------------------------------------------------
/compiler/templates/base.tmpl:
--------------------------------------------------------------------------------
1 | {warning}
2 |
3 |
4 | {copyright}
5 |
6 | import logging
7 | from pydantic import BaseModel
8 | from typing import List, Union
9 |
10 | import tgrambot
11 | from ..storage import get_current_instance
12 | from ..errors import MethodNotFound
13 |
14 | logger = logging.getLogger(__name__)
15 |
16 |
17 | class TelegramObject(BaseModel):
18 |
19 | """
20 | Base TelegramObject Class for TGramBot
21 | """
22 |
23 | def __str__(self):
24 | return str(self.__dict__)
25 |
26 | def __repr__(self):
27 | return f"<{{type(self).__name__}} {{self}}>"
28 |
29 | async def reply_text(self, text: str, parse_mode: str = None, entities: "List[tgrambot.types.MessageEntity]" = None, disable_web_page_preview: bool = None, disable_notification: bool = None, protect_content: bool = None, allow_sending_without_reply: bool = None, reply_markup: "Union[tgrambot.types.InlineKeyboardMarkup, tgrambot.types.ReplyKeyboardMarkup, tgrambot.types.ReplyKeyboardRemove, tgrambot.types.ForceReply]" = None):
30 | if isinstance(self, tgrambot.types.Message):
31 | bot = get_current_instance()
32 | await bot.send_message(
33 | chat_id=self.chat.id,
34 | text=text,
35 | parse_mode=parse_mode or bot.parse_mode,
36 | entities=entities,
37 | reply_to_message_id=self.message_id,
38 | disable_notification=disable_notification,
39 | disable_web_page_preview=disable_web_page_preview,
40 | protect_content=protect_content,
41 | allow_sending_without_reply=allow_sending_without_reply,
42 | reply_markup=reply_markup
43 | )
44 | else:
45 | raise MethodNotFound('reply_text', type(self).__name__)
46 |
47 | async def answer(self, text: str = None, show_alert: bool = None, url: str = None, cache_time: int = None):
48 | if isinstance(self, tgrambot.types.CallbackQuery):
49 | bot = get_current_instance()
50 | return await bot.answer_callback_query(
51 | callback_query_id=self.id,
52 | text=text,
53 | show_alert=show_alert,
54 | url=url,
55 | cache_time=cache_time
56 | )
57 | else:
58 | raise MethodNotFound('answer', type(self).__name__)
59 |
60 | async def forward(self, chat_id: Union[int, str], disable_notification: bool = None, protect_content: bool = None):
61 | if isinstance(self, tgrambot.types.Message):
62 | bot = get_current_instance()
63 | message = await bot.forward_message(
64 | chat_id=chat_id,
65 | from_chat_id=self.chat.id,
66 | message_id=self.message_id,
67 | disable_notification=disable_notification,
68 | protect_content=protect_content
69 | )
70 |
71 | return message
72 | else:
73 | raise MethodNotFound('forward', type(self).__name__)
74 |
75 | async def copy_message(self, chat_id: Union[int, str], caption: str = None, parse_mode: str = None, caption_entities: "List[tgrambot.types.MessageEntity]" = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: "Union[tgrambot.types.InlineKeyboardMarkup, tgrambot.types.ReplyKeyboardMarkup, tgrambot.types.ReplyKeyboardRemove, tgrambot.types.ForceReply]" = None):
76 | if isinstance(self, tgrambot.types.Message):
77 | bot = get_current_instance()
78 | message_id = await bot.copy_message(
79 | chat_id=chat_id,
80 | from_chat_id=self.chat.id,
81 | message_id=self.message_id,
82 | caption=caption,
83 | parse_mode=parse_mode,
84 | caption_entities=caption_entities,
85 | disable_notification=disable_notification,
86 | protect_content=protect_content,
87 | reply_to_message_id=reply_to_message_id,
88 | allow_sending_without_reply=allow_sending_without_reply,
89 | reply_markup=reply_markup
90 | )
91 | return message_id
92 | else:
93 | raise MethodNotFound('copy_message', type(self).__name__)
94 |
95 | async def reply_photo(
96 | self,
97 | photo: "Union[tgrambot.types.InputFile, str]",
98 | caption: str = None,
99 | parse_mode: str = None,
100 | caption_entities: "List[tgrambot.types.MessageEntity]" = None,
101 | disable_notification: bool = None,
102 | protect_content: bool = None,
103 | allow_sending_without_reply: bool = None,
104 | reply_markup: "Union[tgrambot.types.InlineKeyboardMarkup, tgrambot.types.ReplyKeyboardMarkup, tgrambot.types.ReplyKeyboardRemove, tgrambot.types.ForceReply]" = None
105 | ):
106 | if isinstance(self, tgrambot.types.Message):
107 | bot = get_current_instance()
108 | return await bot.send_photo(
109 | self.chat.id,
110 | photo=photo,
111 | caption=caption,
112 | parse_mode=parse_mode,
113 | caption_entities=caption_entities,
114 | disable_notification=disable_notification,
115 | protect_content=protect_content,
116 | allow_sending_without_reply=allow_sending_without_reply,
117 | reply_markup=reply_markup
118 | )
119 | else:
120 | raise MethodNotFound('reply_photo', type(self).__name__)
121 |
122 | async def ban(self, user_id: int, until_date: int = None, revoke_messages: bool = None):
123 | if isinstance(self, tgrambot.types.Chat):
124 | bot = get_current_instance()
125 | return await bot.ban_chat_member(
126 | chat_id=self.id,
127 | user_id=user_id,
128 | until_date=until_date,
129 | revoke_messages=revoke_messages
130 | )
131 | else:
132 | raise MethodNotFound('ban', type(self).__name__)
133 |
134 | async def unban(self, user_id: int, only_if_banned: bool = None):
135 | if isinstance(self, tgrambot.types.Chat):
136 | bot = get_current_instance()
137 | return await bot.unban_chat_member(
138 | chat_id=self.id,
139 | user_id=user_id,
140 | only_if_banned=only_if_banned
141 | )
142 | else:
143 | raise MethodNotFound('unban', type(self).__name__)
144 |
145 | async def pin(self, disable_notification: bool = None):
146 | if isinstance(self, tgrambot.types.Message):
147 | bot = get_current_instance()
148 | return await bot.pin_chat_message(
149 | chat_id=self.chat.id,
150 | message_id=self.message_id,
151 | disable_notification=disable_notification
152 | )
153 | else:
154 | raise MethodNotFound('pin', type(self).__name__)
155 |
156 | async def unpin(self):
157 | if isinstance(self, tgrambot.types.Message):
158 | bot = get_current_instance()
159 | return await bot.unpin_chat_message(
160 | chat_id=self.chat.id,
161 | message_id=self.message_id
162 | )
163 | else:
164 | raise MethodNotFound('unpin', type(self).__name__)
165 |
--------------------------------------------------------------------------------
/compiler/templates/init.tmpl:
--------------------------------------------------------------------------------
1 | {warning}
2 |
3 |
4 | {copyright}
5 |
6 | from .tg_types import (
7 | {imports}
8 | )
9 |
10 | __all__ = [
11 | {all}
12 | ]
13 |
14 |
--------------------------------------------------------------------------------
/compiler/templates/method_class.tmpl:
--------------------------------------------------------------------------------
1 | {warning}
2 |
3 |
4 | {copyright}
5 |
6 | import tgrambot
7 | from typing import List, Union
8 | from telegram_text.bases import Element
9 | from tgrambot.types import (
10 | {imports}
11 | )
12 |
13 |
14 | class Methods:
15 | def __init__(self, bot: "tgrambot.Bot"):
16 | self._bot = bot
17 |
18 | {content}
--------------------------------------------------------------------------------
/compiler/templates/methods.tmpl:
--------------------------------------------------------------------------------
1 | async def {method_name}({fields}):
2 | """
3 | {comments}
4 | """
5 | {markup}
6 | payload = self._bot.generate_payload(**locals())
7 | files = {{}}
8 | {attachment}
9 | method = '{name}'
10 | url = self._bot.get_api_url(method)
11 | result = await self._bot.aio_post(url, payload, files)
12 | return {returns}
13 |
14 |
--------------------------------------------------------------------------------
/compiler/templates/type_class.tmpl:
--------------------------------------------------------------------------------
1 | class {class_name}({class_object}):
2 |
3 | """
4 | {comments}
5 | """
6 | {fields}
7 | {super_class}
8 |
9 |
--------------------------------------------------------------------------------
/compiler/templates/types.tmpl:
--------------------------------------------------------------------------------
1 | {warning}
2 |
3 |
4 | {copyright}
5 |
6 | from typing import Union, List
7 | from pydantic import Field
8 |
9 | from .base import TelegramObject
10 |
11 |
12 | {content}
--------------------------------------------------------------------------------
/examples/callback.py:
--------------------------------------------------------------------------------
1 | from tgrambot import Bot
2 | from tgrambot.types import CallbackQuery
3 |
4 | bot = Bot(
5 | token="",
6 | workers=50,
7 | parse_mode="Markdown"
8 | )
9 |
10 |
11 | @bot.on_callback()
12 | async def callback_echo(c: Bot, m: CallbackQuery):
13 | await c.answer_callback_query(m.id, "Echo", show_alert=True)
--------------------------------------------------------------------------------
/examples/echobot.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 |
3 | from tgrambot import Bot
4 | from tgrambot.types import Message
5 |
6 | bot = Bot(
7 | token="",
8 | workers=50,
9 | parse_mode="Markdown"
10 | )
11 |
12 |
13 | @bot.on_message()
14 | async def echo(c: Bot, m: Message):
15 | await c.send_message(m.chat.id, m.text)
16 |
17 |
18 | async def main():
19 | await bot.start()
20 | await bot.idle()
21 | await bot.stop()
22 |
23 | if __name__ == '__main__':
24 | loop = asyncio.get_event_loop()
25 | loop.run_until_complete(main())
26 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pydantic
2 | httpx[http2]
3 | requests
4 | beautifulsoup4==4.10
5 | html5lib==1.1
6 | telegram-text==0.1.0
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import re
2 | from sys import argv
3 |
4 | from setuptools import setup, find_packages
5 |
6 | from compiler import build_types, build_methods
7 |
8 | with open("requirements.txt", encoding="utf-8") as r:
9 | requires = [i.strip() for i in r]
10 |
11 | with open('tgrambot/version.txt', encoding='utf-8') as f:
12 | version = re.findall(r'__version__ = \"(.+)\"', f.read())[0]
13 |
14 | with open("README.md", encoding="utf-8") as f:
15 | readme = f.read()
16 |
17 | if len(argv) > 1 and argv[1] in ["sdist", "install", "develop"]:
18 | build_types()
19 | build_methods()
20 |
21 | setup(
22 | name="TGramBot",
23 | version=version,
24 | description="Partially Auto-generated and asynchronous Minimal Telegram BOT API framework in Python for bots",
25 | long_description=readme,
26 | long_description_content_type="text/markdown",
27 | url="https://github.com/KeralaBots",
28 | download_url="https://github.com/KeralaBots/TgramBot/releases/latest",
29 | author="Anand",
30 | author_email="anandpskerala@gmail.com",
31 | license="LGPLv3",
32 | classifiers=[
33 | "Development Status :: 3 - Alpha",
34 | "Intended Audience :: Developers",
35 | "Natural Language :: English",
36 | "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
37 | "Operating System :: OS Independent",
38 | "Programming Language :: Python",
39 | "Programming Language :: Python :: 3",
40 | "Programming Language :: Python :: 3.8",
41 | "Programming Language :: Python :: 3.9",
42 | "Programming Language :: Python :: 3.10",
43 | "Programming Language :: Python :: 3.11",
44 | "Programming Language :: Python :: Implementation",
45 | "Programming Language :: Python :: Implementation :: CPython",
46 | "Programming Language :: Python :: Implementation :: PyPy",
47 | "Topic :: Internet",
48 | "Topic :: Communications",
49 | "Topic :: Communications :: Chat",
50 | "Topic :: Software Development :: Libraries",
51 | "Topic :: Software Development :: Libraries :: Python Modules",
52 | "Topic :: Software Development :: Libraries :: Application Frameworks"
53 | ],
54 | keywords="telegram chat messenger bot api library python",
55 | project_urls={
56 | "Tracker": "https://github.com/KeralaBots/Tgrambot/issues",
57 | "Community": "https://t.me/Keralasbots",
58 | "Source": "https://github.com/Keralabots/Tgrambot",
59 | },
60 | python_requires=">=3.8",
61 | packages=find_packages(exclude=["tests*", "examples*"]),
62 | zip_safe=False,
63 | install_requires=requires
64 | )
65 |
--------------------------------------------------------------------------------
/tests/methods.typed:
--------------------------------------------------------------------------------
1 | async def get_updates(self, offset: int = None, limit: int = None, timeout: int = None, allowed_updates: List[str] = None):
2 | """
3 | Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
4 | """
5 | pass
6 |
7 | async def set_webhook(self, url: str, certificate: InputFile = None, ip_address: str = None, max_connections: int = None, allowed_updates: List[str] = None, drop_pending_updates: bool = None, secret_token: str = None):
8 | """
9 | Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.
10 | If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header "X-Telegram-Bot-Api-Secret-Token" with the secret token as content.
11 | """
12 | pass
13 |
14 | async def delete_webhook(self, drop_pending_updates: bool = None):
15 | """
16 | Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.
17 | """
18 | pass
19 |
20 | async def send_message(self, chat_id: Union[int, str], text: str, parse_mode: str = None, entities: List[MessageEntity] = None, disable_web_page_preview: bool = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
21 | """
22 | Use this method to send text messages. On success, the sent Message is returned.
23 | """
24 | pass
25 |
26 | async def forward_message(self, chat_id: Union[int, str], from_chat_id: Union[int, str], disable_notification: bool = None, protect_content: bool = None, message_id: int):
27 | """
28 | Use this method to forward messages of any kind. Service messages can't be forwarded. On success, the sent Message is returned.
29 | """
30 | pass
31 |
32 | async def copy_message(self, chat_id: Union[int, str], from_chat_id: Union[int, str], message_id: int, caption: str = None, parse_mode: str = None, caption_entities: List[MessageEntity] = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
33 | """
34 | Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.
35 | """
36 | pass
37 |
38 | async def send_photo(self, chat_id: Union[int, str], photo: Union[InputFile, str], caption: str = None, parse_mode: str = None, caption_entities: List[MessageEntity] = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
39 | """
40 | Use this method to send photos. On success, the sent Message is returned.
41 | """
42 | pass
43 |
44 | async def send_audio(self, chat_id: Union[int, str], audio: Union[InputFile, str], caption: str = None, parse_mode: str = None, caption_entities: List[MessageEntity] = None, duration: int = None, performer: str = None, title: str = None, thumb: Union[InputFile, str] = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
45 | """
46 | Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
47 | For sending voice messages, use the sendVoice method instead.
48 | """
49 | pass
50 |
51 | async def send_document(self, chat_id: Union[int, str], document: Union[InputFile, str], thumb: Union[InputFile, str] = None, caption: str = None, parse_mode: str = None, caption_entities: List[MessageEntity] = None, disable_content_type_detection: bool = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
52 | """
53 | Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
54 | """
55 | pass
56 |
57 | async def send_video(self, chat_id: Union[int, str], video: Union[InputFile, str], duration: int = None, width: int = None, height: int = None, thumb: Union[InputFile, str] = None, caption: str = None, parse_mode: str = None, caption_entities: List[MessageEntity] = None, supports_streaming: bool = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
58 | """
59 | Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
60 | """
61 | pass
62 |
63 | async def send_animation(self, chat_id: Union[int, str], animation: Union[InputFile, str], duration: int = None, width: int = None, height: int = None, thumb: Union[InputFile, str] = None, caption: str = None, parse_mode: str = None, caption_entities: List[MessageEntity] = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
64 | """
65 | Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
66 | """
67 | pass
68 |
69 | async def send_voice(self, chat_id: Union[int, str], voice: Union[InputFile, str], caption: str = None, parse_mode: str = None, caption_entities: List[MessageEntity] = None, duration: int = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
70 | """
71 | Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
72 | """
73 | pass
74 |
75 | async def send_video_note(self, chat_id: Union[int, str], video_note: Union[InputFile, str], duration: int = None, length: int = None, thumb: Union[InputFile, str] = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
76 | """
77 | As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.
78 | """
79 | pass
80 |
81 | async def send_media_group(self, chat_id: Union[int, str], media: Union[List[InputMediaAudio], List[InputMediaDocument], List[InputMediaPhoto], List[InputMediaVideo]], disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None):
82 | """
83 | Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned.
84 | """
85 | pass
86 |
87 | async def send_location(self, chat_id: Union[int, str], latitude: int, longitude: int, horizontal_accuracy: int = None, live_period: int = None, heading: int = None, proximity_alert_radius: int = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
88 | """
89 | Use this method to send point on the map. On success, the sent Message is returned.
90 | """
91 | pass
92 |
93 | async def edit_message_live_location(self, chat_id: Union[int, str] = None, message_id: int = None, inline_message_id: str = None, latitude: int, longitude: int, horizontal_accuracy: int = None, heading: int = None, proximity_alert_radius: int = None, reply_markup: InlineKeyboardMarkup = None):
94 | """
95 | Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
96 | """
97 | pass
98 |
99 | async def stop_message_live_location(self, chat_id: Union[int, str] = None, message_id: int = None, inline_message_id: str = None, reply_markup: InlineKeyboardMarkup = None):
100 | """
101 | Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.
102 | """
103 | pass
104 |
105 | async def send_venue(self, chat_id: Union[int, str], latitude: int, longitude: int, title: str, address: str, foursquare_id: str = None, foursquare_type: str = None, google_place_id: str = None, google_place_type: str = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
106 | """
107 | Use this method to send information about a venue. On success, the sent Message is returned.
108 | """
109 | pass
110 |
111 | async def send_contact(self, chat_id: Union[int, str], phone_number: str, first_name: str, last_name: str = None, vcard: str = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
112 | """
113 | Use this method to send phone contacts. On success, the sent Message is returned.
114 | """
115 | pass
116 |
117 | async def send_poll(self, chat_id: Union[int, str], question: str, options: List[str], is_anonymous: bool = None, type: str = None, allows_multiple_answers: bool = None, correct_option_id: int = None, explanation: str = None, explanation_parse_mode: str = None, explanation_entities: List[MessageEntity] = None, open_period: int = None, close_date: int = None, is_closed: bool = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
118 | """
119 | Use this method to send a native poll. On success, the sent Message is returned.
120 | """
121 | pass
122 |
123 | async def send_dice(self, chat_id: Union[int, str], emoji: str = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
124 | """
125 | Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.
126 | """
127 | pass
128 |
129 | async def send_chat_action(self, chat_id: Union[int, str], action: str):
130 | """
131 | Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
132 | We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.
133 | """
134 | pass
135 |
136 | async def get_user_profile_photos(self, user_id: int, offset: int = None, limit: int = None):
137 | """
138 | Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
139 | """
140 | pass
141 |
142 | async def get_file(self, file_id: str):
143 | """
144 | Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot/, where is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
145 | Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.
146 | """
147 | pass
148 |
149 | async def ban_chat_member(self, chat_id: Union[int, str], user_id: int, until_date: int = None, revoke_messages: bool = None):
150 | """
151 | Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
152 | """
153 | pass
154 |
155 | async def unban_chat_member(self, chat_id: Union[int, str], user_id: int, only_if_banned: bool = None):
156 | """
157 | Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success.
158 | """
159 | pass
160 |
161 | async def restrict_chat_member(self, chat_id: Union[int, str], user_id: int, permissions: ChatPermissions, until_date: int = None):
162 | """
163 | Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.
164 | """
165 | pass
166 |
167 | async def promote_chat_member(self, chat_id: Union[int, str], user_id: int, is_anonymous: bool = None, can_manage_chat: bool = None, can_post_messages: bool = None, can_edit_messages: bool = None, can_delete_messages: bool = None, can_manage_video_chats: bool = None, can_restrict_members: bool = None, can_promote_members: bool = None, can_change_info: bool = None, can_invite_users: bool = None, can_pin_messages: bool = None):
168 | """
169 | Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success.
170 | """
171 | pass
172 |
173 | async def set_chat_administrator_custom_title(self, chat_id: Union[int, str], user_id: int, custom_title: str):
174 | """
175 | Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.
176 | """
177 | pass
178 |
179 | async def ban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: int):
180 | """
181 | Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.
182 | """
183 | pass
184 |
185 | async def unban_chat_sender_chat(self, chat_id: Union[int, str], sender_chat_id: int):
186 | """
187 | Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.
188 | """
189 | pass
190 |
191 | async def set_chat_permissions(self, chat_id: Union[int, str], permissions: ChatPermissions):
192 | """
193 | Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success.
194 | """
195 | pass
196 |
197 | async def export_chat_invite_link(self, chat_id: Union[int, str]):
198 | """
199 | Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success.
200 | """
201 | pass
202 |
203 | async def create_chat_invite_link(self, chat_id: Union[int, str], name: str = None, expire_date: int = None, member_limit: int = None, creates_join_request: bool = None):
204 | """
205 | Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.
206 | """
207 | pass
208 |
209 | async def edit_chat_invite_link(self, chat_id: Union[int, str], invite_link: str, name: str = None, expire_date: int = None, member_limit: int = None, creates_join_request: bool = None):
210 | """
211 | Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object.
212 | """
213 | pass
214 |
215 | async def revoke_chat_invite_link(self, chat_id: Union[int, str], invite_link: str):
216 | """
217 | Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object.
218 | """
219 | pass
220 |
221 | async def approve_chat_join_request(self, chat_id: Union[int, str], user_id: int):
222 | """
223 | Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
224 | """
225 | pass
226 |
227 | async def decline_chat_join_request(self, chat_id: Union[int, str], user_id: int):
228 | """
229 | Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
230 | """
231 | pass
232 |
233 | async def set_chat_photo(self, chat_id: Union[int, str], photo: InputFile):
234 | """
235 | Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
236 | """
237 | pass
238 |
239 | async def delete_chat_photo(self, chat_id: Union[int, str]):
240 | """
241 | Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
242 | """
243 | pass
244 |
245 | async def set_chat_title(self, chat_id: Union[int, str], title: str):
246 | """
247 | Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
248 | """
249 | pass
250 |
251 | async def set_chat_description(self, chat_id: Union[int, str], description: str = None):
252 | """
253 | Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
254 | """
255 | pass
256 |
257 | async def pin_chat_message(self, chat_id: Union[int, str], message_id: int, disable_notification: bool = None):
258 | """
259 | Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success.
260 | """
261 | pass
262 |
263 | async def unpin_chat_message(self, chat_id: Union[int, str], message_id: int = None):
264 | """
265 | Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success.
266 | """
267 | pass
268 |
269 | async def unpin_all_chat_messages(self, chat_id: Union[int, str]):
270 | """
271 | Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success.
272 | """
273 | pass
274 |
275 | async def leave_chat(self, chat_id: Union[int, str]):
276 | """
277 | Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
278 | """
279 | pass
280 |
281 | async def get_chat(self, chat_id: Union[int, str]):
282 | """
283 | Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
284 | """
285 | pass
286 |
287 | async def get_chat_administrators(self, chat_id: Union[int, str]):
288 | """
289 | Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
290 | """
291 | pass
292 |
293 | async def get_chat_member_count(self, chat_id: Union[int, str]):
294 | """
295 | Use this method to get the number of members in a chat. Returns Int on success.
296 | """
297 | pass
298 |
299 | async def get_chat_member(self, chat_id: Union[int, str], user_id: int):
300 | """
301 | Use this method to get information about a member of a chat. Returns a ChatMember object on success.
302 | """
303 | pass
304 |
305 | async def set_chat_sticker_set(self, chat_id: Union[int, str], sticker_set_name: str):
306 | """
307 | Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
308 | """
309 | pass
310 |
311 | async def delete_chat_sticker_set(self, chat_id: Union[int, str]):
312 | """
313 | Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
314 | """
315 | pass
316 |
317 | async def answer_callback_query(self, callback_query_id: str, text: str = None, show_alert: bool = None, url: str = None, cache_time: int = None):
318 | """
319 | Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
320 | """
321 | pass
322 |
323 | async def set_my_commands(self, commands: List[BotCommand], scope: BotCommandScope = None, language_code: str = None):
324 | """
325 | Use this method to change the list of the bot's commands. See https://core.telegram.org/bots#commands for more details about bot commands. Returns True on success.
326 | """
327 | pass
328 |
329 | async def delete_my_commands(self, scope: BotCommandScope = None, language_code: str = None):
330 | """
331 | Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.
332 | """
333 | pass
334 |
335 | async def get_my_commands(self, scope: BotCommandScope = None, language_code: str = None):
336 | """
337 | Use this method to get the current list of the bot's commands for the given scope and user language. Returns Array of BotCommand on success. If commands aren't set, an empty list is returned.
338 | """
339 | pass
340 |
341 | async def set_chat_menu_button(self, chat_id: int = None, menu_button: MenuButton = None):
342 | """
343 | Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.
344 | """
345 | pass
346 |
347 | async def get_chat_menu_button(self, chat_id: int = None):
348 | """
349 | Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.
350 | """
351 | pass
352 |
353 | async def set_my_default_administrator_rights(self, rights: ChatAdministratorRights = None, for_channels: bool = None):
354 | """
355 | Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success.
356 | """
357 | pass
358 |
359 | async def get_my_default_administrator_rights(self, for_channels: bool = None):
360 | """
361 | Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.
362 | """
363 | pass
364 |
365 | async def edit_message_text(self, chat_id: Union[int, str] = None, message_id: int = None, inline_message_id: str = None, text: str, parse_mode: str = None, entities: List[MessageEntity] = None, disable_web_page_preview: bool = None, reply_markup: InlineKeyboardMarkup = None):
366 | """
367 | Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
368 | """
369 | pass
370 |
371 | async def edit_message_caption(self, chat_id: Union[int, str] = None, message_id: int = None, inline_message_id: str = None, caption: str = None, parse_mode: str = None, caption_entities: List[MessageEntity] = None, reply_markup: InlineKeyboardMarkup = None):
372 | """
373 | Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
374 | """
375 | pass
376 |
377 | async def edit_message_media(self, chat_id: Union[int, str] = None, message_id: int = None, inline_message_id: str = None, media: InputMedia, reply_markup: InlineKeyboardMarkup = None):
378 | """
379 | Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
380 | """
381 | pass
382 |
383 | async def edit_message_reply_markup(self, chat_id: Union[int, str] = None, message_id: int = None, inline_message_id: str = None, reply_markup: InlineKeyboardMarkup = None):
384 | """
385 | Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
386 | """
387 | pass
388 |
389 | async def stop_poll(self, chat_id: Union[int, str], message_id: int, reply_markup: InlineKeyboardMarkup = None):
390 | """
391 | Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned.
392 | """
393 | pass
394 |
395 | async def delete_message(self, chat_id: Union[int, str], message_id: int):
396 | """
397 | Use this method to delete a message, including service messages, with the following limitations:
398 | - A message can only be deleted if it was sent less than 48 hours ago.
399 | - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.
400 | - Bots can delete outgoing messages in private chats, groups, and supergroups.
401 | - Bots can delete incoming messages in private chats.
402 | - Bots granted can_post_messages permissions can delete outgoing messages in channels.
403 | - If the bot is an administrator of a group, it can delete any message there.
404 | - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.
405 | Returns True on success.
406 | """
407 | pass
408 |
409 | async def send_sticker(self, chat_id: Union[int, str], sticker: Union[InputFile, str], disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] = None):
410 | """
411 | Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.
412 | """
413 | pass
414 |
415 | async def get_sticker_set(self, name: str):
416 | """
417 | Use this method to get a sticker set. On success, a StickerSet object is returned.
418 | """
419 | pass
420 |
421 | async def upload_sticker_file(self, user_id: int, png_sticker: InputFile):
422 | """
423 | Use this method to upload a .PNG file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
424 | """
425 | pass
426 |
427 | async def create_new_sticker_set(self, user_id: int, name: str, title: str, png_sticker: Union[InputFile, str] = None, tgs_sticker: InputFile = None, webm_sticker: InputFile = None, emojis: str, contains_masks: bool = None, mask_position: MaskPosition = None):
428 | """
429 | Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. You must use exactly one of the fields png_sticker, tgs_sticker, or webm_sticker. Returns True on success.
430 | """
431 | pass
432 |
433 | async def add_sticker_to_set(self, user_id: int, name: str, png_sticker: Union[InputFile, str] = None, tgs_sticker: InputFile = None, webm_sticker: InputFile = None, emojis: str, mask_position: MaskPosition = None):
434 | """
435 | Use this method to add a new sticker to a set created by the bot. You must use exactly one of the fields png_sticker, tgs_sticker, or webm_sticker. Animated stickers can be added to animated sticker sets and only to them. Animated sticker sets can have up to 50 stickers. Static sticker sets can have up to 120 stickers. Returns True on success.
436 | """
437 | pass
438 |
439 | async def set_sticker_position_in_set(self, sticker: str, position: int):
440 | """
441 | Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.
442 | """
443 | pass
444 |
445 | async def delete_sticker_from_set(self, sticker: str):
446 | """
447 | Use this method to delete a sticker from a set created by the bot. Returns True on success.
448 | """
449 | pass
450 |
451 | async def set_sticker_set_thumb(self, name: str, user_id: int, thumb: Union[InputFile, str] = None):
452 | """
453 | Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Video thumbnails can be set only for video sticker sets only. Returns True on success.
454 | """
455 | pass
456 |
457 | async def answer_inline_query(self, inline_query_id: str, results: List[InlineQueryResult], cache_time: int = None, is_personal: bool = None, next_offset: str = None, switch_pm_text: str = None, switch_pm_parameter: str = None):
458 | """
459 | Use this method to send answers to an inline query. On success, True is returned.
460 | No more than 50 results per query are allowed.
461 | """
462 | pass
463 |
464 | async def answer_web_app_query(self, web_app_query_id: str, result: InlineQueryResult):
465 | """
466 | Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.
467 | """
468 | pass
469 |
470 | async def send_invoice(self, chat_id: Union[int, str], title: str, description: str, payload: str, provider_token: str, currency: str, prices: List[LabeledPrice], max_tip_amount: int = None, suggested_tip_amounts: List[int] = None, start_parameter: str = None, provider_data: str = None, photo_url: str = None, photo_size: int = None, photo_width: int = None, photo_height: int = None, need_name: bool = None, need_phone_number: bool = None, need_email: bool = None, need_shipping_address: bool = None, send_phone_number_to_provider: bool = None, send_email_to_provider: bool = None, is_flexible: bool = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: InlineKeyboardMarkup = None):
471 | """
472 | Use this method to send invoices. On success, the sent Message is returned.
473 | """
474 | pass
475 |
476 | async def create_invoice_link(self, title: str, description: str, payload: str, provider_token: str, currency: str, prices: List[LabeledPrice], max_tip_amount: int = None, suggested_tip_amounts: List[int] = None, provider_data: str = None, photo_url: str = None, photo_size: int = None, photo_width: int = None, photo_height: int = None, need_name: bool = None, need_phone_number: bool = None, need_email: bool = None, need_shipping_address: bool = None, send_phone_number_to_provider: bool = None, send_email_to_provider: bool = None, is_flexible: bool = None):
477 | """
478 | Use this method to create a link for an invoice. Returns the created invoice link as String on success.
479 | """
480 | pass
481 |
482 | async def answer_shipping_query(self, shipping_query_id: str, ok: bool, shipping_options: List[ShippingOption] = None, error_message: str = None):
483 | """
484 | If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
485 | """
486 | pass
487 |
488 | async def answer_pre_checkout_query(self, pre_checkout_query_id: str, ok: bool, error_message: str = None):
489 | """
490 | Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
491 | """
492 | pass
493 |
494 | async def set_passport_data_errors(self, user_id: int, errors: List[PassportElementError]):
495 | """
496 | Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.
497 | Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
498 | """
499 | pass
500 |
501 | async def send_game(self, chat_id: int, game_short_name: str, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: InlineKeyboardMarkup = None):
502 | """
503 | Use this method to send a game. On success, the sent Message is returned.
504 | """
505 | pass
506 |
507 | async def set_game_score(self, user_id: int, score: int, force: bool = None, disable_edit_message: bool = None, chat_id: int = None, message_id: int = None, inline_message_id: str = None):
508 | """
509 | Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.
510 | """
511 | pass
512 |
513 | async def get_game_high_scores(self, user_id: int, chat_id: int = None, message_id: int = None, inline_message_id: str = None):
514 | """
515 | Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. On success, returns an Array of GameHighScore objects.
516 | """
517 | pass
518 |
519 |
--------------------------------------------------------------------------------
/tgrambot/__init__.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import re
18 | import logging
19 | import tgrambot.types
20 | from .bot import Bot
21 |
22 | logger = logging.getLogger(__name__)
23 |
24 |
25 | __all__ = ["Bot", "types"]
26 |
--------------------------------------------------------------------------------
/tgrambot/bot.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import asyncio
18 | import logging
19 | import os
20 | import json
21 | import httpx
22 | from typing import Optional, Callable, Union
23 | from telegram_text.bases import Element
24 |
25 | from .dispatcher import Dispatcher
26 | from .filters import Filters
27 | from .handlers import MessageHandler, CallbackQueryHandler, InlineQueryHandler
28 |
29 |
30 | from .methods import Methods
31 |
32 | from .errors import InvalidToken, TelegramError
33 | from .utils import get_values
34 |
35 | API_TIMEOUT = 60
36 | RETRY = 3
37 |
38 |
39 | class Bot(Methods):
40 | def __init__(
41 | self,
42 | token: str,
43 | parse_mode: str = None,
44 | workers: int = 50,
45 | proxy_url: str = None,
46 | read_timeout: Optional[float] = 5.0,
47 | write_timeout: Optional[float] = 5.0,
48 | connect_timeout: Optional[float] = 5.0,
49 | pool_timeout: Optional[float] = 1.0
50 | ):
51 | super(Bot, self).__init__(bot=self)
52 | self.bot_token = self._validate_bot_token(token)
53 | self._api_url = f"https://api.telegram.org/bot{self.bot_token}/"
54 | self._file_url = f"https://api.telegram.org/file/bot{self.bot_token}/"
55 | self._loop = asyncio.get_event_loop()
56 | self.logger = logging.getLogger(__name__)
57 | self.offset = -1
58 | self._parse_mode = parse_mode
59 | self._parse_modes = ["MarkdownV2", "HTML", "Markdown", None]
60 | self.dispatcher = Dispatcher(self, workers)
61 | self.workers = workers
62 | self.timeout = httpx.Timeout(
63 | connect=connect_timeout,
64 | read=read_timeout,
65 | write=write_timeout,
66 | pool=pool_timeout,
67 | )
68 | self.proxy = proxy_url
69 |
70 | @staticmethod
71 | def _validate_bot_token(token: str):
72 | token_str = token.split(":")
73 | if len(token_str) < 2:
74 | raise InvalidToken()
75 |
76 | if not token_str[0].isdigit():
77 | raise InvalidToken()
78 | return token
79 |
80 | @staticmethod
81 | def _extract_bot_id(token: str) -> int:
82 | raw_bot_id, *_ = token.split(":")
83 | return int(raw_bot_id)
84 |
85 | @property
86 | def id(self):
87 | return self._extract_bot_id(self.bot_token)
88 |
89 | def get_api_url(self, method):
90 | return f"{self._api_url.format(token=self.bot_token)}{method}"
91 |
92 | @property
93 | def parse_mode(self):
94 | return self._parse_mode
95 |
96 | @parse_mode.setter
97 | def parse_mode(self, parse_mode: Optional[str] = None):
98 | if parse_mode not in self._parse_modes:
99 | raise ValueError('parse_mode must be one of {} or None. Not "{}"'.format(
100 | ", ".join(f'"{m}"' for m in self._parse_modes[:-1]),
101 | parse_mode
102 | ))
103 | self._parse_mode = parse_mode
104 |
105 | @parse_mode.deleter
106 | def parse_mode(self):
107 | self.parse_mode = None
108 |
109 | def render_markup_element(self, element: Element, parse_mode: Union[None, str]):
110 | parse_mode = parse_mode or self._parse_mode
111 | if parse_mode is None:
112 | return element.to_plain_text()
113 |
114 | if parse_mode == 'HTML':
115 | return element.to_html()
116 |
117 | if parse_mode == 'MarkdownV2':
118 | return element.to_markdown()
119 |
120 | if parse_mode == 'Markdown':
121 | self.logger.warning(
122 | "Parse mode 'Markdown' is a legacy format. "
123 | "Message will be rendered without markup as plaint text. "
124 | "Try to use 'MarkdownV2'"
125 | )
126 | return element.to_plain_text()
127 |
128 | raise ValueError(f"Unknown parse mode: {parse_mode}")
129 |
130 | @property
131 | async def me(self):
132 | if not hasattr(self, '_me'):
133 | setattr(self, '_me', await self.get_me())
134 | return getattr(self, '_me')
135 |
136 | @me.deleter
137 | def me(self):
138 | if hasattr(self, '_me'):
139 | delattr(self, '_me')
140 |
141 | @staticmethod
142 | def generate_payload(**kwargs):
143 | return_value = {}
144 |
145 | for key, value in kwargs.items():
146 | if not kwargs.get('parse_mode') and key == 'parse_mode':
147 | self = kwargs.get('self')
148 | new_value = self._parse_mode
149 | return_value.update({key: new_value})
150 | if key not in ['self', 'cls'] and value is not None and not key.startswith('_'):
151 | new_value = get_values(value)
152 | return_value.update({key: new_value})
153 | return return_value
154 |
155 | @staticmethod
156 | def attach_file(payload, key, file):
157 | if file and os.path.isfile(file):
158 | files = {key: open(file, 'rb')}
159 | payload.pop(key)
160 | else:
161 | files = None
162 | payload[key] = file
163 |
164 | return files
165 |
166 | async def aio_post(self, url, payload, files=None):
167 | async with httpx.AsyncClient(http2=True, timeout=self.timeout, proxies=self.proxy) as client:
168 | resp = await client.post(url, data=payload, files=files)
169 | try:
170 | data = resp.json()
171 | except json.JSONDecodeError:
172 | raise TelegramError('Error', resp.text)
173 |
174 | if not data['ok']:
175 | raise TelegramError(str(data['error_code']), str(data['description']))
176 |
177 | return data['result']
178 |
179 | async def start(self):
180 | self.logger.info("[Bot] Starting Bot session ...")
181 | await self.dispatcher.start()
182 |
183 | async def stop(self):
184 | self.logger.info("[Bot] Stopped Bot session ...")
185 | await self.dispatcher.stop()
186 |
187 | async def idle(self):
188 | await self.dispatcher.idle()
189 |
190 | async def run(self):
191 | await self.start()
192 | await self.idle()
193 | await self.stop()
194 |
195 | def on_message(self, filters: Filters = None, group: int = 0):
196 | def decorator(func):
197 | self.add_message_handler(func, filters, group)
198 | return decorator
199 |
200 | def on_callback(self, filters: Filters = None, group: int = 0):
201 | def decorator(func):
202 | self.add_callback_handler(func, filters, group)
203 | return decorator
204 |
205 | def on_inlinequery(self, filters: Filters = None, group: int = 0):
206 | def decorator(func):
207 | self.add_inlinequery_handler(func, filters, group)
208 | return decorator
209 |
210 | def add_message_handler(self, callback: Callable, filters: Filters = None, group: int = 0):
211 | handler = MessageHandler(callback, filters)
212 | self.dispatcher.add_handler(handler, group)
213 |
214 | def add_callback_handler(self, callback: Callable, filters: Filters = None, group: int = 0):
215 | handler = CallbackQueryHandler(callback, filters)
216 | self.dispatcher.add_handler(handler, group)
217 |
218 | def add_inlinequery_handler(self, callback: Callable, filters: Filters = None, group: int = 0):
219 | handler = InlineQueryHandler(callback, filters)
220 | self.dispatcher.add_handler(handler, group)
221 |
--------------------------------------------------------------------------------
/tgrambot/dispatcher.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import asyncio
18 | import inspect
19 | import logging
20 | from collections import OrderedDict
21 | from concurrent.futures import ThreadPoolExecutor
22 |
23 | import tgrambot
24 |
25 | import signal
26 | from signal import signal as signal_fn, SIGINT, SIGTERM, SIGABRT
27 | from .storage import create_instance, delete_instance
28 |
29 |
30 | log = logging.getLogger(__name__)
31 |
32 | # Signal number to name
33 | signals = {
34 | k: v for v, k in signal.__dict__.items()
35 | if v.startswith("SIG") and not v.startswith("SIG_")
36 | }
37 |
38 |
39 | class Dispatcher:
40 | def __init__(self, bot: "tgrambot.Bot", workers: int):
41 | self.bot = bot
42 | self.loop = asyncio.get_event_loop_policy().get_event_loop()
43 | self.workers = workers
44 | self.groups = OrderedDict()
45 | self.executor = ThreadPoolExecutor(workers, thread_name_prefix="Handler")
46 | self.is_idling = False
47 | self.is_running = False
48 |
49 | async def start(self):
50 | self.is_running = True
51 | create_instance(self.bot)
52 | asyncio.ensure_future(self.handle_workers())
53 |
54 | async def handle_workers(self):
55 | while self.is_running:
56 | updates = await self.bot.get_updates(offset=self.bot.offset + 1)
57 | for update in updates:
58 | if update is None:
59 | break
60 | self.bot.offset = update.update_id
61 | try:
62 | updated = self._parse_updates(update)
63 |
64 | for group in self.groups.values():
65 | for handler in group:
66 | check = await handler.check(self.bot, updated)
67 |
68 | if check:
69 | if inspect.iscoroutinefunction(handler.callback):
70 | await handler.callback(self.bot, updated)
71 | else:
72 | self.loop.run_in_executor(
73 | self.executor,
74 | handler.callback,
75 | self.bot,
76 | updated
77 | )
78 | break
79 | except Exception as exe:
80 | logging.error(exe, exc_info=True)
81 | continue
82 |
83 | async def idle(self):
84 |
85 | def signal_handler(signum, __):
86 | log.info(f"Stop signal received ({signals[signum]}). Exiting...")
87 | self.is_idling = False
88 |
89 | for s in (SIGINT, SIGTERM, SIGABRT):
90 | signal_fn(s, signal_handler)
91 |
92 | self.is_idling = True
93 | log.info('[Bot] Started Bot session. Idling....')
94 |
95 | while self.is_idling:
96 | await asyncio.sleep(1)
97 |
98 | async def stop(self):
99 | delete_instance()
100 | self.is_running = False
101 | self.groups.clear()
102 |
103 | def add_handler(self, handler, group: int):
104 | try:
105 | if group not in self.groups:
106 | self.groups[group] = []
107 | self.groups = OrderedDict(sorted(self.groups.items()))
108 |
109 | self.groups[group].append(handler)
110 | finally:
111 | pass
112 |
113 | @staticmethod
114 | def _parse_updates(update):
115 | if update.inline_query:
116 | updated = update.inline_query
117 | elif update.callback_query:
118 | updated = update.callback_query
119 | elif (update.message or update.edited_message or update.channel_post
120 | or update.edited_channel_post):
121 | updated = update.message
122 | else:
123 | updated = update
124 |
125 | return updated
126 |
--------------------------------------------------------------------------------
/tgrambot/errors/__init__.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from tgrambot.errors.telegram_error import (
18 | TelegramError,
19 | InvalidToken,
20 | InstanceNotFound,
21 | MethodNotFound
22 | )
23 |
24 |
25 | __all__ = ["TelegramError", "InvalidToken", "InstanceNotFound", "MethodNotFound"]
26 |
--------------------------------------------------------------------------------
/tgrambot/errors/telegram_error.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from typing import Tuple
18 |
19 |
20 | class TelegramError(Exception):
21 | def __init__(self, error: str, status: str):
22 | super().__init__()
23 | self.error = _parse_error(status, error)
24 |
25 | def __str__(self) -> str:
26 | return '%s' % self.error
27 |
28 | def __reduce__(self) -> Tuple[type, Tuple[str]]:
29 | return self.__class__, (self.error,)
30 |
31 |
32 | def _parse_error(code: str, status: str):
33 | status = status.upper()
34 | parsed = f'[{status}] {code}'
35 | return parsed
36 |
37 |
38 | class InvalidToken(TelegramError):
39 | def __init__(self):
40 | super().__init__('invalid token', "The given token is not valid")
41 |
42 | def __reduce__(self) -> Tuple[type, Tuple]:
43 | return self.__class__, ()
44 |
45 |
46 | class InstanceNotFound(TelegramError):
47 | def __init__(self):
48 | super(InstanceNotFound, self).__init__('bot instance not found', "There is no bot instance present")
49 |
50 | def __reduce__(self) -> Tuple[type, Tuple]:
51 | return self.__class__, ()
52 |
53 |
54 | class MethodNotFound(TelegramError):
55 | def __init__(self, method, class_name):
56 | super(MethodNotFound, self).__init__('method not supported', f'{class_name} doesn\'t support {method} method')
57 |
58 | def __reduce__(self) -> Tuple[type, Tuple]:
59 | return self.__class__, ()
60 |
--------------------------------------------------------------------------------
/tgrambot/filters.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from typing import Union
18 |
19 |
20 | class Filters:
21 | def __init__(self):
22 | self.type = 'all'
23 |
24 | document = dict(type="document")
25 |
26 | audio = dict(type="audio")
27 |
28 | video = dict(type="video")
29 |
30 | video_note = dict(type="video_note")
31 |
32 | voice = dict(type="voice")
33 |
34 | sticker = dict(type="sticker")
35 |
36 | animation = dict(type="animation")
37 |
38 | via_bot = dict(type="via_bot")
39 |
40 | poll = dict(type="poll")
41 |
42 | caption = dict(type="caption")
43 |
44 | dice = dict(type="dice")
45 |
46 | game = dict(type="game")
47 |
48 | venue = dict(type="venue")
49 |
50 | location = dict(type="location")
51 |
52 | new_chat_title = dict(type="new_chat_title")
53 |
54 | new_chat_photo = dict(type="new_chat_photo")
55 |
56 | invoice = dict(type="invoice")
57 |
58 | has_protected_content = dict(type="has_protected_content")
59 |
60 | video_chat_scheduled = dict(type="video_chat_scheduled")
61 |
62 | video_chat_started = dict(type="video_chat_started")
63 |
64 | video_chat_ended = dict(type="video_chat_ended")
65 |
66 | video_chat_participants_invited = dict(type="video_chat_participants_invited")
67 |
68 | successful_payment = dict(type="successful_payment")
69 |
70 | all = dict(type="all")
71 |
72 | @staticmethod
73 | def command(commands: Union[str, list], prefixes: Union[list, str] = "/"):
74 | handler_dict = dict(
75 | type="command",
76 | command=commands,
77 | prefix=prefixes
78 | )
79 | return handler_dict
80 |
81 | @staticmethod
82 | def text(text: str = None):
83 | handler_dict = dict(
84 | type="text",
85 | text=text
86 | )
87 | return handler_dict
88 |
89 | @staticmethod
90 | def regex(regex: str):
91 | handler_dict = dict(
92 | type="regex",
93 | regex=regex
94 | )
95 | return handler_dict
96 |
97 | @staticmethod
98 | def callback_data(data: str):
99 | handler_dict = dict(
100 | type="callback_data",
101 | data=data
102 | )
103 | return handler_dict
104 |
105 | private = dict(type="chat", chat_type="private")
106 |
107 | group = dict(type="chat", chat_type="group")
108 |
109 | supergroup = dict(type="chat", chat_type="supergroup")
110 |
111 | channel = dict(type="chat", chat_type="channel")
112 |
--------------------------------------------------------------------------------
/tgrambot/handlers/__init__.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | from .message_handler import MessageHandler
18 | from .callback_handler import CallbackQueryHandler
19 | from .inlinequery_handler import InlineQueryHandler
20 |
21 | __all__ = ["MessageHandler", "CallbackQueryHandler", "InlineQueryHandler"]
22 |
--------------------------------------------------------------------------------
/tgrambot/handlers/callback_handler.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import asyncio
18 | import re
19 |
20 | import tgrambot
21 | from typing import Callable
22 |
23 | from .handler import Handler
24 | from ..types import CallbackQuery
25 |
26 |
27 | class CallbackQueryHandler(Handler):
28 | def __init__(self, callback: Callable, filters=None):
29 | super(CallbackQueryHandler, self).__init__(callback, filters)
30 | self.required_filters = ['callback_data', 'regex']
31 |
32 | async def check(self, bot: 'tgrambot.Bot', update):
33 | if isinstance(update, CallbackQuery):
34 | if self.filters:
35 | filter_type = self.filters.get('type')
36 | if filter_type and filter_type in self.required_filters:
37 | if filter_type == "callback_data":
38 | if update.data:
39 | data = self.filters.get('data')
40 | m = re.search(data, update.data, re.I)
41 | if m:
42 | return True
43 | else:
44 | return False
45 | else:
46 | return False
47 | elif filter_type == "regex":
48 | regex = self.filters.get('regex')
49 | if update.data:
50 | m = re.search(regex, update.data, re.I)
51 | if m:
52 | return True
53 | else:
54 | return False
55 | else:
56 | return False
57 | else:
58 | return False
59 | else:
60 | return True
61 | else:
62 | return False
63 |
--------------------------------------------------------------------------------
/tgrambot/handlers/handler.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | from typing import Callable
19 | import tgrambot
20 |
21 |
22 | class Handler:
23 | def __init__(self, callback: Callable, filters=None):
24 | self.callback = callback
25 | self.filters = filters
26 |
27 | def check(self, bot: 'tgrambot.Bot', update):
28 | raise NotImplemented
29 |
--------------------------------------------------------------------------------
/tgrambot/handlers/inlinequery_handler.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import asyncio
18 | import re
19 |
20 | import tgrambot
21 | from typing import Callable
22 |
23 | from .handler import Handler
24 | from ..types import InlineQuery
25 |
26 |
27 | class InlineQueryHandler(Handler):
28 | def __init__(self, callback: Callable, filters=None):
29 | super(InlineQueryHandler, self).__init__(callback, filters)
30 | self.required_filters = ['regex']
31 |
32 | async def check(self, bot: 'tgrambot.Bot', update):
33 | if isinstance(update, InlineQuery):
34 | if self.filters:
35 | filter_type = self.filters.get('type')
36 | if filter_type and filter_type in self.required_filters:
37 | if update.query:
38 | regex = self.filters.get('regex')
39 | m = re.search(regex, update.query, re.I)
40 | if m:
41 | return True
42 | else:
43 | return False
44 | else:
45 | return False
46 | else:
47 | return False
48 | else:
49 | return True
50 | else:
51 | return False
52 |
--------------------------------------------------------------------------------
/tgrambot/handlers/message_handler.py:
--------------------------------------------------------------------------------
1 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
2 | # Copyright (C) 2022 Anand
3 |
4 | # TGramBot is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # TGramBot is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 |
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 |
17 | import asyncio
18 | import re
19 | import json
20 |
21 | import tgrambot
22 | from typing import Callable
23 |
24 | from .handler import Handler
25 | from ..types import Message
26 |
27 |
28 | class MessageHandler(Handler):
29 | def __init__(self, callback: Callable, filters=None):
30 | super(MessageHandler, self).__init__(callback, filters)
31 | self.exclude = ['callback_data']
32 | self.special_types = ['command', 'all', 'regex', 'text', 'chat']
33 |
34 | async def check(self, bot: 'tgrambot.Bot', update):
35 | if isinstance(update, Message):
36 | if self.filters:
37 | filter_type = self.filters.get('type')
38 | update_json = json.loads(update.json())
39 | if filter_type:
40 | if filter_type not in self.special_types and filter_type not in self.exclude:
41 | if update_json.get(filter_type):
42 | return True
43 | else:
44 | return False
45 | elif filter_type in self.special_types:
46 | if filter_type == "command":
47 | prefixes = self.filters.get('prefix')
48 | commands = self.filters.get('command')
49 | if update.text:
50 | if type(prefixes) is str:
51 | if update.text.startswith(prefixes):
52 | pass
53 | else:
54 | return False
55 | else:
56 | for pre in prefixes:
57 | if update.text.startswith(pre):
58 | pass
59 | else:
60 | return False
61 |
62 | if type(commands) is str:
63 | m = re.search(commands, update.text, re.I)
64 | if m:
65 | return True
66 | else:
67 | return False
68 | else:
69 | for command in commands:
70 | m = re.search(command, update.text, re.I)
71 | if m:
72 | return True
73 | else:
74 | return False
75 | elif filter_type == 'regex':
76 | regex = self.filters.get('regex')
77 | if update.text:
78 | m = re.search(regex, update.text, re.I)
79 | if m:
80 | return True
81 | else:
82 | return False
83 | elif filter_type == 'text':
84 | text = self.filters.get('text')
85 | if update.text:
86 | if text:
87 | m = re.search(text, update.text, re.I)
88 | if m:
89 | return True
90 | else:
91 | return False
92 | else:
93 | return True
94 | elif filter_type == 'chat':
95 | chat_type = self.filters.get('chat_type')
96 | if update.chat.type == chat_type:
97 | return True
98 | else:
99 | return False
100 | else:
101 | return False
102 | else:
103 | return False
104 | else:
105 | return False
106 | else:
107 | return True
108 | else:
109 | return False
110 |
111 |
--------------------------------------------------------------------------------
/tgrambot/storage.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 | import tgrambot
4 |
5 | from .errors import InstanceNotFound
6 |
7 |
8 | def create_instance(bot: "tgrambot.Bot"):
9 | if os.path.exists('tgrambot.session'):
10 | os.remove('tgrambot.session')
11 |
12 | instance = open('tgrambot.session', mode='w')
13 | data = json.dumps({
14 | 'token': bot.bot_token,
15 | 'parse_mode': bot.parse_mode,
16 | 'proxy': bot.proxy
17 | })
18 | instance.write(data)
19 |
20 |
21 | def delete_instance():
22 | if os.path.exists('tgrambot.session'):
23 | os.remove('tgrambot.session')
24 |
25 |
26 | def get_current_instance() -> "tgrambot.Bot":
27 | try:
28 | with open('tgrambot.session', mode='r') as f:
29 | data = json.loads(f.read())
30 | bot = tgrambot.Bot(
31 | token=data.get('token'),
32 | parse_mode=data.get('parse_mode'),
33 | proxy_url=data.get('proxy')
34 | )
35 | return bot
36 | except FileNotFoundError:
37 | raise InstanceNotFound
38 |
--------------------------------------------------------------------------------
/tgrambot/text.py:
--------------------------------------------------------------------------------
1 | from telegram_text import (
2 | Bold,
3 | Chain,
4 | Code,
5 | Hashtag,
6 | InlineCode,
7 | InlineUser,
8 | Italic,
9 | Link,
10 | OrderedList,
11 | PlainText,
12 | Spoiler,
13 | Strikethrough,
14 | TOMLSection,
15 | Text,
16 | Underline,
17 | UnorderedList,
18 | User,
19 | )
20 | from telegram_text.bases import Element
21 |
22 | __all__ = [
23 | 'Bold',
24 | 'Chain',
25 | 'Code',
26 | 'Element',
27 | 'Hashtag',
28 | 'InlineCode',
29 | 'InlineUser',
30 | 'Italic',
31 | 'Link',
32 | 'OrderedList',
33 | 'PlainText',
34 | 'Spoiler',
35 | 'Strikethrough',
36 | 'TOMLSection',
37 | 'Text',
38 | 'Underline',
39 | 'UnorderedList',
40 | 'User',
41 | ]
--------------------------------------------------------------------------------
/tgrambot/types/__init__.py:
--------------------------------------------------------------------------------
1 | # # # # # # # # # # # # # # # # # # # # # # # #
2 | # !!! WARNING !!! #
3 | # This is an auto-generated file! #
4 | # All changes made in this file will be lost! #
5 | # # # # # # # # # # # # # # # # # # # # # # # #
6 |
7 |
8 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
9 | # Copyright (C) 2022 Anand
10 |
11 | # TGramBot is free software: you can redistribute it and/or modify
12 | # it under the terms of the GNU General Public License as published by
13 | # the Free Software Foundation, either version 3 of the License, or
14 | # (at your option) any later version.
15 |
16 | # TGramBot is distributed in the hope that it will be useful,
17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | # GNU General Public License for more details.
20 |
21 | # You should have received a copy of the GNU General Public License
22 | # along with this program. If not, see .
23 |
24 | from .tg_types import (
25 | Update,
26 | WebhookInfo,
27 | User,
28 | Chat,
29 | Message,
30 | MessageId,
31 | MessageEntity,
32 | PhotoSize,
33 | Animation,
34 | Audio,
35 | Document,
36 | Video,
37 | VideoNote,
38 | Voice,
39 | Contact,
40 | Dice,
41 | PollOption,
42 | PollAnswer,
43 | Poll,
44 | Location,
45 | Venue,
46 | WebAppData,
47 | ProximityAlertTriggered,
48 | MessageAutoDeleteTimerChanged,
49 | VideoChatScheduled,
50 | VideoChatStarted,
51 | VideoChatEnded,
52 | VideoChatParticipantsInvited,
53 | UserProfilePhotos,
54 | File,
55 | WebAppInfo,
56 | ReplyKeyboardMarkup,
57 | KeyboardButton,
58 | KeyboardButtonPollType,
59 | ReplyKeyboardRemove,
60 | InlineKeyboardMarkup,
61 | InlineKeyboardButton,
62 | LoginUrl,
63 | CallbackQuery,
64 | ForceReply,
65 | ChatPhoto,
66 | ChatInviteLink,
67 | ChatAdministratorRights,
68 | ChatMember,
69 | ChatMemberOwner,
70 | ChatMemberAdministrator,
71 | ChatMemberMember,
72 | ChatMemberRestricted,
73 | ChatMemberLeft,
74 | ChatMemberBanned,
75 | ChatMemberUpdated,
76 | ChatJoinRequest,
77 | ChatPermissions,
78 | ChatLocation,
79 | BotCommand,
80 | BotCommandScope,
81 | BotCommandScopeDefault,
82 | BotCommandScopeAllPrivateChats,
83 | BotCommandScopeAllGroupChats,
84 | BotCommandScopeAllChatAdministrators,
85 | BotCommandScopeChat,
86 | BotCommandScopeChatAdministrators,
87 | BotCommandScopeChatMember,
88 | MenuButton,
89 | MenuButtonCommands,
90 | MenuButtonWebApp,
91 | MenuButtonDefault,
92 | ResponseParameters,
93 | InputMedia,
94 | InputMediaPhoto,
95 | InputMediaVideo,
96 | InputMediaAnimation,
97 | InputMediaAudio,
98 | InputMediaDocument,
99 | InputFile,
100 | Sticker,
101 | StickerSet,
102 | MaskPosition,
103 | InlineQuery,
104 | InlineQueryResult,
105 | InlineQueryResultArticle,
106 | InlineQueryResultPhoto,
107 | InlineQueryResultGif,
108 | InlineQueryResultMpeg4Gif,
109 | InlineQueryResultVideo,
110 | InlineQueryResultAudio,
111 | InlineQueryResultVoice,
112 | InlineQueryResultDocument,
113 | InlineQueryResultLocation,
114 | InlineQueryResultVenue,
115 | InlineQueryResultContact,
116 | InlineQueryResultGame,
117 | InlineQueryResultCachedPhoto,
118 | InlineQueryResultCachedGif,
119 | InlineQueryResultCachedMpeg4Gif,
120 | InlineQueryResultCachedSticker,
121 | InlineQueryResultCachedDocument,
122 | InlineQueryResultCachedVideo,
123 | InlineQueryResultCachedVoice,
124 | InlineQueryResultCachedAudio,
125 | InputMessageContent,
126 | InputTextMessageContent,
127 | InputLocationMessageContent,
128 | InputVenueMessageContent,
129 | InputContactMessageContent,
130 | InputInvoiceMessageContent,
131 | ChosenInlineResult,
132 | SentWebAppMessage,
133 | LabeledPrice,
134 | Invoice,
135 | ShippingAddress,
136 | OrderInfo,
137 | ShippingOption,
138 | SuccessfulPayment,
139 | ShippingQuery,
140 | PreCheckoutQuery,
141 | PassportData,
142 | PassportFile,
143 | EncryptedPassportElement,
144 | EncryptedCredentials,
145 | PassportElementError,
146 | PassportElementErrorDataField,
147 | PassportElementErrorFrontSide,
148 | PassportElementErrorReverseSide,
149 | PassportElementErrorSelfie,
150 | PassportElementErrorFile,
151 | PassportElementErrorFiles,
152 | PassportElementErrorTranslationFile,
153 | PassportElementErrorTranslationFiles,
154 | PassportElementErrorUnspecified,
155 | Game,
156 | CallbackGame,
157 | GameHighScore
158 | )
159 |
160 | __all__ = [
161 | 'Update', 'WebhookInfo', 'User', 'Chat',
162 | 'Message', 'MessageId', 'MessageEntity', 'PhotoSize',
163 | 'Animation', 'Audio', 'Document', 'Video',
164 | 'VideoNote', 'Voice', 'Contact', 'Dice',
165 | 'PollOption', 'PollAnswer', 'Poll', 'Location',
166 | 'Venue', 'WebAppData', 'ProximityAlertTriggered', 'MessageAutoDeleteTimerChanged',
167 | 'VideoChatScheduled', 'VideoChatStarted', 'VideoChatEnded', 'VideoChatParticipantsInvited',
168 | 'UserProfilePhotos', 'File', 'WebAppInfo', 'ReplyKeyboardMarkup',
169 | 'KeyboardButton', 'KeyboardButtonPollType', 'ReplyKeyboardRemove', 'InlineKeyboardMarkup',
170 | 'InlineKeyboardButton', 'LoginUrl', 'CallbackQuery', 'ForceReply',
171 | 'ChatPhoto', 'ChatInviteLink', 'ChatAdministratorRights', 'ChatMember',
172 | 'ChatMemberOwner', 'ChatMemberAdministrator', 'ChatMemberMember', 'ChatMemberRestricted',
173 | 'ChatMemberLeft', 'ChatMemberBanned', 'ChatMemberUpdated', 'ChatJoinRequest',
174 | 'ChatPermissions', 'ChatLocation', 'BotCommand', 'BotCommandScope',
175 | 'BotCommandScopeDefault', 'BotCommandScopeAllPrivateChats', 'BotCommandScopeAllGroupChats', 'BotCommandScopeAllChatAdministrators',
176 | 'BotCommandScopeChat', 'BotCommandScopeChatAdministrators', 'BotCommandScopeChatMember', 'MenuButton',
177 | 'MenuButtonCommands', 'MenuButtonWebApp', 'MenuButtonDefault', 'ResponseParameters',
178 | 'InputMedia', 'InputMediaPhoto', 'InputMediaVideo', 'InputMediaAnimation',
179 | 'InputMediaAudio', 'InputMediaDocument', 'InputFile', 'Sticker',
180 | 'StickerSet', 'MaskPosition', 'InlineQuery', 'InlineQueryResult',
181 | 'InlineQueryResultArticle', 'InlineQueryResultPhoto', 'InlineQueryResultGif', 'InlineQueryResultMpeg4Gif',
182 | 'InlineQueryResultVideo', 'InlineQueryResultAudio', 'InlineQueryResultVoice', 'InlineQueryResultDocument',
183 | 'InlineQueryResultLocation', 'InlineQueryResultVenue', 'InlineQueryResultContact', 'InlineQueryResultGame',
184 | 'InlineQueryResultCachedPhoto', 'InlineQueryResultCachedGif', 'InlineQueryResultCachedMpeg4Gif', 'InlineQueryResultCachedSticker',
185 | 'InlineQueryResultCachedDocument', 'InlineQueryResultCachedVideo', 'InlineQueryResultCachedVoice', 'InlineQueryResultCachedAudio',
186 | 'InputMessageContent', 'InputTextMessageContent', 'InputLocationMessageContent', 'InputVenueMessageContent',
187 | 'InputContactMessageContent', 'InputInvoiceMessageContent', 'ChosenInlineResult', 'SentWebAppMessage',
188 | 'LabeledPrice', 'Invoice', 'ShippingAddress', 'OrderInfo',
189 | 'ShippingOption', 'SuccessfulPayment', 'ShippingQuery', 'PreCheckoutQuery',
190 | 'PassportData', 'PassportFile', 'EncryptedPassportElement', 'EncryptedCredentials',
191 | 'PassportElementError', 'PassportElementErrorDataField', 'PassportElementErrorFrontSide', 'PassportElementErrorReverseSide',
192 | 'PassportElementErrorSelfie', 'PassportElementErrorFile', 'PassportElementErrorFiles', 'PassportElementErrorTranslationFile',
193 | 'PassportElementErrorTranslationFiles', 'PassportElementErrorUnspecified', 'Game', 'CallbackGame',
194 | 'GameHighScore'
195 | ]
196 |
197 |
--------------------------------------------------------------------------------
/tgrambot/types/base.py:
--------------------------------------------------------------------------------
1 | # # # # # # # # # # # # # # # # # # # # # # # #
2 | # !!! WARNING !!! #
3 | # This is an auto-generated file! #
4 | # All changes made in this file will be lost! #
5 | # # # # # # # # # # # # # # # # # # # # # # # #
6 |
7 |
8 | # TGramBot - Partially Auto-generated Telegram Bot Api Library Python
9 | # Copyright (C) 2022 Anand
10 |
11 | # TGramBot is free software: you can redistribute it and/or modify
12 | # it under the terms of the GNU General Public License as published by
13 | # the Free Software Foundation, either version 3 of the License, or
14 | # (at your option) any later version.
15 |
16 | # TGramBot is distributed in the hope that it will be useful,
17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | # GNU General Public License for more details.
20 |
21 | # You should have received a copy of the GNU General Public License
22 | # along with this program. If not, see .
23 |
24 | import logging
25 | from pydantic import BaseModel
26 | from typing import List, Union
27 |
28 | import tgrambot
29 | from ..storage import get_current_instance
30 | from ..errors import MethodNotFound
31 |
32 | logger = logging.getLogger(__name__)
33 |
34 |
35 | class TelegramObject(BaseModel):
36 |
37 | """
38 | Base TelegramObject Class for TGramBot
39 | """
40 |
41 | def __str__(self):
42 | return str(self.__dict__)
43 |
44 | def __repr__(self):
45 | return f"<{type(self).__name__} {self}>"
46 |
47 | async def reply_text(self, text: str, parse_mode: str = None, entities: "List[tgrambot.types.MessageEntity]" = None, disable_web_page_preview: bool = None, disable_notification: bool = None, protect_content: bool = None, allow_sending_without_reply: bool = None, reply_markup: "Union[tgrambot.types.InlineKeyboardMarkup, tgrambot.types.ReplyKeyboardMarkup, tgrambot.types.ReplyKeyboardRemove, tgrambot.types.ForceReply]" = None):
48 | if isinstance(self, tgrambot.types.Message):
49 | bot = get_current_instance()
50 | await bot.send_message(
51 | chat_id=self.chat.id,
52 | text=text,
53 | parse_mode=parse_mode or bot.parse_mode,
54 | entities=entities,
55 | reply_to_message_id=self.message_id,
56 | disable_notification=disable_notification,
57 | disable_web_page_preview=disable_web_page_preview,
58 | protect_content=protect_content,
59 | allow_sending_without_reply=allow_sending_without_reply,
60 | reply_markup=reply_markup
61 | )
62 | else:
63 | raise MethodNotFound('reply_text', type(self).__name__)
64 |
65 | async def answer(self, text: str = None, show_alert: bool = None, url: str = None, cache_time: int = None):
66 | if isinstance(self, tgrambot.types.CallbackQuery):
67 | bot = get_current_instance()
68 | return await bot.answer_callback_query(
69 | callback_query_id=self.id,
70 | text=text,
71 | show_alert=show_alert,
72 | url=url,
73 | cache_time=cache_time
74 | )
75 | else:
76 | raise MethodNotFound('answer', type(self).__name__)
77 |
78 | async def forward(self, chat_id: Union[int, str], disable_notification: bool = None, protect_content: bool = None):
79 | if isinstance(self, tgrambot.types.Message):
80 | bot = get_current_instance()
81 | message = await bot.forward_message(
82 | chat_id=chat_id,
83 | from_chat_id=self.chat.id,
84 | message_id=self.message_id,
85 | disable_notification=disable_notification,
86 | protect_content=protect_content
87 | )
88 |
89 | return message
90 | else:
91 | raise MethodNotFound('forward', type(self).__name__)
92 |
93 | async def copy_message(self, chat_id: Union[int, str], caption: str = None, parse_mode: str = None, caption_entities: "List[tgrambot.types.MessageEntity]" = None, disable_notification: bool = None, protect_content: bool = None, reply_to_message_id: int = None, allow_sending_without_reply: bool = None, reply_markup: "Union[tgrambot.types.InlineKeyboardMarkup, tgrambot.types.ReplyKeyboardMarkup, tgrambot.types.ReplyKeyboardRemove, tgrambot.types.ForceReply]" = None):
94 | if isinstance(self, tgrambot.types.Message):
95 | bot = get_current_instance()
96 | message_id = await bot.copy_message(
97 | chat_id=chat_id,
98 | from_chat_id=self.chat.id,
99 | message_id=self.message_id,
100 | caption=caption,
101 | parse_mode=parse_mode,
102 | caption_entities=caption_entities,
103 | disable_notification=disable_notification,
104 | protect_content=protect_content,
105 | reply_to_message_id=reply_to_message_id,
106 | allow_sending_without_reply=allow_sending_without_reply,
107 | reply_markup=reply_markup
108 | )
109 | return message_id
110 | else:
111 | raise MethodNotFound('copy_message', type(self).__name__)
112 |
113 | async def reply_photo(
114 | self,
115 | photo: "Union[tgrambot.types.InputFile, str]",
116 | caption: str = None,
117 | parse_mode: str = None,
118 | caption_entities: "List[tgrambot.types.MessageEntity]" = None,
119 | disable_notification: bool = None,
120 | protect_content: bool = None,
121 | allow_sending_without_reply: bool = None,
122 | reply_markup: "Union[tgrambot.types.InlineKeyboardMarkup, tgrambot.types.ReplyKeyboardMarkup, tgrambot.types.ReplyKeyboardRemove, tgrambot.types.ForceReply]" = None
123 | ):
124 | if isinstance(self, tgrambot.types.Message):
125 | bot = get_current_instance()
126 | return await bot.send_photo(
127 | self.chat.id,
128 | photo=photo,
129 | caption=caption,
130 | parse_mode=parse_mode,
131 | caption_entities=caption_entities,
132 | disable_notification=disable_notification,
133 | protect_content=protect_content,
134 | allow_sending_without_reply=allow_sending_without_reply,
135 | reply_markup=reply_markup
136 | )
137 | else:
138 | raise MethodNotFound('reply_photo', type(self).__name__)
139 |
140 | async def ban(self, user_id: int, until_date: int = None, revoke_messages: bool = None):
141 | if isinstance(self, tgrambot.types.Chat):
142 | bot = get_current_instance()
143 | return await bot.ban_chat_member(
144 | chat_id=self.id,
145 | user_id=user_id,
146 | until_date=until_date,
147 | revoke_messages=revoke_messages
148 | )
149 | else:
150 | raise MethodNotFound('ban', type(self).__name__)
151 |
152 | async def unban(self, user_id: int, only_if_banned: bool = None):
153 | if isinstance(self, tgrambot.types.Chat):
154 | bot = get_current_instance()
155 | return await bot.unban_chat_member(
156 | chat_id=self.id,
157 | user_id=user_id,
158 | only_if_banned=only_if_banned
159 | )
160 | else:
161 | raise MethodNotFound('unban', type(self).__name__)
162 |
163 | async def pin(self, disable_notification: bool = None):
164 | if isinstance(self, tgrambot.types.Message):
165 | bot = get_current_instance()
166 | return await bot.pin_chat_message(
167 | chat_id=self.chat.id,
168 | message_id=self.message_id,
169 | disable_notification=disable_notification
170 | )
171 | else:
172 | raise MethodNotFound('pin', type(self).__name__)
173 |
174 | async def unpin(self):
175 | if isinstance(self, tgrambot.types.Message):
176 | bot = get_current_instance()
177 | return await bot.unpin_chat_message(
178 | chat_id=self.chat.id,
179 | message_id=self.message_id
180 | )
181 | else:
182 | raise MethodNotFound('unpin', type(self).__name__)
183 |
--------------------------------------------------------------------------------
/tgrambot/utils.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | CORE_TYPES = [int, str, bool, None, dict, list]
4 |
5 |
6 |
7 | def snake(s: str):
8 | # https://stackoverflow.com/q/1175208
9 | s = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", s)
10 | return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s).lower()
11 |
12 |
13 | def camel(s: str):
14 | return "".join([i[0].upper() + i[1:] for i in s.split("_")])
15 |
16 |
17 | def get_values(value):
18 | if type(value) not in CORE_TYPES:
19 | new_value = value.json()
20 | else:
21 | if type(value) == list:
22 | values = []
23 | for v in value:
24 | if type(value) not in CORE_TYPES:
25 | values.append(v.json())
26 | else:
27 | values.append(v)
28 | new_value = values
29 | else:
30 | new_value = value
31 | return new_value
32 |
--------------------------------------------------------------------------------
/tgrambot/version.txt:
--------------------------------------------------------------------------------
1 | __version__ = "0.0.1b2"
--------------------------------------------------------------------------------