├── .gitignore
├── LICENSE
├── README.md
├── base
├── config.py
├── debug.py
├── format.py
├── log.py
├── message.py
├── mute.py
├── network.py
├── pool.py
├── sentry.py
├── weather.py
└── webvpn.py
├── bot.py
├── command
├── gadget.py
├── heartbeat.py
├── info.py
└── weather.py
├── config.sample.ini
├── ecosystem.config.js
├── requirements.txt
└── template
└── template.jpg
/.gitignore:
--------------------------------------------------------------------------------
1 | config.ini
2 | data/*
3 | log/*
4 | secret/*
5 | tmp/*
6 |
7 | .vscode/*
8 |
9 | # Created by https://www.toptal.com/developers/gitignore/api/python
10 | # Edit at https://www.toptal.com/developers/gitignore?templates=python
11 |
12 | ### Python ###
13 | # Byte-compiled / optimized / DLL files
14 | __pycache__/
15 | *.py[cod]
16 | *$py.class
17 |
18 | # C extensions
19 | *.so
20 |
21 | # Distribution / packaging
22 | .Python
23 | build/
24 | develop-eggs/
25 | dist/
26 | downloads/
27 | eggs/
28 | .eggs/
29 | lib/
30 | lib64/
31 | parts/
32 | sdist/
33 | var/
34 | wheels/
35 | share/python-wheels/
36 | *.egg-info/
37 | .installed.cfg
38 | *.egg
39 | MANIFEST
40 |
41 | # PyInstaller
42 | # Usually these files are written by a python script from a template
43 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
44 | *.manifest
45 | *.spec
46 |
47 | # Installer logs
48 | pip-log.txt
49 | pip-delete-this-directory.txt
50 |
51 | # Unit test / coverage reports
52 | htmlcov/
53 | .tox/
54 | .nox/
55 | .coverage
56 | .coverage.*
57 | .cache
58 | nosetests.xml
59 | coverage.xml
60 | *.cover
61 | *.py,cover
62 | .hypothesis/
63 | .pytest_cache/
64 | cover/
65 |
66 | # Translations
67 | *.mo
68 | *.pot
69 |
70 | # Django stuff:
71 | *.log
72 | local_settings.py
73 | db.sqlite3
74 | db.sqlite3-journal
75 |
76 | # Flask stuff:
77 | instance/
78 | .webassets-cache
79 |
80 | # Scrapy stuff:
81 | .scrapy
82 |
83 | # Sphinx documentation
84 | docs/_build/
85 |
86 | # PyBuilder
87 | .pybuilder/
88 | target/
89 |
90 | # Jupyter Notebook
91 | .ipynb_checkpoints
92 |
93 | # IPython
94 | profile_default/
95 | ipython_config.py
96 |
97 | # pyenv
98 | # For a library or package, you might want to ignore these files since the code is
99 | # intended to run in multiple environments; otherwise, check them in:
100 | # .python-version
101 |
102 | # pipenv
103 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
104 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
105 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
106 | # install all needed dependencies.
107 | #Pipfile.lock
108 |
109 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
110 | __pypackages__/
111 |
112 | # Celery stuff
113 | celerybeat-schedule
114 | celerybeat.pid
115 |
116 | # SageMath parsed files
117 | *.sage.py
118 |
119 | # Environments
120 | .env
121 | .venv
122 | env/
123 | venv/
124 | ENV/
125 | env.bak/
126 | venv.bak/
127 |
128 | # Spyder project settings
129 | .spyderproject
130 | .spyproject
131 |
132 | # Rope project settings
133 | .ropeproject
134 |
135 | # mkdocs documentation
136 | /site
137 |
138 | # mypy
139 | .mypy_cache/
140 | .dmypy.json
141 | dmypy.json
142 |
143 | # Pyre type checker
144 | .pyre/
145 |
146 | # pytype static type analyzer
147 | .pytype/
148 |
149 | # Cython debug symbols
150 | cython_debug/
151 |
152 | # End of https://www.toptal.com/developers/gitignore/api/python
153 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Tuna Erha Bot
2 |
3 | Erha-Bot Tuna 特供版
4 |
5 | ## 目前指令
6 |
7 | 可用:
8 |
9 | - /weather - 显示清华大学天气(彩云 API)
10 | - /forecast - 降雨分钟级预报
11 | - /forecast_hourly - 天气小时级预报
12 | - /mute - 屏蔽发布源
13 | - /unmute - 解除屏蔽发布源
14 | - /mute_list - 列出所有被屏蔽的发布源
15 | - /roll - 从 1 开始的随机数
16 | - /callpolice - 在线报警
17 | - /status - Bot 连接状态
18 | - /washer - 洗衣机在线状态
19 | - /register - 一键注册防止失学
20 | - /hitreds - 一键打红人
21 | - /payme - 显示你的收款码
22 | - /fan - 发起约饭
23 | - /yue - 约~
24 | - /buyue - 不约~
25 | - /san - 饭饱散伙
26 | - /help - 可用指令说明
27 | - /echo - 回显消息到群 (owner)
28 |
29 | 废弃:
30 |
31 | - /libseat - 查看文图座位剩余情况
32 | - /weather_thu - 显示学校区域当前的天气(学校天气站)
33 | - /weather_today - 显示当前位置的今日天气预报(彩云)
34 |
35 | ## Usage
36 |
37 | ```bash
38 | cp config-sample.ini config.ini
39 | vi config.ini
40 | pm2 start ecosystem.config.js
41 | ```
42 |
--------------------------------------------------------------------------------
/base/config.py:
--------------------------------------------------------------------------------
1 | import configparser
2 |
3 | config = configparser.RawConfigParser()
4 | config.read('config.ini')
5 |
6 | accessToken = config['BOT']['accesstoken']
7 |
8 | group = config['BOT'].getint('group')
9 | channel = config['BOT'].getint('channel')
10 | pipe = config['BOT'].getint('pipe')
11 |
12 | logFile = config['BOT']['logpath'] + 'server'
13 |
14 | heartbeatURL = config['BOT'].get('heartbeat')
15 |
16 | caiyunToken = config['CAIYUN']['token']
17 |
18 | webhookConfig = {
19 | 'listen': config['WEBHOOK']['listen'],
20 | 'port': int(config['WEBHOOK']['port']),
21 | 'cert': config['WEBHOOK']['cert'],
22 | 'webhook_url': config['WEBHOOK']['webhook_url'],
23 | 'secret_token': config['WEBHOOK']['secret_token']
24 | }
25 |
--------------------------------------------------------------------------------
/base/debug.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import functools
3 | import logging
4 | import traceback
5 | from datetime import datetime
6 | from typing import Callable, Optional
7 |
8 | from base.log import logger
9 |
10 |
11 | class IgnoreWarning(Exception):
12 | pass
13 |
14 |
15 | def exception_desc(e: Exception) -> str:
16 | """
17 | Return exception description.
18 | """
19 | if str(e) != '':
20 | return f'{e.__class__.__module__}.{e.__class__.__name__} ({e})'
21 | return f'{e.__class__.__module__}.{e.__class__.__name__}'
22 |
23 |
24 | def eprint(e: Exception, level: int = logging.WARNING, msg: Optional[str] = None, stacklevel: int = 2, print_trace=True) -> None:
25 | """
26 | Print exception with traceback.
27 | """
28 | if not (isinstance(level, int) and level in logging._levelToName):
29 | level = logging.WARNING
30 |
31 | if msg is not None:
32 | logger.log(level, msg, stacklevel=stacklevel)
33 |
34 | exception_str = f'Exception: {exception_desc(e)}'
35 | logger.log(level, exception_str, stacklevel=stacklevel)
36 |
37 | if print_trace:
38 | logger.debug(traceback.format_exc(), stacklevel=stacklevel)
39 |
40 |
41 | def try_except(level: int = logging.WARNING, msg: Optional[str] = None, return_value: bool = True, exclude=(IgnoreWarning,)) -> Callable:
42 | """
43 | Try to execute the function.
44 | If an exception is raised, log it in debug level and return True/False or Return/None.
45 | """
46 | def decorate(func):
47 | if asyncio.iscoroutinefunction(func):
48 | @functools.wraps(func)
49 | async def wrap_async(*args, **kwargs):
50 | try:
51 | ret = await func(*args, **kwargs)
52 | return ret if return_value else True
53 | except exclude as e:
54 | eprint(e, logging.DEBUG, msg, stacklevel=3)
55 | return None if return_value else False
56 | except Exception as e:
57 | eprint(e, level, msg, stacklevel=3)
58 | return None if return_value else False
59 | return wrap_async
60 | else:
61 | @functools.wraps(func)
62 | def wrap(*args, **kwargs):
63 | try:
64 | ret = func(*args, **kwargs)
65 | return ret if return_value else True
66 | except exclude as e:
67 | eprint(e, logging.DEBUG, msg, stacklevel=3)
68 | return None if return_value else False
69 | except Exception as e:
70 | eprint(e, level, msg, stacklevel=3)
71 | return None if return_value else False
72 | return wrap
73 | return decorate
74 |
75 |
76 | def archive(content: str | bytes, suffix: Optional[str] = None) -> str:
77 | """
78 | Archive content to file.
79 | """
80 | now = str(datetime.now()).replace(' ', '_').replace(':', '-')
81 | filepath = f'log/archive/{now}' + (f'.{suffix}' if suffix else '')
82 | if isinstance(content, str):
83 | open(filepath, 'w').write(content)
84 | elif isinstance(content, bytes):
85 | open(filepath, 'wb').write(content)
86 | else:
87 | raise TypeError('content must be str or bytes')
88 | return filepath
89 |
--------------------------------------------------------------------------------
/base/format.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 |
4 | def escaped(str): # MarkdownV2 Mode
5 | return re.sub(r'([\_\*\[\]\(\)\~\`\>\#\+\-\=\|\{\}\.\!])', '\\\\\\1', str)
6 |
--------------------------------------------------------------------------------
/base/log.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import sys
3 | from logging import Filter, StreamHandler
4 | from logging.handlers import TimedRotatingFileHandler
5 |
6 | import colorlog
7 |
8 | from base.config import logFile
9 | from base.sentry import sentry_init
10 |
11 | sentry_init()
12 |
13 |
14 | BASIC_FORMAT = '%(asctime)s - %(levelname)s - %(module)s - %(lineno)d - %(funcName)s - %(message)s'
15 | COLOR_FORMAT = '%(log_color)s%(asctime)s - %(filename)s:%(lineno)d - %(funcName)s - %(message)s'
16 | DATE_FORMAT = None
17 | basic_formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
18 | color_formatter = colorlog.ColoredFormatter(COLOR_FORMAT, DATE_FORMAT)
19 |
20 |
21 | class MaxFilter(Filter):
22 | def __init__(self, max_level):
23 | self.max_level = max_level
24 |
25 | def filter(self, record):
26 | if record.levelno <= self.max_level:
27 | return True
28 |
29 |
30 | class EnhancedRotatingFileHandler(TimedRotatingFileHandler):
31 | def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False):
32 | super().__init__(filename, when, interval, backupCount, encoding, delay, utc)
33 |
34 | def computeRollover(self, currentTime: int):
35 | """
36 | Work out the rollover time based on the specified time.
37 | """
38 | if self.when == 'MIDNIGHT' or self.when.startswith('W'):
39 | return super().computeRollover(currentTime)
40 | if self.when == 'D':
41 | # 8 hours ahead of UTC
42 | return currentTime - currentTime % self.interval + self.interval - 8 * 3600
43 | return currentTime - currentTime % self.interval + self.interval
44 |
45 |
46 | chlr = StreamHandler(stream=sys.stdout)
47 | chlr.setFormatter(color_formatter)
48 | chlr.setLevel('INFO')
49 | chlr.addFilter(MaxFilter(logging.INFO))
50 |
51 | ehlr = StreamHandler(stream=sys.stderr)
52 | ehlr.setFormatter(color_formatter)
53 | ehlr.setLevel('WARNING')
54 |
55 |
56 | fhlr = EnhancedRotatingFileHandler(
57 | logFile, when='H', interval=1, backupCount=24*7)
58 | fhlr.setFormatter(basic_formatter)
59 | fhlr.setLevel('DEBUG')
60 |
61 | # 自行调用 + 模组调用
62 | logger = logging.getLogger()
63 | logger.setLevel('INFO') # 改成 DEBUG 之后,模组自身调用的 logger 也会输出
64 | logger.addHandler(fhlr)
65 |
66 | # 自行调用
67 | logger = logging.getLogger(__name__)
68 | logger.setLevel('DEBUG')
69 | logger.addHandler(chlr)
70 | logger.addHandler(ehlr)
71 |
--------------------------------------------------------------------------------
/base/message.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | from telegram import Bot
4 | from telegram.error import TimedOut
5 |
6 | from base.debug import try_except
7 |
8 |
9 | def init(_bot: Bot):
10 | global bot
11 | bot = _bot
12 |
13 |
14 | """
15 | Using "msg" instead of "message" to avoid conflict with the message module in the python-telegram-bot package.
16 | """
17 |
18 |
19 | @try_except(level=logging.DEBUG, return_value=False, exclude=(TimedOut,))
20 | async def delete_msg(chat_id: str | int, message_id: int, **kwargs):
21 | """
22 | Delete a message.
23 | Return True if successful, False otherwise.
24 | """
25 | await bot.delete_message(chat_id=chat_id, message_id=message_id, **kwargs)
26 |
27 |
28 | @try_except(level=logging.DEBUG, return_value=False, exclude=(TimedOut,))
29 | async def edit_msg_text(chat_id: str | int, message_id: int, text: str, **kwargs):
30 | """
31 | Edit the text of a message.
32 | Return True if successful, False otherwise.
33 | """
34 | await bot.edit_message_text(chat_id=chat_id, message_id=message_id, text=text, **kwargs)
35 |
36 |
37 | @try_except(level=logging.DEBUG, return_value=False, exclude=(TimedOut,))
38 | async def send_msg(chat_id: str | int, text: str, **kwargs):
39 | """
40 | Send a message.
41 | Return True if successful, False otherwise.
42 | """
43 | await bot.send_message(chat_id=chat_id, text=text, **kwargs)
44 |
45 |
46 | @try_except(level=logging.DEBUG, return_value=False, exclude=(TimedOut,))
47 | async def edit_msg_media(chat_id: str | int, message_id: int, media, **kwargs):
48 | """
49 | Edit the media of a message.
50 | Return True if successful, False otherwise.
51 | """
52 | await bot.edit_message_media(chat_id=chat_id, message_id=message_id, media=media, **kwargs)
53 |
--------------------------------------------------------------------------------
/base/mute.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | from telegram import Update
4 | from telegram.ext import ContextTypes
5 |
6 | try:
7 | with open('data/mute.json', 'r') as file:
8 | muted = json.load(file)
9 | except:
10 | muted = []
11 |
12 |
13 | async def mute(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
14 | assert update.effective_chat
15 | if not context.args:
16 | await update.effective_chat.send_message('Usage: /mute [source]')
17 | return
18 | for each in context.args:
19 | if each not in muted:
20 | muted.append(each)
21 | with open('data/mute.json', 'w') as file:
22 | json.dump(muted, file)
23 | await update.effective_chat.send_message('Muted: ' + ' '.join(context.args))
24 |
25 |
26 | async def unmute(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
27 | assert update.effective_chat
28 | if not context.args:
29 | await update.effective_chat.send_message('Usage: /unmute [source]')
30 | return
31 | for each in context.args:
32 | muted.remove(each)
33 | with open('data/mute.json', 'w') as file:
34 | json.dump(muted, file)
35 | await update.effective_chat.send_message('Unmuted: ' + ' '.join(context.args))
36 |
37 |
38 | async def mute_show(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
39 | assert update.effective_chat
40 | text = '\n'.join(['Muted list:'] + muted)
41 | await update.effective_chat.send_message(text)
42 |
--------------------------------------------------------------------------------
/base/network.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import functools
3 | import logging
4 | from asyncio.exceptions import TimeoutError
5 | from typing import Optional
6 |
7 | import aiohttp
8 | from aiohttp.client_exceptions import ContentTypeError
9 |
10 | from base.debug import archive, eprint
11 |
12 |
13 | class ErrorAfterAttempts(Exception):
14 | pass
15 |
16 |
17 | class ErrorStatusCode(Exception):
18 | def __init__(self, status_code: int, content: str | bytes, *args, **kwargs):
19 | self.status_code = status_code
20 | self.archive = archive(content)
21 | super().__init__(*args, **kwargs)
22 |
23 | def __str__(self):
24 | return f'{self.status_code}:{self.archive}'
25 |
26 | def __repr__(self):
27 | return f'ErrorStatusCode ({self.status_code}:{self.archive})'
28 |
29 |
30 | def attempt(times: int, wait: int = 5):
31 | def decorate(func):
32 | @functools.wraps(func)
33 | async def wrap(*args, **kwargs):
34 | for _ in range(times):
35 | try:
36 | return await func(*args, **kwargs)
37 | except TimeoutError as e:
38 | eprint(e, logging.DEBUG, print_trace=False)
39 | except (ErrorStatusCode, ContentTypeError, AssertionError) as e:
40 | eprint(e, logging.DEBUG)
41 | except Exception as e:
42 | raise e
43 | if wait > 0:
44 | await asyncio.sleep(wait)
45 | else:
46 | raise ErrorAfterAttempts(f'Network error in {times} attempts')
47 | return wrap
48 | return decorate
49 |
50 |
51 | # ==================== GET ====================
52 |
53 |
54 | @attempt(3)
55 | async def get(url: str, timeout: float = 15, **kwargs) -> bytes:
56 | _timeout = aiohttp.ClientTimeout(total=timeout)
57 | async with aiohttp.request('GET', url, timeout=_timeout, **kwargs) as r:
58 | content = await r.read()
59 | return content
60 |
61 |
62 | @attempt(3)
63 | async def get_redirect(url: str, timeout: float = 15, **kwargs) -> Optional[str]:
64 | _timeout = aiohttp.ClientTimeout(total=timeout)
65 | async with aiohttp.request('GET', url, timeout=_timeout, allow_redirects=False, **kwargs) as r:
66 | if r.status in (301, 302):
67 | return r.headers['Location']
68 | return None
69 |
70 |
71 | @attempt(3)
72 | async def get_noreturn(url: str, timeout: float = 15, **kwargs) -> None:
73 | _timeout = aiohttp.ClientTimeout(total=timeout)
74 | async with aiohttp.request('GET', url, timeout=_timeout, **kwargs) as r:
75 | await r.read()
76 |
77 |
78 | @attempt(3)
79 | async def get_str(url: str, timeout: float = 15, **kwargs) -> str:
80 | _timeout = aiohttp.ClientTimeout(total=timeout)
81 | async with aiohttp.request('GET', url, timeout=_timeout, **kwargs) as r:
82 | content = await r.text()
83 | if r.status != 200:
84 | raise ErrorStatusCode(r.status, content)
85 | return content
86 |
87 |
88 | @attempt(3)
89 | async def get_json(url: str, timeout: float = 15, **kwargs) -> dict | list:
90 | _timeout = aiohttp.ClientTimeout(total=timeout)
91 | async with aiohttp.request('GET', url, timeout=_timeout, **kwargs) as r:
92 | data = await r.json()
93 | return data
94 |
95 |
96 | @attempt(3)
97 | async def get_dict(url: str, timeout: float = 15, **kwargs) -> dict:
98 | _timeout = aiohttp.ClientTimeout(total=timeout)
99 | async with aiohttp.request('GET', url, timeout=_timeout, **kwargs) as r:
100 | data = await r.json()
101 | assert isinstance(data, dict), f'Expect dict, but got {type(data)}'
102 | return data
103 |
104 |
105 | @attempt(3)
106 | async def get_photo(url: str, timeout: float = 15, **kwargs) -> bytes:
107 | _timeout = aiohttp.ClientTimeout(total=timeout)
108 | async with aiohttp.request('GET', url, timeout=_timeout, **kwargs) as r:
109 | content = await r.read()
110 | assert len(content) >= 1024, f'Photo size is too small: {
111 | len(content)}, it may be wrong.'
112 | return content
113 |
114 |
115 | # ==================== POST ====================
116 |
117 | @attempt(3)
118 | async def post(url: str, data=None, timeout: float = 15, **kwargs) -> bytes:
119 | _timeout = aiohttp.ClientTimeout(total=timeout)
120 | async with aiohttp.request('POST', url, data=data, timeout=_timeout, **kwargs) as r:
121 | content = await r.read()
122 | return content
123 |
124 |
125 | @attempt(3)
126 | async def post_json(url: str, data=None, timeout: float = 15, **kwargs) -> dict | list:
127 | _timeout = aiohttp.ClientTimeout(total=timeout)
128 | async with aiohttp.request('POST', url, data=data, timeout=_timeout, **kwargs) as r:
129 | data = await r.json()
130 | return data
131 |
132 |
133 | @attempt(3)
134 | async def post_dict(url: str, data=None, timeout: float = 15, **kwargs) -> dict:
135 | _timeout = aiohttp.ClientTimeout(total=timeout)
136 | async with aiohttp.request('POST', url, data=data, timeout=_timeout, **kwargs) as r:
137 | data = await r.json()
138 | assert isinstance(data, dict), f'Expect dict, but got {type(data)}'
139 | return data
140 |
141 |
142 | @attempt(3)
143 | async def post_status(url: str, data=None, timeout: float = 15, **kwargs) -> tuple[str, int]:
144 | _timeout = aiohttp.ClientTimeout(total=timeout)
145 | async with aiohttp.request('POST', url, data=data, timeout=_timeout, **kwargs) as r:
146 | content = await r.text()
147 | status = r.status
148 | return content, status
149 |
--------------------------------------------------------------------------------
/base/pool.py:
--------------------------------------------------------------------------------
1 | import json
2 | import traceback
3 | from datetime import datetime, timedelta
4 |
5 | from telegram import Message
6 | from telegram.ext import ContextTypes
7 |
8 | from base.config import group
9 | from base.log import logger
10 |
11 | try:
12 | with open('data/msgpool.json', 'r') as file:
13 | msg_pool = json.load(file)
14 | for x in msg_pool:
15 | x[0] = datetime.fromisoformat(x[0])
16 | except:
17 | msg_pool = []
18 |
19 |
20 | def add_pool(msg: Message) -> None:
21 | if msg.chat.id == group:
22 | msg_pool.append((msg.date, msg.chat.id, msg.message_id))
23 |
24 |
25 | async def auto_delete(context: ContextTypes.DEFAULT_TYPE) -> None:
26 | tot = 0
27 | for x in msg_pool:
28 | if x[0] < datetime.now(x[0].tzinfo) - timedelta(days=1):
29 | tot += 1
30 | try:
31 | await context.bot.delete_message(chat_id=x[1], message_id=x[2])
32 | except Exception as e:
33 | if 'Message to delete not found' not in str(e):
34 | logger.warning(traceback.format_exc())
35 | pass
36 | else:
37 | break
38 | del msg_pool[:tot]
39 | with open('data/msgpool.json', 'w') as file:
40 | json.dump(msg_pool, file, default=str)
41 |
--------------------------------------------------------------------------------
/base/sentry.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from datetime import datetime
3 |
4 | import sentry_sdk
5 | from sentry_sdk.integrations.logging import SentryHandler
6 |
7 | from base.config import config
8 |
9 | SENTRY_INIT = False
10 |
11 |
12 | def sentry_init():
13 | global SENTRY_INIT
14 | if SENTRY_INIT:
15 | return
16 | SENTRY_INIT = True
17 |
18 | if 'SENTRY' not in config or config['SENTRY'].get('dsn') is None:
19 | return
20 |
21 | sentry_sdk.init(
22 | dsn=config['SENTRY']['dsn'],
23 | release=datetime.now().strftime('%Y-%m-%d'),
24 | attach_stacktrace=True,
25 | # Set traces_sample_rate to 1.0 to capture 100%
26 | # of transactions for tracing.
27 | traces_sample_rate=1.0,
28 | _experiments={
29 | # Set continuous_profiling_auto_start to True
30 | # to automatically start the profiler on when
31 | # possible.
32 | "continuous_profiling_auto_start": True,
33 | },
34 | )
35 |
36 | shlr = SentryHandler()
37 | shlr.setLevel('WARNING')
38 | logging.getLogger().addHandler(shlr)
39 | logging.getLogger(__name__).addHandler(shlr)
40 |
--------------------------------------------------------------------------------
/base/weather.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | import aiohttp
4 |
5 | from base.config import caiyunToken
6 | from base.network import attempt
7 |
8 | # ==================== function ====================
9 |
10 |
11 | class CaiyunAPIError(Exception):
12 | pass
13 |
14 |
15 | def level_rain(intensity: str | float) -> str:
16 | """降雨量等级"""
17 | intensity = float(intensity)
18 | if intensity == 0:
19 | return '无'
20 | elif intensity < 0.031:
21 | return '毛毛雨'
22 | elif intensity < 0.25:
23 | return '小雨'
24 | elif intensity < 0.35:
25 | return '中雨'
26 | elif intensity < 0.48:
27 | return '大雨'
28 | else:
29 | return '暴雨'
30 |
31 |
32 | def level_windspeed(speed: str | float) -> str:
33 | """风速等级"""
34 | speed = float(speed)
35 | if speed <= 0.2:
36 | return 'Lv 0'
37 | elif speed <= 1.5:
38 | return 'Lv 1'
39 | elif speed <= 3.3:
40 | return 'Lv 2'
41 | elif speed <= 5.4:
42 | return 'Lv 3'
43 | elif speed <= 7.9:
44 | return 'Lv 4'
45 | elif speed <= 10.7:
46 | return 'Lv 5'
47 | elif speed <= 13.8:
48 | return 'Lv 6'
49 | elif speed <= 17.1:
50 | return 'Lv 7'
51 | elif speed <= 20.7:
52 | return 'Lv 8'
53 | elif speed <= 24.4:
54 | return 'Lv 9'
55 | elif speed <= 28.4:
56 | return 'Lv 10'
57 | elif speed <= 32.6:
58 | return 'Lv 11'
59 | elif speed <= 36.9:
60 | return 'Lv 12'
61 | elif speed <= 41.4:
62 | return 'Lv 13'
63 | elif speed <= 46.1:
64 | return 'Lv 14'
65 | elif speed <= 50.9:
66 | return 'Lv 15'
67 | elif speed <= 56.0:
68 | return 'Lv 16'
69 | elif speed <= 61.2:
70 | return 'Lv 17'
71 | else:
72 | return 'Lv 17+'
73 |
74 |
75 | def type_alert(alert: str) -> str:
76 | """预警类型"""
77 | switchA = {
78 | '01': '台风',
79 | '02': '暴雨',
80 | '03': '暴雪',
81 | '04': '寒潮',
82 | '05': '大风',
83 | '06': '沙尘暴',
84 | '07': '高温',
85 | '08': '干旱',
86 | '09': '雷电',
87 | '10': '冰雹',
88 | '11': '霜冻',
89 | '12': '大雾',
90 | '13': '霾',
91 | '14': '道路结冰',
92 | '15': '森林火灾',
93 | '16': '雷雨大风',
94 | '18': '沙尘'
95 | }
96 | switchB = {
97 | '01': '蓝色预警',
98 | '02': '黄色预警',
99 | '03': '橙色预警',
100 | '04': '红色预警'
101 | }
102 | try:
103 | return switchA[alert[:2]] + switchB[alert[-2:]]
104 | except KeyError:
105 | return alert + '(UnknownCode)'
106 |
107 |
108 | def type_skycon(skycon: str) -> str:
109 | """天气类型"""
110 | switch = {
111 | 'CLEAR_DAY': '晴',
112 | 'CLEAR_NIGHT': '晴',
113 | 'PARTLY_CLOUDY_DAY': '多云',
114 | 'PARTLY_CLOUDY_NIGHT': '多云',
115 | 'CLOUDY': '阴',
116 | 'LIGHT_HAZE': '轻度雾霾',
117 | 'MODERATE_HAZE': '中度雾霾',
118 | 'HEAVY_HAZE': '重度雾霾',
119 | 'HAZE': '雾霾',
120 | 'LIGHT_RAIN': '小雨',
121 | 'MODERATE_RAIN': '中雨',
122 | 'HEAVY_RAIN': '大雨',
123 | 'STORM_RAIN': '暴雨',
124 | 'RAIN': '雨',
125 | 'FOG': '雾',
126 | 'LIGHT_SNOW': '小雪',
127 | 'MODERATE_SNOW': '中雪',
128 | 'HEAVY_SNOW': '大雪',
129 | 'STORM_SNOW': '暴雪',
130 | 'SNOW': '雪',
131 | 'WIND': '大风',
132 | 'DUST': '浮尘',
133 | 'SAND': '沙尘',
134 | 'THUNDER_SHOWER': '雷阵雨',
135 | 'HAIL': '冰雹',
136 | 'SLEET': '雨夹雪'
137 | }
138 | try:
139 | return switch[skycon]
140 | except KeyError:
141 | return skycon
142 |
143 |
144 | def wind_direction(dir: str | float) -> str:
145 | """风向"""
146 |
147 | def dir_diff(a: float, b: float) -> float:
148 | c = a - b
149 | c = c - 360 if c > 180 else c
150 | c = c + 360 if c < -180 else c
151 | return c
152 |
153 | def dir_diff_abs(a: float, b: float) -> float:
154 | a, b = max(a, b), min(a, b)
155 | return min(a - b, 360 - (a - b))
156 |
157 | dir = float(dir)
158 | dir_val = [0, 45, 90, 135, 180, 225, 270, 315]
159 | dir_desc = ['正北', '东北', '正东', '东南', '正南', '西南', '正西', '西北']
160 | dir_bias = ['西东', '北东', '北南', '东南', '东西', '南西', '南北', '西北']
161 |
162 | main_dir = 0
163 | for i in range(1, 8):
164 | if dir_diff_abs(dir, dir_val[i]) < dir_diff_abs(dir, dir_val[main_dir]):
165 | main_dir = i
166 | if dir_diff(dir, dir_val[main_dir]) < 0:
167 | return dir_desc[main_dir] + '偏' + dir_bias[main_dir][0]
168 | else:
169 | return dir_desc[main_dir] + '偏' + dir_bias[main_dir][1]
170 |
171 |
172 | # ==================== alert ====================
173 |
174 |
175 | def alert_now(data: dict) -> list[str]:
176 | """
177 | 获取当前预警信息
178 | """
179 |
180 | data = data['result']['alert']
181 | alerts = []
182 | if data['status'] == 'ok':
183 | alerts = [type_alert(each['code'])
184 | for each in data['content'] if each['request_status'] == 'ok']
185 | return alerts
186 |
187 | # ==================== weather ====================
188 |
189 |
190 | def temp_min(data) -> float:
191 | return min(float(hour['value'])
192 | for hour in data['result']['hourly']['temperature'][:12])
193 |
194 |
195 | def temp_max(data) -> float:
196 | return max(float(hour['value'])
197 | for hour in data['result']['hourly']['temperature'][:12])
198 |
199 |
200 | def humi_avg(data) -> float:
201 | humi_sum = sum(float(hour['value'])
202 | for hour in data['result']['hourly']['humidity'][:12])
203 | return round(humi_sum / 12, 2)
204 |
205 |
206 | def wind_avg(data) -> float:
207 | wind_sum = sum(float(hour['speed'])
208 | for hour in data['result']['hourly']['wind'][:12])
209 | return round(wind_sum / 12, 1)
210 |
211 |
212 | def vis_avg(data) -> float:
213 | vis_sum = sum(float(hour['value'])
214 | for hour in data['result']['hourly']['visibility'][:12])
215 | return round(vis_sum / 12, 2)
216 |
217 |
218 | def aqi_avg(data) -> int:
219 | aqi_sum = sum(float(hour['value']['chn'])
220 | for hour in data['result']['hourly']['air_quality']['aqi'][:12])
221 | return int(aqi_sum / 12)
222 |
223 |
224 | def daily_weather(data: dict, hour: int, more: bool = True) -> str:
225 | """
226 | 获取日间或晚间天气信息
227 | :param hour: 当前小时
228 | """
229 | if 6 <= hour < 18:
230 | infos = [
231 | '天气:{}'.format(data['result']['hourly']['description']),
232 | '白天气温:{}~{}℃'.format(data['result']['daily']['temperature_08h_20h'][0]
233 | ['min'], data['result']['daily']['temperature_08h_20h'][0]['max']),
234 | '近12小时气温:{}~{}℃'.format(temp_min(data), temp_max(data)),
235 | '湿度:{}%'.format(int(humi_avg(data)*100)),
236 | '风速:{}m/s ({})'.format(wind_avg(data),
237 | level_windspeed(wind_avg(data))),
238 | '能见度:{}km'.format(vis_avg(data)),
239 | '今日日出:{}'.format(data['result']['daily']
240 | ['astro'][0]['sunrise']['time']),
241 | '今日日落:{}'.format(data['result']['daily']
242 | ['astro'][0]['sunset']['time']),
243 | 'AQI:{}'.format(aqi_avg(data)),
244 | '紫外线:{}'.format(data['result']['daily']
245 | ['life_index']['ultraviolet'][0]['desc']),
246 | '舒适度:{}'.format(data['result']['daily']
247 | ['life_index']['comfort'][0]['desc']),
248 | ('现挂预警信号:{}'.format(' '.join(alert_now(data)))
249 | if alert_now(data) != [] else ''),
250 | ]
251 | else:
252 | infos = [
253 | '天气:{}'.format(data['result']['hourly']['description']),
254 | '夜间气温:{}~{}℃'.format(data['result']['daily']['temperature_20h_32h'][0]
255 | ['min'], data['result']['daily']['temperature_20h_32h'][0]['max']),
256 | '近12小时气温:{}~{}℃'.format(temp_min(data), temp_max(data)),
257 | '湿度:{}%'.format(int(humi_avg(data)*100)),
258 | '风速:{}m/s ({})'.format(wind_avg(data),
259 | level_windspeed(wind_avg(data))),
260 | '能见度:{}km'.format(vis_avg(data)),
261 | '明日日出:{}'.format(data['result']['daily']
262 | ['astro'][1]['sunrise']['time']),
263 | '明日日落:{}'.format(data['result']['daily']
264 | ['astro'][1]['sunset']['time']),
265 | 'AQI:{}'.format(aqi_avg(data)),
266 | '紫外线:{}'.format(data['result']['daily']
267 | ['life_index']['ultraviolet'][0]['desc']),
268 | '舒适度:{}'.format(data['result']['daily']
269 | ['life_index']['comfort'][0]['desc']),
270 | ('现挂预警信号:{}'.format(' '.join(alert_now(data)))
271 | if alert_now(data) != [] else ''),
272 | ]
273 | if more:
274 | return '\n'.join(infos)
275 | else:
276 | return '\n'.join(infos[0:2] + infos[3:5] + infos[-1:])
277 |
278 |
279 | def now_weather(data: dict) -> str:
280 | """
281 | 获取当前天气信息
282 | """
283 | text = ''
284 | text += '清华当前天气:{}\n'.format(
285 | type_skycon(data['result']['realtime']['skycon']))
286 | text += '温度:{}℃\n'.format(
287 | data['result']['realtime']['temperature'])
288 | if 'apparent_temperature' in data['result']['realtime']:
289 | text += '体感:{}℃\n'.format(
290 | data['result']['realtime']['apparent_temperature'])
291 | text += '湿度:{}%\n'.format(
292 | int(float(data['result']['realtime']['humidity']) * 100))
293 | text += '风向:{}\n'.format(
294 | wind_direction(data['result']['realtime']['wind']['direction']))
295 | text += '风速:{}m/s ({})\n'.format(
296 | data['result']['realtime']['wind']['speed'],
297 | level_windspeed(data['result']['realtime']['wind']['speed']))
298 | if data['result']['realtime']['precipitation']['local']['status'] == 'ok':
299 | text += '降水:{}\n'.format(
300 | level_rain(data['result']['realtime']['precipitation']['local']['intensity']))
301 | text += '能见度:{}km\n'.format(
302 | data['result']['realtime']['visibility'])
303 | text += 'PM2.5:{}\n'.format(
304 | data['result']['realtime']['air_quality']['pm25'])
305 | text += 'AQI:{} ({})\n'.format(
306 | data['result']['realtime']['air_quality']['aqi']['chn'],
307 | data['result']['realtime']['air_quality']['description']['chn'])
308 | text += '紫外线:{}\n'.format(
309 | data['result']['realtime']['life_index']['ultraviolet']['desc'])
310 | text += '舒适度:{}\n'.format(
311 | data['result']['realtime']['life_index']['comfort']['desc'])
312 | alert_signal = alert_now(data)
313 | if alert_signal != []:
314 | text += '现挂预警信号:{}\n'.format(' '.join(alert_signal))
315 | return text
316 |
317 |
318 | @attempt(5, wait=0)
319 | async def caiyun_api_get(url: str, timeout: float = 1, **kwargs) -> dict:
320 | # 针对一个 api 行为的猜测:对于非家宽 IP,服务器有 1/2 的概率无响应
321 | # 为了提高成功率,设置 1s 超时,且重试 5 次。如果假设成立的话,失败的概率只有 1/32,且不会超过 5s
322 | _timeout = aiohttp.ClientTimeout(total=timeout)
323 | async with aiohttp.request('GET', url, timeout=_timeout, **kwargs) as r:
324 | data = await r.json()
325 | assert isinstance(data, dict), f'Expect dict, but got {type(data)}'
326 | return data
327 |
328 |
329 | async def caiyun_api(longitude, latitude):
330 | """
331 | 获取彩云天气数据
332 | """
333 | url = 'https://api.caiyunapp.com/v2.6/%s/%s,%s/weather.json?lang=zh_CN&alert=true' % (
334 | caiyunToken, longitude, latitude)
335 | data = await caiyun_api_get(url)
336 | if data.get('status') != 'ok':
337 | raise CaiyunAPIError(f'彩云天气 API 返回错误: {json.dumps(data)}')
338 | return data
339 |
--------------------------------------------------------------------------------
/base/webvpn.py:
--------------------------------------------------------------------------------
1 | import binascii
2 | import re
3 |
4 | from Crypto.Cipher import AES
5 |
6 |
7 | def webvpn(url):
8 |
9 | encryStr = b'wrdvpnisthebest!'
10 |
11 | def encrypt(url):
12 | url = str.encode(url)
13 | cryptor = AES.new(encryStr, AES.MODE_CFB, encryStr, segment_size=16*8)
14 |
15 | return bytes.decode(binascii.b2a_hex(encryStr)) + \
16 | bytes.decode(binascii.b2a_hex(cryptor.encrypt(url)))
17 |
18 | if url[0:7] == 'http://':
19 | url = url[7:]
20 | protocol = 'http'
21 | elif url[0:8] == 'https://':
22 | url = url[8:]
23 | protocol = 'https'
24 |
25 | v6 = re.match('[0-9a-fA-F:]+', url)
26 | if v6 != None:
27 | v6 = v6.group(0)
28 | url = url[len(v6):]
29 |
30 | segments = url.split('?')[0].split(':')
31 | port = None
32 | if len(segments) > 1:
33 | port = segments[1].split('/')[0]
34 | url = url[0: len(segments[0])] + url[len(segments[0]) + len(port) + 1:]
35 |
36 | try:
37 | idx = url.index('/')
38 | host = url[0: idx]
39 | path = url[idx:]
40 | if v6 != None:
41 | host = v6
42 | url = encrypt(host) + path
43 | except:
44 | if v6 != None:
45 | url = v6
46 | url = encrypt(url)
47 |
48 | if port != None:
49 | url = 'https://webvpn.tsinghua.edu.cn/' + protocol + '-' + port + '/' + url
50 | else:
51 | url = 'https://webvpn.tsinghua.edu.cn/' + protocol + '/' + url
52 |
53 | return url
54 |
--------------------------------------------------------------------------------
/bot.py:
--------------------------------------------------------------------------------
1 | import configparser
2 | import logging
3 | import sys
4 | import traceback
5 | from datetime import datetime, time, timedelta
6 | from logging import Filter
7 | from logging.handlers import TimedRotatingFileHandler
8 | from typing import Optional
9 |
10 | from pytz import timezone
11 | from telegram import (BotCommandScopeChat, BotCommandScopeDefault, Chat,
12 | Message, Update)
13 | from telegram.error import Forbidden, TelegramError
14 | from telegram.ext import (Application, CommandHandler, ContextTypes, JobQueue,
15 | MessageHandler, Updater, filters)
16 |
17 | from base import message
18 | from base.config import accessToken, group, pipe, webhookConfig
19 | from base.log import logger
20 | from base.mute import mute, mute_show, unmute
21 | from base.pool import auto_delete
22 | from command.gadget import (callpolice, fan, gu, payme, payme_upload, register,
23 | roll, san, yue)
24 | from command.heartbeat import send_heartbeat
25 | from command.info import daily_report, info
26 | from command.weather import (realtime_forecast, realtime_weather, weather_poll,
27 | weather_report)
28 |
29 |
30 | async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
31 | """Log the error for debuging."""
32 | logger.error("Exception while handling an update: %s", context.error)
33 | logger.debug(msg="The traceback of the exception:", exc_info=context.error)
34 |
35 | update_str = update.to_dict() if isinstance(update, Update) else str(update)
36 | logger.debug(update_str)
37 |
38 |
39 | def main():
40 | """Start the bot."""
41 | app = Application.builder().token(accessToken).build()
42 |
43 | app.add_error_handler(error_handler)
44 | message.init(app.bot)
45 |
46 | f_group = filters.Chat(group)
47 | f_pipe = filters.Chat(pipe)
48 |
49 | assert app.job_queue
50 | job: JobQueue = app.job_queue
51 | tz = timezone("Asia/Shanghai") # local_tz
52 | jk = {"misfire_grace_time": None} # job_kwargs
53 |
54 | groupCommands = []
55 | allCommands = []
56 |
57 | # ===== weather =====
58 | # 定期获取天气数据
59 | job.run_repeating(weather_poll, interval=60, first=0, job_kwargs=jk)
60 | # 当前位置天气
61 | app.add_handler(CommandHandler('weather', realtime_weather))
62 | allCommands.append(('weather', '此时清华的天气', 45))
63 | # 当前位置降雨概率
64 | app.add_handler(CommandHandler('forecast', realtime_forecast))
65 | allCommands.append(('forecast', '此时清华的降雨概率', 46))
66 | # 天气预报以及更新
67 | for hour in range(24):
68 | job.run_daily(weather_report, time=time(hour, 0, 0, tzinfo=tz),
69 | data=hour, name='weather_report')
70 |
71 | # ===== info =====
72 | app.add_handler(CommandHandler('mute', mute, filters=f_group))
73 | groupCommands.append(('mute', '屏蔽发布源', 71))
74 | app.add_handler(CommandHandler('unmute', unmute, filters=f_group))
75 | groupCommands.append(('unmute', '解除屏蔽发布源', 72))
76 | app.add_handler(CommandHandler('mute_list', mute_show, filters=f_group))
77 | groupCommands.append(('mute_list', '列出所有被屏蔽的发布源', 73))
78 | app.add_handler(MessageHandler(
79 | f_pipe & filters.UpdateType.CHANNEL_POST, info))
80 | job.run_daily(daily_report, time=time(23, 0, 0, tzinfo=tz))
81 |
82 | # ===== gadget =====
83 | app.add_handler(CommandHandler('roll', roll))
84 | allCommands.append(('roll', '从 1 开始的随机数', 81))
85 | app.add_handler(CommandHandler('callpolice', callpolice))
86 | allCommands.append(('callpolice', '在线报警', 82))
87 | app.add_handler(CommandHandler('register', register))
88 | allCommands.append(('register', '一键注册防止失学', 83))
89 |
90 | # ===== yue =====
91 | app.add_handler(CommandHandler('payme', payme, filters=f_group))
92 | groupCommands.append(('payme', '显示你的收款码', 121))
93 | app.add_handler(CommandHandler('fan', fan, filters=f_group))
94 | groupCommands.append(('fan', '发起约饭', 122))
95 | app.add_handler(CommandHandler('yue', yue, filters=f_group))
96 | groupCommands.append(('yue', '约~', 123))
97 | app.add_handler(CommandHandler('buyue', gu, filters=f_group))
98 | groupCommands.append(('buyue', '不约~', 124))
99 | app.add_handler(CommandHandler('san', san, filters=f_group))
100 | groupCommands.append(('san', '饭饱散伙', 125))
101 | app.add_handler(MessageHandler(
102 | filters.ChatType.PRIVATE & filters.PHOTO, payme_upload))
103 |
104 | # ===== other =====
105 | job.run_repeating(send_heartbeat, interval=60, first=0, job_kwargs=jk)
106 | job.run_repeating(auto_delete, interval=60, first=30, job_kwargs=jk)
107 |
108 | # Add commands into menu
109 | groupCommands += allCommands
110 | groupCommands = sorted(groupCommands, key=lambda x: x[2])
111 | groupCommands = [(x[0], x[1]) for x in groupCommands]
112 | allCommands = sorted(allCommands, key=lambda x: x[2])
113 | allCommands = [(x[0], x[1]) for x in allCommands]
114 |
115 | async def set_commands(context: ContextTypes.DEFAULT_TYPE):
116 | await context.bot.set_my_commands(allCommands, scope=BotCommandScopeDefault())
117 | await context.bot.set_my_commands(groupCommands, scope=BotCommandScopeChat(group))
118 | job.run_once(set_commands, when=0, job_kwargs=jk)
119 |
120 | logger.info('bot start')
121 | app.run_webhook(**webhookConfig)
122 |
123 |
124 | if __name__ == '__main__':
125 | main()
126 |
--------------------------------------------------------------------------------
/command/gadget.py:
--------------------------------------------------------------------------------
1 | import io
2 | import json
3 | import os
4 | import re
5 | import time
6 | from pathlib import Path
7 | from random import Random
8 | from typing import Optional
9 |
10 | import numpy as np
11 | import qrcode
12 | from PIL import Image
13 | from pyzbar.pyzbar import decode
14 | from telegram import InputMediaPhoto, Update
15 | from telegram.ext import ContextTypes
16 |
17 | from base.debug import eprint
18 | from base.format import escaped
19 | from base.log import logger
20 |
21 |
22 | async def roll(update: Update, context: ContextTypes.DEFAULT_TYPE):
23 | assert update.message
24 | try:
25 | assert context.args
26 | rd = Random(int(time.time()))
27 | await update.message.reply_text(f'Choose: {rd.randint(1, int(context.args[0]))}')
28 | except:
29 | await update.message.reply_text('Usage: /roll [total]')
30 |
31 |
32 | async def callpolice(update: Update, context: ContextTypes.DEFAULT_TYPE):
33 | assert update.effective_chat
34 | rd = Random(int(time.time()))
35 | emoji = '👮🚔🚨🚓'
36 | text = ''.join([emoji[rd.randint(0, 3)]
37 | for _ in range(rd.randint(10, 100))])
38 | await update.effective_chat.send_message(text)
39 |
40 |
41 | dig = np.array([
42 | [1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1,
43 | 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1],
44 | [1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1,
45 | 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1],
46 | [1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0,
47 | 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0],
48 | [0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0,
49 | 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1],
50 | [1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1,
51 | 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0],
52 | [0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1,
53 | 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1],
54 | [1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0,
55 | 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1],
56 | [0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1,
57 | 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
58 | [1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0,
59 | 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1],
60 | [1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0,
61 | 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1],
62 | ]) * 255
63 |
64 |
65 | def generator_register(id: str, tm: str) -> Optional[str]:
66 | try:
67 | pic = f'./tmp/{id}_{tm}.png'
68 | if not os.path.exists(pic):
69 | tmp = f'./tmp/{int(time.time())}.png'
70 | qrcode.make(id).save(tmp) # type: ignore
71 | bg = np.array(Image.open('template/template.jpg').convert('L'))
72 | tmp = np.array(Image.open(tmp).convert('L'))[40:-45, 40:-45]
73 | tmp = np.array(Image.fromarray(tmp).resize((41, 41)))
74 | bg[14:55, 25:66] = tmp
75 | points = [29, 35, 41, 47, 53, 59]
76 | edit = [int(_) for _ in tm]
77 | for i in range(6):
78 | x, y, d = 55, points[i], edit[i]
79 | bg[x:x+7, y:y+4] = dig[d].reshape(7, 4)
80 | Image.fromarray(bg).save(pic)
81 | return pic
82 | except Exception as e:
83 | eprint(e)
84 |
85 |
86 | async def register(update: Update, context: ContextTypes.DEFAULT_TYPE):
87 | assert update.message
88 | args = context.args
89 | logger.info(f'\\register {update.message.chat_id} {json.dumps(args)}')
90 |
91 | try:
92 | assert args
93 | assert len(args) == 2
94 | assert len(re.findall(r'^\d{10}$', args[0])) == 1
95 | assert len(re.findall(r'^\d{6}$', args[1])) == 1
96 |
97 | pic = generator_register(args[0], args[1])
98 | assert pic is not None
99 | await update.message.reply_photo(open(pic, 'rb'))
100 | Path(pic).unlink()
101 | except:
102 | await update.message.reply_text('Usage: /register [StudentID] [Month]\nExample: /register 1994990239 202102')
103 |
104 |
105 | users = {}
106 |
107 |
108 | async def yue(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
109 | assert update.message and update.message.from_user
110 | user_id = update.message.from_user.id
111 | user_name = update.message.from_user.name
112 | users[user_id] = user_name
113 | await update.message.reply_text('约😘')
114 |
115 |
116 | async def gu(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
117 | assert update.message and update.message.from_user
118 | user_id = update.message.from_user.id
119 | if user_id in users:
120 | del users[user_id]
121 | await update.message.reply_text('不约😭')
122 |
123 |
124 | async def fan(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
125 | assert update.message
126 | if len(users) == 0:
127 | await update.message.reply_text('没人约😭')
128 | return
129 | info = ' '.join([f'[{escaped(user_name)}](tg://user?id={user_id})'
130 | for user_id, user_name in users.items()])
131 | await update.message.reply_markdown_v2(info)
132 |
133 |
134 | async def san(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
135 | assert update.message
136 | global users
137 | users = {}
138 | await update.message.reply_text('散🎉')
139 |
140 |
141 | async def payme_upload(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
142 | assert update.message and update.message.from_user
143 | user_id = update.message.from_user.id
144 | folder = Path(f'./data/pay/{user_id}')
145 | folder.mkdir(exist_ok=True)
146 | try:
147 | file = await update.message.photo[-1].get_file()
148 | buf = await file.download_as_bytearray()
149 | for res in decode(Image.open(io.BytesIO(buf))):
150 | url: str = res.data.decode()
151 | if url.startswith('https://qr.alipay.com/'):
152 | with (folder / 'ali.png').open('wb') as f:
153 | f.write(buf)
154 | await update.message.reply_text('检测到:Alipay 收款码')
155 | return
156 | elif url.startswith('wxp://'):
157 | with (folder / 'wx.png').open('wb') as f:
158 | f.write(buf)
159 | await update.message.reply_text('检测到:Wechat 收款码')
160 | return
161 | elif url.startswith('https://qr.95516.com/'):
162 | with (folder / 'uni.png').open('wb') as f:
163 | f.write(buf)
164 | await update.message.reply_text('检测到:UnionPay 收款码')
165 | return
166 | else:
167 | await update.message.reply_text('Unsupported QRCode')
168 | logger.warning(url)
169 | return
170 | except Exception as e:
171 | await update.message.reply_text('QRCode not found')
172 | eprint(e)
173 |
174 |
175 | async def payme(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
176 | assert update.message and update.message.from_user
177 | user_id = update.message.from_user.id
178 | folder = Path(f'./data/pay/{user_id}')
179 | if not (folder.exists() and len(list(folder.iterdir()))):
180 | await update.message.reply_text('No QRCodes found, send to me first!')
181 | return
182 | images = [InputMediaPhoto(file.open('rb')) for file in folder.iterdir()]
183 | await update.message.reply_media_group(images)
184 |
--------------------------------------------------------------------------------
/command/heartbeat.py:
--------------------------------------------------------------------------------
1 | from telegram.ext import ContextTypes
2 |
3 | from base import network
4 | from base.config import heartbeatURL
5 | from base.log import logger
6 |
7 |
8 | async def send_heartbeat(context: ContextTypes.DEFAULT_TYPE) -> None:
9 | logger.debug('heartbeat')
10 | await network.get(url=heartbeatURL)
11 |
--------------------------------------------------------------------------------
/command/info.py:
--------------------------------------------------------------------------------
1 | import json
2 | import traceback
3 |
4 | from telegram import Update
5 | from telegram.ext import ContextTypes
6 |
7 | import base.mute as mt
8 | from base.config import group
9 | from base.format import escaped
10 | from base.log import logger
11 | from base.webvpn import webvpn
12 |
13 | try:
14 | with open('data/today.json', 'r') as file:
15 | today = json.load(file)
16 | except:
17 | today = {}
18 |
19 |
20 | async def info(update: Update, context: ContextTypes.DEFAULT_TYPE):
21 | assert update.channel_post and update.channel_post.text
22 | try:
23 | rev = json.loads(update.channel_post.text)
24 | logger.info(rev)
25 | data = rev['data']
26 |
27 | if rev['type'] == 'newinfo':
28 | url = data['url']
29 | today[url] = data
30 | today[url]['msgid'] = None
31 | if data['source'] not in mt.muted:
32 | text = 'Info %s\n[%s](%s) [\\(webvpn\\)](%s)' % (escaped(
33 | data['source']), escaped(data['title']), data['url'], webvpn(data['url']))
34 | msg = await context.bot.send_message(
35 | chat_id=group, text=text, parse_mode='MarkdownV2', disable_web_page_preview=True)
36 | today[url]['msgid'] = msg.message_id
37 |
38 | elif rev['type'] == 'delinfo':
39 | url = data
40 | if url in today.keys():
41 | if today[url]['msgid'] is not None:
42 | await context.bot.delete_message(chat_id=group, message_id=today[url]['msgid'])
43 | del today[url]
44 |
45 | with open('data/today.json', 'w') as file:
46 | json.dump(today, file)
47 |
48 | except Exception as e:
49 | logger.error(e)
50 | logger.debug(traceback.format_exc())
51 |
52 |
53 | def info_daily(clear=True):
54 | ret = {}
55 | for info in today.values():
56 | if info['source'] not in ret.keys():
57 | ret[info['source']] = []
58 | ret[info['source']].append(info)
59 | if clear:
60 | today.clear()
61 | with open('data/today.json', 'w') as file:
62 | json.dump(today, file)
63 | return ret
64 |
65 |
66 | async def daily_report(context: ContextTypes.DEFAULT_TYPE):
67 | text = 'Today Info:'
68 | today = info_daily()
69 | for source in today.keys():
70 | _text = ' \\- %s' % escaped(source)
71 | for news in today[source]:
72 | _text += '\n[%s](%s)' % (escaped(news['title']), news['url'])
73 | if len(text + '\n' + _text) > 4096:
74 | await context.bot.send_message(
75 | chat_id=group, text=text, parse_mode='MarkdownV2', disable_web_page_preview=True)
76 | text = 'Today Info:'
77 | text += '\n' + _text
78 | await context.bot.send_message(
79 | chat_id=group, text=text, parse_mode='MarkdownV2', disable_web_page_preview=True)
80 |
--------------------------------------------------------------------------------
/command/weather.py:
--------------------------------------------------------------------------------
1 | import json
2 | import logging
3 | import os
4 | from datetime import datetime, timedelta
5 | from typing import cast
6 |
7 | import matplotlib
8 | import matplotlib.pyplot as plt
9 | import numpy as np
10 | from PIL import Image
11 | from pytz import timezone
12 | from telegram import Bot, InputMediaPhoto, Message, Update
13 | from telegram.error import TimedOut
14 | from telegram.ext import ContextTypes
15 |
16 | from base.config import channel, config, group
17 | from base.debug import try_except
18 | from base.format import escaped
19 | from base.log import logger
20 | from base.message import delete_msg, edit_msg_media
21 | from base.pool import add_pool
22 | from base.weather import CaiyunAPIError, caiyun_api, daily_weather, now_weather
23 |
24 | matplotlib.use('Agg')
25 |
26 | if not os.path.exists('./tmp/'):
27 | os.makedirs('./tmp/')
28 |
29 | # ==================== data ====================
30 |
31 |
32 | try:
33 | caiyunData = json.load(open('data/caiyun.json', 'r'))
34 | except Exception:
35 | caiyunData = {}
36 |
37 |
38 | @try_except(level=logging.DEBUG, return_value=False, exclude=(CaiyunAPIError,))
39 | async def weather_update():
40 | """更新彩云天气数据"""
41 | global caiyunData
42 | caiyunData = await caiyun_api(config['CAIYUN']['longitude'], config['CAIYUN']['latitude'])
43 | with open('data/caiyun.json', 'w') as file:
44 | json.dump(caiyunData, file)
45 |
46 |
47 | # ==================== rain ====================
48 |
49 | start_probability = 0.8
50 | stop_probability = 0.2
51 | start_precipitation = 0.03
52 | stop_precipitation = 0.01
53 | rain_2h = rain_60 = rain_15 = rain_0 = False
54 | rainfall = False
55 | alert_text = ''
56 |
57 | try:
58 | weather_msgid = json.load(
59 | open('data/weather_msgid.json', 'r'))
60 | except Exception:
61 | weather_msgid = 0
62 |
63 |
64 | async def rain_alert(bot: Bot, text: str):
65 | """降雨预警"""
66 | global alert_text, weather_msgid
67 | if alert_text == text:
68 | return
69 | alert_text = text
70 | await delete_msg(group, weather_msgid)
71 | msg: Message = await bot.send_message(chat_id=group, text=text)
72 | weather_msgid = msg.message_id
73 | with open('data/weather_msgid.json', 'w') as file:
74 | json.dump(weather_msgid, file)
75 |
76 |
77 | async def forecast_rain(bot: Bot):
78 | """根据两小时内的降雨预测发出预警"""
79 | if caiyunData == {} or caiyunData['result']['minutely']['status'] != 'ok':
80 | return
81 |
82 | global rain_2h
83 | probability_2h = caiyunData['result']['minutely']['probability']
84 | if max(probability_2h) < stop_probability and rain_2h == True:
85 | rain_2h = False
86 | logger.debug('rain_2h T to F')
87 | if max(probability_2h) > start_probability and rain_2h == False:
88 | rain_2h = True
89 | logger.debug('rain_2h F to T')
90 | # await rain_alert(bot, '未来两小时内可能会下雨。')
91 |
92 | global rain_60, rain_15, rain_0
93 | changed = False
94 | precipitation = caiyunData['result']['minutely']['precipitation_2h']
95 | if (precipitation[60] < stop_precipitation and rain_60 == True) or (precipitation[60] > start_precipitation and rain_60 == False):
96 | rain_60 = not rain_60
97 | changed = True
98 | if (precipitation[15] < stop_precipitation and rain_15 == True) or (precipitation[15] > start_precipitation and rain_15 == False):
99 | rain_15 = not rain_15
100 | changed = True
101 | if (precipitation[0] < stop_precipitation and rain_0 == True) or (precipitation[0] > start_precipitation and rain_0 == False):
102 | rain_0 = not rain_0
103 | changed = True
104 |
105 | if changed:
106 | await rain_alert(bot, caiyunData['result']['forecast_keypoint'])
107 |
108 | global rainfall
109 | rainfall = rain_2h or rain_60 or rain_15 or rain_0
110 |
111 |
112 | # ==================== alert ====================
113 |
114 | try:
115 | alert_info = json.load(
116 | open('data/alert_info.json', 'r'))
117 | except Exception:
118 | alert_info = {}
119 |
120 |
121 | async def alert_info_update(bot: Bot):
122 | """更新预警信息"""
123 | if caiyunData == {} or caiyunData['result']['alert']['status'] != 'ok':
124 | return
125 |
126 | modified = False
127 | alertIds = [each['alertId']
128 | for each in caiyunData['result']['alert']['content']]
129 | for id in list(alert_info.keys()):
130 | if id not in alertIds:
131 | await delete_msg(group, alert_info[id]['msgid'])
132 | del alert_info[id]
133 | for each in caiyunData['result']['alert']['content']:
134 | if each['request_status'] == 'ok' and each['alertId'] not in alert_info:
135 | text = '*%s*\n\n%s' % (escaped(each['title']),
136 | escaped(each['description']))
137 | msg = await bot.send_message(chat_id=group, text=text,
138 | parse_mode='MarkdownV2')
139 | # mark_autodel(msg)
140 | each['msgid'] = msg.message_id
141 | alert_info[each['alertId']] = each
142 | modified = True
143 | if modified:
144 | with open('data/alert_info.json', 'w') as file:
145 | json.dump(alert_info, file)
146 |
147 |
148 | # ==================== pic ====================
149 |
150 | @try_except(level=logging.WARNING)
151 | def temperature_graph():
152 | """未来 24 小时气温折线图"""
153 | pic = f'./tmp/temperature.png'
154 | logger.debug(f'file {pic} created')
155 |
156 | temperature: list[float] = []
157 | datetimes: list[str] = []
158 | for x in caiyunData['result']['hourly']['temperature'][:25]:
159 | dt = datetime.fromisoformat(x['datetime'])
160 | if datetime.now(timezone("Asia/Shanghai")) - timedelta(hours=1) <= dt:
161 | temperature.append(x['value'])
162 | datetimes.append(str(dt.hour))
163 | if len(temperature) == 24:
164 | break
165 | plt.figure(figsize=(6, 3))
166 | plt.plot(np.array(datetimes), np.array(temperature), linewidth=0)
167 |
168 | for i in range(len(datetimes)):
169 | plt.axvline(x=i, color='gray', linestyle='dashed', linewidth=0.5)
170 |
171 | z = np.polyfit(np.arange(len(temperature)), np.array(temperature), 8)
172 | p = np.poly1d(z)
173 | t = np.arange(0, len(temperature) - 1 + 0.1, 0.1)
174 | plt.plot(t, p(t), color='red', linewidth=1)
175 |
176 | plt.title('Temperature within 24 hours')
177 | plt.savefig(pic)
178 | plt.close() # Close the figure to avoid the warning
179 | return pic
180 |
181 |
182 | @try_except(level=logging.WARNING)
183 | def precipitation_graph():
184 | """未来 2 小时降雨概率折线图"""
185 | pic = f'./tmp/precipitation.png'
186 | logger.debug(f'file {pic} created')
187 |
188 | precipitation = caiyunData['result']['minutely']['precipitation_2h']
189 | plt.figure(figsize=(6, 3))
190 | plt.plot(np.arange(120), np.array(precipitation))
191 | plt.ylim(bottom=0)
192 | if plt.axis()[3] > 0.03:
193 | plt.hlines(0.03, 0, 120, colors=['skyblue'], linestyles='dashed')
194 | if plt.axis()[3] > 0.25:
195 | plt.hlines(0.25, 0, 120, colors=['blue'], linestyles='dashed')
196 | if plt.axis()[3] > 0.35:
197 | plt.hlines(0.35, 0, 120, colors=['orange'], linestyles='dashed')
198 | if plt.axis()[3] > 0.48:
199 | plt.hlines(0.48, 0, 120, colors=['darkred'], linestyles='dashed')
200 |
201 | plt.title('Probability of precipitation within 2 hours')
202 | plt.savefig(pic)
203 | plt.close() # Close the figure to avoid the warning
204 | return pic
205 |
206 |
207 | @try_except(level=logging.WARNING)
208 | def mixed_graph():
209 | """将未来 2 小时降雨概率折线图和未来 24 小时气温折线图合并"""
210 | pic = pic_temp = temperature_graph()
211 | if max(caiyunData['result']['minutely']['precipitation_2h']) > 0:
212 | pic_rain = precipitation_graph()
213 | pic = f'./tmp/mixed.png'
214 | logger.debug(f'file {pic} created')
215 | img_rain = Image.open(pic_rain)
216 | img_temp = Image.open(pic_temp)
217 | width, height = img_rain.size
218 | img_combined = Image.new('RGB', (width, height * 2))
219 | img_combined.paste(img_rain, (0, 0))
220 | img_combined.paste(img_temp, (0, height))
221 | img_combined.save(pic)
222 | return pic
223 |
224 |
225 | # ==================== weather report ====================
226 |
227 | try:
228 | weather_report_msgid = json.load(
229 | open('data/weather_report_msgid.json', 'r'))
230 | except Exception:
231 | weather_report_msgid = {'group': 0, 'channel': 0}
232 |
233 |
234 | @try_except(exclude=(TimedOut,))
235 | async def weather_report(context: ContextTypes.DEFAULT_TYPE) -> None:
236 | """定时发送或者更新天气预报"""
237 | assert context.job
238 | hour = cast(int, context.job.data)
239 | text = daily_weather(caiyunData, hour)
240 | if hour == 6 or hour == 18:
241 | await delete_msg(group, weather_report_msgid['group'])
242 | await delete_msg(channel, weather_report_msgid['channel'])
243 | pic = mixed_graph()
244 | msg = await context.bot.send_photo(group, open(pic, 'rb'), text)
245 | weather_report_msgid['group'] = msg.message_id
246 | msg = await context.bot.send_photo(channel, open(pic, 'rb'), text)
247 | weather_report_msgid['channel'] = msg.message_id
248 | with open('data/weather_report_msgid.json', 'w') as file:
249 | json.dump(weather_report_msgid, file)
250 | else:
251 | pic = mixed_graph()
252 | pic = InputMediaPhoto(media=open(pic, 'rb'), caption=text)
253 | await edit_msg_media(group, weather_report_msgid['group'], pic)
254 | await edit_msg_media(channel, weather_report_msgid['channel'], pic)
255 |
256 |
257 | # ==================== poll ====================
258 |
259 | remain_minutes = 0
260 |
261 |
262 | async def weather_poll(context: ContextTypes.DEFAULT_TYPE):
263 | """定时更新天气数据"""
264 | # 如果降雨则更新粒度为 5mins
265 | # 如果不降雨则更新粒度为 15mins
266 | global remain_minutes
267 | remain_minutes -= 1
268 | if remain_minutes <= 0:
269 | if await weather_update():
270 | await forecast_rain(context.bot)
271 | await alert_info_update(context.bot)
272 | remain_minutes = 5 if rainfall else 15
273 | else:
274 | # 如果更新失败则 2mins 后重试
275 | remain_minutes = 2
276 | logger.debug(f'next update: {remain_minutes} mins')
277 |
278 |
279 | # ==================== realtime ====================
280 |
281 | async def realtime_weather(update: Update, context: ContextTypes.DEFAULT_TYPE):
282 | """实时天气预报"""
283 | assert update.message
284 | await weather_update()
285 | if caiyunData != {} and caiyunData['result']['realtime']['status'] == 'ok':
286 | text = now_weather(caiyunData)
287 | await update.message.reply_text(text)
288 | else:
289 | await update.message.reply_text('天气数据获取失败')
290 |
291 |
292 | async def realtime_forecast(update: Update, context: ContextTypes.DEFAULT_TYPE):
293 | """实时降雨预报"""
294 | assert update.message
295 | await weather_update()
296 | if caiyunData == {} or caiyunData['result']['minutely']['status'] != 'ok':
297 | await update.message.reply_text('天气数据获取失败')
298 | return
299 |
300 | pic = precipitation_graph()
301 | if pic is None:
302 | await update.message.reply_text('图表生成错误')
303 | return
304 |
305 | msg = await update.message.reply_photo(
306 | photo=open(pic, 'rb'),
307 | caption=caiyunData['result']['forecast_keypoint']
308 | )
309 | add_pool(msg)
310 |
--------------------------------------------------------------------------------
/config.sample.ini:
--------------------------------------------------------------------------------
1 | [BOT]
2 | owner =
3 | group =
4 | channel = -100
5 | pipe = -100
6 | accesstoken =
7 | logpath = ./log/
8 | heartbeat =
9 |
10 | [CAIYUN]
11 | token =
12 | longitude = 116.32043123245238
13 | latitude = 40.00238837283399
14 |
15 | [WEBHOOK]
16 | listen = 0.0.0.0
17 | port = 8443
18 | secret_token = RANDOM_STRING
19 | webhook_url =
20 | cert = ./secret/cert.pem
21 |
22 | [SENTRY]
23 | dsn =
24 |
--------------------------------------------------------------------------------
/ecosystem.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | apps: [{
3 | name: 'ErhaBot',
4 | cmd: 'bot.py',
5 | interpreter: '/home/ubuntu/.miniconda3/envs/telegram/bin/python3',
6 | // autorestart: false,
7 | // watch: true,
8 | }]
9 | };
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | python-telegram-bot~=21.5
2 | pytz~=2023.3.post1
3 |
4 | colorlog~=6.7.0
5 | aiohttp~=3.9.1
6 | pyzbar~=0.1.9
7 | numpy~=2.1.1
8 | Pillow~=10.4.0
9 | matplotlib~=3.9.2
10 | beautifulsoup4~=4.12.3
11 | pycryptodome~=3.20.0
12 | qrcode~=7.4.2
13 |
--------------------------------------------------------------------------------
/template/template.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Konano/Tuna-Erha-Bot/ba518687ad3b3f45224ddfc2f47f9b3d13d80429/template/template.jpg
--------------------------------------------------------------------------------