├── .env.exp
├── .github
└── workflows
│ ├── docker-ci.yml
│ ├── ruff.yml
│ └── update-deps.yml
├── .gitignore
├── .pre-commit-config.yaml
├── Dockerfile
├── LICENSE
├── README.md
├── app
├── Controller.py
├── DashBoard.py
├── Event.py
├── JoinRequest.py
├── KickRequest.py
├── PollButton.py
└── __init__.py
├── app_conf.py
├── conf_dir
└── settings.toml
├── main.py
├── pdm.lock
├── pm2.json
├── pyproject.toml
├── setting
├── __init__.py
└── telegrambot.py
└── utils
├── LogChannel.py
└── __init__.py
/.env.exp:
--------------------------------------------------------------------------------
1 | TELEGRAM_BOT_TOKEN=xxx
2 | # TELEGRAM_BOT_PROXY_ADDRESS=socks5://127.0.0.1:7890
3 | TELEGRAM_BOT_LOG_CHANNEL=-1001234567890
4 |
--------------------------------------------------------------------------------
/.github/workflows/docker-ci.yml:
--------------------------------------------------------------------------------
1 | name: Docker Image CI
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | paths-ignore:
7 | - '**.md'
8 | - '**.toml'
9 | - 'LICENSE'
10 | - '!.github/workflows/**'
11 |
12 | env:
13 | REGISTRY: ghcr.io
14 | IMAGE_NAME: ${{ github.repository }}
15 |
16 | jobs:
17 | build-and-push-image:
18 | runs-on: ubuntu-latest
19 |
20 | permissions:
21 | contents: read
22 | packages: write
23 |
24 | steps:
25 | - name: Checkout repository
26 | uses: actions/checkout@v4
27 |
28 | - name: Log in to ghcr.io
29 | uses: docker/login-action@v3
30 | with:
31 | registry: ${{ env.REGISTRY }}
32 | username: ${{ github.actor }}
33 | password: ${{ secrets.GITHUB_TOKEN }}
34 |
35 | - name: Extract metadata (tags, labels) for Docker
36 | id: meta
37 | uses: docker/metadata-action@v5
38 | with:
39 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
40 |
41 | - name: Set up QEMU
42 | uses: docker/setup-qemu-action@v3
43 |
44 | - name: Set up Docker Buildx
45 | uses: docker/setup-buildx-action@v3
46 |
47 | - name: Build and push Docker image
48 | uses: docker/build-push-action@v6
49 | with:
50 | context: .
51 | push: true
52 | platforms: linux/arm64, linux/amd64
53 | tags: ${{ steps.meta.outputs.tags }}
54 | labels: ${{ steps.meta.outputs.labels }}
55 |
--------------------------------------------------------------------------------
/.github/workflows/ruff.yml:
--------------------------------------------------------------------------------
1 | name: Ruff
2 | on: [ push, pull_request ]
3 | jobs:
4 | ruff:
5 | runs-on: ubuntu-latest
6 | steps:
7 | - uses: actions/checkout@v3
8 | - uses: chartboost/ruff-action@v1
9 |
--------------------------------------------------------------------------------
/.github/workflows/update-deps.yml:
--------------------------------------------------------------------------------
1 | name: Update dependencies
2 |
3 | on:
4 | schedule:
5 | - cron: "0 0 * * *"
6 | workflow_dispatch:
7 |
8 | permissions:
9 | contents: write
10 | pull-requests: write
11 |
12 | jobs:
13 | update-dependencies:
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: actions/checkout@v4
17 |
18 | - name: Update dependencies
19 | uses: pdm-project/update-deps-action@main
20 | with:
21 | sign-off-commit: true
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | .idea/
161 | /.pdm-python
162 |
163 | # Ignore dynaconf secret files
164 | /conf_dir/.*.toml
165 | /conf_dir/.*.yaml
166 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/pre-commit/pre-commit-hooks
3 | rev: v3.2.0
4 | hooks:
5 | - id: trailing-whitespace
6 | - id: end-of-file-fixer
7 | - id: check-yaml
8 | - id: check-added-large-files
9 |
10 | - repo: https://github.com/astral-sh/ruff-pre-commit
11 | # Ruff version.
12 | rev: v0.1.7
13 | hooks:
14 | # Run the linter.
15 | - id: ruff
16 | args: [ --fix ]
17 | # Run the formatter.
18 | - id: ruff-format
19 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.11-slim
2 | WORKDIR /app
3 | COPY . /app
4 | RUN pip install pdm && pdm install --prod
5 | CMD ["pdm", "run", "python", "main.py"]
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ApproveByPoll / Telegram 投票入群机器人
2 | [](https://wakatime.com/badge/user/f5b3fb10-0bfa-4783-9750-a21ca2b68285/project/f4986200-f605-49a5-8163-e53dddb58e7b)
3 | [](https://github.com/KimmyXYC/ApproveByPoll/actions/workflows/docker-ci.yaml)
4 | [](https://github.com/KimmyXYC/ApproveByPoll/actions/workflows/ruff.yml)
5 | ## 安装 / Installation
6 |
7 | - 下载源码。 Download the code.
8 | ```shell
9 | git clone https://github.com/KimmyXYC/ApproveByPoll.git
10 | cd ApproveByPoll
11 | ```
12 |
13 | - 复制配置文件。 Copy configuration file.
14 | ```shell
15 | cp .env.exp .env
16 | ```
17 |
18 | - 填写配置文件。 Fill out the configuration file.
19 | ```
20 | TELEGRAM_BOT_TOKEN=xxx
21 | # TELEGRAM_BOT_PROXY_ADDRESS=socks5://127.0.0.1:7890
22 | TELEGRAM_BOT_LOG_CHANNEL=-1001234567890
23 | ```
24 |
25 | ### 本地部署 / Local Deployment
26 | - 安装依赖并运行。 Install dependencies and run.
27 | ```shell
28 | pip3 install pdm
29 | pdm install
30 | pdm run python main.py
31 | ```
32 | - 使用 PM2 守护进程。 Use PM2 to daemonize the process.
33 | ```shell
34 | pm2 start pm2.json
35 | pm2 monit
36 | pm2 restart pm2.json
37 | pm2 stop pm2.json
38 | ```
39 |
40 | ### Docker 部署 / Docker Deployment
41 | - 使用预构建镜像。 Use pre-built image.
42 | ```shell
43 | docker run -d --name approvebypoll --env-file .env ghcr.io/kimmyxyc/approvebypoll:main
44 | ```
45 |
46 | ## 注意 / Attention
47 | - 机器人必须有邀请用户,封禁用户,删除消息,置顶消息的权限。
48 | - The robot must have the permission to invite users, ban users, delete messages, and pin messages.
49 |
--------------------------------------------------------------------------------
/app/Controller.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time: 2023/6/16 17:46
3 | # @FileName: Controller.py
4 | # @Software: PyCharm
5 | # @GitHub: KimmyXYC
6 | import base64
7 | from asgiref.sync import sync_to_async
8 | from loguru import logger
9 | from telebot import types
10 | from telebot import util
11 | from telebot.async_telebot import AsyncTeleBot
12 | from telebot.asyncio_helper import ApiTelegramException
13 | from telebot.asyncio_storage import StateMemoryStorage
14 |
15 | from setting.telegrambot import BotSetting
16 | from app import Event, DashBoard, KickRequest
17 | from app.JoinRequest import JoinRequest
18 |
19 | StepCache = StateMemoryStorage()
20 |
21 |
22 | @sync_to_async
23 | def sync_to_async_func():
24 | pass
25 |
26 |
27 | class BotRunner(object):
28 | def __init__(self, db):
29 | self.bot = AsyncTeleBot(BotSetting.token, state_storage=StepCache)
30 | self.db = db
31 | self.bot_id = BotSetting.bot_id
32 | self.log_channel = BotSetting.log_channel
33 | self.kick_tasks = {} # Dict used to store kick requests
34 | self.join_tasks = {} # Dict used to store join requests
35 |
36 | async def run(self):
37 | logger.info("Bot Start")
38 | bot = self.bot
39 | if BotSetting.proxy_address:
40 | from telebot import asyncio_helper
41 |
42 | asyncio_helper.proxy = BotSetting.proxy_address
43 | logger.info("Proxy tunnels are being used!")
44 | await self.bot.set_my_commands([
45 | types.BotCommand("help", "Show help"),
46 | ], scope=types.BotCommandScopeAllPrivateChats())
47 | await self.bot.set_my_commands([
48 | types.BotCommand("setting", "Open Settings Dashboard"),
49 | types.BotCommand("set_vote_time", "Setting the polling time (unit: s)"),
50 | types.BotCommand("start_kick_vote", "Initiate a banishment"),
51 | ], scope=types.BotCommandScopeAllGroupChats())
52 |
53 | @bot.message_handler(commands=["start"], chat_types=['private'])
54 | async def handle_command(message: types.Message):
55 | start_param = message.text.split(' ')[-1]
56 | if start_param.startswith("getresult_"):
57 | join_request_id = start_param.split("_")[-1]
58 | join_request_id = base64.b64decode(join_request_id.encode()).decode()
59 | if join_request_id in self.join_tasks:
60 | poll_result = self.join_tasks[join_request_id].get_poll_result(message)
61 | if poll_result is not None:
62 | await bot.reply_to(message, poll_result, parse_mode="HTML")
63 | else:
64 | await bot.reply_to(message, "Illegal requests")
65 | else:
66 | await bot.reply_to(message, "Illegal requests")
67 | else:
68 | await Event.start(bot, message)
69 |
70 | @bot.message_handler(commands=["help"], chat_types=['private'])
71 | async def handle_command_help(message: types.Message):
72 | await Event.start(bot, message)
73 |
74 | @bot.message_handler(commands=["setting"], chat_types=['group', 'supergroup'])
75 | async def handle_command_setting(message: types.Message):
76 | await DashBoard.homepage(bot, message, self.db, self.bot_id)
77 |
78 | @bot.message_handler(commands=["set_vote_time"], chat_types=['group', 'supergroup'])
79 | async def handle_command_set_vote_time(message: types.Message):
80 | await Event.set_vote_time(bot, message, self.db)
81 |
82 | @bot.message_handler(commands=["start_kick_vote"], chat_types=['group', 'supergroup'])
83 | async def handle_command_start_kick_vote(message: types.Message):
84 | chat_dict = self.db.get(str(message.chat.id))
85 | if chat_dict is None:
86 | chat_dict = {}
87 | vote_to_kick = chat_dict.get("vote_to_kick", False)
88 | if not vote_to_kick:
89 | await bot.reply_to(message, "Vote to kick is not enabled in this chat.")
90 | return
91 | if len(message.text.split()) == 1:
92 | if message.reply_to_message is None:
93 | await bot.reply_to(message, "Malformed, expected /start_kick_vote [user_id] or reply to a user.")
94 | return
95 | target_user_id = message.reply_to_message.from_user.id
96 | elif len(message.text.split()) == 2:
97 | target_user_id = int(message.text.split()[1])
98 | else:
99 | await bot.reply_to(message, "Malformed, expected /start_kick_vote [user_id] or reply to a user.")
100 | return
101 | ostracism_id = f"{message.chat.id}@{target_user_id}"
102 | if ostracism_id in self.kick_tasks:
103 | ostracism_task = self.kick_tasks[ostracism_id]
104 | if not ostracism_task.check_up_status():
105 | return
106 | ostracism_task = KickRequest.Ostracism(message.chat.id, message.from_user.id, target_user_id, self.bot_id)
107 | self.kick_tasks[ostracism_id] = ostracism_task
108 | await ostracism_task.start_kick_vote(bot, message)
109 |
110 | @bot.message_handler(content_types=['pinned_message'], chat_types=['group', 'supergroup'])
111 | async def delete_pinned_message(message: types.Message):
112 | status = self.db.get(str(message.chat.id))
113 | if not status:
114 | return
115 | if status.get("clean_pinned_message", False):
116 | try:
117 | await bot.delete_message(message.chat.id, message.message_id)
118 | except Exception as e:
119 | logger.error(f"Delete pinned message failed: {e}")
120 |
121 | @bot.chat_join_request_handler()
122 | async def handle_new_chat_members(request: types.ChatJoinRequest):
123 | chat_dict = self.db.get(str(request.chat.id))
124 | if chat_dict is None:
125 | chat_dict = {}
126 | vote_to_join = chat_dict.get("vote_to_join", True)
127 | if not vote_to_join:
128 | return
129 | join_request_id = f"{request.chat.id}@{request.from_user.id}"
130 | if join_request_id in self.join_tasks:
131 | join_task = self.join_tasks[join_request_id]
132 | if not join_task.check_up_status():
133 | return
134 | join_task = JoinRequest(request.chat.id, request.from_user.id, self.bot_id, self.log_channel)
135 | self.join_tasks[join_request_id] = join_task
136 | await join_task.handle_join_request(bot, request, self.db)
137 | try:
138 | del self.join_tasks[join_request_id]
139 | except KeyError:
140 | pass
141 |
142 | @bot.callback_query_handler(lambda c: True)
143 | async def handle_callback_query(callback_query: types.CallbackQuery):
144 | requests_type = callback_query.data.split()[0]
145 | if requests_type == "JR":
146 | action = callback_query.data.split()[1]
147 | join_request_id = callback_query.data.split()[2]
148 | if join_request_id in self.join_tasks:
149 | join_task = self.join_tasks.get(join_request_id)
150 | else:
151 | return
152 | await join_task.handle_button(bot, callback_query, action)
153 | if join_task.check_up_status():
154 | try:
155 | del self.join_tasks[join_request_id]
156 | except KeyError:
157 | pass
158 | elif requests_type == "KR":
159 | action = callback_query.data.split()[1]
160 | ostracism_id = callback_query.data.split()[2]
161 | if ostracism_id not in self.kick_tasks:
162 | return
163 | ostracism_task = self.kick_tasks.get(ostracism_id)
164 | await ostracism_task.handle_button(bot, callback_query, action, self.db)
165 | elif requests_type == "PB":
166 | request_id = callback_query.data.split()[2]
167 | if request_id in self.join_tasks:
168 | await self.join_tasks[request_id].poll_button_handle(bot, callback_query)
169 | elif requests_type == "Setting":
170 | await DashBoard.command_handler(bot, callback_query, self.db, self.bot_id)
171 |
172 | try:
173 | await bot.polling(
174 | non_stop=True, allowed_updates=util.update_types, skip_pending=True
175 | )
176 | except ApiTelegramException as e:
177 | logger.opt(exception=e).exception("ApiTelegramException")
178 | except Exception as e:
179 | logger.exception(e)
180 |
--------------------------------------------------------------------------------
/app/DashBoard.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time: 2024/2/8 9:53
3 | # @FileName: DashBoard.py
4 | # @Software: PyCharm
5 | # @GitHub: KimmyXYC
6 | from telebot import types
7 | from loguru import logger
8 |
9 | FORMAT = {
10 | True: "✅",
11 | False: "❌"
12 | }
13 | ADDITION = "If you want to change the settings, please click the button below."
14 |
15 |
16 | def db_analyzer(db, chat_id, data_type="all", default_value=None):
17 | chat_dict = db.get(str(chat_id))
18 | if chat_dict is None:
19 | chat_dict = {}
20 | if data_type == "all":
21 | return chat_dict
22 | else:
23 | return chat_dict.get(data_type, default_value), chat_dict
24 |
25 |
26 | def message_creator(chat_id, db, addition=ADDITION):
27 | chat_dict = db_analyzer(db, chat_id)
28 | vote_to_join = chat_dict.get("vote_to_join", True)
29 | vote_to_kick = chat_dict.get("vote_to_kick", False)
30 | pin_msg = chat_dict.get("pin_msg", False)
31 | vote_time = chat_dict.get("vote_time", 600)
32 | clean_pinned_message = chat_dict.get("clean_pinned_message", False)
33 | anonymous_vote = chat_dict.get("anonymous_vote", True)
34 | advanced_vote = chat_dict.get("advanced_vote", False)
35 | # Time format
36 | minutes = vote_time // 60
37 | seconds = vote_time % 60
38 | time_parts = []
39 | if minutes > 0:
40 | time_parts.append(f"{minutes} minute{'s' if minutes > 1 else ''}")
41 | if seconds > 0:
42 | time_parts.append(f"{seconds} second{'s' if seconds > 1 else ''}")
43 | _time = " and ".join(time_parts) if time_parts else "0 seconds"
44 |
45 | reply_message = (
46 | f"Group Setting\n\n"
47 | f"Vote To Join: {vote_to_join}\n"
48 | f"Vote To Kick: {vote_to_kick}\n"
49 | f"Vote Time: {_time}\n"
50 | f"Pin Vote Message: {pin_msg}\n"
51 | f"Clean Pinned Message: {clean_pinned_message}\n"
52 | f"Anonymous Vote: {anonymous_vote}\n"
53 | f"Advanced Vote: {advanced_vote}"
54 | )
55 | reply_message += f"\n{addition}" if addition else ""
56 |
57 | buttons = button_creator(vote_to_join, vote_to_kick, pin_msg, clean_pinned_message, chat_id, anonymous_vote, advanced_vote)
58 |
59 | return reply_message, buttons
60 |
61 |
62 | def button_creator(vote_to_join, vote_to_kick, pin_msg, clean_pinned_message, chat_id, anonymous_vote, advanced_vote):
63 | buttons = types.InlineKeyboardMarkup()
64 | buttons.add(types.InlineKeyboardButton(f"{FORMAT.get(vote_to_join)} Vote To Join",
65 | callback_data=f"Setting vote_to_join {chat_id}"),
66 | types.InlineKeyboardButton(f"{FORMAT.get(vote_to_kick)} Vote To Kick",
67 | callback_data=f"Setting vote_to_kick {chat_id}"))
68 | buttons.add(types.InlineKeyboardButton("Set Vote Time",
69 | callback_data=f"Setting vote_time {chat_id}"))
70 | buttons.add(types.InlineKeyboardButton(f"{FORMAT.get(pin_msg)} Pin Vote Message",
71 | callback_data=f"Setting pin_msg {chat_id}"),
72 | types.InlineKeyboardButton(f"{FORMAT.get(clean_pinned_message)} Clean Pinned Message",
73 | callback_data=f"Setting clean_pinned_message {chat_id}"))
74 | buttons.add(types.InlineKeyboardButton(f"{FORMAT.get(anonymous_vote)} Anonymous Vote",
75 | callback_data=f"Setting anonymous_vote {chat_id}"),
76 | types.InlineKeyboardButton(f"{FORMAT.get(advanced_vote)} Advanced Vote",
77 | callback_data=f"Setting advanced_vote {chat_id}"))
78 | buttons.add(types.InlineKeyboardButton("Close", callback_data="Setting close"))
79 | return buttons
80 |
81 |
82 | async def homepage(bot, message: types.Message, db, bot_id):
83 | chat_member = await bot.get_chat_member(message.chat.id, message.from_user.id)
84 | if (chat_member.status == 'administrator' or
85 | chat_member.status == 'creator' or message.from_user.username == "GroupAnonymousBot"):
86 | reply_message, buttons = message_creator(message.chat.id, db)
87 | await bot.reply_to(
88 | message,
89 | reply_message,
90 | parse_mode="HTML",
91 | reply_markup=buttons,
92 | disable_web_page_preview=True
93 | )
94 | else:
95 | await bot.reply_to(message, "You don't have permission to do this.")
96 | bot_member = await bot.get_chat_member(message.chat.id, bot_id)
97 | if bot_member.status == 'administrator' and bot_member.can_delete_messages:
98 | await bot.delete_message(message.chat.id, message.message_id)
99 |
100 |
101 | async def homepage_back(bot, callback_query, db, chat_member):
102 | if chat_member.status == 'administrator' or chat_member.status == 'creator':
103 | reply_message, buttons = message_creator(callback_query.message.chat.id, db)
104 | await bot.edit_message_text(
105 | reply_message,
106 | callback_query.message.chat.id,
107 | callback_query.message.message_id,
108 | parse_mode="HTML",
109 | reply_markup=buttons,
110 | disable_web_page_preview=True
111 | )
112 | else:
113 | await bot.answer_callback_query(callback_query.id, "You don't have permission to do this.")
114 | return
115 |
116 |
117 | async def command_handler(bot, callback_query: types.CallbackQuery, db, bot_id):
118 | requests_type = callback_query.data.split()[1]
119 | chat_member = await bot.get_chat_member(callback_query.message.chat.id, callback_query.from_user.id)
120 | bot_member = await bot.get_chat_member(callback_query.message.chat.id, bot_id)
121 | if chat_member.status != 'administrator' and chat_member.status != 'creator':
122 | await bot.answer_callback_query(callback_query.id, "You don't have permission to do this.")
123 | return
124 | if requests_type == "vote_to_join":
125 | await vote_to_join_handler(bot, callback_query, db, chat_member)
126 | elif requests_type == "vote_to_kick":
127 | await vote_to_kick_handler(bot, callback_query, db, chat_member)
128 | elif requests_type == "vote_time":
129 | await vote_time_handler(bot, callback_query, db, chat_member)
130 | elif requests_type == "edit_vote_time":
131 | await edit_vote_time_handler(bot, callback_query, db, chat_member)
132 | elif requests_type == "pin_msg":
133 | await pin_msg_handler(bot, callback_query, db, chat_member, bot_member)
134 | elif requests_type == "clean_pinned_message":
135 | await clean_pinned_message_handler(bot, callback_query, db, chat_member, bot_member)
136 | elif requests_type == "anonymous_vote":
137 | await anonymous_vote_handler(bot, callback_query, db, chat_member)
138 | elif requests_type == "advanced_vote":
139 | await advanced_vote_handler(bot, callback_query, db, chat_member)
140 | elif requests_type == "back":
141 | await homepage_back(bot, callback_query, db, chat_member)
142 | elif requests_type == "close":
143 | chat_member = await bot.get_chat_member(callback_query.message.chat.id, callback_query.from_user.id)
144 | if chat_member.status == 'creator' or chat_member.status == 'administrator':
145 | await bot.delete_message(callback_query.message.chat.id, callback_query.message.message_id)
146 | else:
147 | await bot.answer_callback_query(callback_query.id, "Unknown request.")
148 | logger.error(f"Unknown request: {callback_query.data}")
149 |
150 |
151 | async def vote_to_join_handler(bot, callback_query: types.CallbackQuery, db, chat_member):
152 | if chat_member.status != 'creator' and (chat_member.status != 'administrator' or not chat_member.can_invite_users):
153 | await bot.answer_callback_query(callback_query.id, "You don't have permission to do this.")
154 | return
155 | chat_id = int(callback_query.data.split()[2])
156 | vote_to_join, chat_dict = db_analyzer(db, chat_id, "vote_to_join", True)
157 | if vote_to_join:
158 | chat_dict["vote_to_join"] = False
159 | db.set(str(chat_id), chat_dict)
160 | else:
161 | chat_dict["vote_to_join"] = True
162 | db.set(str(chat_id), chat_dict)
163 | reply_message, buttons = message_creator(chat_id, db)
164 | await bot.edit_message_text(
165 | reply_message,
166 | callback_query.message.chat.id,
167 | callback_query.message.message_id,
168 | parse_mode="HTML",
169 | reply_markup=buttons,
170 | disable_web_page_preview=True
171 | )
172 |
173 |
174 | async def vote_to_kick_handler(bot, callback_query: types.CallbackQuery, db, chat_member):
175 | if chat_member.status != 'creator' and (
176 | chat_member.status != 'administrator' or not chat_member.can_restrict_members):
177 | await bot.answer_callback_query(callback_query.id, "You don't have permission to do this.")
178 | return
179 | chat_id = int(callback_query.data.split()[2])
180 | vote_to_kick, chat_dict = db_analyzer(db, chat_id, "vote_to_kick", False)
181 | if vote_to_kick:
182 | chat_dict["vote_to_kick"] = False
183 | db.set(str(chat_id), chat_dict)
184 | else:
185 | chat_dict["vote_to_kick"] = True
186 | db.set(str(chat_id), chat_dict)
187 | reply_message, buttons = message_creator(chat_id, db)
188 | await bot.edit_message_text(
189 | reply_message,
190 | callback_query.message.chat.id,
191 | callback_query.message.message_id,
192 | parse_mode="HTML",
193 | reply_markup=buttons,
194 | disable_web_page_preview=True
195 | )
196 |
197 |
198 | async def vote_time_handler(bot, callback_query: types.CallbackQuery, db, chat_member):
199 | if chat_member.status != 'creator' and (chat_member.status != 'administrator' or not chat_member.can_change_info):
200 | await bot.answer_callback_query(callback_query.id, "You don't have permission to do this.")
201 | return
202 | chat_id = int(callback_query.data.split()[2])
203 | addition = "If you want to change the vote time precisely, please use the command /set_vote_time"
204 | reply_message, _ = message_creator(chat_id, db, addition)
205 | buttons = types.InlineKeyboardMarkup()
206 | buttons.add(types.InlineKeyboardButton("1 min", callback_data=f"Setting edit_vote_time {chat_id} 60"),
207 | types.InlineKeyboardButton("2 min", callback_data=f"Setting edit_vote_time {chat_id} 120"),
208 | types.InlineKeyboardButton("3 min", callback_data=f"Setting edit_vote_time {chat_id} 180"))
209 | buttons.add(types.InlineKeyboardButton("5min", callback_data=f"Setting edit_vote_time {chat_id} 300"),
210 | types.InlineKeyboardButton("10min", callback_data=f"Setting edit_vote_time {chat_id} 600"),
211 | types.InlineKeyboardButton("15min", callback_data=f"Setting edit_vote_time {chat_id} 900"))
212 | buttons.add(types.InlineKeyboardButton("20min", callback_data=f"Setting edit_vote_time {chat_id} 1200"),
213 | types.InlineKeyboardButton("30min", callback_data=f"Setting edit_vote_time {chat_id} 1800"),
214 | types.InlineKeyboardButton("60min", callback_data=f"Setting edit_vote_time {chat_id} 3600"))
215 | buttons.add(types.InlineKeyboardButton("⬅️ Go Back", callback_data="Setting back"))
216 | await bot.edit_message_text(
217 | reply_message,
218 | callback_query.message.chat.id,
219 | callback_query.message.message_id,
220 | parse_mode="HTML",
221 | reply_markup=buttons,
222 | disable_web_page_preview=True
223 | )
224 |
225 |
226 | async def edit_vote_time_handler(bot, callback_query: types.CallbackQuery, db, chat_member):
227 | if chat_member.status != 'creator' and (chat_member.status != 'administrator' or not chat_member.can_change_info):
228 | await bot.answer_callback_query(callback_query.id, "You don't have permission to do this.")
229 | return
230 | chat_id = int(callback_query.data.split()[2])
231 | vote_time = int(callback_query.data.split()[3])
232 | chat_dict = db_analyzer(db, chat_id, "all")
233 | chat_dict["vote_time"] = vote_time
234 | db.set(str(chat_id), chat_dict)
235 | reply_message, buttons = message_creator(chat_id, db)
236 | await bot.edit_message_text(
237 | reply_message,
238 | callback_query.message.chat.id,
239 | callback_query.message.message_id,
240 | parse_mode="HTML",
241 | reply_markup=buttons,
242 | disable_web_page_preview=True
243 | )
244 |
245 |
246 | async def pin_msg_handler(bot, callback_query: types.CallbackQuery, db, chat_member, bot_member):
247 | if bot_member.status != 'administrator' or not bot_member.can_pin_messages:
248 | await bot.answer_callback_query(callback_query.id, "I don't have permission to pin messages.")
249 | return
250 | if chat_member.status != 'creator' and (chat_member.status != 'administrator' or not chat_member.can_pin_messages):
251 | await bot.answer_callback_query(callback_query.id, "You don't have permission to do this.")
252 | return
253 | chat_id = int(callback_query.data.split()[2])
254 | pin_msg, chat_dict = db_analyzer(db, chat_id, "pin_msg", False)
255 | if pin_msg:
256 | chat_dict["pin_msg"] = False
257 | db.set(str(chat_id), chat_dict)
258 | else:
259 | chat_dict["pin_msg"] = True
260 | db.set(str(chat_id), chat_dict)
261 | reply_message, buttons = message_creator(chat_id, db)
262 | await bot.edit_message_text(
263 | reply_message,
264 | callback_query.message.chat.id,
265 | callback_query.message.message_id,
266 | parse_mode="HTML",
267 | reply_markup=buttons,
268 | disable_web_page_preview=True
269 | )
270 |
271 |
272 | async def clean_pinned_message_handler(bot, callback_query: types.CallbackQuery, db, chat_member, bot_member):
273 | if bot_member.status != 'administrator' or not bot_member.can_delete_messages:
274 | await bot.answer_callback_query(callback_query.id, "I don't have permission to delete messages.")
275 | return
276 | if chat_member.status != 'creator' and (
277 | chat_member.status != 'administrator' or not chat_member.can_delete_messages):
278 | await bot.answer_callback_query(callback_query.id, "You don't have permission to do this.")
279 | return
280 | chat_id = int(callback_query.data.split()[2])
281 | clean_pinned_message, chat_dict = db_analyzer(db, chat_id, "clean_pinned_message", False)
282 | if clean_pinned_message:
283 | chat_dict["clean_pinned_message"] = False
284 | db.set(str(chat_id), chat_dict)
285 | else:
286 | chat_dict["clean_pinned_message"] = True
287 | db.set(str(chat_id), chat_dict)
288 | reply_message, buttons = message_creator(chat_id, db)
289 | await bot.edit_message_text(
290 | reply_message,
291 | callback_query.message.chat.id,
292 | callback_query.message.message_id,
293 | parse_mode="HTML",
294 | reply_markup=buttons,
295 | disable_web_page_preview=True
296 | )
297 |
298 |
299 | async def anonymous_vote_handler(bot, callback_query: types.CallbackQuery, db, chat_member):
300 | if chat_member.status != 'creator' and (chat_member.status != 'administrator' or not chat_member.can_change_info):
301 | await bot.answer_callback_query(callback_query.id, "You don't have permission to do this.")
302 | return
303 | chat_id = int(callback_query.data.split()[2])
304 | anonymous_vote, chat_dict = db_analyzer(db, chat_id, "anonymous_vote", True)
305 | if anonymous_vote:
306 | chat_dict["anonymous_vote"] = False
307 | db.set(str(chat_id), chat_dict)
308 | else:
309 | chat_dict["anonymous_vote"] = True
310 | db.set(str(chat_id), chat_dict)
311 | reply_message, buttons = message_creator(chat_id, db)
312 | await bot.edit_message_text(
313 | reply_message,
314 | callback_query.message.chat.id,
315 | callback_query.message.message_id,
316 | parse_mode="HTML",
317 | reply_markup=buttons,
318 | disable_web_page_preview=True
319 | )
320 |
321 |
322 | async def advanced_vote_handler(bot, callback_query: types.CallbackQuery, db, chat_member):
323 | if chat_member.status != 'creator' and (chat_member.status != 'administrator' or not chat_member.can_change_info):
324 | await bot.answer_callback_query(callback_query.id, "You don't have permission to do this.")
325 | return
326 | chat_id = int(callback_query.data.split()[2])
327 | advanced_vote, chat_dict = db_analyzer(db, chat_id, "advanced_vote", False)
328 | if advanced_vote:
329 | chat_dict["advanced_vote"] = False
330 | db.set(str(chat_id), chat_dict)
331 | else:
332 | chat_dict["advanced_vote"] = True
333 | db.set(str(chat_id), chat_dict)
334 | reply_message, buttons = message_creator(chat_id, db)
335 | await bot.edit_message_text(
336 | reply_message,
337 | callback_query.message.chat.id,
338 | callback_query.message.message_id,
339 | parse_mode="HTML",
340 | reply_markup=buttons,
341 | disable_web_page_preview=True
342 | )
343 |
--------------------------------------------------------------------------------
/app/Event.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time: 2023/6/16 17:50
3 | # @FileName: Event.py
4 | # @Software: PyCharm
5 | # @GitHub: KimmyXYC
6 | from telebot import types
7 |
8 |
9 | async def start(bot, message: types.Message):
10 | _url = "https://github.com/KimmyXYC/ApproveByPoll"
11 | _info = "This is a Bot for voting to join the group."
12 | await bot.reply_to(
13 | message,
14 | f"{_info}\n\nOpen-source repository: {_url}",
15 | disable_web_page_preview=True
16 | )
17 |
18 |
19 | async def set_vote_time(bot, message: types.Message, db):
20 | chat_member = await bot.get_chat_member(message.chat.id, message.from_user.id)
21 | if (chat_member.status == 'administrator' and chat_member.can_invite_users) \
22 | or chat_member.status == 'creator' or message.from_user.username == "GroupAnonymousBot":
23 | if message.from_user.username == "GroupAnonymousBot":
24 | await bot.reply_to(message, "As an anonymous administrator, please use the Dashboard for this purpose.")
25 | return
26 | command_args = message.text.split()
27 | if len(command_args) != 2:
28 | await bot.reply_to(message, "Malformed, expected /set_vote_time [time]")
29 | return
30 | try:
31 | time = int(command_args[1])
32 | if time > 3600 or time < 10:
33 | await bot.reply_to(message, "Time should be in range [10, 3600]")
34 | return
35 | await bot.reply_to(message, f"Set vote time to {time} seconds")
36 | chat_dict = db.get(str(message.chat.id))
37 | if chat_dict is None:
38 | chat_dict = {}
39 | chat_dict["vote_time"] = time
40 | db.set(str(message.chat.id), chat_dict)
41 | except ValueError:
42 | await bot.reply_to(message, "Malformed, expected /set_vote_time [time]")
43 | else:
44 | await bot.reply_to(message, "You don't have permission to do this.")
45 |
--------------------------------------------------------------------------------
/app/JoinRequest.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time: 2023/11/4 20:00
3 | # @FileName: JoinRequest.py
4 | # @Software: PyCharm
5 | # @GitHub: KimmyXYC
6 | import asyncio
7 | from loguru import logger
8 | from telebot import types
9 | from utils.LogChannel import LogChannel
10 | from app.PollButton import PollButton
11 |
12 |
13 | class JoinRequest:
14 | def __init__(self, chat_id, user_id, bot_id, log_channel_id):
15 | self.chat_id = chat_id
16 | self.user_id = user_id
17 | self.finished = False
18 |
19 | self.log_channel_id = log_channel_id
20 |
21 | self.bot_id = bot_id
22 | self.bot_member = None
23 |
24 | self.request = None
25 | self.user_message = None
26 | self.notice_message = None
27 | self.polling = None
28 | self.anonymous_vote = True
29 |
30 | self.user_mention = None
31 |
32 | self.LogChannel = None
33 | self.PollButton = None
34 |
35 | def check_up_status(self):
36 | return self.finished
37 |
38 | def get_poll_result(self, message):
39 | if self.PollButton is None:
40 | return None
41 | return (f"{self.request.chat.title}\n"
42 | f"Join request from {self.user_mention}\n\n"
43 | f"{self.PollButton.get_result(message.from_user.id, self.anonymous_vote)}")
44 |
45 | async def handle_join_request(self, bot, request: types.ChatJoinRequest, db):
46 | self.LogChannel = LogChannel(bot, self.log_channel_id)
47 | self.request = request
48 | self.bot_member = await bot.get_chat_member(self.chat_id, self.bot_id)
49 |
50 | if request.from_user.username is not None:
51 | self.user_mention = f'@{request.from_user.username}'
52 | else:
53 | self.user_mention = f'{request.from_user.first_name}'
54 | if request.from_user.last_name is not None:
55 | self.user_mention += f" {request.from_user.last_name}"
56 | else:
57 | self.user_mention += ""
58 |
59 | # Log
60 | logger.info(f"New join request from {request.from_user.first_name}(ID: {self.user_id}) in {self.chat_id}")
61 | await self.LogChannel.create_log(request, "JoinRequest")
62 |
63 | chat_dict = db.get(str(self.chat_id))
64 | if chat_dict is None:
65 | chat_dict = {}
66 | status_pin_msg = chat_dict.get("pin_msg", False)
67 | vote_time = chat_dict.get("vote_time", 600)
68 | advanced_vote = chat_dict.get("advanced_vote", False)
69 | self.anonymous_vote = chat_dict.get("anonymous_vote", True)
70 |
71 | # Time format
72 | minutes = vote_time // 60
73 | seconds = vote_time % 60
74 | cn_parts = []
75 | en_parts = []
76 | if minutes > 0:
77 | cn_parts.append(f"{minutes}分钟")
78 | en_parts.append(f"{minutes} minute{'s' if minutes > 1 else ''}")
79 | if seconds > 0:
80 | cn_parts.append(f"{seconds}秒")
81 | en_parts.append(f"{seconds} second{'s' if seconds > 1 else ''}")
82 | _cn_time = ''.join(cn_parts) if cn_parts else "0秒"
83 | _en_time = ' and '.join(en_parts) if en_parts else "0 seconds"
84 |
85 | # Send message to user
86 | _zh_info = f"您正在申请加入「{request.chat.title}」,结果将于 {_cn_time} 后告知您。"
87 | _en_info = f"You are applying to join 「{request.chat.title}」. " \
88 | f"The result will be communicated to you in {_en_time}."
89 | try:
90 | self.user_message = await bot.send_message(
91 | self.user_id,
92 | f"{_zh_info}\n{_en_info}",
93 | )
94 | except Exception as e:
95 | logger.error(f"Send message to User_id:{self.user_id}: {e}")
96 |
97 | # Buttons
98 | join_request_id = f"{self.chat_id}@{self.user_id}"
99 | keyboard = types.InlineKeyboardMarkup(row_width=3)
100 | approve_button = types.InlineKeyboardButton(text="Approve", callback_data=f"JR Approve {join_request_id}")
101 | reject_button = types.InlineKeyboardButton(text="Reject", callback_data=f"JR Reject {join_request_id}")
102 | ban_button = types.InlineKeyboardButton(text="Ban", callback_data=f"JR Ban {join_request_id}")
103 | keyboard.add(approve_button, reject_button, ban_button)
104 |
105 | notice_message_text = f"{self.user_mention} (ID: {self.user_id}
) is requesting to join this group."
106 | if request.from_user.username is None:
107 | notice_message_text += f"\n\nAlternate Link: tg://user?id={self.user_id}"
108 |
109 | notice_message = await bot.send_message(
110 | self.chat_id,
111 | notice_message_text,
112 | reply_markup=keyboard,
113 | parse_mode="HTML"
114 | )
115 | self.notice_message = notice_message
116 |
117 | # Polling
118 | if advanced_vote:
119 | self.PollButton = PollButton(join_request_id)
120 | keyboard = self.PollButton.button_create()
121 | self.polling = await bot.send_message(
122 | self.chat_id,
123 | "Approve this user?",
124 | reply_markup=keyboard,
125 | parse_mode="HTML",
126 | protect_content=True,
127 | )
128 | else:
129 | vote_question = "Approve this user?"
130 | vote_options = ["Yes", "No"]
131 | self.polling = await bot.send_poll(
132 | self.chat_id,
133 | vote_question,
134 | vote_options,
135 | is_anonymous=self.anonymous_vote,
136 | allows_multiple_answers=False,
137 | reply_to_message_id=notice_message.message_id,
138 | protect_content=True,
139 | )
140 |
141 | if status_pin_msg and self.bot_member.status == 'administrator' and self.bot_member.can_pin_messages:
142 | await bot.pin_chat_message(
143 | chat_id=self.chat_id,
144 | message_id=self.polling.message_id,
145 | disable_notification=True,
146 | )
147 |
148 | await asyncio.sleep(vote_time)
149 |
150 | # Check if the request has been processed
151 | if self.finished:
152 | return
153 |
154 | if status_pin_msg and self.bot_member.status == 'administrator' and self.bot_member.can_pin_messages:
155 | await bot.unpin_chat_message(
156 | chat_id=self.chat_id,
157 | message_id=self.polling.message_id,
158 | )
159 |
160 | # Get vote result
161 | if advanced_vote:
162 | allow_count, deny_count = self.PollButton.stop_poll()
163 | else:
164 | vote_message = await bot.stop_poll(request.chat.id, self.polling.message_id)
165 | allow_count = vote_message.options[0].voter_count
166 | deny_count = vote_message.options[1].voter_count
167 |
168 | # Process the vote result
169 | if allow_count + deny_count == 0:
170 | logger.info(f"{self.user_id}: No one voted in {self.chat_id}")
171 | result_message = bot.reply_to(notice_message, "No one voted.")
172 | approve_user = False
173 | edit_msg = f"{self.user_mention} (ID: {self.user_id}
): No one voted."
174 | user_reply_msg = "无人投票,请稍后尝试重新申请。\nNo one voted. Please request again later."
175 | elif allow_count > deny_count:
176 | logger.info(f"{self.user_id}: Approved in {self.chat_id}")
177 | result_message = await bot.reply_to(notice_message, "Approved.")
178 | approve_user = True
179 | edit_msg = f"{self.user_mention} (ID: {self.user_id}
): Approved."
180 | user_reply_msg = "您已获批准加入\nYou have been approved."
181 | elif allow_count == deny_count:
182 | logger.info(f"{self.user_id}: Tie in {self.chat_id}")
183 | result_message = await bot.reply_to(notice_message, "Tie.")
184 | approve_user = False
185 | edit_msg = f"{self.user_mention} (ID: {self.user_id}
): Tie."
186 | user_reply_msg = "平票,请稍后尝试重新申请。\nTie. Please request again later."
187 | else:
188 | logger.info(f"{self.user_id}: Denied in {self.chat_id}")
189 | result_message = await bot.reply_to(notice_message, "Denied.")
190 | approve_user = False
191 | edit_msg = f"{self.user_mention} (ID: {self.user_id}
): Denied."
192 | user_reply_msg = "您的申请已被拒绝。\nYou have been denied."
193 |
194 | # Process the request
195 | if self.PollButton is not None:
196 | await bot.edit_message_text(f"Poll has ended\nAllow : Deny = {allow_count} : {deny_count}",
197 | chat_id=self.chat_id, message_id=self.polling.message_id)
198 | edit_task = bot.edit_message_text(edit_msg, chat_id=self.chat_id,
199 | message_id=notice_message.message_id, parse_mode="HTML")
200 | reply_task = bot.reply_to(self.user_message, user_reply_msg)
201 | if approve_user:
202 | log_task = self.LogChannel.update_log("Approved", allow_count, deny_count)
203 | request_task = bot.approve_chat_join_request(request.chat.id, request.from_user.id)
204 | else:
205 | log_task = self.LogChannel.update_log("Denied", allow_count, deny_count)
206 | request_task = bot.decline_chat_join_request(request.chat.id, request.from_user.id)
207 | try:
208 | await asyncio.gather(
209 | edit_task,
210 | reply_task,
211 | log_task,
212 | request_task
213 | )
214 | except Exception as e:
215 | logger.error(f"An error occurred during processing: {e}")
216 |
217 | self.finished = True
218 |
219 | await asyncio.sleep(60)
220 |
221 | # Clean up
222 | await bot.delete_message(chat_id=request.chat.id, message_id=self.polling.message_id)
223 | await bot.delete_message(chat_id=request.chat.id, message_id=result_message.message_id)
224 |
225 | async def handle_button(self, bot, callback_query: types.CallbackQuery, action):
226 | chat_member = await bot.get_chat_member(self.chat_id, callback_query.from_user.id)
227 |
228 | # Check permission
229 | if not (chat_member.status == 'creator'):
230 | if not (chat_member.status == 'administrator'):
231 | await bot.answer_callback_query(callback_query.id, "You have no permission to do this.")
232 | return
233 | if action in ["Approve", "Reject"]:
234 | if not chat_member.can_invite_users:
235 | await bot.answer_callback_query(callback_query.id, "You have no permission to do this.")
236 | return
237 | elif action == "Ban":
238 | if not chat_member.can_restrict_members:
239 | await bot.answer_callback_query(callback_query.id, "You have no permission to do this.")
240 | return
241 |
242 | # Process the request
243 | if self.finished:
244 | await bot.answer_callback_query(callback_query.id, "This request has been processed")
245 | return
246 |
247 | admin_mention = f'{callback_query.from_user.first_name}'
248 | if callback_query.from_user.last_name is not None:
249 | admin_mention += f" {callback_query.from_user.last_name}"
250 | else:
251 | admin_mention += ""
252 |
253 | if action == "Approve":
254 | self.finished = True
255 | approve_user = True
256 | await bot.answer_callback_query(callback_query.id, "Approved.")
257 | logger.info(f"{self.user_id}: Approved by {callback_query.from_user.id} in {self.chat_id}")
258 | await self.LogChannel.update_log_admin("Approved", admin_mention)
259 | edit_msg = f"{self.user_mention} (ID: {self.user_id}
): Approved by {admin_mention}"
260 | reply_msg = "您已获批准加入\nYour application have been approved."
261 | elif action == "Reject":
262 | self.finished = True
263 | approve_user = False
264 | await bot.answer_callback_query(callback_query.id, "Denied.")
265 | logger.info(f"{self.user_id}: Denied by {callback_query.from_user.id} in {self.chat_id}")
266 | await self.LogChannel.update_log_admin("Denied", admin_mention)
267 | edit_msg = f"{self.user_mention} (ID: {self.user_id}
): Denied by {admin_mention}"
268 | reply_msg = "您的申请已被拒绝。\nYour application have been denied."
269 | elif action == "Ban":
270 | if self.bot_member.status == 'administrator' and self.bot_member.can_restrict_members:
271 | self.finished = True
272 | approve_user = False
273 | await bot.kick_chat_member(self.chat_id, self.user_id)
274 | await bot.answer_callback_query(callback_query.id, "Banned.")
275 | logger.info(f"{self.user_id}: Banned by {callback_query.from_user.id} in {self.chat_id}")
276 | await self.LogChannel.update_log_admin("Banned", admin_mention)
277 | edit_msg = f"{self.user_mention} (ID: {self.user_id}
): Banned by {admin_mention}"
278 | reply_msg = "您的申请已被拒绝。\nYour application have been denied."
279 | else:
280 | self.finished = True
281 | approve_user = False
282 | await bot.answer_callback_query(callback_query.id, "Bot has no permission to ban.")
283 | logger.info(f"{self.user_id}: Denied by {callback_query.from_user.id} in {self.chat_id}")
284 | await self.LogChannel.update_log_admin("Denied", admin_mention)
285 | edit_msg = f"{self.user_mention} (ID: {self.user_id}
): Denied by {admin_mention}"
286 | reply_msg = "您的申请已被拒绝。\nYour application have been denied."
287 | else:
288 | await bot.answer_callback_query(callback_query.id, "Unknown action.")
289 | logger.error(f"Unknown action: {action}")
290 | return
291 |
292 | edit_task = bot.edit_message_text(edit_msg, chat_id=self.chat_id,
293 | message_id=self.notice_message.message_id, parse_mode="HTML")
294 | reply_task = bot.reply_to(self.user_message, reply_msg)
295 | if approve_user:
296 | request_task = bot.approve_chat_join_request(self.request.chat.id, self.request.from_user.id)
297 | else:
298 | request_task = bot.decline_chat_join_request(self.request.chat.id, self.request.from_user.id)
299 | try:
300 | await asyncio.gather(
301 | edit_task,
302 | reply_task,
303 | request_task,
304 | )
305 | except Exception as e:
306 | logger.error(f"An error occurred: {e}")
307 | if self.PollButton is not None:
308 | self.PollButton.stop_poll()
309 | else:
310 | try:
311 | bot.stop_poll(self.request.chat.id, self.polling.message_id)
312 | except Exception as e:
313 | logger.error(f"Stop poll failed: {e}")
314 | await bot.delete_message(chat_id=self.chat_id, message_id=self.polling.message_id)
315 |
316 | async def poll_button_handle(self, bot, callback_query: types.CallbackQuery):
317 | if self.finished:
318 | await bot.answer_callback_query(callback_query.id, "Poll has ended")
319 | return
320 | user_id = callback_query.from_user.id
321 | try:
322 | user_member = await bot.get_chat_member(self.chat_id, user_id)
323 | if user_member.status not in ['administrator', 'creator', 'member']:
324 | await bot.answer_callback_query(callback_query.id, "You are not in this group")
325 | return
326 | except Exception:
327 | await bot.answer_callback_query(callback_query.id, "You are not in this group")
328 | return
329 | await self.PollButton.user_poll_handle(bot, callback_query)
330 |
--------------------------------------------------------------------------------
/app/KickRequest.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time: 2024/2/9 17:23
3 | # @FileName: KickRequest.py
4 | # @Software: PyCharm
5 | # @GitHub: KimmyXYC
6 | import asyncio
7 | from loguru import logger
8 | from telebot import types
9 |
10 |
11 | class Ostracism:
12 | def __init__(self, chat_id, initiator_user_id, target_user_id, bot_id):
13 | self.chat_id = chat_id
14 | self.bot_id = bot_id
15 | self.initiator_user_id = initiator_user_id
16 | self.target_user_id = target_user_id
17 |
18 | self.admin_status = False
19 | self.cancelled = False
20 | self.finished = False
21 |
22 | self.ostracism_id = None
23 | self.start_msg = None
24 | self.polling = None
25 |
26 | self.target_user_mention = None
27 | self.initiator_user_mention = None
28 | self.bot_member = None
29 |
30 | def check_up_status(self):
31 | return self.finished
32 |
33 | async def start_kick_vote(self, bot, message):
34 | self.bot_member = await bot.get_chat_member(self.chat_id, self.bot_id)
35 | try:
36 | target_user_member = await bot.get_chat_member(self.chat_id, self.target_user_id)
37 | except Exception as e:
38 | logger.error(f"User_id:{self.initiator_user_id} in Chat_id:{self.chat_id} "
39 | f"want to kick ID:{self.target_user_id}: {e}")
40 | await bot.reply_to(message, "Cannot find the target user.")
41 | return
42 | if target_user_member.status == 'creator' or target_user_member.status == 'administrator':
43 | await bot.reply_to(message, "Cannot kick the administrator.")
44 | return
45 | elif target_user_member.status == 'none':
46 | await bot.reply_to(message, "Cannot find the target user.")
47 | return
48 |
49 | self.ostracism_id = f"{self.chat_id}@{int(self.target_user_id)}"
50 |
51 | self.initiator_user_mention = f'{message.from_user.first_name}'
52 | if message.from_user.last_name is not None:
53 | self.initiator_user_mention += f" {message.from_user.last_name}"
54 | else:
55 | self.initiator_user_mention += ""
56 |
57 | self.target_user_mention = f'{target_user_member.user.first_name}'
58 | if target_user_member.user.last_name is not None:
59 | self.target_user_mention += f" {target_user_member.user.last_name}"
60 | else:
61 | self.target_user_mention += ""
62 |
63 | buttons = types.InlineKeyboardMarkup()
64 | buttons.add(types.InlineKeyboardButton(text="Approve", callback_data=f"KR Approve {self.ostracism_id}"),
65 | types.InlineKeyboardButton(text="Cancel", callback_data=f"KR Cancel {self.ostracism_id}"))
66 | self.start_msg = await bot.reply_to(
67 | message,
68 | f"{self.initiator_user_mention} want to start a kick voting to user {self.target_user_mention}.",
69 | reply_markup=buttons,
70 | parse_mode="HTML"
71 | )
72 |
73 | await asyncio.sleep(300)
74 | if not self.admin_status:
75 | await bot.edit_message_text(
76 | chat_id=self.chat_id,
77 | message_id=self.start_msg.message_id,
78 | text="No one approve this kick voting."
79 | )
80 | self.finished = True
81 |
82 | async def handle_button(self, bot, callback_query: types.CallbackQuery, action, db):
83 | chat_member = await bot.get_chat_member(self.chat_id, callback_query.from_user.id)
84 | if not callback_query.from_user.id == self.initiator_user_id:
85 | if not ((chat_member.status == 'administrator' and chat_member.can_restrict_members) or
86 | chat_member.status == 'creator'):
87 | await bot.answer_callback_query(callback_query.id, "You have no permission to do this.")
88 | return
89 | admin_mention = f'{callback_query.from_user.first_name}'
90 | if callback_query.from_user.last_name is not None:
91 | admin_mention += f" {callback_query.from_user.last_name}"
92 | else:
93 | admin_mention += ""
94 | if self.admin_status and action == "Approve":
95 | await bot.answer_callback_query(callback_query.id, "Admin have already done this.")
96 | return
97 | if action == "Approve":
98 | if callback_query.from_user.id == self.initiator_user_id:
99 | if not ((chat_member.status == 'administrator' and chat_member.can_restrict_members) or
100 | chat_member.status == 'creator'):
101 | await bot.answer_callback_query(callback_query.id, "You cannot approve your own request.")
102 | return
103 | self.admin_status = True
104 | elif action == "Cancel":
105 | self.admin_status = True
106 | self.cancelled = True
107 | await bot.answer_callback_query(callback_query.id, "Canceled.")
108 | await bot.edit_message_text(
109 | chat_id=self.chat_id,
110 | message_id=self.start_msg.message_id,
111 | text=f"Kick voting to user {self.target_user_mention} was canceled by {admin_mention}.",
112 | parse_mode="HTML"
113 | )
114 | self.finished = True
115 | if self.polling:
116 | await bot.delete_message(chat_id=self.chat_id, message_id=self.polling.message_id)
117 | return
118 | else:
119 | await bot.answer_callback_query(callback_query.id, "Unknown action.")
120 | logger.error(f"Unknown action: {action}")
121 | return
122 |
123 | buttons = types.InlineKeyboardMarkup()
124 | buttons.add(types.InlineKeyboardButton(text="Cancel", callback_data=f"KR Cancel {self.ostracism_id}"))
125 | await bot.edit_message_text(
126 | chat_id=self.chat_id,
127 | message_id=self.start_msg.message_id,
128 | text=f"Start kick voting to user {self.target_user_mention}."
129 | f"\nInitiator: {self.initiator_user_mention} Approver: {admin_mention}.",
130 | reply_markup=buttons,
131 | parse_mode="HTML"
132 | )
133 |
134 | chat_dict = db.get(str(self.chat_id))
135 | status_pin_msg = chat_dict.get("pin_msg", False)
136 | anonymous_vote = chat_dict.get("anonymous_vote", True)
137 |
138 | vote_question = "Kick out this user?"
139 | vote_options = ["Yes", "No"]
140 | self.polling = await bot.send_poll(
141 | self.chat_id,
142 | vote_question,
143 | vote_options,
144 | is_anonymous=anonymous_vote,
145 | allows_multiple_answers=False,
146 | reply_to_message_id=self.start_msg.message_id,
147 | protect_content=True
148 | )
149 |
150 | if status_pin_msg and self.bot_member.status == 'administrator' and self.bot_member.can_pin_messages:
151 | await bot.pin_chat_message(
152 | chat_id=self.chat_id,
153 | message_id=self.polling.message_id,
154 | disable_notification=True,
155 | )
156 |
157 | vote_time = chat_dict.get("vote_time", 600)
158 | await asyncio.sleep(vote_time)
159 | if self.cancelled:
160 | return
161 | if status_pin_msg and self.bot_member.status == 'administrator' and self.bot_member.can_pin_messages:
162 | await bot.unpin_chat_message(
163 | chat_id=self.chat_id,
164 | message_id=self.polling.message_id,
165 | )
166 |
167 | vote_message = await bot.stop_poll(self.chat_id, self.polling.message_id)
168 | allow_count = vote_message.options[0].voter_count
169 | deny_count = vote_message.options[1].voter_count
170 |
171 | if vote_message.total_voter_count == 0:
172 | logger.info(f"Ostracism {self.target_user_id}: No one voted in {self.chat_id}")
173 | result_message = await bot.reply_to(self.start_msg, "No one voted.")
174 | kick_user = False
175 | edit_msg = f"Kick {self.target_user_mention} (ID: {self.target_user_id}
): No one voted."
176 | elif allow_count > deny_count:
177 | logger.info(f"Ostracism {self.target_user_id}: Kicking out in {self.chat_id}")
178 | result_message = await bot.reply_to(self.start_msg, "Kick out.")
179 | kick_user = True
180 | edit_msg = f"Kick {self.target_user_mention} (ID: {self.target_user_id}
): Kick out."
181 | elif allow_count == deny_count:
182 | logger.info(f"Ostracism {self.target_user_id}: Tie in {self.chat_id}")
183 | result_message = await bot.reply_to(self.start_msg, "Tie.")
184 | kick_user = False
185 | edit_msg = f"Ostracism {self.target_user_mention} (ID: {self.target_user_id}
): Tie."
186 | else:
187 | logger.info(f"Ostracism {self.target_user_id}: Not kicking out in {self.chat_id}")
188 | result_message = await bot.reply_to(self.start_msg, "Not kicking out")
189 | kick_user = False
190 | edit_msg = (f"Ostracism {self.target_user_mention} "
191 | f"(ID: {self.target_user_id}
): Not kicking out.")
192 |
193 | await bot.edit_message_text(
194 | chat_id=self.chat_id,
195 | message_id=self.start_msg.message_id,
196 | text=edit_msg,
197 | parse_mode="HTML"
198 | )
199 |
200 | if kick_user:
201 | await bot.kick_chat_member(self.chat_id, self.target_user_id)
202 | permissions = types.ChatPermissions(
203 | can_send_messages=True,
204 | can_send_media_messages=True,
205 | can_send_polls=True,
206 | can_send_other_messages=True,
207 | can_add_web_page_previews=True,
208 | can_change_info=True,
209 | can_invite_users=True,
210 | can_pin_messages=True
211 | )
212 | await bot.restrict_chat_member(self.chat_id, self.target_user_id, permissions=permissions)
213 |
214 | self.finished = True
215 |
216 | await asyncio.sleep(60)
217 |
218 | try:
219 | await bot.delete_message(chat_id=self.chat_id, message_id=self.polling.message_id)
220 | await bot.delete_message(chat_id=self.chat_id, message_id=result_message.message_id)
221 | except Exception as e:
222 | logger.error(f"User_id:{self.initiator_user_id} in Chat_id:{self.chat_id}: {e}")
223 |
--------------------------------------------------------------------------------
/app/PollButton.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time: 2024/8/24 下午9:22
3 | # @Author: KimmyXYC
4 | # @File: PollButton.py
5 | # @Software: PyCharm
6 |
7 | import base64
8 | import telebot.types
9 | from setting.telegrambot import BotSetting
10 |
11 |
12 | class PollButton:
13 | def __init__(self, request_id):
14 | self.request_id = request_id
15 | self.finished = False
16 | self.allow_list = {}
17 | self.deny_list = {}
18 |
19 | def button_create(self):
20 | requests_id = base64.b64encode(str(self.request_id).encode()).decode()
21 | keyboard = telebot.types.InlineKeyboardMarkup()
22 | keyboard.add(telebot.types.InlineKeyboardButton("Yes", callback_data=f"PB Allow {self.request_id}"),
23 | telebot.types.InlineKeyboardButton("No", callback_data=f"PB Deny {self.request_id}"))
24 | keyboard.add(telebot.types.InlineKeyboardButton("Real-time Result",
25 | url=f"t.me/{BotSetting.bot_username}?start=getresult_{requests_id}"))
26 | return keyboard
27 |
28 | async def user_poll_handle(self, bot, call):
29 | if self.finished:
30 | await bot.answer_callback_query(call.id, "Poll has ended")
31 | return
32 | user_id = call.from_user.id
33 |
34 | if call.from_user.username is not None:
35 | user_mention = f'@{call.from_user.username}'
36 | else:
37 | user_mention = f'{call.from_user.first_name}'
38 | if call.from_user.last_name is not None:
39 | user_mention += f" {call.from_user.last_name}"
40 | else:
41 | user_mention += ""
42 |
43 | if user_id in self.allow_list:
44 | await bot.answer_callback_query(call.id, "You have already voted")
45 | elif user_id in self.deny_list:
46 | await bot.answer_callback_query(call.id, "You have already voted")
47 | else:
48 | if call.data == f"PB Allow {self.request_id}":
49 | self.allow_list[user_id] = user_mention
50 | await bot.answer_callback_query(call.id, "You have voted to allow")
51 | elif call.data == f"PB Deny {self.request_id}":
52 | self.deny_list[user_id] = user_mention
53 | await bot.answer_callback_query(call.id, "You have voted to deny")
54 | else:
55 | await bot.answer_callback_query(call.id, "Invalid operation")
56 |
57 | def stop_poll(self):
58 | self.finished = True
59 | return len(self.allow_list), len(self.deny_list)
60 |
61 | def get_result(self, user_id, anonymous_vote=True):
62 | if user_id not in self.allow_list and user_id not in self.deny_list:
63 | return "You have not voted"
64 | info = f"Allow : Deny = {len(self.allow_list)} : {len(self.deny_list)}"
65 | if not anonymous_vote:
66 | info += "\n\nAllow List:\n"
67 | for user in self.allow_list.values():
68 | info += f"- {user}\n"
69 | info += "\nDeny List:\n"
70 | for user in self.deny_list.values():
71 | info += f"- {user}\n"
72 | return info
73 |
--------------------------------------------------------------------------------
/app/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time : 2023/11/18 上午12:47
3 | # @Author : sudoskys
4 | # @File : __init__.py
5 | # @Software: PyCharm
6 |
--------------------------------------------------------------------------------
/app_conf.py:
--------------------------------------------------------------------------------
1 | import dynaconf
2 | from dynaconf import Dynaconf, Validator
3 | from loguru import logger
4 |
5 | settings = Dynaconf(
6 | envvar_prefix="DYNACONF",
7 | settings_files=["conf_dir/settings.toml", "conf_dir/.secrets.toml"],
8 | validators=[
9 | # Ensure some parameter meets a condition
10 | # Validator('AGE', lte=30, gte=10),
11 | # validate a value is eq in specific env
12 | # Validator('PROJECT', eq='hello_world', env='production'),
13 | ],
14 | )
15 | settings.validators.register(
16 | Validator("app.debug", condition=lambda v: isinstance(v, bool), env="DEBUG"),
17 | )
18 | # raises after all possible errors are evaluated
19 | try:
20 | settings.validators.validate_all()
21 | except dynaconf.ValidationError as e:
22 | accumulative_errors = e.details
23 | logger.error(f"Setting Validation Error {accumulative_errors}")
24 | raise e
25 |
26 | # :) Look https://www.dynaconf.com/validation/ for more validations
27 |
28 |
29 | # `envvar_prefix` = export envvars with `export DYNACONF_FOO=bar`.
30 | # `settings_files` = Load these files in the order.
31 |
--------------------------------------------------------------------------------
/conf_dir/settings.toml:
--------------------------------------------------------------------------------
1 | [app]
2 | debug = false
3 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import sys
3 | import elara
4 |
5 | from dotenv import load_dotenv
6 | from loguru import logger
7 |
8 | from app.Controller import BotRunner
9 | from app_conf import settings
10 |
11 | load_dotenv()
12 | # 移除默认的日志处理器
13 | logger.remove()
14 | # 添加标准输出
15 | print("从配置文件中读取到的DEBUG为", settings.app.debug)
16 | handler_id = logger.add(sys.stderr, level="INFO" if not settings.app.debug else "DEBUG")
17 | # 添加文件写出
18 | logger.add(
19 | sink="run.log",
20 | format="{time} - {level} - {message}",
21 | level="INFO",
22 | rotation="100 MB",
23 | enqueue=True,
24 | )
25 |
26 | logger.info("Log Is Secret, Please Don't Share It To Others")
27 | db = elara.exe(path="conf_dir/chat.db", commitdb=True)
28 |
29 |
30 | async def main():
31 | await asyncio.gather(BotRunner(db).run())
32 |
33 |
34 | loop = asyncio.get_event_loop()
35 | loop.run_until_complete(main())
36 |
--------------------------------------------------------------------------------
/pm2.json:
--------------------------------------------------------------------------------
1 | {
2 | "apps": [
3 | {
4 | "name": "ApproveByPoll",
5 | "script": "pdm run python3 main.py",
6 | "instances": 1,
7 | "max_restarts": 3,
8 | "restart_delay": 10000,
9 | "exp_backoff_restart_delay": 100,
10 | "error_file": "app.log",
11 | "out_file": "app.log",
12 | "log_date_format": "YYYY-MM-DD HH-mm-ss"
13 | }
14 | ]
15 | }
16 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = ""
3 | version = ""
4 | description = ""
5 | authors = [
6 | { name = "KimmyXYC", email = "kimmyxyc@gamil.com" },
7 | ]
8 | dependencies = [
9 | "pydantic<3.0.0,>=2.0.0",
10 | "pydantic-settings<3.0.0,>=2.1.0",
11 | "python-dotenv<2.0.0,>=1.0.0",
12 | "pytelegrambotapi<5.0.0,>=4.14.0",
13 | "loguru<1.0.0,>=0.7.0",
14 | "elara>=0.5.5",
15 | "httpx<1.0.0,>=0.25.1",
16 | "shortuuid<2.0.0,>=1.0.11",
17 | "asgiref<4.0.0,>=3.7.2",
18 | "aiohttp>=3.9.0",
19 | "dynaconf>=3.2.4",
20 | "pre-commit>=3.5.0",
21 | ]
22 |
23 |
24 |
25 | requires-python = ">=3.8"
26 | readme = "README.md"
27 | license = { text = "AGPL-3.0" }
28 |
29 |
30 | [tool.ruff]
31 | # Exclude a variety of commonly ignored directories.
32 | exclude = [
33 | ".idea",
34 | ".bzr",
35 | ".direnv",
36 | ".eggs",
37 | ".git",
38 | ".git-rewrite",
39 | ".hg",
40 | ".mypy_cache",
41 | ".nox",
42 | ".pants.d",
43 | ".pytype",
44 | ".ruff_cache",
45 | ".svn",
46 | ".tox",
47 | ".venv",
48 | "__pypackages__",
49 | "_build",
50 | "buck-out",
51 | "build",
52 | "dist",
53 | "node_modules",
54 | "venv",
55 | ]
56 |
57 | # Same as Black.
58 | line-length = 88
59 | indent-width = 4
60 |
61 | # Assume Python 3.8
62 | target-version = "py38"
63 |
64 | [tool.ruff.lint]
65 | # Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
66 | select = ["E4", "E7", "E9", "F"]
67 | ignore = []
68 |
69 | # Allow fix for all enabled rules (when `--fix`) is provided.
70 | fixable = ["ALL"]
71 | unfixable = []
72 |
73 | # Allow unused variables when underscore-prefixed.
74 | dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
75 |
76 | [tool.ruff.format]
77 | # Like Black, use double quotes for strings.
78 | quote-style = "double"
79 |
80 | # Like Black, indent with spaces, rather than tabs.
81 | indent-style = "space"
82 |
83 | # Like Black, respect magic trailing commas.
84 | skip-magic-trailing-comma = false
85 |
86 | # Like Black, automatically detect the appropriate line ending.
87 | line-ending = "auto"
88 |
89 | [tool.pdm]
90 |
--------------------------------------------------------------------------------
/setting/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time : 2023/11/25 下午9:05
3 | # @Author : sudoskys
4 | # @File : __init__.py.py
5 | # @Software: PyCharm
6 |
--------------------------------------------------------------------------------
/setting/telegrambot.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time : 2023/11/18 上午12:32
3 | # @File : schema.py
4 | # @Software: PyCharm
5 | from typing import Optional
6 |
7 | import requests
8 | from dotenv import load_dotenv
9 | from loguru import logger
10 | from pydantic import Field, model_validator
11 | from pydantic_settings import BaseSettings, SettingsConfigDict
12 |
13 |
14 | class TelegramBot(BaseSettings):
15 | """
16 | 代理设置
17 | """
18 |
19 | token: Optional[str] = Field(None, validation_alias="TELEGRAM_BOT_TOKEN")
20 | proxy_address: Optional[str] = Field(
21 | None, validation_alias="TELEGRAM_BOT_PROXY_ADDRESS"
22 | ) # "all://127.0.0.1:7890"
23 | bot_link: Optional[str] = Field(None, validation_alias="TELEGRAM_BOT_LINK")
24 | bot_id: Optional[str] = Field(None, validation_alias="TELEGRAM_BOT_ID")
25 | bot_username: Optional[str] = Field(None, validation_alias="TELEGRAM_BOT_USERNAME")
26 | log_channel: Optional[str] = Field(None, validation_alias="TELEGRAM_BOT_LOG_CHANNEL")
27 | model_config = SettingsConfigDict(
28 | env_file=".env", env_file_encoding="utf-8", extra="ignore"
29 | )
30 |
31 | @model_validator(mode="after")
32 | def bot_validator(self):
33 | if self.proxy_address:
34 | logger.success(f"TelegramBot proxy was set to {self.proxy_address}")
35 | if self.token is None:
36 | logger.info("\n🍀Check:Telegrambot token is empty")
37 | if self.bot_id is None and self.token:
38 | try:
39 | from telebot import TeleBot
40 |
41 | # 创建 Bot
42 | if self.proxy_address is not None:
43 | from telebot import apihelper
44 |
45 | if "socks5://" in self.proxy_address:
46 | self.proxy_address = self.proxy_address.replace(
47 | "socks5://", "socks5h://"
48 | )
49 | apihelper.proxy = {"https": self.proxy_address}
50 | _bot = TeleBot(token=self.token).get_me()
51 | self.bot_id = str(_bot.id)
52 | self.bot_username = _bot.username
53 | self.bot_link = f"https://t.me/{self.bot_username}"
54 | except requests.exceptions.ConnectTimeout:
55 | logger.error(
56 | "\n🍀TelegramBot Connect Error --error ConnectTimeout, Please Check Your Network To Telegram"
57 | )
58 | raise requests.exceptions.ConnectTimeout
59 | except Exception as e:
60 | logger.error(f"\n🍀TelegramBot Connect Error --error {e}")
61 | else:
62 | logger.success(
63 | f"🍀TelegramBot Init Connection Success --bot_name {self.bot_username} --bot_id {self.bot_id}"
64 | )
65 | return self
66 |
67 | @property
68 | def available(self):
69 | return self.token is not None
70 |
71 |
72 | load_dotenv()
73 | BotSetting = TelegramBot()
74 |
--------------------------------------------------------------------------------
/utils/LogChannel.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time: 2023/12/23 19:24
3 | # @FileName: LogChannel.py
4 | # @Software: PyCharm
5 | # @GitHub: KimmyXYC
6 | from loguru import logger
7 | from telebot import types
8 |
9 |
10 | class LogChannel:
11 | def __init__(self, bot, channel_id):
12 | self.bot = bot
13 | self.message = None
14 | self.channel_id = channel_id
15 | self.message_text = None
16 | self.message = None
17 |
18 | async def create_log(self, request: types.ChatJoinRequest, log_type):
19 | mention = f'{request.from_user.first_name}'
20 | if request.from_user.last_name is not None:
21 | mention += f" {request.from_user.last_name}"
22 | mention += ""
23 | self.message_text = (
24 | f"#ApproveByPoll #{log_type}:\n"
25 | f"Chat: {request.chat.title}\n"
26 | f"User: {mention}\n"
27 | f"User ID: {request.from_user.id}
"
28 | )
29 | message_text = self.message_text + "\nStatus: Pending"
30 | try:
31 | self.message = await self.bot.send_message(self.channel_id, message_text, parse_mode="HTML")
32 | except Exception as e:
33 | logger.error(f"Cannot send message to log channel: {e}")
34 |
35 | async def update_log_admin(self, status, admin_mention):
36 | self.message_text += (
37 | f"\nStatus: {status}\n"
38 | f"Admin: {admin_mention}"
39 | )
40 | try:
41 | await self.bot.edit_message_text(self.message_text, self.channel_id, self.message.message_id, parse_mode="HTML")
42 | except Exception as e:
43 | logger.error(f"Cannot send message to log channel: {e}")
44 |
45 | async def update_log(self, status, allow_count, deny_count):
46 | self.message_text += (
47 | f"\nStatus: {status}\n"
48 | f"Result: Allow : Deny = {allow_count} : {deny_count}"
49 | )
50 | try:
51 | await self.bot.edit_message_text(self.message_text, self.channel_id, self.message.message_id, parse_mode="HTML")
52 | except Exception as e:
53 | logger.error(f"Cannot send message to log channel: {e}")
54 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # @Time : 2023/11/25 下午9:05
3 | # @Author : sudoskys
4 | # @File : __init__.py.py
5 | # @Software: PyCharm
6 |
--------------------------------------------------------------------------------