Compare commits
82 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d30e932f94 | |||
| 87a3e124f4 | |||
| 579a8ca7e4 | |||
| b1276c42a4 | |||
| 0996f15c30 | |||
| b2fb41edc3 | |||
| 10ce155b8c | |||
| 0ca647fd64 | |||
| 33d4fd2e2e | |||
| 7a2f5cd899 | |||
| 6fbe1632bc | |||
| 36baacc0e1 | |||
| eb7effed4c | |||
| f27b62f8e7 | |||
| 4aa9be2408 | |||
| 4fca2cad95 | |||
| b41314af76 | |||
| ce3985ff96 | |||
| 9b9a72ef04 | |||
| ce78caf065 | |||
| c01b528055 | |||
| 725167f663 | |||
| 18dde7e882 | |||
| f5ec703994 | |||
| 5e07feb815 | |||
| c394fb3d2a | |||
| a7979af27a | |||
| d29d454727 | |||
| de6a79a634 | |||
| fd3d5d8de6 | |||
| f1358b36b7 | |||
| 831472ab51 | |||
| bbb554e4e9 | |||
| 7677ae9193 | |||
| ca87286898 | |||
| f821241edb | |||
| 9706730d37 | |||
| 8b11c65c8e | |||
| 2750517be4 | |||
| e5da607c9d | |||
| 1e912487af | |||
| 69f7d05527 | |||
| 2b572da089 | |||
| c75fd8516a | |||
| a81b09eb1e | |||
| 145c716529 | |||
| bc1ddc349a | |||
| 5f557fa2b2 | |||
| 940867baed | |||
| 4ea1f101ff | |||
| d0d36d9f1a | |||
| eee8d86426 | |||
| 94d335d950 | |||
| 9756d2e2b7 | |||
| 3e4d7972c7 | |||
| 0e9c128a15 | |||
| e850bd85a8 | |||
| b02c716992 | |||
| 822d845241 | |||
| 8dc478a606 | |||
| d664036f5e | |||
| fe655a7ee5 | |||
| 56ff84f7a5 | |||
| 69b1705fd5 | |||
| 956cdaf020 | |||
| 0b44237317 | |||
| 67880704a0 | |||
| 682fb0bdb0 | |||
| 71c7a10165 | |||
| 5577780565 | |||
| 5db2b7c861 | |||
| 370ceb8382 | |||
| 3226438e69 | |||
| c432edf8fc | |||
| 49aa863eb4 | |||
| c58039cb9e | |||
| ee242c98c7 | |||
| f3dfb03749 | |||
| 02ea333af1 | |||
| 142a5ffaab | |||
| db24a9abda | |||
| 3fcb6adaad |
@@ -1,6 +0,0 @@
|
||||
[flake8]
|
||||
max-line-length = 120
|
||||
ignore = E203, E266, E501, W503, F541, E704, W293, W291, E126, E121, E123, E128, E302, E131, E231, W292, E402, E261, E305, E701
|
||||
max-complexity = 15
|
||||
select = B, C, E, F, W, T4, B9
|
||||
exclude = .venv,.git,.tox,dist,doc,*lib/python*,*egg,build,.txt,config.py
|
||||
+3
-1
@@ -53,4 +53,6 @@ nginx.conf
|
||||
scripts
|
||||
models.py
|
||||
Dockerfile
|
||||
.csv
|
||||
.csv
|
||||
|
||||
setup.py
|
||||
@@ -0,0 +1,330 @@
|
||||
Creative Commons Attribution-NonCommercial 4.0 International Public
|
||||
License © Vladless, 2024.
|
||||
|
||||
By exercising the Licensed Rights (defined below), You accept and agree
|
||||
to be bound by the terms and conditions of this Creative Commons
|
||||
Attribution-NonCommercial 4.0 International Public License ("Public
|
||||
License"). To the extent this Public License may be interpreted as a
|
||||
contract, You are granted the Licensed Rights in consideration of Your
|
||||
acceptance of these terms and conditions, and the Licensor grants You
|
||||
such rights in consideration of benefits the Licensor receives from
|
||||
making the Licensed Material available under these terms and
|
||||
conditions.
|
||||
|
||||
|
||||
Section 1 -- Definitions.
|
||||
|
||||
a. Adapted Material means material subject to Copyright and Similar
|
||||
Rights that is derived from or based upon the Licensed Material
|
||||
and in which the Licensed Material is translated, altered,
|
||||
arranged, transformed, or otherwise modified in a manner requiring
|
||||
permission under the Copyright and Similar Rights held by the
|
||||
Licensor. For purposes of this Public License, where the Licensed
|
||||
Material is a musical work, performance, or sound recording,
|
||||
Adapted Material is always produced where the Licensed Material is
|
||||
synched in timed relation with a moving image.
|
||||
|
||||
b. Adapter's License means the license You apply to Your Copyright
|
||||
and Similar Rights in Your contributions to Adapted Material in
|
||||
accordance with the terms and conditions of this Public License.
|
||||
|
||||
c. Copyright and Similar Rights means copyright and/or similar rights
|
||||
closely related to copyright including, without limitation,
|
||||
performance, broadcast, sound recording, and Sui Generis Database
|
||||
Rights, without regard to how the rights are labeled or
|
||||
categorized. For purposes of this Public License, the rights
|
||||
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
||||
Rights.
|
||||
d. Effective Technological Measures means those measures that, in the
|
||||
absence of proper authority, may not be circumvented under laws
|
||||
fulfilling obligations under Article 11 of the WIPO Copyright
|
||||
Treaty adopted on December 20, 1996, and/or similar international
|
||||
agreements.
|
||||
|
||||
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
||||
any other exception or limitation to Copyright and Similar Rights
|
||||
that applies to Your use of the Licensed Material.
|
||||
|
||||
f. Licensed Material means the artistic or literary work, database,
|
||||
or other material to which the Licensor applied this Public
|
||||
License.
|
||||
|
||||
g. Licensed Rights means the rights granted to You subject to the
|
||||
terms and conditions of this Public License, which are limited to
|
||||
all Copyright and Similar Rights that apply to Your use of the
|
||||
Licensed Material and that the Licensor has authority to license.
|
||||
|
||||
h. Licensor means the individual(s) or entity(ies) granting rights
|
||||
under this Public License.
|
||||
|
||||
i. NonCommercial means not primarily intended for or directed towards
|
||||
commercial advantage or monetary compensation. For purposes of
|
||||
this Public License, the exchange of the Licensed Material for
|
||||
other material subject to Copyright and Similar Rights by digital
|
||||
file-sharing or similar means is NonCommercial provided there is
|
||||
no payment of monetary compensation in connection with the
|
||||
exchange.
|
||||
|
||||
j. Share means to provide material to the public by any means or
|
||||
process that requires permission under the Licensed Rights, such
|
||||
as reproduction, public display, public performance, distribution,
|
||||
dissemination, communication, or importation, and to make material
|
||||
available to the public including in ways that members of the
|
||||
public may access the material from a place and at a time
|
||||
individually chosen by them.
|
||||
|
||||
k. Sui Generis Database Rights means rights other than copyright
|
||||
resulting from Directive 96/9/EC of the European Parliament and of
|
||||
the Council of 11 March 1996 on the legal protection of databases,
|
||||
as amended and/or succeeded, as well as other essentially
|
||||
equivalent rights anywhere in the world.
|
||||
|
||||
l. You means the individual or entity exercising the Licensed Rights
|
||||
under this Public License. Your has a corresponding meaning.
|
||||
|
||||
|
||||
Section 2 -- Scope.
|
||||
|
||||
a. License grant.
|
||||
|
||||
1. Subject to the terms and conditions of this Public License,
|
||||
the Licensor hereby grants You a worldwide, royalty-free,
|
||||
non-sublicensable, non-exclusive, irrevocable license to
|
||||
exercise the Licensed Rights in the Licensed Material to:
|
||||
|
||||
a. reproduce and Share the Licensed Material, in whole or
|
||||
in part, for NonCommercial purposes only; and
|
||||
|
||||
b. produce, reproduce, and Share Adapted Material for
|
||||
NonCommercial purposes only.
|
||||
|
||||
2. Exceptions and Limitations. For the avoidance of doubt, where
|
||||
Exceptions and Limitations apply to Your use, this Public
|
||||
License does not apply, and You do not need to comply with
|
||||
its terms and conditions.
|
||||
|
||||
3. Term. The term of this Public License is specified in Section
|
||||
6(a).
|
||||
|
||||
4. Media and formats; technical modifications allowed. The
|
||||
Licensor authorizes You to exercise the Licensed Rights in
|
||||
all media and formats whether now known or hereafter created,
|
||||
and to make technical modifications necessary to do so. The
|
||||
Licensor waives and/or agrees not to assert any right or
|
||||
authority to forbid You from making technical modifications
|
||||
necessary to exercise the Licensed Rights, including
|
||||
technical modifications necessary to circumvent Effective
|
||||
Technological Measures. For purposes of this Public License,
|
||||
simply making modifications authorized by this Section 2(a)
|
||||
(4) never produces Adapted Material.
|
||||
|
||||
5. Downstream recipients.
|
||||
|
||||
a. Offer from the Licensor -- Licensed Material. Every
|
||||
recipient of the Licensed Material automatically
|
||||
receives an offer from the Licensor to exercise the
|
||||
Licensed Rights under the terms and conditions of this
|
||||
Public License.
|
||||
|
||||
b. No downstream restrictions. You may not offer or impose
|
||||
any additional or different terms or conditions on, or
|
||||
apply any Effective Technological Measures to, the
|
||||
Licensed Material if doing so restricts exercise of the
|
||||
Licensed Rights by any recipient of the Licensed
|
||||
Material.
|
||||
|
||||
6. No endorsement. Nothing in this Public License constitutes or
|
||||
may be construed as permission to assert or imply that You
|
||||
are, or that Your use of the Licensed Material is, connected
|
||||
with, or sponsored, endorsed, or granted official status by,
|
||||
the Licensor or others designated to receive attribution as
|
||||
provided in Section 3(a)(1)(A)(i).
|
||||
|
||||
b. Other rights.
|
||||
|
||||
1. Moral rights, such as the right of integrity, are not
|
||||
licensed under this Public License, nor are publicity,
|
||||
privacy, and/or other similar personality rights; however, to
|
||||
the extent possible, the Licensor waives and/or agrees not to
|
||||
assert any such rights held by the Licensor to the limited
|
||||
extent necessary to allow You to exercise the Licensed
|
||||
Rights, but not otherwise.
|
||||
|
||||
2. Patent and trademark rights are not licensed under this
|
||||
Public License.
|
||||
|
||||
3. To the extent possible, the Licensor waives any right to
|
||||
collect royalties from You for the exercise of the Licensed
|
||||
Rights, whether directly or through a collecting society
|
||||
under any voluntary or waivable statutory or compulsory
|
||||
licensing scheme. In all other cases the Licensor expressly
|
||||
reserves any right to collect such royalties, including when
|
||||
the Licensed Material is used other than for NonCommercial
|
||||
purposes.
|
||||
|
||||
|
||||
Section 3 -- License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the
|
||||
following conditions.
|
||||
|
||||
a. Attribution.
|
||||
|
||||
1. If You Share the Licensed Material (including in modified
|
||||
form), You must:
|
||||
|
||||
a. retain the following if it is supplied by the Licensor
|
||||
with the Licensed Material:
|
||||
|
||||
i. identification of the creator(s) of the Licensed
|
||||
Material and any others designated to receive
|
||||
attribution, in any reasonable manner requested by
|
||||
the Licensor (including by pseudonym if
|
||||
designated);
|
||||
|
||||
ii. a copyright notice;
|
||||
|
||||
iii. a notice that refers to this Public License;
|
||||
|
||||
iv. a notice that refers to the disclaimer of
|
||||
warranties;
|
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the
|
||||
extent reasonably practicable;
|
||||
|
||||
b. indicate if You modified the Licensed Material and
|
||||
retain an indication of any previous modifications; and
|
||||
|
||||
c. indicate the Licensed Material is licensed under this
|
||||
Public License, and include the text of, or the URI or
|
||||
hyperlink to, this Public License.
|
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any
|
||||
reasonable manner based on the medium, means, and context in
|
||||
which You Share the Licensed Material. For example, it may be
|
||||
reasonable to satisfy the conditions by providing a URI or
|
||||
hyperlink to a resource that includes the required
|
||||
information.
|
||||
|
||||
3. If requested by the Licensor, You must remove any of the
|
||||
information required by Section 3(a)(1)(A) to the extent
|
||||
reasonably practicable.
|
||||
|
||||
4. If You Share Adapted Material You produce, the Adapter's
|
||||
License You apply must not prevent recipients of the Adapted
|
||||
Material from complying with this Public License.
|
||||
|
||||
|
||||
Section 4 -- Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that
|
||||
apply to Your use of the Licensed Material:
|
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
||||
to extract, reuse, reproduce, and Share all or a substantial
|
||||
portion of the contents of the database for NonCommercial purposes
|
||||
only;
|
||||
|
||||
b. if You include all or a substantial portion of the database
|
||||
contents in a database in which You have Sui Generis Database
|
||||
Rights, then the database in which You have Sui Generis Database
|
||||
Rights (but not its individual contents) is Adapted Material; and
|
||||
|
||||
c. You must comply with the conditions in Section 3(a) if You Share
|
||||
all or a substantial portion of the contents of the database.
|
||||
|
||||
For the avoidance of doubt, this Section 4 supplements and does not
|
||||
replace Your obligations under this Public License where the Licensed
|
||||
Rights include other Copyright and Similar Rights.
|
||||
|
||||
|
||||
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
||||
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
||||
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
||||
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
||||
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
||||
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
||||
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
||||
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
||||
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
||||
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
||||
|
||||
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
||||
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
||||
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
||||
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
||||
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
||||
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
||||
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
||||
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
||||
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided
|
||||
above shall be interpreted in a manner that, to the extent
|
||||
possible, most closely approximates an absolute disclaimer and
|
||||
waiver of all liability.
|
||||
|
||||
|
||||
Section 6 -- Term and Termination.
|
||||
|
||||
a. This Public License applies for the term of the Copyright and
|
||||
Similar Rights licensed here. However, if You fail to comply with
|
||||
this Public License, then Your rights under this Public License
|
||||
terminate automatically.
|
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under
|
||||
Section 6(a), it reinstates:
|
||||
|
||||
1. automatically as of the date the violation is cured, provided
|
||||
it is cured within 30 days of Your discovery of the
|
||||
violation; or
|
||||
|
||||
2. upon express reinstatement by the Licensor.
|
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any
|
||||
right the Licensor may have to seek remedies for Your violations
|
||||
of this Public License.
|
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the
|
||||
Licensed Material under separate terms or conditions or stop
|
||||
distributing the Licensed Material at any time; however, doing so
|
||||
will not terminate this Public License.
|
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
||||
License.
|
||||
|
||||
|
||||
Section 7 -- Other Terms and Conditions.
|
||||
|
||||
a. The Licensor shall not be bound by any additional or different
|
||||
terms or conditions communicated by You unless expressly agreed.
|
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the
|
||||
Licensed Material not stated herein are separate from and
|
||||
independent of the terms and conditions of this Public License.
|
||||
|
||||
|
||||
Section 8 -- Interpretation.
|
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and
|
||||
shall not be interpreted to, reduce, limit, restrict, or impose
|
||||
conditions on any use of the Licensed Material that could lawfully
|
||||
be made without permission under this Public License.
|
||||
|
||||
b. To the extent possible, if any provision of this Public License is
|
||||
deemed unenforceable, it shall be automatically reformed to the
|
||||
minimum extent necessary to make it enforceable. If the provision
|
||||
cannot be reformed, it shall be severed from this Public License
|
||||
without affecting the enforceability of the remaining terms and
|
||||
conditions.
|
||||
|
||||
c. No term or condition of this Public License will be waived and no
|
||||
failure to comply consented to unless expressly agreed to by the
|
||||
Licensor.
|
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted
|
||||
as a limitation upon, or waiver of, any privileges and immunities
|
||||
that apply to the Licensor or You, including from the legal
|
||||
processes of any jurisdiction or authority.
|
||||
@@ -1,5 +1,6 @@
|
||||
formatting:
|
||||
@echo "Running black..." && black .
|
||||
@echo "Running isort..." && isort .
|
||||
@echo "Running flake8..." && flake8 --config .flake8
|
||||
# @echo "Running pylint..." && pylint .
|
||||
@echo "Running Ruff..." && ruff check . --fix
|
||||
@echo "Running Ruff format..." && ruff format .
|
||||
|
||||
lint:
|
||||
@echo "Running Ruff checks..." && ruff check .
|
||||
@@ -1,27 +1,31 @@
|
||||
# 🚀 SoloBot
|
||||
|
||||
**SoloBot** — ваш идеальный помощник для управления API 3x-UI VPN на протоколе VLESS.
|
||||
**SoloBot** — ваш идеальный помощник для управления API 3x-UI VPN на протоколе VLESS.
|
||||
|
||||
Три версии — море возможностей:
|
||||
- v1.4 — бот для продажи ключей vless:
|
||||
|
||||

|
||||
- v2.3.1 — стабильная версия подписок вместо ключей с кнопками автодобавления в приложение:
|
||||
- [v1.4](https://github.com/Vladless/Solo_bot/releases/tag/v1.4) — бот для продажи ключей VLESS:
|
||||
|
||||

|
||||
- v3.1 — настолько большая, что смотрите в [релизе](https://github.com/Vladless/Solo_bot/releases/tag/v3.1):
|
||||

|
||||
|
||||
- [v2.3.1](https://github.com/Vladless/Solo_bot/releases/tag/v2.3.1) — стабильная версия подписок вместо ключей с
|
||||
кнопками автодобавления в приложение:
|
||||
|
||||

|
||||
|
||||
Если вам не хватает функций — направьте их в issue, мы реализуем
|
||||
- [v3.1](https://github.com/Vladless/Solo_bot/releases/tag/v3.1) — версия бота со значительным расширением возможностей.
|
||||
|
||||
[Последние актуальные релизы.](https://github.com/Vladless/Solo_bot/releases)
|
||||
Если вам не хватает функций — направьте их в [issue](https://github.com/Vladless/Solo_bot/issues), мы реализуем.
|
||||
|
||||
## 📋 Оглавление
|
||||
1. [Описание](#описание)
|
||||
2. [Стек технологий](#стек-технологий)
|
||||
3. [Установка](#установка)
|
||||
4. [Конфигурация](#конфигурация)
|
||||
5. [Запуск](#запуск)
|
||||
6. [Контакты](#контакты)
|
||||
|
||||
1. [Описание](#-описание)
|
||||
2. [Стек технологий](#-стек-технологий)
|
||||
3. [Установка](#-установка)
|
||||
4. [Конфигурация](#-конфигурация)
|
||||
5. [Запуск](#-запуск)
|
||||
6. [Контакты](#-solobot-в-telegram-и-полная-версия)
|
||||
|
||||
---
|
||||
|
||||
@@ -29,47 +33,47 @@
|
||||
|
||||
SoloBot реализует множество функций, включая:
|
||||
|
||||
|
||||
- **Выдача ключей на пробный период**.
|
||||
- **Выдача ключей на длительные периоды** (1 месяц, 3 месяца, полгода, год).
|
||||
- **Выдача подписок на различные периоды** (1 месяц, 3 месяца, полгода, год).
|
||||
- **Использование тестового периода подписки.**
|
||||
- **Продление ключей** на указанные периоды.
|
||||
- Полный контроль клиента над своими ключами:
|
||||
- Удаление ключей.
|
||||
- Продление ключей.
|
||||
- Просмотр информации о ключе (сервер, оставшееся время, сам ключ).
|
||||
- **Полный контроль** клиента над своими ключами:
|
||||
- **Просмотр** информации о ключе (сервер, оставшееся время, сам ключ).
|
||||
- **Продление** ключей.
|
||||
- **Удаление** ключей.
|
||||
- **Смена локации** (перемещение ключа между серверами).
|
||||
- Поддержка нескольких ключей для одного клиента (несколько устройств).
|
||||
- **Реферальная программа** с пригласительной ссылкой.
|
||||
- Доступ к **инструкциям**.
|
||||
- **Пополнение баланса**:
|
||||
* через Юкасса (самозанятость и ИП)
|
||||
* через freekassa (Физические Лица)
|
||||
* Криптовалюта (Thanks [izzzzzi](https://github.com/izzzzzi))
|
||||
- **Поддержка нескольких ключей и устройств** для одного клиента.
|
||||
- **Реферальная программа** с уникальной ссылкой для приглашений.
|
||||
- Доступ к **инструкциям** для подключения к сервису.
|
||||
- Пополнение баланса:
|
||||
* **Юкасса** (Самозанятость и ИП)
|
||||
* **Юмани** (Физические Лица) ([TrackLine](https://github.com/TrackLine))
|
||||
* **FreeKassa** (Физические Лица)
|
||||
* **Robokassa** (Физические Лица)
|
||||
* **Cryptobot** (Криптовалюта) ([izzzzzi](https://github.com/izzzzzi))
|
||||
* **Звезды Telegram**
|
||||
- Периодические **бэкапы базы данных клиентов**.
|
||||
- Уведомления:
|
||||
- Произвольные сообщения через админку.
|
||||
- Уведомления о неиспользованных пробниках.
|
||||
- Уведомления о истекающих ключах (за сутки, за 6 часов и в момент истечения).
|
||||
- Произвольные сообщения через панель администратора.
|
||||
- Уведомления о неиспользованных пробниках.
|
||||
- Уведомления об истекающих ключах (за сутки, за 6 часов и в момент истечения).
|
||||
- **Чат поддержки** и канал для связи.
|
||||
- **Автоматическое продление ключа** при наличии достаточного баланса.
|
||||
- **Удобная админка прямо в боте**
|
||||
- **мультисерверность** добавляй сервера в конфиг, и они автоматически будут в боте
|
||||
|
||||
- **Удобная панель администратора прямо в боте**
|
||||
- Серверы:
|
||||
- **Мультисерверность** — добавление сервера прямо в админке
|
||||
- **Проверка на доступность** — бот следит за серверами и их откликом
|
||||
- **Балансировка** — бот выдает подписку на наименее загруженный сервер
|
||||
|
||||
---
|
||||
|
||||
## 💻 Стек технологий
|
||||
|
||||
Проект использует следующие технологии:
|
||||
Основные технологии, используемые в проекте:
|
||||
|
||||
- **Python** версии 3.8 или выше.
|
||||
- **Git** для клонирования репозитория.
|
||||
- **Virtualenv** для создания виртуального окружения (рекомендуется).
|
||||
- **PostgreSQL** для хранения данных.
|
||||
- **Nginx** для работы с вебхуками.
|
||||
- **aiogram** (версия 3.13) для взаимодействия с Telegram API.
|
||||
- **youkassa** для обработки платежей.
|
||||
- **aiohttp** для API запросов к панелям.
|
||||
- **Python** версии 3.10 (3.12, для последних версий).
|
||||
- **PostgreSQL** — для хранения данных.
|
||||
- **aiogram** — для взаимодействия с Telegram API.
|
||||
- **aiohttp** — для API запросов к панелям.
|
||||
|
||||
Проект полностью асинхронный, что обеспечивает высокую скорость работы.
|
||||
|
||||
@@ -86,7 +90,9 @@ git clone https://github.com/Vladless/Solo_bot.git
|
||||
cd solo_bot
|
||||
```
|
||||
|
||||
### 2️⃣ Шаг 2: Создание и активация виртуального окружения
|
||||
### 2️⃣ Шаг 2: Создание и подключение виртуального окружения
|
||||
|
||||
Создайте виртуальное окружение **Python** и перейдите в сессию:
|
||||
|
||||
```
|
||||
python3 -m venv venv
|
||||
@@ -95,6 +101,8 @@ source venv/bin/activate
|
||||
|
||||
### 3️⃣ Шаг 3: Установка зависимостей
|
||||
|
||||
Установите зависимости:
|
||||
|
||||
```
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
@@ -103,46 +111,44 @@ pip install -r requirements.txt
|
||||
|
||||
Для правильной работы вам нужно:
|
||||
|
||||
* установить и запустить postgresql, создать пользователя для работы с базой данных и выдать ему права
|
||||
* Настроить ваш сервер на работу с ботом, выпустить SSL сертификат для домена
|
||||
* Настроить вебхуки и пути до них в NGINX
|
||||
* Установить и запустить **PostgreSQL**, создать пользователя для работы с базой данных и выдать ему права
|
||||
* Настроить ваш сервер для работы с ботом, выпустить SSL сертификат для домена
|
||||
* Настроить вебхуки и указать пути до них через любой веб-сервер, например **nginx**
|
||||
|
||||
* Создать файл config.py в корневой папке проекта с вашими данными:
|
||||
|
||||
```
|
||||
API_TOKEN = "токен вашего бота телеграм"
|
||||
|
||||
API_TOKEN = токен вашего бота телеграм
|
||||
|
||||
ADMIN_USERNAME = логин от вашей панели x-ray
|
||||
ADMIN_PASSWORD = пароль от вашей панели x-ray
|
||||
ADMIN_USERNAME = "логин от вашей панели x-ray"
|
||||
ADMIN_PASSWORD = "пароль от вашей панели x-ray"
|
||||
ADD_CLIENT_URL = f"{API_URL}/panel/api/inbounds/addClient"
|
||||
GET_INBOUNDS_URL = f"{API_URL}/panel/api/inbounds/list/"
|
||||
AUTH_URL = f"{API_URL}/login/"
|
||||
DATABASE_URL = путь к вашей базе данных, имеет вид "postgresql://{user}:{password}@{Ip-adress}:{port}/{имя базы данных}"
|
||||
ADMIN_ID = ID телеграм профиля администратора
|
||||
CHANNEL_URL = ссылка на ваш телеграм канал
|
||||
YOOKASSA_SECRET_KEY = ваш ключ юкассы
|
||||
YOOKASSA_SHOP_ID = ваш шопайди
|
||||
WEBHOOK_HOST = адрес вашего сервера для вебхуков
|
||||
WEBHOOK_PATH = '/webhook/'
|
||||
WEBHOOK_URL = f"{WEBHOOK_HOST}{WEBHOOK_PATH}"
|
||||
SUPPORT_CHAT_URL = ваша ссылка на поддержку
|
||||
|
||||
```
|
||||
**Мы высылаем детальный гайд и недостающие файлы в боте**
|
||||
|
||||
**Все описания в одном файле!** Удобно настроить бот под свой сервис изменив информацию и цены в одном месте
|
||||
**Мы высылаем детальный гайд и недостающие файлы в поддержке бота!**
|
||||
|
||||
### 🚀 Запуск
|
||||
|
||||
введите команду из виртуального окружения
|
||||
Введите команду из виртуального окружения `venv/bin/activate`
|
||||
|
||||
```
|
||||
python main.py
|
||||
python3 main.py
|
||||
```
|
||||
|
||||
### 🔗 SoloBot в Telegram и Полная версия
|
||||
|
||||
Попробуйте SoloBot прямо сейчас в Telegram [по этой ссылке](https://t.me/SoloNetVPN_bot).
|
||||
#### Наш [**➡ сайт**](https://pocomacho.ru/solonetbot/):
|
||||
|
||||
Вы также можете поддержать автора или купить полную версию бота с сопровождением по установке в поддержке бота!
|
||||
Полная пошаговая инстуркция по запуску бота предоставляется в поддержке бота
|
||||
Всегда актуальные гайды по установке, файлы для запуска и ссылка на общий чат:
|
||||

|
||||
|
||||
Попробовать SoloBot прямо сейчас в Telegram [**➡ Попробовать**](https://t.me/SoloNetVPN_bot).
|
||||
|
||||
Связаться с нами через [**➡ поддержку**](https://t.me/solonet_sup). Там вы сможете купить полную версию и получить логин
|
||||
и пароль от сайта, а также задать необходимые вопросы!
|
||||
|
||||
## Права на использование
|
||||
|
||||
[Этот проект использует лицензию CC BY-NC 4.0](LICENSE)
|
||||
@@ -0,0 +1,102 @@
|
||||
CREATE TABLE IF NOT EXISTS users
|
||||
(
|
||||
tg_id BIGINT PRIMARY KEY NOT NULL,
|
||||
username TEXT,
|
||||
first_name TEXT,
|
||||
last_name TEXT,
|
||||
language_code TEXT,
|
||||
is_bot BOOLEAN DEFAULT FALSE,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS connections
|
||||
(
|
||||
tg_id BIGINT PRIMARY KEY NOT NULL,
|
||||
balance REAL NOT NULL DEFAULT 0.0,
|
||||
trial INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS payments
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
tg_id BIGINT NOT NULL,
|
||||
amount REAL NOT NULL,
|
||||
payment_system TEXT NOT NULL,
|
||||
status TEXT DEFAULT 'success',
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (tg_id) REFERENCES users (tg_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS keys
|
||||
(
|
||||
tg_id BIGINT NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
email TEXT NOT NULL,
|
||||
created_at BIGINT NOT NULL,
|
||||
expiry_time BIGINT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
server_id TEXT NOT NULL DEFAULT 'cluster1',
|
||||
notified BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
notified_24h BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
PRIMARY KEY (tg_id, client_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS referrals
|
||||
(
|
||||
referred_tg_id BIGINT PRIMARY KEY NOT NULL,
|
||||
referrer_tg_id BIGINT NOT NULL,
|
||||
reward_issued BOOLEAN DEFAULT FALSE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS coupons
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
code TEXT UNIQUE NOT NULL,
|
||||
amount INTEGER NOT NULL,
|
||||
usage_limit INTEGER NOT NULL DEFAULT 1,
|
||||
usage_count INTEGER NOT NULL DEFAULT 0,
|
||||
is_used BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS coupon_usages
|
||||
(
|
||||
coupon_id INTEGER NOT NULL REFERENCES coupons (id) ON DELETE CASCADE,
|
||||
user_id BIGINT NOT NULL,
|
||||
used_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (coupon_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS notifications
|
||||
(
|
||||
tg_id BIGINT NOT NULL,
|
||||
last_notification_time TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
notification_type TEXT NOT NULL,
|
||||
PRIMARY KEY (tg_id, notification_type)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS servers
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
cluster_name TEXT NOT NULL,
|
||||
server_name TEXT NOT NULL,
|
||||
api_url TEXT NOT NULL,
|
||||
subscription_url TEXT NOT NULL,
|
||||
inbound_id TEXT NOT NULL,
|
||||
UNIQUE (cluster_name, server_name)
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS gifts
|
||||
(
|
||||
gift_id TEXT PRIMARY KEY NOT NULL,
|
||||
sender_tg_id BIGINT NOT NULL,
|
||||
selected_months INTEGER NOT NULL,
|
||||
expiry_time TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
gift_link TEXT NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
is_used BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
recipient_tg_id BIGINT,
|
||||
CONSTRAINT fk_sender FOREIGN KEY (sender_tg_id) REFERENCES users (tg_id),
|
||||
CONSTRAINT fk_recipient FOREIGN KEY (recipient_tg_id) REFERENCES users (tg_id)
|
||||
);
|
||||
@@ -1,7 +1,6 @@
|
||||
from datetime import datetime
|
||||
import os
|
||||
import subprocess
|
||||
from typing import Union
|
||||
from datetime import datetime
|
||||
|
||||
from aiogram.types import BufferedInputFile
|
||||
|
||||
@@ -57,8 +56,10 @@ def _create_database_backup():
|
||||
async def _send_backup_to_admin(bot, backup_file_path):
|
||||
try:
|
||||
with open(backup_file_path, "rb") as backup_file:
|
||||
backup_input_file = BufferedInputFile(backup_file.read(), filename=os.path.basename(backup_file_path))
|
||||
admin_ids: Union[int, list[int]] = ADMIN_ID
|
||||
backup_input_file = BufferedInputFile(
|
||||
backup_file.read(), filename=os.path.basename(backup_file_path)
|
||||
)
|
||||
admin_ids: int | list[int] = ADMIN_ID
|
||||
if isinstance(admin_ids, list):
|
||||
for id in admin_ids:
|
||||
await bot.send_document(id, backup_input_file)
|
||||
@@ -92,3 +93,8 @@ def _cleanup_old_backups():
|
||||
logger.info("Старые бэкапы удалены.")
|
||||
except subprocess.CalledProcessError as e:
|
||||
logger.error(f"Ошибка при удалении старых бэкапов: {e}")
|
||||
|
||||
|
||||
async def create_backup_and_send_to_admins(xui):
|
||||
await xui.login()
|
||||
await xui.database.export()
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import traceback
|
||||
|
||||
from aiogram import Bot, Dispatcher, Router
|
||||
from aiogram import Bot, Dispatcher
|
||||
from aiogram.client.default import DefaultBotProperties
|
||||
from aiogram.enums import ParseMode
|
||||
from aiogram.fsm.storage.memory import MemoryStorage
|
||||
from aiogram.types import ErrorEvent
|
||||
|
||||
from config import API_TOKEN, CRYPTO_BOT_ENABLE, FREEKASSA_ENABLE, ROBOKASSA_ENABLE, STARS_ENABLE, YOOKASSA_ENABLE
|
||||
from config import API_TOKEN
|
||||
from logger import logger
|
||||
from middlewares.admin import AdminMiddleware
|
||||
from middlewares.database import DatabaseMiddleware
|
||||
@@ -17,44 +17,12 @@ from middlewares.user import UserMiddleware
|
||||
bot = Bot(token=API_TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
|
||||
storage = MemoryStorage()
|
||||
dp = Dispatcher(bot=bot, storage=storage)
|
||||
router = Router()
|
||||
|
||||
from handlers import coupons, donate, notifications, pay, profile, start
|
||||
from handlers.admin import admin_coupons, admin_panel, admin_servers, admin_user_editor
|
||||
from handlers.instructions import instructions
|
||||
from handlers.keys import key_management, keys
|
||||
from handlers.payments import cryprobot_pay, freekassa_pay, robokassa_pay, stars_pay, yookassa_pay
|
||||
|
||||
dp.include_router(admin_coupons.router)
|
||||
dp.include_router(admin_panel.router)
|
||||
dp.include_router(admin_user_editor.router)
|
||||
dp.include_router(admin_servers.router)
|
||||
dp.include_router(coupons.router)
|
||||
dp.include_router(start.router)
|
||||
dp.include_router(profile.router)
|
||||
dp.include_router(keys.router)
|
||||
dp.include_router(key_management.router)
|
||||
dp.include_router(pay.router)
|
||||
dp.include_router(notifications.router)
|
||||
dp.include_router(instructions.router)
|
||||
dp.include_router(donate.router)
|
||||
if YOOKASSA_ENABLE:
|
||||
dp.include_router(yookassa_pay.router)
|
||||
if FREEKASSA_ENABLE:
|
||||
dp.include_router(freekassa_pay.router)
|
||||
if CRYPTO_BOT_ENABLE:
|
||||
dp.include_router(cryprobot_pay.router)
|
||||
if STARS_ENABLE:
|
||||
dp.include_router(stars_pay.router)
|
||||
if ROBOKASSA_ENABLE:
|
||||
dp.include_router(robokassa_pay.router)
|
||||
|
||||
dp.message.middleware(LoggingMiddleware())
|
||||
dp.callback_query.middleware(LoggingMiddleware())
|
||||
|
||||
dp.message.middleware(AdminMiddleware())
|
||||
dp.callback_query.middleware(AdminMiddleware())
|
||||
|
||||
dp.message.middleware(UserMiddleware())
|
||||
dp.callback_query.middleware(UserMiddleware())
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import py3xui
|
||||
|
||||
from config import LIMIT_IP
|
||||
from logger import logger
|
||||
|
||||
|
||||
@@ -44,7 +45,9 @@ async def add_client(
|
||||
return {"status": "failed", "error": str(e)}
|
||||
|
||||
|
||||
async def extend_client_key(xui, inbound_id, email: str, new_expiry_time: int, client_id: str, total_gb: int):
|
||||
async def extend_client_key(
|
||||
xui, inbound_id, email: str, new_expiry_time: int, client_id: str, total_gb: int
|
||||
):
|
||||
"""
|
||||
Функция для обновления срока действия ключа клиента по email.
|
||||
"""
|
||||
@@ -60,7 +63,9 @@ async def extend_client_key(xui, inbound_id, email: str, new_expiry_time: int, c
|
||||
logger.warning(f"Ошибка: клиент {email} не имеет действительного ID.")
|
||||
return
|
||||
|
||||
logger.info(f"Обновление ключа клиента {client.email} с ID {client.id} до нового времени: {new_expiry_time}")
|
||||
logger.info(
|
||||
f"Обновление ключа клиента {client.email} с ID {client.id} до нового времени: {new_expiry_time}"
|
||||
)
|
||||
|
||||
client.id = client_id
|
||||
client.expiry_time = new_expiry_time
|
||||
@@ -68,12 +73,14 @@ async def extend_client_key(xui, inbound_id, email: str, new_expiry_time: int, c
|
||||
client.sub_id = email
|
||||
client.total_gb = total_gb
|
||||
client.enable = True
|
||||
client.limit_ip = 1
|
||||
client.limit_ip = LIMIT_IP
|
||||
client.inbound_id = inbound_id
|
||||
|
||||
await xui.client.update(client.id, client)
|
||||
await xui.client.reset_stats(inbound_id, email)
|
||||
logger.info(f"Ключ клиента {client.email} успешно продлён до {new_expiry_time}.")
|
||||
logger.info(
|
||||
f"Ключ клиента {client.email} успешно продлён до {new_expiry_time}."
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при обновлении клиента с email {email}: {e}")
|
||||
|
||||
+265
-226
@@ -7,132 +7,21 @@ from config import DATABASE_URL, REFERRAL_BONUS_PERCENTAGES
|
||||
from logger import logger
|
||||
|
||||
|
||||
async def init_db():
|
||||
async def init_db(file_path: str = "assets/schema.sql"):
|
||||
with open(file_path) as file:
|
||||
sql_content = file.read()
|
||||
|
||||
statements = [stmt.strip() for stmt in sql_content.split(";") if stmt.strip()]
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
# Таблица для хранения основной информации о пользователях из Telegram
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
tg_id BIGINT PRIMARY KEY NOT NULL,
|
||||
username TEXT,
|
||||
first_name TEXT,
|
||||
last_name TEXT,
|
||||
language_code TEXT,
|
||||
is_bot BOOLEAN DEFAULT FALSE,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
# Таблица для хранения информации о пользователях
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS connections (
|
||||
tg_id BIGINT PRIMARY KEY NOT NULL,
|
||||
balance REAL NOT NULL DEFAULT 0.0,
|
||||
trial INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
# Таблица для хранения информации о платежах
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS payments (
|
||||
id SERIAL PRIMARY KEY,
|
||||
tg_id BIGINT NOT NULL,
|
||||
amount REAL NOT NULL,
|
||||
payment_system TEXT NOT NULL,
|
||||
status TEXT DEFAULT 'success',
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (tg_id) REFERENCES users(tg_id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
# Таблица для хранения ключей
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS keys (
|
||||
tg_id BIGINT NOT NULL,
|
||||
client_id TEXT NOT NULL,
|
||||
email TEXT NOT NULL,
|
||||
created_at BIGINT NOT NULL,
|
||||
expiry_time BIGINT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
server_id TEXT NOT NULL DEFAULT 'cluster1',
|
||||
notified BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
notified_24h BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
PRIMARY KEY (tg_id, client_id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
# Таблица для хранения рефералов
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS referrals (
|
||||
referred_tg_id BIGINT PRIMARY KEY NOT NULL,
|
||||
referrer_tg_id BIGINT NOT NULL,
|
||||
reward_issued BOOLEAN DEFAULT FALSE
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
# Таблица для хранения купонов
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS coupons (
|
||||
id SERIAL PRIMARY KEY,
|
||||
code TEXT UNIQUE NOT NULL,
|
||||
amount INTEGER NOT NULL,
|
||||
usage_limit INTEGER NOT NULL DEFAULT 1,
|
||||
usage_count INTEGER NOT NULL DEFAULT 0,
|
||||
is_used BOOLEAN NOT NULL DEFAULT FALSE
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
# Таблица для отслеживания использований купонов пользователями
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS coupon_usages (
|
||||
coupon_id INTEGER NOT NULL REFERENCES coupons(id) ON DELETE CASCADE,
|
||||
user_id BIGINT NOT NULL,
|
||||
used_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (coupon_id, user_id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
# Таблица для отслеживания отправленных уведомлений
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
tg_id BIGINT NOT NULL,
|
||||
last_notification_time TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
notification_type TEXT NOT NULL,
|
||||
PRIMARY KEY (tg_id, notification_type)
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS servers (
|
||||
id SERIAL PRIMARY KEY,
|
||||
cluster_name TEXT NOT NULL,
|
||||
server_name TEXT NOT NULL,
|
||||
api_url TEXT NOT NULL,
|
||||
subscription_url TEXT NOT NULL,
|
||||
inbound_id TEXT NOT NULL,
|
||||
UNIQUE(cluster_name, server_name) -- Уникальность по названию кластера и сервера
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
await conn.close()
|
||||
try:
|
||||
for statement in statements:
|
||||
await conn.execute(statement)
|
||||
except Exception as e:
|
||||
logger.error(f"Error while executing SQL statement: {e}")
|
||||
finally:
|
||||
logger.info("Tables created successfully")
|
||||
await conn.close()
|
||||
|
||||
|
||||
async def check_unique_server_name(server_name: str) -> bool:
|
||||
@@ -144,14 +33,18 @@ async def check_unique_server_name(server_name: str) -> bool:
|
||||
"""
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
|
||||
result = await conn.fetchrow("SELECT 1 FROM servers WHERE server_name = $1 LIMIT 1", server_name)
|
||||
result = await conn.fetchrow(
|
||||
"SELECT 1 FROM servers WHERE server_name = $1 LIMIT 1", server_name
|
||||
)
|
||||
|
||||
await conn.close()
|
||||
|
||||
return result is None
|
||||
|
||||
|
||||
async def create_coupon(coupon_code: str, amount: float, usage_limit: int, session: Any):
|
||||
async def create_coupon(
|
||||
coupon_code: str, amount: float, usage_limit: int, session: Any
|
||||
):
|
||||
"""
|
||||
Создает новый купон в базе данных.
|
||||
|
||||
@@ -198,7 +91,6 @@ async def get_all_coupons(session: Any):
|
||||
Exception: В случае ошибки при получении данных из базы
|
||||
"""
|
||||
try:
|
||||
# Выполняем запрос на получение всех купонов из базы данных
|
||||
coupons = await session.fetch(
|
||||
"""
|
||||
SELECT code, amount, usage_limit, usage_count
|
||||
@@ -206,12 +98,10 @@ async def get_all_coupons(session: Any):
|
||||
"""
|
||||
)
|
||||
|
||||
# Логируем успешное получение списка купонов
|
||||
logger.info(f"Успешно получено {len(coupons)} купонов из базы данных")
|
||||
|
||||
return coupons
|
||||
except Exception as e:
|
||||
# Подробное логирование ошибки при получении купонов
|
||||
logger.error(f"Критическая ошибка при получении списка купонов: {e}")
|
||||
logger.exception("Трассировка стека ошибки получения купонов")
|
||||
return []
|
||||
@@ -235,7 +125,6 @@ async def delete_coupon_from_db(coupon_code: str, session: Any):
|
||||
result = await delete_coupon_from_db('SALE50', session)
|
||||
"""
|
||||
try:
|
||||
# Проверяем существование купона в базе данных
|
||||
coupon_record = await session.fetchrow(
|
||||
"""
|
||||
SELECT id FROM coupons WHERE code = $1
|
||||
@@ -243,12 +132,10 @@ async def delete_coupon_from_db(coupon_code: str, session: Any):
|
||||
coupon_code,
|
||||
)
|
||||
|
||||
# Если купон не найден, возвращаем False
|
||||
if not coupon_record:
|
||||
logger.info(f"Купон {coupon_code} не найден в базе данных")
|
||||
return False
|
||||
|
||||
# Удаляем купон из базы данных
|
||||
await session.execute(
|
||||
"""
|
||||
DELETE FROM coupons WHERE code = $1
|
||||
@@ -256,12 +143,10 @@ async def delete_coupon_from_db(coupon_code: str, session: Any):
|
||||
coupon_code,
|
||||
)
|
||||
|
||||
# Логируем успешное удаление купона
|
||||
logger.info(f"Купон {coupon_code} успешно удален из базы данных")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
# Логируем ошибку на русском с подробным описанием
|
||||
logger.error(f"Произошла ошибка при удалении купона {coupon_code}: {e}")
|
||||
return False
|
||||
|
||||
@@ -290,7 +175,9 @@ async def restore_trial(tg_id: int, session: Any):
|
||||
logger.info(f"Триальный период успешно восстановлен для пользователя {tg_id}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при восстановлении триального периода для пользователя {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при восстановлении триального периода для пользователя {tg_id}: {e}"
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
@@ -322,7 +209,9 @@ async def use_trial(tg_id: int, session: Any):
|
||||
return False
|
||||
|
||||
|
||||
async def add_connection(tg_id: int, balance: float = 0.0, trial: int = 0, session: Any = None):
|
||||
async def add_connection(
|
||||
tg_id: int, balance: float = 0.0, trial: int = 0, session: Any = None
|
||||
):
|
||||
"""
|
||||
Добавляет новое подключение для пользователя в базу данных.
|
||||
|
||||
@@ -349,7 +238,9 @@ async def add_connection(tg_id: int, balance: float = 0.0, trial: int = 0, sessi
|
||||
f"Успешно добавлено новое подключение для пользователя {tg_id} с балансом {balance} и статусом триала {trial}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Не удалось добавить подключение для пользователя {tg_id}. Причина: {e}")
|
||||
logger.error(
|
||||
f"Не удалось добавить подключение для пользователя {tg_id}. Причина: {e}"
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
@@ -386,7 +277,15 @@ async def check_connection_exists(tg_id: int):
|
||||
await conn.close()
|
||||
|
||||
|
||||
async def store_key(tg_id: int, client_id: str, email: str, expiry_time: int, key: str, server_id: str, session: Any):
|
||||
async def store_key(
|
||||
tg_id: int,
|
||||
client_id: str,
|
||||
email: str,
|
||||
expiry_time: int,
|
||||
key: str,
|
||||
server_id: str,
|
||||
session: Any,
|
||||
):
|
||||
"""
|
||||
Сохраняет информацию о ключе в базу данных.
|
||||
|
||||
@@ -415,7 +314,9 @@ async def store_key(tg_id: int, client_id: str, email: str, expiry_time: int, ke
|
||||
key,
|
||||
server_id,
|
||||
)
|
||||
logger.info(f"Ключ успешно сохранен для пользователя {tg_id} на сервере {server_id}")
|
||||
logger.info(
|
||||
f"Ключ успешно сохранен для пользователя {tg_id} на сервере {server_id}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при сохранении ключа для пользователя {tg_id}: {e}")
|
||||
raise
|
||||
@@ -481,10 +382,14 @@ async def get_keys_by_server(tg_id: int, server_id: str):
|
||||
tg_id,
|
||||
server_id,
|
||||
)
|
||||
logger.info(f"Успешно получено {len(records)} ключей для пользователя {tg_id} на сервере {server_id}")
|
||||
logger.info(
|
||||
f"Успешно получено {len(records)} ключей для пользователя {tg_id} на сервере {server_id}"
|
||||
)
|
||||
return records
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при получении ключей для пользователя {tg_id} на сервере {server_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при получении ключей для пользователя {tg_id} на сервере {server_id}: {e}"
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
if conn:
|
||||
@@ -508,10 +413,14 @@ async def has_active_key(tg_id: int) -> bool:
|
||||
try:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
count = await conn.fetchval("SELECT COUNT(*) FROM keys WHERE tg_id = $1", tg_id)
|
||||
logger.info(f"Проверка наличия ключей для пользователя {tg_id}. Найдено ключей: {count}")
|
||||
logger.info(
|
||||
f"Проверка наличия ключей для пользователя {tg_id}. Найдено ключей: {count}"
|
||||
)
|
||||
return count > 0
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при проверке наличия ключей для пользователя {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при проверке наличия ключей для пользователя {tg_id}: {e}"
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
if conn:
|
||||
@@ -534,7 +443,9 @@ async def get_balance(tg_id: int) -> float:
|
||||
conn = None
|
||||
try:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
balance = await conn.fetchval("SELECT balance FROM connections WHERE tg_id = $1", tg_id)
|
||||
balance = await conn.fetchval(
|
||||
"SELECT balance FROM connections WHERE tg_id = $1", tg_id
|
||||
)
|
||||
logger.info(f"Получен баланс для пользователя {tg_id}: {balance}")
|
||||
return balance if balance is not None else 0.0
|
||||
except Exception as e:
|
||||
@@ -592,11 +503,15 @@ async def get_trial(tg_id: int, session: Any) -> int:
|
||||
int: Статус триала (0 - не использован, 1 - использован)
|
||||
"""
|
||||
try:
|
||||
trial = await session.fetchval("SELECT trial FROM connections WHERE tg_id = $1", tg_id)
|
||||
trial = await session.fetchval(
|
||||
"SELECT trial FROM connections WHERE tg_id = $1", tg_id
|
||||
)
|
||||
logger.info(f"Получен статус триала для пользователя {tg_id}: {trial}")
|
||||
return trial if trial is not None else 0
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при получении статуса триала для пользователя {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при получении статуса триала для пользователя {tg_id}: {e}"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
@@ -620,7 +535,9 @@ async def get_key_count(tg_id: int) -> int:
|
||||
logger.info(f"Получено количество ключей для пользователя {tg_id}: {count}")
|
||||
return count if count is not None else 0
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при получении количества ключей для пользователя {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при получении количества ключей для пользователя {tg_id}: {e}"
|
||||
)
|
||||
return 0
|
||||
finally:
|
||||
if conn:
|
||||
@@ -651,7 +568,11 @@ async def get_all_users(conn):
|
||||
|
||||
async def add_referral(referred_tg_id: int, referrer_tg_id: int, session: Any):
|
||||
try:
|
||||
# Вставка записи о реферале в базу данных
|
||||
|
||||
if referred_tg_id == referrer_tg_id:
|
||||
logger.warning(f"Пользователь {referred_tg_id} попытался использовать свою собственную реферальную ссылку.")
|
||||
return
|
||||
|
||||
await session.execute(
|
||||
"""
|
||||
INSERT INTO referrals (referred_tg_id, referrer_tg_id)
|
||||
@@ -660,7 +581,9 @@ async def add_referral(referred_tg_id: int, referrer_tg_id: int, session: Any):
|
||||
referred_tg_id,
|
||||
referrer_tg_id,
|
||||
)
|
||||
logger.info(f"Добавлена реферальная связь: приглашенный {referred_tg_id}, пригласивший {referrer_tg_id}")
|
||||
logger.info(
|
||||
f"Добавлена реферальная связь: приглашенный {referred_tg_id}, пригласивший {referrer_tg_id}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при добавлении реферала: {e}")
|
||||
raise
|
||||
@@ -671,30 +594,35 @@ async def handle_referral_on_balance_update(tg_id: int, amount: float):
|
||||
Обработка многоуровневой реферальной системы при обновлении баланса пользователя.
|
||||
|
||||
Метод анализирует цепочку рефералов для указанного пользователя и начисляет
|
||||
бонусы рефереерам на разных уровнях согласно настроенным процентам.
|
||||
бонусы реферерам на разных уровнях согласно настроенным процентам.
|
||||
|
||||
Args:
|
||||
tg_id (int): Идентификатор Telegram пользователя, пополнившего баланс
|
||||
amount (float): Сумма пополнения баланса
|
||||
|
||||
Raises:
|
||||
Exception: В случае ошибки при работе с базой данных
|
||||
"""
|
||||
conn = None
|
||||
try:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
logger.info(f"Начало обработки реферальной системы для пользователя {tg_id}")
|
||||
|
||||
# Максимальное количество уровней рефералов
|
||||
MAX_REFERRAL_LEVELS = len(REFERRAL_BONUS_PERCENTAGES.keys())
|
||||
if MAX_REFERRAL_LEVELS == 0:
|
||||
logger.warning("Реферальные бонусы отключены.")
|
||||
return
|
||||
|
||||
# Текущий уровень для отслеживания
|
||||
visited_tg_ids = set()
|
||||
current_tg_id = tg_id
|
||||
referral_chain = []
|
||||
|
||||
# Собираем цепочку рефералов
|
||||
for level in range(1, MAX_REFERRAL_LEVELS + 1):
|
||||
# Получаем информацию о рефере текущего уровня
|
||||
if current_tg_id in visited_tg_ids:
|
||||
logger.warning(
|
||||
f"Обнаружен цикл в реферальной цепочке для пользователя {current_tg_id}. Прекращение."
|
||||
)
|
||||
break
|
||||
|
||||
visited_tg_ids.add(current_tg_id)
|
||||
|
||||
referral = await conn.fetchrow(
|
||||
"""
|
||||
SELECT referrer_tg_id
|
||||
@@ -704,56 +632,46 @@ async def handle_referral_on_balance_update(tg_id: int, amount: float):
|
||||
current_tg_id,
|
||||
)
|
||||
|
||||
# Если реферер не найден, прекращаем поиск
|
||||
if not referral:
|
||||
logger.info(f"Цепочка рефералов завершена на уровне {level}.")
|
||||
break
|
||||
|
||||
referrer_tg_id = referral['referrer_tg_id']
|
||||
referral_chain.append({'tg_id': referrer_tg_id, 'level': level})
|
||||
referrer_tg_id = referral["referrer_tg_id"]
|
||||
|
||||
# Переходим к следующему уровню
|
||||
if referrer_tg_id in visited_tg_ids:
|
||||
logger.warning(f"Реферер {referrer_tg_id} уже обработан. Пропуск.")
|
||||
break
|
||||
|
||||
referral_chain.append({"tg_id": referrer_tg_id, "level": level})
|
||||
current_tg_id = referrer_tg_id
|
||||
|
||||
# Начисляем бонусы по цепочке рефералов
|
||||
for referral in referral_chain:
|
||||
referrer_tg_id = referral['tg_id']
|
||||
level = referral['level']
|
||||
referrer_tg_id = referral["tg_id"]
|
||||
level = referral["level"]
|
||||
|
||||
# Расчет бонуса для текущего уровня
|
||||
bonus_percent = REFERRAL_BONUS_PERCENTAGES.get(level, 0)
|
||||
bonus = amount * bonus_percent
|
||||
bonus = max(bonus, 0) # Гарантируем неотрицательный бонус
|
||||
if bonus_percent <= 0:
|
||||
logger.warning(f"Процент бонуса для уровня {level} равен 0. Пропуск.")
|
||||
continue
|
||||
|
||||
bonus = round(amount * bonus_percent, 2)
|
||||
|
||||
if bonus > 0:
|
||||
logger.info(f"Начисление бонуса {bonus} рублей рефереру {referrer_tg_id} на уровне {level}")
|
||||
|
||||
# Обновляем баланс реферера
|
||||
logger.info(
|
||||
f"Начисление бонуса {bonus} рублей рефереру {referrer_tg_id} на уровне {level}."
|
||||
)
|
||||
await update_balance(referrer_tg_id, bonus)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при обработке многоуровневой реферальной системы для {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при обработке многоуровневой реферальной системы для {tg_id}: {e}"
|
||||
)
|
||||
finally:
|
||||
if conn:
|
||||
await conn.close()
|
||||
|
||||
|
||||
async def get_referral_stats(referrer_tg_id: int):
|
||||
"""
|
||||
Получение подробной статистики рефералов для указанного пользователя.
|
||||
|
||||
Args:
|
||||
referrer_tg_id (int): Telegram ID пользователя, для которого запрашивается статистика рефералов.
|
||||
|
||||
Returns:
|
||||
dict: Словарь с детальной статистикой рефералов, содержащий:
|
||||
- total_referrals (int): Общее количество рефералов
|
||||
- active_referrals (int): Количество активных рефералов (с начисленным бонусом)
|
||||
- referrals_by_level (dict): Количество рефералов по каждому уровню
|
||||
- total_referral_bonus (float): Общая сумма бонусов от рефералов
|
||||
|
||||
Raises:
|
||||
Exception: В случае ошибки при подключении к базе данных или выполнении запроса
|
||||
"""
|
||||
conn = None
|
||||
try:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
@@ -761,27 +679,26 @@ async def get_referral_stats(referrer_tg_id: int):
|
||||
f"Установлено подключение к базе данных для получения статистики рефералов пользователя {referrer_tg_id}"
|
||||
)
|
||||
|
||||
# Общее количество рефералов
|
||||
total_referrals = await conn.fetchval(
|
||||
"""
|
||||
SELECT COUNT(*) FROM referrals WHERE referrer_tg_id = $1
|
||||
""",
|
||||
""",
|
||||
referrer_tg_id,
|
||||
)
|
||||
logger.debug(f"Получено общее количество рефералов: {total_referrals}")
|
||||
|
||||
# Активные рефералы
|
||||
active_referrals = await conn.fetchval(
|
||||
"""
|
||||
SELECT COUNT(*) FROM referrals WHERE referrer_tg_id = $1 AND reward_issued = TRUE
|
||||
""",
|
||||
""",
|
||||
referrer_tg_id,
|
||||
)
|
||||
logger.debug(f"Получено количество активных рефералов: {active_referrals}")
|
||||
|
||||
# Рефералы по уровням
|
||||
MAX_REFERRAL_LEVELS = len(REFERRAL_BONUS_PERCENTAGES.keys())
|
||||
|
||||
referrals_by_level_records = await conn.fetch(
|
||||
"""
|
||||
f"""
|
||||
WITH RECURSIVE referral_levels AS (
|
||||
SELECT referred_tg_id, referrer_tg_id, 1 AS level
|
||||
FROM referrals
|
||||
@@ -792,7 +709,7 @@ async def get_referral_stats(referrer_tg_id: int):
|
||||
SELECT r.referred_tg_id, r.referrer_tg_id, rl.level + 1
|
||||
FROM referrals r
|
||||
JOIN referral_levels rl ON r.referrer_tg_id = rl.referred_tg_id
|
||||
WHERE rl.level < 5
|
||||
WHERE rl.level < {MAX_REFERRAL_LEVELS}
|
||||
)
|
||||
SELECT level,
|
||||
COUNT(*) AS level_count,
|
||||
@@ -801,31 +718,55 @@ async def get_referral_stats(referrer_tg_id: int):
|
||||
JOIN referrals r ON rl.referred_tg_id = r.referred_tg_id
|
||||
GROUP BY level
|
||||
ORDER BY level
|
||||
""",
|
||||
""",
|
||||
referrer_tg_id,
|
||||
)
|
||||
|
||||
# Преобразование результатов в словарь
|
||||
referrals_by_level = {
|
||||
record['level']: {'total': record['level_count'], 'active': record['active_level_count']}
|
||||
record["level"]: {
|
||||
"total": record["level_count"],
|
||||
"active": record["active_level_count"],
|
||||
}
|
||||
for record in referrals_by_level_records
|
||||
}
|
||||
logger.debug(f"Получена статистика рефералов по уровням: {referrals_by_level}")
|
||||
|
||||
# Общая сумма бонусов от рефералов
|
||||
total_referral_bonus = await conn.fetchval(
|
||||
"""
|
||||
SELECT COALESCE(SUM(amount), 0)
|
||||
FROM payments
|
||||
WHERE tg_id IN (
|
||||
SELECT referred_tg_id
|
||||
f"""
|
||||
WITH RECURSIVE referral_levels AS (
|
||||
SELECT
|
||||
referred_tg_id,
|
||||
referrer_tg_id,
|
||||
1 AS level
|
||||
FROM referrals
|
||||
WHERE referrer_tg_id = $1
|
||||
) AND status = 'success'
|
||||
""",
|
||||
|
||||
UNION
|
||||
|
||||
SELECT
|
||||
r.referred_tg_id,
|
||||
r.referrer_tg_id,
|
||||
rl.level + 1
|
||||
FROM referrals r
|
||||
JOIN referral_levels rl ON r.referrer_tg_id = rl.referred_tg_id
|
||||
WHERE rl.level < {MAX_REFERRAL_LEVELS}
|
||||
)
|
||||
SELECT
|
||||
SUM(p.amount * CASE
|
||||
{" ".join([f"WHEN rl.level = {level} THEN {REFERRAL_BONUS_PERCENTAGES[level]}" for level in REFERRAL_BONUS_PERCENTAGES])}
|
||||
ELSE 0
|
||||
END) AS total_bonus
|
||||
FROM referral_levels rl
|
||||
JOIN payments p ON rl.referred_tg_id = p.tg_id
|
||||
WHERE p.status = 'success'
|
||||
""",
|
||||
referrer_tg_id,
|
||||
)
|
||||
logger.debug(f"Получена общая сумма бонусов от рефералов: {total_referral_bonus}")
|
||||
|
||||
total_referral_bonus = total_referral_bonus or 0
|
||||
logger.debug(
|
||||
f"Получена общая сумма бонусов от рефералов: {total_referral_bonus}"
|
||||
)
|
||||
|
||||
return {
|
||||
"total_referrals": total_referrals,
|
||||
@@ -835,7 +776,9 @@ async def get_referral_stats(referrer_tg_id: int):
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при получении статистики рефералов для пользователя {referrer_tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при получении статистики рефералов для пользователя {referrer_tg_id}: {e}"
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
if conn:
|
||||
@@ -857,7 +800,9 @@ async def update_key_expiry(client_id: str, new_expiry_time: int):
|
||||
conn = None
|
||||
try:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
logger.info(f"Установлено подключение к базе данных для обновления времени истечения ключа клиента {client_id}")
|
||||
logger.info(
|
||||
f"Установлено подключение к базе данных для обновления времени истечения ключа клиента {client_id}"
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -871,7 +816,9 @@ async def update_key_expiry(client_id: str, new_expiry_time: int):
|
||||
logger.info(f"Успешно обновлено время истечения ключа для клиента {client_id}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при обновлении времени истечения ключа для клиента {client_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при обновлении времени истечения ключа для клиента {client_id}: {e}"
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
if conn:
|
||||
@@ -892,7 +839,9 @@ async def delete_key(client_id: str):
|
||||
conn = None
|
||||
try:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
logger.info(f"Установлено подключение к базе данных для удаления ключа клиента {client_id}")
|
||||
logger.info(
|
||||
f"Установлено подключение к базе данных для удаления ключа клиента {client_id}"
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -926,7 +875,9 @@ async def add_balance_to_client(client_id: str, amount: float):
|
||||
conn = None
|
||||
try:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
logger.info(f"Установлено подключение к базе данных для пополнения баланса клиента {client_id}")
|
||||
logger.info(
|
||||
f"Установлено подключение к базе данных для пополнения баланса клиента {client_id}"
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -964,7 +915,9 @@ async def get_client_id_by_email(email: str):
|
||||
conn = None
|
||||
try:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
logger.info(f"Установлено подключение к базе данных для поиска client_id по email: {email}")
|
||||
logger.info(
|
||||
f"Установлено подключение к базе данных для поиска client_id по email: {email}"
|
||||
)
|
||||
|
||||
client_id = await conn.fetchval(
|
||||
"""
|
||||
@@ -1005,9 +958,13 @@ async def get_tg_id_by_client_id(client_id: str):
|
||||
conn = None
|
||||
try:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
logger.info(f"Установлено подключение к базе данных для поиска Telegram ID по client_id: {client_id}")
|
||||
logger.info(
|
||||
f"Установлено подключение к базе данных для поиска Telegram ID по client_id: {client_id}"
|
||||
)
|
||||
|
||||
result = await conn.fetchrow("SELECT tg_id FROM keys WHERE client_id = $1", client_id)
|
||||
result = await conn.fetchrow(
|
||||
"SELECT tg_id FROM keys WHERE client_id = $1", client_id
|
||||
)
|
||||
|
||||
if result:
|
||||
logger.info(f"Найден Telegram ID для client_id: {client_id}")
|
||||
@@ -1050,7 +1007,9 @@ async def upsert_user(
|
||||
conn = None
|
||||
try:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
logger.info(f"Установлено подключение к базе данных для обновления пользователя {tg_id}")
|
||||
logger.info(
|
||||
f"Установлено подключение к базе данных для обновления пользователя {tg_id}"
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -1097,7 +1056,9 @@ async def add_payment(tg_id: int, amount: float, payment_system: str):
|
||||
conn = None
|
||||
try:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
logger.info(f"Установлено подключение к базе данных для добавления платежа пользователя {tg_id}")
|
||||
logger.info(
|
||||
f"Установлено подключение к базе данных для добавления платежа пользователя {tg_id}"
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -1108,7 +1069,9 @@ async def add_payment(tg_id: int, amount: float, payment_system: str):
|
||||
amount,
|
||||
payment_system,
|
||||
)
|
||||
logger.info(f"Успешно добавлен платеж для пользователя {tg_id} на сумму {amount}")
|
||||
logger.info(
|
||||
f"Успешно добавлен платеж для пользователя {tg_id} на сумму {amount}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при добавлении платежа для пользователя {tg_id}: {e}")
|
||||
raise
|
||||
@@ -1141,13 +1104,19 @@ async def add_notification(tg_id: int, notification_type: str, session: Any):
|
||||
tg_id,
|
||||
notification_type,
|
||||
)
|
||||
logger.info(f"Успешно добавлено уведомление типа {notification_type} для пользователя {tg_id}")
|
||||
logger.info(
|
||||
f"Успешно добавлено уведомление типа {notification_type} для пользователя {tg_id}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при добавлении notification для пользователя {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при добавлении notification для пользователя {tg_id}: {e}"
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
async def check_notification_time(tg_id: int, notification_type: str, hours: int = 12, session: Any = None) -> bool:
|
||||
async def check_notification_time(
|
||||
tg_id: int, notification_type: str, hours: int = 12, session: Any = None
|
||||
) -> bool:
|
||||
"""
|
||||
Проверяет, прошло ли указанное количество часов с момента последнего уведомления.
|
||||
|
||||
@@ -1192,7 +1161,9 @@ async def check_notification_time(tg_id: int, notification_type: str, hours: int
|
||||
return can_notify
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при проверке времени уведомления для пользователя {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при проверке времени уведомления для пользователя {tg_id}: {e}"
|
||||
)
|
||||
return False
|
||||
|
||||
finally:
|
||||
@@ -1214,17 +1185,85 @@ async def get_servers_from_db():
|
||||
|
||||
servers = {}
|
||||
for row in result:
|
||||
cluster_name = row['cluster_name']
|
||||
cluster_name = row["cluster_name"]
|
||||
if cluster_name not in servers:
|
||||
servers[cluster_name] = []
|
||||
|
||||
servers[cluster_name].append(
|
||||
{
|
||||
'server_name': row['server_name'],
|
||||
'api_url': row['api_url'],
|
||||
'subscription_url': row['subscription_url'],
|
||||
'inbound_id': row['inbound_id'],
|
||||
"server_name": row["server_name"],
|
||||
"api_url": row["api_url"],
|
||||
"subscription_url": row["subscription_url"],
|
||||
"inbound_id": row["inbound_id"],
|
||||
}
|
||||
)
|
||||
|
||||
return servers
|
||||
|
||||
|
||||
async def delete_user_data(session: Any, tg_id: int):
|
||||
|
||||
try:
|
||||
await session.execute("DELETE FROM gifts WHERE sender_tg_id = $1 OR recipient_tg_id = $1", tg_id)
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"У Вас версия без подарков для {tg_id}: {e}"
|
||||
)
|
||||
await session.execute("DELETE FROM payments WHERE tg_id = $1", tg_id)
|
||||
await session.execute("DELETE FROM users WHERE tg_id = $1", tg_id)
|
||||
await session.execute("DELETE FROM connections WHERE tg_id = $1", tg_id)
|
||||
await session.execute("DELETE FROM keys WHERE tg_id = $1", tg_id)
|
||||
await session.execute("DELETE FROM referrals WHERE referrer_tg_id = $1", tg_id)
|
||||
|
||||
|
||||
async def store_gift_link(
|
||||
gift_id: str, sender_tg_id: int, selected_months: int, expiry_time: datetime, gift_link: str, session: Any = None
|
||||
):
|
||||
"""
|
||||
Добавляет информацию о подарке в базу данных.
|
||||
|
||||
Args:
|
||||
gift_id (str): Уникальный идентификатор подарка
|
||||
sender_tg_id (int): Идентификатор пользователя, который отправил подарок
|
||||
selected_months (int): Количество месяцев подписки
|
||||
expiry_time (datetime): Время окончания подписки
|
||||
gift_link (str): Ссылка для активации подарка
|
||||
session (Any): Сессия базы данных для выполнения запроса
|
||||
|
||||
Returns:
|
||||
bool: True, если информация о подарке успешно добавлена, иначе False
|
||||
|
||||
Raises:
|
||||
Exception: В случае ошибки при сохранении информации о подарке
|
||||
"""
|
||||
conn = None
|
||||
try:
|
||||
conn = session if session is not None else await asyncpg.connect(DATABASE_URL)
|
||||
|
||||
result = await conn.execute(
|
||||
"""
|
||||
INSERT INTO gifts (gift_id, sender_tg_id, recipient_tg_id, selected_months, expiry_time, gift_link, created_at, is_used)
|
||||
VALUES ($1, $2, NULL, $3, $4, $5, $6, FALSE)
|
||||
""",
|
||||
gift_id,
|
||||
sender_tg_id,
|
||||
selected_months,
|
||||
expiry_time,
|
||||
gift_link,
|
||||
datetime.utcnow(),
|
||||
)
|
||||
|
||||
if result:
|
||||
logger.info(f"Подарок с ID {gift_id} успешно добавлен в базу данных.")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"Не удалось добавить подарок с ID {gift_id} в базу данных.")
|
||||
return False
|
||||
except Exception as e:
|
||||
|
||||
logger.error(f"Ошибка при сохранении подарка с ID {gift_id} в базе данных: {e}")
|
||||
return False
|
||||
|
||||
finally:
|
||||
if conn is not None and session is None:
|
||||
await conn.close()
|
||||
|
||||
+1
-2
@@ -1,4 +1,3 @@
|
||||
from typing import Union
|
||||
|
||||
from aiogram.filters import BaseFilter
|
||||
from aiogram.types import Message
|
||||
@@ -9,7 +8,7 @@ from config import ADMIN_ID
|
||||
class IsAdminFilter(BaseFilter):
|
||||
async def __call__(self, message: Message) -> bool:
|
||||
try:
|
||||
admin_ids: Union[int, list[int]] = ADMIN_ID
|
||||
admin_ids: int | list[int] = ADMIN_ID
|
||||
if isinstance(admin_ids, list):
|
||||
return message.from_user.id in admin_ids
|
||||
return message.from_user.id == admin_ids
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
__all__ = ("router",)
|
||||
|
||||
from aiogram import Router
|
||||
|
||||
from .admin import router as admin_router
|
||||
from .coupons import router as coupons_router
|
||||
from .donate import router as donate_router
|
||||
from .instructions import router as instructions_router
|
||||
from .keys import router as keys_router
|
||||
from .notifications import router as notifications_router
|
||||
from .pay import router as pay_router
|
||||
from .payments import router as payments_router
|
||||
from .profile import router as profile_router
|
||||
from .start import router as start_router
|
||||
|
||||
router = Router(name="handlers_main_router")
|
||||
|
||||
router.include_routers(
|
||||
start_router,
|
||||
profile_router,
|
||||
pay_router,
|
||||
donate_router,
|
||||
coupons_router,
|
||||
notifications_router,
|
||||
payments_router,
|
||||
keys_router,
|
||||
instructions_router,
|
||||
admin_router,
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
__all__ = ("router",)
|
||||
|
||||
from aiogram import Router
|
||||
|
||||
from .admin_coupons import router as coupons_router
|
||||
from .admin_panel import router as panel_router
|
||||
from .admin_servers import router as servers_router
|
||||
from .admin_user_editor import router as user_editor_router
|
||||
|
||||
router = Router(name="admins_main_router")
|
||||
|
||||
router.include_routers(
|
||||
panel_router,
|
||||
servers_router,
|
||||
coupons_router,
|
||||
user_editor_router,
|
||||
)
|
||||
@@ -19,13 +19,19 @@ router = Router()
|
||||
|
||||
|
||||
@router.callback_query(F.data == "coupons_editor", IsAdminFilter())
|
||||
async def show_coupon_management_menu(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
async def show_coupon_management_menu(
|
||||
callback_query: types.CallbackQuery, state: FSMContext
|
||||
):
|
||||
await state.clear()
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="➕ Создать купон", callback_data="create_coupon"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="➕ Создать купон", callback_data="create_coupon")
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="Купоны", callback_data="coupons"))
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="admin"))
|
||||
await callback_query.message.answer("🛠 Меню управления купонами:", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"🛠 Меню управления купонами:", reply_markup=builder.as_markup()
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "coupons", IsAdminFilter())
|
||||
@@ -35,7 +41,9 @@ async def show_coupon_list(callback_query: types.CallbackQuery, session: Any):
|
||||
|
||||
if not coupons:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="coupons_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🔙 Назад", callback_data="coupons_editor")
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
"❌ На данный момент нет доступных купонов. 🚫\nВы можете вернуться в меню управления. 🔙",
|
||||
@@ -61,8 +69,12 @@ async def show_coupon_list(callback_query: types.CallbackQuery, session: Any):
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="coupons_editor"))
|
||||
await callback_query.message.answer(coupon_list, reply_markup=builder.as_markup())
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🔙 Назад", callback_data="coupons_editor")
|
||||
)
|
||||
await callback_query.message.answer(
|
||||
coupon_list, reply_markup=builder.as_markup()
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при получении списка купонов: {e}")
|
||||
@@ -141,7 +153,9 @@ async def process_coupon_data(message: types.Message, state: FSMContext, session
|
||||
)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="coupons_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🔙 Назад", callback_data="coupons_editor")
|
||||
)
|
||||
|
||||
await message.answer(result_message, reply_markup=builder.as_markup())
|
||||
await state.clear()
|
||||
|
||||
+134
-33
@@ -1,6 +1,6 @@
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
import subprocess
|
||||
from typing import Any
|
||||
|
||||
from aiogram import F, Router, types
|
||||
@@ -34,16 +34,63 @@ async def handle_admin_callback_query(callback_query: CallbackQuery, state: FSMC
|
||||
async def handle_admin_message(message: types.Message, state: FSMContext):
|
||||
await state.clear()
|
||||
|
||||
BOT_VERSION = "3.2.4-beta" # Укажите текущую версию бота
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="📊 Статистика пользователей", callback_data="user_stats"))
|
||||
builder.row(InlineKeyboardButton(text="👥 Управление пользователями", callback_data="user_editor"))
|
||||
builder.row(InlineKeyboardButton(text="🖥️ Управление серверами", callback_data="servers_editor"))
|
||||
builder.row(InlineKeyboardButton(text="🎟️ Управление купонами", callback_data="coupons_editor"))
|
||||
builder.row(InlineKeyboardButton(text="📢 Массовая рассылка", callback_data="send_to_alls"))
|
||||
builder.row(InlineKeyboardButton(text="💾 Создать резервную копию", callback_data="backups"))
|
||||
builder.row(InlineKeyboardButton(text="🔄 Перезагрузить бота", callback_data="restart_bot"))
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
await message.answer("🤖 Панель администратора", reply_markup=builder.as_markup())
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="📊 Статистика пользователей", callback_data="user_stats"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="👥 Управление пользователями", callback_data="user_editor"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🖥️ Управление серверами", callback_data="servers_editor"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🎟️ Управление купонами", callback_data="coupons_editor"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="📢 Массовая рассылка", callback_data="send_to_alls")
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🤖 Управление Ботом", callback_data="bot_management"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile")
|
||||
)
|
||||
await message.answer(
|
||||
f"🤖 Панель администратора\n\nВерсия бота: <b>{BOT_VERSION}</b>",
|
||||
reply_markup=builder.as_markup(),
|
||||
parse_mode="HTML"
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "bot_management")
|
||||
async def handle_bot_management(callback_query: types.CallbackQuery):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="💾 Создать резервную копию", callback_data="backups")
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🔄 Перезагрузить бота", callback_data="restart_bot")
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="⬅️ Назад", callback_data="admin")
|
||||
)
|
||||
await callback_query.message.answer(
|
||||
"🤖 Управление ботом",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "user_stats", IsAdminFilter())
|
||||
@@ -59,7 +106,12 @@ async def user_stats_menu(callback_query: CallbackQuery, session: Any):
|
||||
total_payments_week = await session.fetchval(
|
||||
"SELECT COALESCE(SUM(amount), 0) FROM payments WHERE created_at >= date_trunc('week', CURRENT_DATE)"
|
||||
)
|
||||
total_payments_all_time = await session.fetchval("SELECT COALESCE(SUM(amount), 0) FROM payments")
|
||||
total_payments_month = await session.fetchval(
|
||||
"SELECT COALESCE(SUM(amount), 0) FROM payments WHERE created_at >= date_trunc('month', CURRENT_DATE)"
|
||||
)
|
||||
total_payments_all_time = await session.fetchval(
|
||||
"SELECT COALESCE(SUM(amount), 0) FROM payments"
|
||||
)
|
||||
|
||||
active_keys = await session.fetchval(
|
||||
"SELECT COUNT(*) FROM keys WHERE expiry_time > $1",
|
||||
@@ -79,16 +131,32 @@ async def user_stats_menu(callback_query: CallbackQuery, session: Any):
|
||||
f"💰 Финансовая статистика:\n"
|
||||
f" 📅 За день: <b>{total_payments_today} ₽</b>\n"
|
||||
f" 📆 За неделю: <b>{total_payments_week} ₽</b>\n"
|
||||
f" 📆 За месяц: <b>{total_payments_month} ₽</b>\n"
|
||||
f" 🏦 За все время: <b>{total_payments_all_time} ₽</b>\n"
|
||||
)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔄 Обновить", callback_data="user_stats"))
|
||||
builder.row(InlineKeyboardButton(text="📥 Выгрузить пользователей в CSV", callback_data="export_users_csv"))
|
||||
builder.row(InlineKeyboardButton(text="📥 Выгрузить оплаты в CSV", callback_data="export_payments_csv"))
|
||||
builder.row(InlineKeyboardButton(text="🔙 Вернуться в меню", callback_data="admin"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🔄 Обновить", callback_data="user_stats")
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="📥 Выгрузить пользователей в CSV",
|
||||
callback_data="export_users_csv",
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="📥 Выгрузить оплаты в CSV", callback_data="export_payments_csv"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🔙 Вернуться в меню", callback_data="admin")
|
||||
)
|
||||
|
||||
await callback_query.message.answer(stats_message, reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
stats_message, reply_markup=builder.as_markup()
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error in user_stats_menu: {e}")
|
||||
|
||||
@@ -115,10 +183,12 @@ async def export_users_csv(callback_query: CallbackQuery, session: Any):
|
||||
)
|
||||
|
||||
if not users:
|
||||
await callback_query.message.answer("📭 Нет пользователей для экспорта.", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"📭 Нет пользователей для экспорта.", reply_markup=builder.as_markup()
|
||||
)
|
||||
return
|
||||
|
||||
csv_data = "tg_id,username,first_name,last_name,language_code,is_bot,balance,trial\n" # Заголовки CSV
|
||||
csv_data = "tg_id,username,first_name,last_name,language_code,is_bot,balance,trial\n"
|
||||
for user in users:
|
||||
csv_data += f"{user['tg_id']},{user['username']},{user['first_name']},{user['last_name']},{user['language_code']},{user['is_bot']},{user['balance']},{user['trial']}\n"
|
||||
|
||||
@@ -128,14 +198,17 @@ async def export_users_csv(callback_query: CallbackQuery, session: Any):
|
||||
file = BufferedInputFile(file_name.getvalue(), filename="users_export.csv")
|
||||
|
||||
await callback_query.message.answer_document(
|
||||
file, caption="📥 Экспорт пользователей в CSV", reply_markup=builder.as_markup()
|
||||
file,
|
||||
caption="📥 Экспорт пользователей в CSV",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
file_name.close()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при экспорте пользователей в CSV: {e}")
|
||||
await callback_query.message.answer(
|
||||
"❗ Произошла ошибка при экспорте пользователей.", reply_markup=builder.as_markup()
|
||||
"❗ Произошла ошибка при экспорте пользователей.",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
|
||||
@@ -161,7 +234,9 @@ async def export_payments_csv(callback_query: CallbackQuery, session: Any):
|
||||
)
|
||||
|
||||
if not payments:
|
||||
await callback_query.message.answer("📭 Нет платежей для экспорта.", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"📭 Нет платежей для экспорта.", reply_markup=builder.as_markup()
|
||||
)
|
||||
return
|
||||
|
||||
csv_data = "tg_id,username,first_name,last_name,amount,payment_system,status,created_at\n" # Заголовки CSV
|
||||
@@ -181,7 +256,8 @@ async def export_payments_csv(callback_query: CallbackQuery, session: Any):
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при экспорте платежей в CSV: {e}")
|
||||
await callback_query.message.answer(
|
||||
"❗ Произошла ошибка при экспорте платежей.", reply_markup=builder.as_markup()
|
||||
"❗ Произошла ошибка при экспорте платежей.",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
|
||||
@@ -197,7 +273,9 @@ async def handle_send_to_all(callback_query: CallbackQuery, state: FSMContext):
|
||||
|
||||
|
||||
@router.message(UserEditorState.waiting_for_message, IsAdminFilter())
|
||||
async def process_message_to_all(message: types.Message, state: FSMContext, session: Any):
|
||||
async def process_message_to_all(
|
||||
message: types.Message, state: FSMContext, session: Any
|
||||
):
|
||||
text_message = message.text
|
||||
|
||||
try:
|
||||
@@ -214,7 +292,9 @@ async def process_message_to_all(message: types.Message, state: FSMContext, sess
|
||||
success_count += 1
|
||||
except Exception as e:
|
||||
error_count += 1
|
||||
logger.error(f"❌ Ошибка при отправке сообщения пользователю {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"❌ Ошибка при отправке сообщения пользователю {tg_id}: {e}"
|
||||
)
|
||||
|
||||
await message.answer(
|
||||
f"📤 Рассылка завершена:\n"
|
||||
@@ -230,9 +310,13 @@ async def process_message_to_all(message: types.Message, state: FSMContext, sess
|
||||
|
||||
@router.callback_query(F.data == "backups", IsAdminFilter())
|
||||
async def handle_backup(callback_query: CallbackQuery, state: FSMContext):
|
||||
await callback_query.message.answer("💾 Инициализация резервного копирования базы данных...")
|
||||
await callback_query.message.answer(
|
||||
"💾 Инициализация резервного копирования базы данных..."
|
||||
)
|
||||
await backup_database()
|
||||
await callback_query.message.answer("✅ Резервная копия успешно создана и отправлена администратору.")
|
||||
await callback_query.message.answer(
|
||||
"✅ Резервная копия успешно создана и отправлена администратору."
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "restart_bot", IsAdminFilter())
|
||||
@@ -240,7 +324,9 @@ async def handle_restart(callback_query: CallbackQuery, state: FSMContext):
|
||||
await state.set_state(UserEditorState.waiting_for_restart_confirmation)
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="✅ Да, перезапустить", callback_data="confirm_restart"),
|
||||
InlineKeyboardButton(
|
||||
text="✅ Да, перезапустить", callback_data="confirm_restart"
|
||||
),
|
||||
InlineKeyboardButton(text="❌ Нет, отмена", callback_data="admin"),
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="🔙 Вернуться в меню", callback_data="admin"))
|
||||
@@ -266,12 +352,17 @@ async def confirm_restart_bot(callback_query: CallbackQuery, state: FSMContext):
|
||||
text=True,
|
||||
)
|
||||
await state.clear()
|
||||
await callback_query.message.answer("🔄 Бот успешно перезапущен.", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"🔄 Бот успешно перезапущен.", reply_markup=builder.as_markup()
|
||||
)
|
||||
except subprocess.CalledProcessError:
|
||||
await callback_query.message.answer("🔄 Бот успешно перезапущен.", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"🔄 Бот успешно перезапущен.", reply_markup=builder.as_markup()
|
||||
)
|
||||
except Exception as e:
|
||||
await callback_query.message.answer(
|
||||
f"⚠️ Ошибка при перезагрузке бота: {e.stderr}", reply_markup=builder.as_markup()
|
||||
f"⚠️ Ошибка при перезагрузке бота: {e.stderr}",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
|
||||
@@ -284,7 +375,17 @@ async def user_editor_menu(callback_query: CallbackQuery):
|
||||
callback_data="search_by_key_name",
|
||||
)
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="🆔 Поиск по Telegram ID", callback_data="search_by_tg_id"))
|
||||
builder.row(InlineKeyboardButton(text="🌐 Поиск по Username", callback_data="search_by_username"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🆔 Поиск по Telegram ID", callback_data="search_by_tg_id"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🌐 Поиск по Username", callback_data="search_by_username"
|
||||
)
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="🔙 Вернуться назад", callback_data="admin"))
|
||||
await callback_query.message.answer("👇 Выберите способ поиска пользователя:", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"👇 Выберите способ поиска пользователя:", reply_markup=builder.as_markup()
|
||||
)
|
||||
|
||||
+212
-44
@@ -1,11 +1,13 @@
|
||||
import asyncpg
|
||||
from aiogram import F, Router, types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.fsm.state import State, StatesGroup
|
||||
from aiogram.types import InlineKeyboardButton
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
import asyncpg
|
||||
from py3xui import AsyncApi
|
||||
|
||||
from config import DATABASE_URL
|
||||
from backup import create_backup_and_send_to_admins
|
||||
from config import ADMIN_PASSWORD, ADMIN_USERNAME, DATABASE_URL
|
||||
from database import check_unique_server_name, get_servers_from_db
|
||||
from filters.admin import IsAdminFilter
|
||||
|
||||
@@ -27,9 +29,15 @@ async def handle_servers_editor(callback_query: types.CallbackQuery):
|
||||
builder = InlineKeyboardBuilder()
|
||||
|
||||
for cluster_name, cluster_servers in servers.items():
|
||||
builder.row(InlineKeyboardButton(text=f"⚙️ {cluster_name}", callback_data=f"manage_cluster|{cluster_name}"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=f"⚙️ {cluster_name}", callback_data=f"manage_cluster|{cluster_name}"
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(InlineKeyboardButton(text="➕ Добавить кластер", callback_data="add_cluster"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="➕ Добавить кластер", callback_data="add_cluster")
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад в админку", callback_data="admin"))
|
||||
|
||||
await callback_query.message.answer(
|
||||
@@ -62,7 +70,11 @@ async def handle_cluster_name_input(message: types.Message, state: FSMContext):
|
||||
if cluster_name == "❌ Отменить":
|
||||
await state.clear()
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔧 Управление кластерами", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔧 Управление кластерами", callback_data="servers_editor"
|
||||
)
|
||||
)
|
||||
await message.answer(
|
||||
"Процесс создания кластера отменен. Вы вернулись в меню управления серверами.",
|
||||
reply_markup=builder.as_markup(),
|
||||
@@ -76,7 +88,9 @@ async def handle_cluster_name_input(message: types.Message, state: FSMContext):
|
||||
await state.update_data(cluster_name=cluster_name)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="❌ Отменить", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="❌ Отменить", callback_data="servers_editor")
|
||||
)
|
||||
|
||||
await message.answer(
|
||||
f"<b>Введите имя сервера для кластера {cluster_name}:</b>\n\n"
|
||||
@@ -95,7 +109,11 @@ async def handle_server_name_input(message: types.Message, state: FSMContext):
|
||||
if server_name == "❌ Отменить":
|
||||
await state.clear()
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔧 Управление кластерами", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔧 Управление кластерами", callback_data="servers_editor"
|
||||
)
|
||||
)
|
||||
await message.answer(
|
||||
"Процесс создания кластера был отменен. Вы вернулись в меню управления серверами.",
|
||||
reply_markup=builder.as_markup(),
|
||||
@@ -108,15 +126,19 @@ async def handle_server_name_input(message: types.Message, state: FSMContext):
|
||||
|
||||
server_unique = await check_unique_server_name(server_name)
|
||||
if not server_unique:
|
||||
await message.answer("❌ Сервер с таким именем уже существует. Пожалуйста, выберите другое имя.")
|
||||
await message.answer(
|
||||
"❌ Сервер с таким именем уже существует. Пожалуйста, выберите другое имя."
|
||||
)
|
||||
return
|
||||
|
||||
user_data = await state.get_data()
|
||||
cluster_name = user_data.get('cluster_name')
|
||||
cluster_name = user_data.get("cluster_name")
|
||||
await state.update_data(server_name=server_name)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="❌ Отменить", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="❌ Отменить", callback_data="servers_editor")
|
||||
)
|
||||
|
||||
await message.answer(
|
||||
f"<b>Введите API URL для сервера {server_name} в кластере {cluster_name}:</b>\n\n"
|
||||
@@ -136,7 +158,11 @@ async def handle_api_url_input(message: types.Message, state: FSMContext):
|
||||
if api_url == "❌ Отменить":
|
||||
await state.clear()
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔧 Управление кластерами", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔧 Управление кластерами", callback_data="servers_editor"
|
||||
)
|
||||
)
|
||||
await message.answer(
|
||||
"Процесс создания кластера был отменен. Вы вернулись в меню управления серверами.",
|
||||
reply_markup=builder.as_markup(),
|
||||
@@ -150,15 +176,17 @@ async def handle_api_url_input(message: types.Message, state: FSMContext):
|
||||
)
|
||||
return
|
||||
|
||||
api_url = api_url.rstrip('/')
|
||||
api_url = api_url.rstrip("/")
|
||||
|
||||
user_data = await state.get_data()
|
||||
cluster_name = user_data.get('cluster_name')
|
||||
server_name = user_data.get('server_name')
|
||||
cluster_name = user_data.get("cluster_name")
|
||||
server_name = user_data.get("server_name")
|
||||
await state.update_data(api_url=api_url)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="❌ Отменить", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="❌ Отменить", callback_data="servers_editor")
|
||||
)
|
||||
|
||||
await message.answer(
|
||||
f"<b>Введите subscription_url для сервера {server_name} в кластере {cluster_name}:</b>\n\n"
|
||||
@@ -179,7 +207,11 @@ async def handle_subscription_url_input(message: types.Message, state: FSMContex
|
||||
if subscription_url == "❌ Отменить":
|
||||
await state.clear()
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔧 Управление кластерами", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔧 Управление кластерами", callback_data="servers_editor"
|
||||
)
|
||||
)
|
||||
await message.answer(
|
||||
"Процесс создания кластера был отменен. Вы вернулись в меню управления серверами.",
|
||||
reply_markup=builder.as_markup(),
|
||||
@@ -193,15 +225,17 @@ async def handle_subscription_url_input(message: types.Message, state: FSMContex
|
||||
)
|
||||
return
|
||||
|
||||
subscription_url = subscription_url.rstrip('/')
|
||||
subscription_url = subscription_url.rstrip("/")
|
||||
|
||||
user_data = await state.get_data()
|
||||
cluster_name = user_data.get('cluster_name')
|
||||
server_name = user_data.get('server_name')
|
||||
cluster_name = user_data.get("cluster_name")
|
||||
server_name = user_data.get("server_name")
|
||||
await state.update_data(subscription_url=subscription_url)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="❌ Отменить", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="❌ Отменить", callback_data="servers_editor")
|
||||
)
|
||||
|
||||
await message.answer(
|
||||
f"<b>Введите inbound_id для сервера {server_name} в кластере {cluster_name}:</b>\n\n"
|
||||
@@ -217,14 +251,16 @@ async def handle_inbound_id_input(message: types.Message, state: FSMContext):
|
||||
inbound_id = message.text.strip()
|
||||
|
||||
if not inbound_id.isdigit():
|
||||
await message.answer("❌ inbound_id должен быть числовым значением. Попробуйте снова.")
|
||||
await message.answer(
|
||||
"❌ inbound_id должен быть числовым значением. Попробуйте снова."
|
||||
)
|
||||
return
|
||||
|
||||
user_data = await state.get_data()
|
||||
cluster_name = user_data.get('cluster_name')
|
||||
server_name = user_data.get('server_name')
|
||||
api_url = user_data.get('api_url')
|
||||
subscription_url = user_data.get('subscription_url')
|
||||
cluster_name = user_data.get("cluster_name")
|
||||
server_name = user_data.get("server_name")
|
||||
api_url = user_data.get("api_url")
|
||||
subscription_url = user_data.get("subscription_url")
|
||||
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
await conn.execute(
|
||||
@@ -241,10 +277,15 @@ async def handle_inbound_id_input(message: types.Message, state: FSMContext):
|
||||
await conn.close()
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад к кластерам", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔙 Назад к кластерам", callback_data="servers_editor"
|
||||
)
|
||||
)
|
||||
|
||||
await message.answer(
|
||||
f"✅ Кластер {cluster_name} и сервер {server_name} успешно добавлены!", reply_markup=builder.as_markup()
|
||||
f"✅ Кластер {cluster_name} и сервер {server_name} успешно добавлены!",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
await state.clear()
|
||||
@@ -262,18 +303,93 @@ async def handle_manage_cluster(callback_query: types.CallbackQuery, state: FSMC
|
||||
for server in cluster_servers:
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=f"🌍 {server['server_name']}", callback_data=f"manage_server|{server['server_name']}"
|
||||
text=f"🌍 {server['server_name']}",
|
||||
callback_data=f"manage_server|{server['server_name']}",
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(InlineKeyboardButton(text="➕ Добавить сервер", callback_data=f"add_server|{cluster_name}"))
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад в управление кластерами", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="➕ Добавить сервер", callback_data=f"add_server|{cluster_name}"
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🌐 Доступность серверов",
|
||||
callback_data=f"server_availability|{cluster_name}",
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="💾 Создать бэкап кластера",
|
||||
callback_data=f"backup_cluster|{cluster_name}",
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔙 Назад в управление кластерами", callback_data="servers_editor"
|
||||
)
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
f"🔧 Управление серверами для кластера {cluster_name}", reply_markup=builder.as_markup()
|
||||
f"🔧 Управление серверами для кластера {cluster_name}",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("server_availability|"), IsAdminFilter())
|
||||
async def handle_check_server_availability(callback_query: types.CallbackQuery):
|
||||
cluster_name = callback_query.data.split("|")[1]
|
||||
|
||||
servers = await get_servers_from_db()
|
||||
cluster_servers = servers.get(cluster_name, [])
|
||||
|
||||
if not cluster_servers:
|
||||
await callback_query.answer(f"Кластер '{cluster_name}' не содержит серверов.")
|
||||
return
|
||||
|
||||
in_progress_message = await callback_query.message.answer(
|
||||
f"🖥️ Проверка доступности серверов для кластера {cluster_name}.\n\n"
|
||||
"Это может занять до 1 минуты, пожалуйста, подождите..."
|
||||
)
|
||||
|
||||
availability_message = (
|
||||
f"🖥️ Проверка доступности серверов для кластера {cluster_name} завершена:\n\n"
|
||||
)
|
||||
|
||||
for server in cluster_servers:
|
||||
xui = AsyncApi(
|
||||
server["api_url"], username=ADMIN_USERNAME, password=ADMIN_PASSWORD
|
||||
)
|
||||
|
||||
try:
|
||||
await xui.login()
|
||||
|
||||
online_users = len(await xui.client.online())
|
||||
availability_message += (
|
||||
f"🌍 {server['server_name']}: {online_users} активных пользователей.\n"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
availability_message += f"❌ {server['server_name']}: Не удалось получить информацию. Ошибка: {e}\n"
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔙 Назад", callback_data=f"manage_cluster|{cluster_name}"
|
||||
)
|
||||
)
|
||||
|
||||
await in_progress_message.edit_text(
|
||||
availability_message, reply_markup=builder.as_markup()
|
||||
)
|
||||
|
||||
await callback_query.answer()
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("manage_server|"), IsAdminFilter())
|
||||
async def handle_manage_server(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
server_name = callback_query.data.split("|")[1]
|
||||
@@ -283,19 +399,29 @@ async def handle_manage_server(callback_query: types.CallbackQuery, state: FSMCo
|
||||
server = None
|
||||
cluster_name = None
|
||||
for cluster, cluster_servers in servers.items():
|
||||
server = next((s for s in cluster_servers if s['server_name'] == server_name), None)
|
||||
server = next(
|
||||
(s for s in cluster_servers if s["server_name"] == server_name), None
|
||||
)
|
||||
if server:
|
||||
cluster_name = cluster
|
||||
break
|
||||
|
||||
if server:
|
||||
api_url = server['api_url']
|
||||
subscription_url = server['subscription_url']
|
||||
inbound_id = server['inbound_id']
|
||||
api_url = server["api_url"]
|
||||
subscription_url = server["subscription_url"]
|
||||
inbound_id = server["inbound_id"]
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🗑️ Удалить", callback_data=f"delete_server|{server_name}"))
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data=f"manage_cluster|{cluster_name}"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🗑️ Удалить", callback_data=f"delete_server|{server_name}"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔙 Назад", callback_data=f"manage_cluster|{cluster_name}"
|
||||
)
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
f"<b>🔧 Информация о сервере {server_name}:</b>\n\n"
|
||||
@@ -315,17 +441,24 @@ async def handle_delete_server(callback_query: types.CallbackQuery, state: FSMCo
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="✅ Да", callback_data=f"confirm_delete_server|{server_name}"),
|
||||
InlineKeyboardButton(text="❌ Нет", callback_data=f"manage_server|{server_name}"),
|
||||
InlineKeyboardButton(
|
||||
text="✅ Да", callback_data=f"confirm_delete_server|{server_name}"
|
||||
),
|
||||
InlineKeyboardButton(
|
||||
text="❌ Нет", callback_data=f"manage_server|{server_name}"
|
||||
),
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
f"🗑️ Вы уверены, что хотите удалить сервер {server_name}?", reply_markup=builder.as_markup()
|
||||
f"🗑️ Вы уверены, что хотите удалить сервер {server_name}?",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("confirm_delete_server|"), IsAdminFilter())
|
||||
async def handle_confirm_delete_server(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
async def handle_confirm_delete_server(
|
||||
callback_query: types.CallbackQuery, state: FSMContext
|
||||
):
|
||||
server_name = callback_query.data.split("|")[1]
|
||||
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
@@ -338,9 +471,15 @@ async def handle_confirm_delete_server(callback_query: types.CallbackQuery, stat
|
||||
await conn.close()
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад в управление кластерами", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔙 Назад в управление кластерами", callback_data="servers_editor"
|
||||
)
|
||||
)
|
||||
|
||||
await callback_query.message.answer(f"🗑️ Сервер {server_name} успешно удален.", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
f"🗑️ Сервер {server_name} успешно удален.", reply_markup=builder.as_markup()
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("add_server|"), IsAdminFilter())
|
||||
@@ -350,7 +489,9 @@ async def handle_add_server(callback_query: types.CallbackQuery, state: FSMConte
|
||||
await state.update_data(cluster_name=cluster_name)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="❌ Отменить", callback_data="servers_editor"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="❌ Отменить", callback_data="servers_editor")
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
f"<b>Введите имя сервера для кластера {cluster_name}:</b>\n\n"
|
||||
@@ -361,3 +502,30 @@ async def handle_add_server(callback_query: types.CallbackQuery, state: FSMConte
|
||||
)
|
||||
|
||||
await state.set_state(UserEditorState.waiting_for_server_name)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("backup_cluster|"), IsAdminFilter())
|
||||
async def handle_backup_cluster(callback_query: types.CallbackQuery):
|
||||
cluster_name = callback_query.data.split("|")[1]
|
||||
|
||||
servers = await get_servers_from_db()
|
||||
cluster_servers = servers.get(cluster_name, [])
|
||||
|
||||
for server in cluster_servers:
|
||||
xui = AsyncApi(
|
||||
server["api_url"],
|
||||
username=ADMIN_USERNAME,
|
||||
password=ADMIN_PASSWORD,
|
||||
)
|
||||
await create_backup_and_send_to_admins(xui)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="servers_editor"))
|
||||
|
||||
await callback_query.message.answer(
|
||||
f"<b>Бэкап для кластера {cluster_name} был успешно создан и отправлен администраторам!</b>\n\n"
|
||||
f"🔔 <i>Бэкапы отправлены в боты панелей.</i>",
|
||||
parse_mode="HTML",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
await callback_query.answer()
|
||||
|
||||
@@ -2,16 +2,20 @@ import asyncio
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from aiogram import F, Router, types
|
||||
from aiogram import Bot, F, Router, types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.fsm.state import State, StatesGroup
|
||||
from aiogram.types import CallbackQuery, InlineKeyboardButton
|
||||
from aiogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
|
||||
from config import TOTAL_GB
|
||||
from database import get_client_id_by_email, get_servers_from_db, restore_trial, update_key_expiry
|
||||
from database import delete_user_data, get_client_id_by_email, get_servers_from_db, restore_trial, update_key_expiry
|
||||
from filters.admin import IsAdminFilter
|
||||
from handlers.keys.key_utils import delete_key_from_cluster, delete_key_from_db, renew_key_in_cluster
|
||||
from handlers.keys.key_utils import (
|
||||
delete_key_from_cluster,
|
||||
delete_key_from_db,
|
||||
renew_key_in_cluster,
|
||||
)
|
||||
from handlers.utils import sanitize_key_name
|
||||
from logger import logger
|
||||
|
||||
@@ -25,13 +29,16 @@ class UserEditorState(StatesGroup):
|
||||
waiting_for_new_balance = State()
|
||||
waiting_for_key_name = State()
|
||||
waiting_for_expiry_time = State()
|
||||
waiting_for_message_text = State()
|
||||
|
||||
|
||||
@router.callback_query(F.data == "search_by_tg_id", IsAdminFilter())
|
||||
async def prompt_tg_id(callback_query: CallbackQuery, state: FSMContext):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await callback_query.message.answer("🔍 Введите Telegram ID клиента:", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"🔍 Введите Telegram ID клиента:", reply_markup=builder.as_markup()
|
||||
)
|
||||
await state.set_state(UserEditorState.waiting_for_tg_id)
|
||||
|
||||
|
||||
@@ -39,39 +46,60 @@ async def prompt_tg_id(callback_query: CallbackQuery, state: FSMContext):
|
||||
async def prompt_username(callback_query: CallbackQuery, state: FSMContext):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await callback_query.message.answer("🔍 Введите Username клиента:", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"🔍 Введите Username клиента:", reply_markup=builder.as_markup()
|
||||
)
|
||||
await state.set_state(UserEditorState.waiting_for_username)
|
||||
|
||||
|
||||
@router.message(UserEditorState.waiting_for_username, IsAdminFilter())
|
||||
async def handle_username_input(message: types.Message, state: FSMContext, session: Any):
|
||||
username = message.text.strip().lstrip("@")
|
||||
user_record = await session.fetchrow("SELECT tg_id FROM users WHERE username = $1", username)
|
||||
async def handle_username_input(
|
||||
message: types.Message, state: FSMContext, session: Any
|
||||
):
|
||||
# Extract the username from a message text by removing leading '@' and the Telegram URL prefix
|
||||
username = message.text.strip().lstrip('@').replace('https://t.me/', '')
|
||||
user_record = await session.fetchrow(
|
||||
"SELECT tg_id FROM users WHERE username = $1", username
|
||||
)
|
||||
|
||||
if not user_record:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await message.answer("🔍 Пользователь с указанным username не найден. 🚫", reply_markup=builder.as_markup())
|
||||
await message.answer(
|
||||
"🔍 Пользователь с указанным username не найден. 🚫",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
tg_id = user_record["tg_id"]
|
||||
username = await session.fetchval("SELECT username FROM users WHERE tg_id = $1", tg_id)
|
||||
balance = await session.fetchval("SELECT balance FROM connections WHERE tg_id = $1", tg_id)
|
||||
username = await session.fetchval(
|
||||
"SELECT username FROM users WHERE tg_id = $1", tg_id
|
||||
)
|
||||
balance = await session.fetchval(
|
||||
"SELECT balance FROM connections WHERE tg_id = $1", tg_id
|
||||
)
|
||||
key_records = await session.fetch("SELECT email FROM keys WHERE tg_id = $1", tg_id)
|
||||
referral_count = await session.fetchval("SELECT COUNT(*) FROM referrals WHERE referrer_tg_id = $1", tg_id)
|
||||
referral_count = await session.fetchval(
|
||||
"SELECT COUNT(*) FROM referrals WHERE referrer_tg_id = $1", tg_id
|
||||
)
|
||||
|
||||
if balance is None:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await message.answer("🚫 Пользователь с указанным tg_id не найден. 🔍", reply_markup=builder.as_markup())
|
||||
await message.answer(
|
||||
"🚫 Пользователь с указанным tg_id не найден. 🔍",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
|
||||
for (email,) in key_records:
|
||||
builder.row(InlineKeyboardButton(text=f"🔑 {email}", callback_data=f"edit_key_{email}"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text=f"🔑 {email}", callback_data=f"edit_key_{email}")
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
@@ -86,7 +114,13 @@ async def handle_username_input(message: types.Message, state: FSMContext, sessi
|
||||
callback_data=f"restore_trial_{tg_id}",
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(InlineKeyboardButton(text="❌ Удалить клиента", callback_data=f"confirm_delete_user_{tg_id}"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="✉️ Отправить сообщение",
|
||||
callback_data=f"send_message_{tg_id}"
|
||||
)
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
|
||||
user_info = (
|
||||
@@ -101,25 +135,65 @@ async def handle_username_input(message: types.Message, state: FSMContext, sessi
|
||||
await state.set_state(UserEditorState.displaying_user_info)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("send_message_"))
|
||||
async def handle_send_message(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
tg_id = callback_query.data.split("_")[2]
|
||||
await state.update_data(target_tg_id=tg_id)
|
||||
await callback_query.message.answer(
|
||||
"✉️ Введите текст сообщения, которое вы хотите отправить пользователю."
|
||||
)
|
||||
await state.set_state(UserEditorState.waiting_for_message_text)
|
||||
|
||||
|
||||
@router.message(UserEditorState.waiting_for_message_text, IsAdminFilter())
|
||||
async def process_send_message(message: types.Message, state: FSMContext, bot: Bot):
|
||||
data = await state.get_data()
|
||||
target_tg_id = data.get("target_tg_id")
|
||||
|
||||
if not target_tg_id:
|
||||
await message.answer("🚫 Ошибка: ID пользователя не найден.")
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
try:
|
||||
await bot.send_message(chat_id=target_tg_id, text=message.text)
|
||||
await message.answer("✅ Сообщение успешно отправлено.")
|
||||
except Exception as e:
|
||||
await message.answer(f"❌ Не удалось отправить сообщение: {e}")
|
||||
|
||||
await state.clear()
|
||||
|
||||
|
||||
@router.message(UserEditorState.waiting_for_tg_id, F.text.isdigit(), IsAdminFilter())
|
||||
async def handle_tg_id_input(message: types.Message, state: FSMContext, session: Any):
|
||||
tg_id = int(message.text)
|
||||
username = await session.fetchval("SELECT username FROM users WHERE tg_id = $1", tg_id)
|
||||
balance = await session.fetchval("SELECT balance FROM connections WHERE tg_id = $1", tg_id)
|
||||
username = await session.fetchval(
|
||||
"SELECT username FROM users WHERE tg_id = $1", tg_id
|
||||
)
|
||||
balance = await session.fetchval(
|
||||
"SELECT balance FROM connections WHERE tg_id = $1", tg_id
|
||||
)
|
||||
key_records = await session.fetch("SELECT email FROM keys WHERE tg_id = $1", tg_id)
|
||||
referral_count = await session.fetchval("SELECT COUNT(*) FROM referrals WHERE referrer_tg_id = $1", tg_id)
|
||||
referral_count = await session.fetchval(
|
||||
"SELECT COUNT(*) FROM referrals WHERE referrer_tg_id = $1", tg_id
|
||||
)
|
||||
|
||||
if balance is None:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await message.answer("❌ Пользователь с указанным tg_id не найден. 🔍", reply_markup=builder.as_markup())
|
||||
await message.answer(
|
||||
"❌ Пользователь с указанным tg_id не найден. 🔍",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
|
||||
for (email,) in key_records:
|
||||
builder.row(InlineKeyboardButton(text=f"🔑 {email}", callback_data=f"edit_key_{email}"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text=f"🔑 {email}", callback_data=f"edit_key_{email}")
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
@@ -127,13 +201,19 @@ async def handle_tg_id_input(message: types.Message, state: FSMContext, session:
|
||||
callback_data=f"change_balance_{tg_id}",
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(InlineKeyboardButton(text="❌ Удалить клиента", callback_data=f"confirm_delete_user_{tg_id}"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔄 Восстановить пробник",
|
||||
callback_data=f"restore_trial_{tg_id}",
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="✉️ Отправить сообщение",
|
||||
callback_data=f"send_message_{tg_id}"
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
|
||||
@@ -156,9 +236,15 @@ async def handle_restore_trial(callback_query: types.CallbackQuery, session: Any
|
||||
await restore_trial(tg_id, session)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад в меню администратора", callback_data="admin"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔙 Назад в меню администратора", callback_data="admin"
|
||||
)
|
||||
)
|
||||
|
||||
await callback_query.message.answer("✅ Триал успешно восстановлен.", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"✅ Триал успешно восстановлен.", reply_markup=builder.as_markup()
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("change_balance_"), IsAdminFilter())
|
||||
@@ -167,17 +253,22 @@ async def process_balance_change(callback_query: CallbackQuery, state: FSMContex
|
||||
await state.update_data(tg_id=tg_id)
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await callback_query.message.answer("💸 Введите новую сумму баланса:", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"💸 Введите новую сумму баланса:", reply_markup=builder.as_markup()
|
||||
)
|
||||
await state.set_state(UserEditorState.waiting_for_new_balance)
|
||||
|
||||
|
||||
@router.message(UserEditorState.waiting_for_new_balance, IsAdminFilter())
|
||||
async def handle_new_balance_input(message: types.Message, state: FSMContext, session: Any):
|
||||
async def handle_new_balance_input(
|
||||
message: types.Message, state: FSMContext, session: Any
|
||||
):
|
||||
if not message.text.isdigit() or int(message.text) < 0:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await message.answer(
|
||||
"❌ Пожалуйста, введите корректную сумму для изменения баланса.", reply_markup=builder.as_markup()
|
||||
"❌ Пожалуйста, введите корректную сумму для изменения баланса.",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
return
|
||||
|
||||
@@ -222,11 +313,13 @@ async def get_key_details(email, session):
|
||||
|
||||
cluster_name = "Неизвестный кластер"
|
||||
for cluster_name, cluster_servers in servers.items():
|
||||
if any(server['inbound_id'] == record['server_id'] for server in cluster_servers):
|
||||
if any(
|
||||
server["inbound_id"] == record["server_id"] for server in cluster_servers
|
||||
):
|
||||
cluster_name = cluster_name
|
||||
break
|
||||
|
||||
expiry_date = datetime.utcfromtimestamp(record['expiry_time'] / 1000)
|
||||
expiry_date = datetime.utcfromtimestamp(record["expiry_time"] / 1000)
|
||||
current_date = datetime.utcnow()
|
||||
time_left = expiry_date - current_date
|
||||
|
||||
@@ -239,12 +332,12 @@ async def get_key_details(email, session):
|
||||
days_left_message = f"Осталось часов: <b>{hours_left}</b>"
|
||||
|
||||
return {
|
||||
'key': record['key'],
|
||||
'expiry_date': expiry_date.strftime("%d %B %Y года"),
|
||||
'days_left_message': days_left_message,
|
||||
'server_name': cluster_name,
|
||||
'balance': record['balance'],
|
||||
'tg_id': record['tg_id'],
|
||||
"key": record["key"],
|
||||
"expiry_date": expiry_date.strftime("%d %B %Y года"),
|
||||
"days_left_message": days_left_message,
|
||||
"server_name": cluster_name,
|
||||
"balance": record["balance"],
|
||||
"tg_id": record["tg_id"],
|
||||
}
|
||||
|
||||
|
||||
@@ -257,7 +350,8 @@ async def process_key_edit(callback_query: CallbackQuery, session: Any):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await callback_query.message.answer(
|
||||
"🔍 <b>Информация о ключе не найдена.</b> 🚫", reply_markup=builder.as_markup()
|
||||
"🔍 <b>Информация о ключе не найдена.</b> 🚫",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
return
|
||||
|
||||
@@ -287,21 +381,27 @@ async def process_key_edit(callback_query: CallbackQuery, session: Any):
|
||||
callback_data=f"delete_key_admin|{email}",
|
||||
)
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="admin"))
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
|
||||
await callback_query.message.answer(response_message, reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
response_message, reply_markup=builder.as_markup()
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "search_by_key_name", IsAdminFilter())
|
||||
async def prompt_key_name(callback_query: CallbackQuery, state: FSMContext):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await callback_query.message.answer("🔑 Введите имя ключа:", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"🔑 Введите имя ключа:", reply_markup=builder.as_markup()
|
||||
)
|
||||
await state.set_state(UserEditorState.waiting_for_key_name)
|
||||
|
||||
|
||||
@router.message(UserEditorState.waiting_for_key_name, IsAdminFilter())
|
||||
async def handle_key_name_input(message: types.Message, state: FSMContext, session: Any):
|
||||
async def handle_key_name_input(
|
||||
message: types.Message, state: FSMContext, session: Any
|
||||
):
|
||||
key_name = sanitize_key_name(message.text)
|
||||
key_details = await get_key_details(key_name, session)
|
||||
|
||||
@@ -358,34 +458,52 @@ async def prompt_expiry_change(callback_query: CallbackQuery, state: FSMContext)
|
||||
|
||||
|
||||
@router.message(UserEditorState.waiting_for_expiry_time, IsAdminFilter())
|
||||
async def handle_expiry_time_input(message: types.Message, state: FSMContext, session: Any):
|
||||
async def handle_expiry_time_input(
|
||||
message: types.Message, state: FSMContext, session: Any
|
||||
):
|
||||
user_data = await state.get_data()
|
||||
email = user_data.get("email")
|
||||
|
||||
if not email:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await message.answer("📧 Email не найден в состоянии. 🚫", reply_markup=builder.as_markup())
|
||||
await message.answer(
|
||||
"📧 Email не найден в состоянии. 🚫", reply_markup=builder.as_markup()
|
||||
)
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
try:
|
||||
expiry_time_str = message.text
|
||||
expiry_time = int(datetime.strptime(expiry_time_str, "%Y-%m-%d %H:%M:%S").timestamp() * 1000)
|
||||
expiry_time = int(
|
||||
datetime.strptime(expiry_time_str, "%Y-%m-%d %H:%M:%S").timestamp() * 1000
|
||||
)
|
||||
|
||||
client_id = await get_client_id_by_email(email)
|
||||
if client_id is None:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await message.answer(f"🚫 Клиент с email {email} не найден. 🔍", reply_markup=builder.as_markup())
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor")
|
||||
)
|
||||
await message.answer(
|
||||
f"🚫 Клиент с email {email} не найден. 🔍",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
record = await session.fetchrow("SELECT server_id FROM keys WHERE client_id = $1", client_id)
|
||||
record = await session.fetchrow(
|
||||
"SELECT server_id FROM keys WHERE client_id = $1", client_id
|
||||
)
|
||||
if not record:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await message.answer("🚫 Клиент не найден в базе данных. 🔍", reply_markup=builder.as_markup())
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor")
|
||||
)
|
||||
await message.answer(
|
||||
"🚫 Клиент не найден в базе данных. 🔍",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
@@ -412,9 +530,7 @@ async def handle_expiry_time_input(message: types.Message, state: FSMContext, se
|
||||
|
||||
await update_key_expiry(client_id, expiry_time)
|
||||
|
||||
response_message = (
|
||||
f"✅ Время истечения ключа для клиента {client_id} ({email}) успешно обновлено на всех серверах."
|
||||
)
|
||||
response_message = f"✅ Время истечения ключа для клиента {client_id} ({email}) успешно обновлено на всех серверах."
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="admin"))
|
||||
@@ -423,7 +539,8 @@ async def handle_expiry_time_input(message: types.Message, state: FSMContext, se
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await message.answer(
|
||||
"❌ Пожалуйста, используйте формат: YYYY-MM-DD HH:MM:SS.", reply_markup=builder.as_markup()
|
||||
"❌ Пожалуйста, используйте формат: YYYY-MM-DD HH:MM:SS.",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
@@ -431,14 +548,20 @@ async def handle_expiry_time_input(message: types.Message, state: FSMContext, se
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("delete_key_admin|"), IsAdminFilter())
|
||||
async def process_callback_delete_key(callback_query: types.CallbackQuery, session: Any):
|
||||
async def process_callback_delete_key(
|
||||
callback_query: types.CallbackQuery, session: Any
|
||||
):
|
||||
email = callback_query.data.split("|")[1]
|
||||
client_id = await session.fetchval("SELECT client_id FROM keys WHERE email = $1", email)
|
||||
client_id = await session.fetchval(
|
||||
"SELECT client_id FROM keys WHERE email = $1", email
|
||||
)
|
||||
|
||||
if client_id is None:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
await callback_query.message.answer("🔍 Ключ не найден. 🚫", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"🔍 Ключ не найден. 🚫", reply_markup=builder.as_markup()
|
||||
)
|
||||
return
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
@@ -448,7 +571,9 @@ async def process_callback_delete_key(callback_query: types.CallbackQuery, sessi
|
||||
callback_data=f"confirm_delete_admin|{client_id}",
|
||||
)
|
||||
)
|
||||
builder.row(types.InlineKeyboardButton(text="❌ Нет, отменить", callback_data="user_editor"))
|
||||
builder.row(
|
||||
types.InlineKeyboardButton(text="❌ Нет, отменить", callback_data="user_editor")
|
||||
)
|
||||
await callback_query.message.answer(
|
||||
"<b>❓ Вы уверены, что хотите удалить ключ?</b>",
|
||||
reply_markup=builder.as_markup(),
|
||||
@@ -456,9 +581,13 @@ async def process_callback_delete_key(callback_query: types.CallbackQuery, sessi
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("confirm_delete_admin|"), IsAdminFilter())
|
||||
async def process_callback_confirm_delete(callback_query: types.CallbackQuery, session: Any):
|
||||
async def process_callback_confirm_delete(
|
||||
callback_query: types.CallbackQuery, session: Any
|
||||
):
|
||||
client_id = callback_query.data.split("|")[1]
|
||||
record = await session.fetchrow("SELECT email FROM keys WHERE client_id = $1", client_id)
|
||||
record = await session.fetchrow(
|
||||
"SELECT email FROM keys WHERE client_id = $1", client_id
|
||||
)
|
||||
|
||||
if record:
|
||||
email = record["email"]
|
||||
@@ -472,47 +601,52 @@ async def process_callback_confirm_delete(callback_query: types.CallbackQuery, s
|
||||
tasks = []
|
||||
for cluster_name, cluster_servers in clusters.items():
|
||||
for server in cluster_servers:
|
||||
tasks.append(delete_key_from_cluster(cluster_name, email, client_id))
|
||||
tasks.append(
|
||||
delete_key_from_cluster(cluster_name, email, client_id)
|
||||
)
|
||||
await asyncio.gather(*tasks)
|
||||
|
||||
await delete_key_from_servers(email, client_id)
|
||||
await delete_key_from_db(client_id, session)
|
||||
|
||||
await callback_query.message.answer(response_message, reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
response_message, reply_markup=builder.as_markup()
|
||||
)
|
||||
else:
|
||||
response_message = "🚫 Ключ не найден или уже удален."
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="⬅️ Назад", callback_data="view_keys"))
|
||||
await callback_query.message.answer(response_message, reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
response_message, reply_markup=builder.as_markup()
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("user_info|"), IsAdminFilter())
|
||||
async def handle_user_info(callback_query: types.CallbackQuery, state: FSMContext, session: Any):
|
||||
async def handle_user_info(
|
||||
callback_query: types.CallbackQuery, state: FSMContext, session: Any
|
||||
):
|
||||
tg_id = int(callback_query.data.split("|")[1])
|
||||
username = await session.fetchval("SELECT username FROM users WHERE tg_id = $1", tg_id)
|
||||
balance = await session.fetchval("SELECT balance FROM connections WHERE tg_id = $1", tg_id)
|
||||
username = await session.fetchval(
|
||||
"SELECT username FROM users WHERE tg_id = $1", tg_id
|
||||
)
|
||||
balance = await session.fetchval(
|
||||
"SELECT balance FROM connections WHERE tg_id = $1", tg_id
|
||||
)
|
||||
key_records = await session.fetch("SELECT email FROM keys WHERE tg_id = $1", tg_id)
|
||||
referral_count = await session.fetchval("SELECT COUNT(*) FROM referrals WHERE referrer_tg_id = $1", tg_id)
|
||||
referral_count = await session.fetchval(
|
||||
"SELECT COUNT(*) FROM referrals WHERE referrer_tg_id = $1", tg_id
|
||||
)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
|
||||
for (email,) in key_records:
|
||||
builder.row(InlineKeyboardButton(text=f"🔑 {email}", callback_data=f"edit_key_{email}"))
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="📝 Изменить баланс",
|
||||
callback_data=f"change_balance_{tg_id}",
|
||||
builder.row(
|
||||
InlineKeyboardButton(text=f"🔑 {email}", callback_data=f"edit_key_{email}")
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🔄 Восстановить пробник",
|
||||
callback_data=f"restore_trial_{tg_id}",
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(InlineKeyboardButton(text="📝 Изменить баланс", callback_data=f"change_balance_{tg_id}"))
|
||||
builder.row(InlineKeyboardButton(text="🔄 Восстановить пробник", callback_data=f"restore_trial_{tg_id}"))
|
||||
builder.row(InlineKeyboardButton(text="❌ Удалить клиента", callback_data=f"confirm_delete_user_{tg_id}"))
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor"))
|
||||
|
||||
user_info = (
|
||||
@@ -523,5 +657,56 @@ async def handle_user_info(callback_query: types.CallbackQuery, state: FSMContex
|
||||
f"👥 Количество рефералов: <b>{referral_count}</b>\n"
|
||||
f"🔑 Ключи (для редактирования нажмите на ключ):"
|
||||
)
|
||||
|
||||
await callback_query.message.answer(user_info, reply_markup=builder.as_markup())
|
||||
await state.set_state(UserEditorState.displaying_user_info)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("confirm_delete_user_"), IsAdminFilter())
|
||||
async def confirm_delete_user(callback_query: types.CallbackQuery, state: FSMContext, session: Any):
|
||||
tg_id = int(callback_query.data.split("_")[3])
|
||||
|
||||
confirmation_markup = InlineKeyboardMarkup(
|
||||
row_width=2,
|
||||
inline_keyboard=[
|
||||
[InlineKeyboardButton(text="✅ Подтвердить", callback_data=f"delete_user_{tg_id}")],
|
||||
[InlineKeyboardButton(text="❌ Отменить", callback_data="user_editor")],
|
||||
],
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
f"Вы уверены, что хотите удалить пользователя с ID {tg_id}?", reply_markup=confirmation_markup
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("delete_user_"), IsAdminFilter())
|
||||
async def delete_user(callback_query: types.CallbackQuery, session: Any):
|
||||
tg_id = int(callback_query.data.split("_")[2])
|
||||
|
||||
key_records = await session.fetch("SELECT email, client_id FROM keys WHERE tg_id = $1", tg_id)
|
||||
|
||||
async def delete_keys_from_servers():
|
||||
try:
|
||||
tasks = []
|
||||
for email, client_id in key_records:
|
||||
servers = await get_servers_from_db()
|
||||
for cluster_id, cluster in servers.items():
|
||||
tasks.append(delete_key_from_cluster(cluster_id, email, client_id))
|
||||
await asyncio.gather(*tasks)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при удалении ключей с серверов для пользователя {tg_id}: {e}")
|
||||
|
||||
await delete_keys_from_servers()
|
||||
|
||||
try:
|
||||
await delete_user_data(session, tg_id)
|
||||
|
||||
back_button = InlineKeyboardButton(text="🔙 Назад", callback_data="user_editor")
|
||||
keyboard = InlineKeyboardMarkup(inline_keyboard=[[back_button]])
|
||||
|
||||
await callback_query.message.answer(f"🗑️ Пользователь с ID {tg_id} был удален.", reply_markup=keyboard)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при удалении данных из базы данных для пользователя {tg_id}: {e}")
|
||||
await callback_query.message.answer(
|
||||
f"❌ Произошла ошибка при удалении пользователя с ID {tg_id}. Попробуйте снова."
|
||||
)
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
GIFT = "🎁 Подарить подписку"
|
||||
MY_GIFTS = "🎁 Мои подарки"
|
||||
PROFILE = "👤 Личный кабинет"
|
||||
BACK = "🔙 Назад"
|
||||
GIFTS_ABOUT = "<b>Дарите подарки и следите, чтобы они дошли до адресата! 🎄</b>"
|
||||
@@ -0,0 +1,8 @@
|
||||
ADD_SUB = "➕ Устройство"
|
||||
MY_SUBS = "📱 Мои устройства"
|
||||
PAYMENT = "💳 Пополнить баланс"
|
||||
INVITE = "👥 Пригласить"
|
||||
GIFTS = "🎁 Подарить"
|
||||
TARRIFS = "💡 Тарифы"
|
||||
INSTRUCTIONS = "📘 Инструкции"
|
||||
MAIN_MENU = "⬅️ Главное меню"
|
||||
@@ -0,0 +1,3 @@
|
||||
PAY = "Пополнить"
|
||||
BACK = "⬅️ Назад"
|
||||
CUSTOM_SUM = "💰 Ввести свою сумму"
|
||||
+6
-2
@@ -18,7 +18,9 @@ router = Router()
|
||||
|
||||
|
||||
@router.callback_query(F.data == "activate_coupon")
|
||||
async def handle_activate_coupon(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
async def handle_activate_coupon(
|
||||
callback_query: types.CallbackQuery, state: FSMContext
|
||||
):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
|
||||
@@ -38,7 +40,9 @@ async def process_coupon_code(message: types.Message, state: FSMContext, session
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
|
||||
await message.answer(activation_result, reply_markup=builder.as_markup(), parse_mode="HTML")
|
||||
await message.answer(
|
||||
activation_result, reply_markup=builder.as_markup(), parse_mode="HTML"
|
||||
)
|
||||
await state.clear()
|
||||
|
||||
|
||||
|
||||
+17
-5
@@ -22,7 +22,11 @@ async def process_donate(callback_query: types.CallbackQuery, state: FSMContext)
|
||||
await state.clear()
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🤖 Бот для покупки звезд", url="https://t.me/PremiumBot"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="🤖 Бот для покупки звезд", url="https://t.me/PremiumBot"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="💰 Ввести сумму доната",
|
||||
@@ -40,10 +44,14 @@ async def process_donate(callback_query: types.CallbackQuery, state: FSMContext)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "enter_custom_donate_amount")
|
||||
async def process_enter_donate_amount(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
async def process_enter_donate_amount(
|
||||
callback_query: types.CallbackQuery, state: FSMContext
|
||||
):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="⬅️ Назад", callback_data="donate"))
|
||||
await callback_query.message.answer(f"💸 Введите сумму доната в рублях:", reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
"💸 Введите сумму доната в рублях:", reply_markup=builder.as_markup()
|
||||
)
|
||||
await state.set_state(DonateState.entering_donate_amount)
|
||||
|
||||
|
||||
@@ -52,7 +60,9 @@ async def process_donate_amount_input(message: types.Message, state: FSMContext)
|
||||
if message.text.isdigit():
|
||||
amount = int(message.text)
|
||||
if amount // RUB_TO_XTR <= 0:
|
||||
await message.answer(f"Сумма доната должна быть больше {RUB_TO_XTR}. Пожалуйста, введите сумму еще раз:")
|
||||
await message.answer(
|
||||
f"Сумма доната должна быть больше {RUB_TO_XTR}. Пожалуйста, введите сумму еще раз:"
|
||||
)
|
||||
return
|
||||
|
||||
await state.update_data(amount=amount)
|
||||
@@ -89,7 +99,9 @@ async def on_successful_donate(message: types.Message, state: FSMContext):
|
||||
try:
|
||||
amount = float(message.successful_payment.invoice_payload.split("_")[0])
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile")
|
||||
)
|
||||
await message.answer(
|
||||
text=f"🙏 Спасибо за донат {amount} рублей! Ваша поддержка очень важна для нас. 💖",
|
||||
reply_markup=builder.as_markup(),
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
__all__ = ("router",)
|
||||
|
||||
from aiogram import Router
|
||||
|
||||
from .instructions import router as instructions_router
|
||||
|
||||
router = Router(name="instructions_main_router")
|
||||
|
||||
router.include_routers(
|
||||
instructions_router,
|
||||
)
|
||||
@@ -1,22 +1,28 @@
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import asyncpg
|
||||
from aiogram import F, Router, types
|
||||
from aiogram.types import BufferedInputFile, InlineKeyboardButton
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
|
||||
from config import CONNECT_IOS, CONNECT_WINDOWS, SUPPORT_CHAT_URL
|
||||
from handlers.texts import INSTRUCTION_PC, INSTRUCTIONS, KEY_MESSAGE
|
||||
from config import CONNECT_MACOS, CONNECT_WINDOWS, DATABASE_URL, SUPPORT_CHAT_URL
|
||||
from handlers.texts import CONNECT_TV_TEXT, INSTRUCTION_PC, INSTRUCTIONS, KEY_MESSAGE, SUBSCRIPTION_DETAILS_TEXT
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
@router.callback_query(F.data == "instructions")
|
||||
async def send_instructions(callback_query: types.CallbackQuery):
|
||||
@router.message(F.text == "/instructions")
|
||||
async def send_instructions(callback_query_or_message: types.CallbackQuery | types.Message):
|
||||
instructions_message = INSTRUCTIONS
|
||||
image_path = os.path.join("img", "instructions.jpg")
|
||||
|
||||
if not os.path.isfile(image_path):
|
||||
await callback_query.message.answer("Файл изображения не найден.")
|
||||
if isinstance(callback_query_or_message, types.CallbackQuery):
|
||||
await callback_query_or_message.message.answer("Файл изображения не найден.")
|
||||
else:
|
||||
await callback_query_or_message.answer("Файл изображения не найден.")
|
||||
return
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
@@ -25,14 +31,20 @@ async def send_instructions(callback_query: types.CallbackQuery):
|
||||
InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"),
|
||||
)
|
||||
|
||||
if isinstance(callback_query_or_message, types.CallbackQuery):
|
||||
send_photo = callback_query_or_message.message.answer_photo
|
||||
else:
|
||||
send_photo = callback_query_or_message.answer_photo
|
||||
|
||||
with open(image_path, "rb") as image_from_buffer:
|
||||
await callback_query.message.answer_photo(
|
||||
await send_photo(
|
||||
BufferedInputFile(image_from_buffer.read(), filename="instructions.jpg"),
|
||||
caption=instructions_message,
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("connect_pc|"))
|
||||
async def process_connect_pc(callback_query: types.CallbackQuery, session: Any):
|
||||
tg_id = callback_query.message.chat.id
|
||||
@@ -49,7 +61,9 @@ async def process_connect_pc(callback_query: types.CallbackQuery, session: Any):
|
||||
)
|
||||
|
||||
if not record:
|
||||
await callback_query.message.answer("❌ <b>Ключ не найден. Проверьте имя ключа.</b> 🔍")
|
||||
await callback_query.message.answer(
|
||||
"❌ <b>Ключ не найден. Проверьте имя ключа.</b> 🔍"
|
||||
)
|
||||
return
|
||||
|
||||
key = record["key"]
|
||||
@@ -57,9 +71,87 @@ async def process_connect_pc(callback_query: types.CallbackQuery, session: Any):
|
||||
instruction_message = f"{key_message}{INSTRUCTION_PC}"
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="💻 Подключить Windows", url=f"{CONNECT_WINDOWS}{key}"))
|
||||
builder.row(InlineKeyboardButton(text="💻 Подключить MacOS", url=f"{CONNECT_IOS}{key}"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="💻 Подключить Windows", url=f"{CONNECT_WINDOWS}{key}"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="💻 Подключить MacOS", url=f"{CONNECT_MACOS}{key}")
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="🆘 Поддержка", url=f"{SUPPORT_CHAT_URL}"))
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
|
||||
await callback_query.message.answer(instruction_message, reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
instruction_message,
|
||||
reply_markup=builder.as_markup(),
|
||||
parse_mode="HTML",
|
||||
disable_web_page_preview=True,
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("connect_tv|"))
|
||||
async def process_connect_tv(callback_query: types.CallbackQuery):
|
||||
key_name = callback_query.data.split("|")[1]
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="▶ Продолжить", callback_data=f"continue_tv|{key_name}"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile")
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
text=CONNECT_TV_TEXT,
|
||||
reply_markup=builder.as_markup(),
|
||||
parse_mode="HTML",
|
||||
disable_web_page_preview=True
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("continue_tv|"))
|
||||
async def process_continue_tv(callback_query: types.CallbackQuery):
|
||||
key_name = callback_query.data.split("|")[1]
|
||||
tg_id = callback_query.from_user.id
|
||||
|
||||
print(f"tg_id: {tg_id}, key_name: {key_name}") # Отладочный вывод
|
||||
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
try:
|
||||
record = await conn.fetchrow(
|
||||
"""
|
||||
SELECT k.key
|
||||
FROM keys k
|
||||
WHERE k.tg_id = $1 AND k.email = $2
|
||||
""",
|
||||
tg_id,
|
||||
key_name,
|
||||
)
|
||||
|
||||
print(f"Query result: {record}") # Отладочный вывод результата
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
subscription_link = record['key']
|
||||
|
||||
message_text = SUBSCRIPTION_DETAILS_TEXT.format(subscription_link=subscription_link)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="📖 Полная инструкция", url="https://vpn4tv.com/quick-guide.html"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile")
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
text=message_text,
|
||||
reply_markup=builder.as_markup(),
|
||||
parse_mode="HTML"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
__all__ = ("router",)
|
||||
|
||||
from aiogram import Router
|
||||
|
||||
from .key_management import router as management_router
|
||||
from .keys import router as keys_router
|
||||
|
||||
router = Router(name="keys_main_router")
|
||||
|
||||
router.include_routers(
|
||||
keys_router,
|
||||
management_router,
|
||||
)
|
||||
@@ -1,7 +1,7 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Union
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from aiogram import F, Router
|
||||
from aiogram.fsm.context import FSMContext
|
||||
@@ -15,14 +15,13 @@ from config import (
|
||||
DOWNLOAD_ANDROID,
|
||||
DOWNLOAD_IOS,
|
||||
PUBLIC_LINK,
|
||||
RENEWAL_PLANS,
|
||||
RENEWAL_PRICES,
|
||||
SUPPORT_CHAT_URL,
|
||||
TRIAL_TIME,
|
||||
)
|
||||
from database import get_balance, get_trial, store_key, update_balance
|
||||
from handlers.keys.key_utils import create_key_on_cluster
|
||||
from handlers.texts import KEY, NULL_BALANCE, key_message_success
|
||||
from handlers.texts import DISCOUNTS, key_message_success
|
||||
from handlers.utils import generate_random_email, get_least_loaded_cluster
|
||||
from logger import logger
|
||||
|
||||
@@ -37,51 +36,18 @@ class Form(StatesGroup):
|
||||
|
||||
|
||||
@router.callback_query(F.data == "create_key")
|
||||
async def process_callback_create_key(callback_query: CallbackQuery, state: FSMContext, session: Any):
|
||||
server_id = "все сервера"
|
||||
await state.update_data(selected_server_id=server_id)
|
||||
await select_server(callback_query, state, session)
|
||||
|
||||
|
||||
async def select_server(callback_query: CallbackQuery, state: FSMContext, session: Any):
|
||||
trial_status = await get_trial(callback_query.message.chat.id, session)
|
||||
if trial_status == 1:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="✅ Да, подключить новое устройство", callback_data="confirm_create_new_key")
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
|
||||
await callback_query.message.answer(
|
||||
text=KEY,
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
await state.update_data(creating_new_key=True)
|
||||
else:
|
||||
await handle_key_creation(callback_query.message.chat.id, state, session, callback_query)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "confirm_create_new_key")
|
||||
async def confirm_create_new_key(callback_query: CallbackQuery, state: FSMContext, session: Any):
|
||||
tg_id = callback_query.message.chat.id
|
||||
|
||||
logger.info(f"User {tg_id} confirmed creation of a new key.")
|
||||
|
||||
balance = await get_balance(tg_id)
|
||||
if balance < RENEWAL_PLANS["1"]["price"]:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
await callback_query.message.answer(NULL_BALANCE, reply_markup=builder.as_markup())
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
logger.info(f"Balance for user {tg_id} is sufficient. Proceeding with key creation.")
|
||||
|
||||
await handle_key_creation(tg_id, state, session, callback_query)
|
||||
|
||||
|
||||
async def handle_key_creation(
|
||||
tg_id: int, state: FSMContext, session: Any, message_or_query: Union[Message, CallbackQuery]
|
||||
tg_id: int, state: FSMContext, session: Any, message_or_query: Message | CallbackQuery
|
||||
):
|
||||
"""Создание ключа с учётом выбора тарифного плана."""
|
||||
current_time = datetime.utcnow()
|
||||
@@ -90,22 +56,21 @@ async def handle_key_creation(
|
||||
if trial_status == 0:
|
||||
expiry_time = current_time + timedelta(days=TRIAL_TIME)
|
||||
logger.info(f"Assigned 1-day trial to user {tg_id}.")
|
||||
|
||||
await session.execute(
|
||||
"UPDATE connections SET trial = 1 WHERE tg_id = $1", tg_id
|
||||
)
|
||||
|
||||
await session.execute("UPDATE connections SET trial = 1 WHERE tg_id = $1", tg_id)
|
||||
await create_key(tg_id, expiry_time, state, session, message_or_query)
|
||||
else:
|
||||
builder = InlineKeyboardBuilder()
|
||||
|
||||
for plan_id, price in RENEWAL_PRICES.items():
|
||||
for index, (plan_id, price) in enumerate(RENEWAL_PRICES.items()):
|
||||
discount_text = ""
|
||||
if plan_id == "3":
|
||||
discount_text = " (5% скидка)"
|
||||
elif plan_id == "6":
|
||||
discount_text = " (10% скидка)"
|
||||
elif plan_id == "12":
|
||||
discount_text = " (20% 🔥)"
|
||||
|
||||
if plan_id in DISCOUNTS:
|
||||
discount_percentage = DISCOUNTS[plan_id]
|
||||
discount_text = f" ({discount_percentage}% скидка)"
|
||||
|
||||
if index == len(RENEWAL_PRICES) - 1:
|
||||
discount_text = f" ({discount_percentage}% 🔥)"
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
@@ -122,7 +87,6 @@ async def handle_key_creation(
|
||||
await state.set_state(Form.waiting_for_server_selection)
|
||||
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("select_plan_"))
|
||||
async def select_tariff_plan(callback_query: CallbackQuery, state: FSMContext, session: Any):
|
||||
tg_id = callback_query.message.chat.id
|
||||
@@ -138,6 +102,7 @@ async def select_tariff_plan(callback_query: CallbackQuery, state: FSMContext, s
|
||||
balance = await get_balance(tg_id)
|
||||
if balance < plan_price:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="💳 Пополнить баланс", callback_data="pay"))
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
await callback_query.message.answer(
|
||||
"💳 Недостаточно средств для создания подписки. Пополните баланс в личном кабинете.",
|
||||
@@ -154,7 +119,7 @@ async def select_tariff_plan(callback_query: CallbackQuery, state: FSMContext, s
|
||||
|
||||
|
||||
async def create_key(
|
||||
tg_id: int, expiry_time: datetime, state: FSMContext, session: Any, message_or_query: Union[Message, CallbackQuery]
|
||||
tg_id: int, expiry_time: datetime, state: FSMContext, session: Any, message_or_query: Message | CallbackQuery
|
||||
):
|
||||
"""Создаёт ключ с заданным сроком действия."""
|
||||
while True:
|
||||
@@ -197,7 +162,13 @@ async def create_key(
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error while creating the key for user {tg_id} on cluster: {e}")
|
||||
await message_or_query.message.answer("❌ Произошла ошибка при создании ключа. Пожалуйста, попробуйте снова.")
|
||||
|
||||
if isinstance(message_or_query, Message):
|
||||
await message_or_query.answer("❌ Произошла ошибка при создании ключа. Пожалуйста, попробуйте снова.")
|
||||
elif isinstance(message_or_query, CallbackQuery):
|
||||
await message_or_query.message.answer(
|
||||
"❌ Произошла ошибка при создании ключа. Пожалуйста, попробуйте снова."
|
||||
)
|
||||
return
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
@@ -210,12 +181,16 @@ async def create_key(
|
||||
InlineKeyboardButton(text="🍏 Подключить на iOS", url=f"{CONNECT_IOS}{public_link}"),
|
||||
InlineKeyboardButton(text="🤖 Подключить на Android", url=f"{CONNECT_ANDROID}{public_link}"),
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="💻 Windows/Linux", callback_data=f"connect_pc|{email}"))
|
||||
builder.row(InlineKeyboardButton(text="💻 Windows/Linux/MacOS", callback_data=f"connect_pc|{email}"))
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
|
||||
remaining_time = expiry_time - datetime.utcnow()
|
||||
days = remaining_time.days
|
||||
key_message = key_message_success(public_link, f"⏳ Осталось дней: {days} 📅")
|
||||
|
||||
await message_or_query.message.answer(key_message, reply_markup=builder.as_markup())
|
||||
if isinstance(message_or_query, Message):
|
||||
await message_or_query.answer(key_message, reply_markup=builder.as_markup())
|
||||
elif isinstance(message_or_query, CallbackQuery):
|
||||
await message_or_query.message.answer(key_message, reply_markup=builder.as_markup())
|
||||
|
||||
await state.clear()
|
||||
|
||||
@@ -4,7 +4,7 @@ import asyncpg
|
||||
from py3xui import AsyncApi
|
||||
|
||||
from client import add_client, delete_client, extend_client_key
|
||||
from config import ADMIN_PASSWORD, ADMIN_USERNAME, DATABASE_URL, TOTAL_GB
|
||||
from config import ADMIN_PASSWORD, ADMIN_USERNAME, DATABASE_URL, LIMIT_IP, TOTAL_GB
|
||||
from database import get_servers_from_db
|
||||
from logger import logger
|
||||
|
||||
@@ -33,7 +33,9 @@ async def create_key_on_cluster(cluster_id, tg_id, client_id, email, expiry_time
|
||||
continue
|
||||
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
existing_key = await conn.fetchrow("SELECT 1 FROM keys WHERE email = $1", email)
|
||||
existing_key = await conn.fetchrow(
|
||||
"SELECT 1 FROM keys WHERE email = $1", email
|
||||
)
|
||||
|
||||
if existing_key:
|
||||
raise ValueError(f"Email {email} уже существует в базе данных.")
|
||||
@@ -44,7 +46,7 @@ async def create_key_on_cluster(cluster_id, tg_id, client_id, email, expiry_time
|
||||
client_id,
|
||||
email,
|
||||
tg_id,
|
||||
limit_ip=1,
|
||||
limit_ip=LIMIT_IP,
|
||||
total_gb=TOTAL_GB,
|
||||
expiry_time=expiry_timestamp,
|
||||
enable=True,
|
||||
@@ -98,7 +100,9 @@ async def renew_key_in_cluster(cluster_id, email, client_id, new_expiry_time, to
|
||||
await asyncio.gather(*tasks)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Не удалось продлить ключ {client_id} в кластере {cluster_id}: {e}")
|
||||
logger.error(
|
||||
f"Не удалось продлить ключ {client_id} в кластере {cluster_id}: {e}"
|
||||
)
|
||||
raise e
|
||||
|
||||
|
||||
@@ -145,7 +149,9 @@ async def delete_key_from_cluster(cluster_id, email, client_id):
|
||||
await asyncio.gather(*tasks)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Не удалось удалить ключ {client_id} в кластере {cluster_id}: {e}")
|
||||
logger.error(
|
||||
f"Не удалось удалить ключ {client_id} в кластере {cluster_id}: {e}"
|
||||
)
|
||||
raise e
|
||||
|
||||
|
||||
@@ -178,7 +184,7 @@ async def update_key_on_cluster(tg_id, client_id, email, expiry_time, cluster_id
|
||||
client_id,
|
||||
email,
|
||||
tg_id,
|
||||
limit_ip=1,
|
||||
limit_ip=LIMIT_IP,
|
||||
total_gb=TOTAL_GB,
|
||||
expiry_time=expiry_time,
|
||||
enable=True,
|
||||
@@ -189,8 +195,12 @@ async def update_key_on_cluster(tg_id, client_id, email, expiry_time, cluster_id
|
||||
|
||||
await asyncio.gather(*tasks)
|
||||
|
||||
logger.info(f"Ключ успешно обновлен для {client_id} на всех серверах в кластере {cluster_id}")
|
||||
logger.info(
|
||||
f"Ключ успешно обновлен для {client_id} на всех серверах в кластере {cluster_id}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при обновлении ключа на серверах кластера {cluster_id} для {client_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при обновлении ключа на серверах кластера {cluster_id} для {client_id}: {e}"
|
||||
)
|
||||
raise e
|
||||
|
||||
+210
-87
@@ -1,15 +1,30 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
import locale
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from aiogram import F, Router, types
|
||||
from aiogram.types import BufferedInputFile, InlineKeyboardButton
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
|
||||
from config import CONNECT_ANDROID, CONNECT_IOS, DOWNLOAD_ANDROID, DOWNLOAD_IOS, PUBLIC_LINK, RENEWAL_PLANS, TOTAL_GB
|
||||
from database import delete_key, get_balance, get_servers_from_db, store_key, update_balance, update_key_expiry
|
||||
from config import (
|
||||
CONNECT_ANDROID,
|
||||
CONNECT_IOS,
|
||||
DOWNLOAD_ANDROID,
|
||||
DOWNLOAD_IOS,
|
||||
PUBLIC_LINK,
|
||||
RENEWAL_PLANS,
|
||||
TOTAL_GB,
|
||||
)
|
||||
from database import (
|
||||
delete_key,
|
||||
get_balance,
|
||||
get_servers_from_db,
|
||||
store_key,
|
||||
update_balance,
|
||||
update_key_expiry,
|
||||
)
|
||||
from handlers.keys.key_utils import (
|
||||
delete_key_from_cluster,
|
||||
delete_key_from_db,
|
||||
@@ -17,9 +32,9 @@ from handlers.keys.key_utils import (
|
||||
update_key_on_cluster,
|
||||
)
|
||||
from handlers.texts import (
|
||||
DISCOUNTS,
|
||||
INSUFFICIENT_FUNDS_MSG,
|
||||
KEY_NOT_FOUND_MSG,
|
||||
NO_KEYS,
|
||||
PLAN_SELECTION_MSG,
|
||||
SUCCESS_RENEWAL_MSG,
|
||||
key_message,
|
||||
@@ -33,67 +48,106 @@ router = Router()
|
||||
|
||||
|
||||
@router.callback_query(F.data == "view_keys")
|
||||
async def process_callback_view_keys(callback_query: types.CallbackQuery, session: Any):
|
||||
tg_id = callback_query.message.chat.id
|
||||
@router.message(F.text == "/subs")
|
||||
async def process_callback_or_message_view_keys(
|
||||
callback_query_or_message: types.Message | types.CallbackQuery, session: Any
|
||||
):
|
||||
if isinstance(callback_query_or_message, types.CallbackQuery):
|
||||
chat_id = callback_query_or_message.message.chat.id
|
||||
send_message = callback_query_or_message.message.answer
|
||||
send_photo = callback_query_or_message.message.answer_photo
|
||||
else:
|
||||
chat_id = callback_query_or_message.chat.id
|
||||
send_message = callback_query_or_message.answer
|
||||
send_photo = callback_query_or_message.answer_photo
|
||||
|
||||
try:
|
||||
records = await session.fetch(
|
||||
"""
|
||||
SELECT email, client_id FROM keys WHERE tg_id = $1
|
||||
""",
|
||||
tg_id,
|
||||
""",
|
||||
chat_id,
|
||||
)
|
||||
|
||||
if records:
|
||||
builder = InlineKeyboardBuilder()
|
||||
for record in records:
|
||||
key_name = record["email"]
|
||||
builder.row(InlineKeyboardButton(text=f"🔑 {key_name}", callback_data=f"view_key|{key_name}"))
|
||||
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
|
||||
inline_keyboard = builder.as_markup()
|
||||
response_message = (
|
||||
"<b>🔑 Список ваших устройств</b>\n\n" "<i>👇 Выберите устройство для управления подпиской:</i>"
|
||||
)
|
||||
|
||||
image_path = os.path.join("img", "pic_keys.jpg")
|
||||
if os.path.isfile(image_path):
|
||||
with open(image_path, "rb") as image_file:
|
||||
await callback_query.message.answer_photo(
|
||||
photo=BufferedInputFile(image_file.read(), filename="pic_keys.jpg"),
|
||||
caption=response_message,
|
||||
reply_markup=inline_keyboard,
|
||||
)
|
||||
else:
|
||||
await callback_query.message.answer(
|
||||
text=response_message,
|
||||
reply_markup=inline_keyboard,
|
||||
)
|
||||
|
||||
inline_keyboard, response_message = build_keys_response(records)
|
||||
else:
|
||||
response_message = NO_KEYS
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="➕ Создать подписку", callback_data="create_key"))
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
inline_keyboard, response_message = build_no_keys_response()
|
||||
|
||||
keyboard = builder.as_markup()
|
||||
|
||||
image_path = os.path.join("img", "pic_keys.jpg")
|
||||
|
||||
if os.path.isfile(image_path):
|
||||
with open(image_path, "rb") as image_file:
|
||||
await callback_query.message.answer_photo(
|
||||
photo=BufferedInputFile(image_file.read(), filename="pic_keys.jpg"),
|
||||
caption=response_message,
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
else:
|
||||
await callback_query.message.answer(
|
||||
text=response_message,
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
image_path = os.path.join("img", "pic_keys.jpg")
|
||||
await send_with_optional_image(
|
||||
send_message, send_photo, image_path, response_message, inline_keyboard
|
||||
)
|
||||
except Exception as e:
|
||||
await handle_error(tg_id, callback_query, f"Ошибка при получении ключей: {e}")
|
||||
error_message = f"Ошибка при получении ключей: {e}"
|
||||
await send_message(text=error_message)
|
||||
|
||||
|
||||
def build_keys_response(records):
|
||||
"""
|
||||
Формирует сообщение и клавиатуру, если у пользователя есть устройства.
|
||||
"""
|
||||
builder = InlineKeyboardBuilder()
|
||||
for record in records:
|
||||
key_name = record["email"]
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=f"🔑 {key_name}", callback_data=f"view_key|{key_name}"
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile")
|
||||
)
|
||||
|
||||
inline_keyboard = builder.as_markup()
|
||||
response_message = (
|
||||
"<b>🔑 Список ваших устройств</b>\n\n"
|
||||
"<i>👇 Выберите устройство для управления подпиской:</i>"
|
||||
)
|
||||
return inline_keyboard, response_message
|
||||
|
||||
|
||||
def build_no_keys_response():
|
||||
"""
|
||||
Формирует сообщение и клавиатуру, если у пользователя нет устройств.
|
||||
"""
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="➕ Создать подписку", callback_data="create_key"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile")
|
||||
)
|
||||
|
||||
inline_keyboard = builder.as_markup()
|
||||
response_message = (
|
||||
"<b>❌ У вас пока нет активных устройств</b>\n\n"
|
||||
"<i>Нажмите кнопку ниже, чтобы создать устройство:</i>"
|
||||
)
|
||||
return inline_keyboard, response_message
|
||||
|
||||
|
||||
async def send_with_optional_image(send_message, send_photo, image_path, text, keyboard):
|
||||
"""
|
||||
Отправляет сообщение с изображением, если файл существует. В противном случае отправляет только текст.
|
||||
"""
|
||||
if os.path.isfile(image_path):
|
||||
with open(image_path, "rb") as image_file:
|
||||
await send_photo(
|
||||
photo=BufferedInputFile(image_file.read(), filename=os.path.basename(image_path)),
|
||||
caption=text,
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
else:
|
||||
await send_message(
|
||||
text=text,
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("view_key|"))
|
||||
@@ -120,7 +174,9 @@ async def process_callback_view_key(callback_query: types.CallbackQuery, session
|
||||
time_left = expiry_date - current_date
|
||||
|
||||
if time_left.total_seconds() <= 0:
|
||||
days_left_message = "<b>🕒 Статус подписки:</b>\n🔴 Истекла\nОсталось часов: 0"
|
||||
days_left_message = (
|
||||
"<b>🕒 Статус подписки:</b>\n🔴 Истекла\nОсталось часов: 0"
|
||||
)
|
||||
elif time_left.days > 0:
|
||||
days_left_message = f"Осталось дней: <b>{time_left.days}</b>"
|
||||
else:
|
||||
@@ -128,33 +184,57 @@ async def process_callback_view_key(callback_query: types.CallbackQuery, session
|
||||
days_left_message = f"Осталось часов: <b>{hours_left}</b>"
|
||||
|
||||
formatted_expiry_date = expiry_date.strftime("%d %B %Y года")
|
||||
response_message = key_message(key, formatted_expiry_date, days_left_message, server_name)
|
||||
response_message = key_message(
|
||||
key, formatted_expiry_date, days_left_message, server_name
|
||||
)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🍏 Скачать для iOS", url=DOWNLOAD_IOS),
|
||||
InlineKeyboardButton(text="🤖 Скачать для Android", url=DOWNLOAD_ANDROID),
|
||||
InlineKeyboardButton(
|
||||
text="🤖 Скачать для Android", url=DOWNLOAD_ANDROID
|
||||
),
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🍏 Подключить на iOS", url=f"{CONNECT_IOS}{key}"),
|
||||
InlineKeyboardButton(text="🤖 Подключить на Android", url=f"{CONNECT_ANDROID}{key}"),
|
||||
InlineKeyboardButton(
|
||||
text="🍏 Подключить на iOS", url=f"{CONNECT_IOS}{key}"
|
||||
),
|
||||
InlineKeyboardButton(
|
||||
text="🤖 Подключить на Android", url=f"{CONNECT_ANDROID}{key}"
|
||||
),
|
||||
)
|
||||
|
||||
builder.row(InlineKeyboardButton(text="💻 Windows/Linux", callback_data=f"connect_pc|{key_name}"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="💻 Компьютеры", callback_data=f"connect_pc|{key_name}"
|
||||
),
|
||||
InlineKeyboardButton(
|
||||
text="📺 Андроид TV", callback_data=f"connect_tv|{key_name}"
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="⏳ Продлить", callback_data=f"renew_key|{key_name}"),
|
||||
InlineKeyboardButton(text="❌ Удалить", callback_data=f"delete_key|{key_name}"),
|
||||
InlineKeyboardButton(
|
||||
text="⏳ Продлить", callback_data=f"renew_key|{key_name}"
|
||||
),
|
||||
InlineKeyboardButton(
|
||||
text="❌ Удалить", callback_data=f"delete_key|{key_name}"
|
||||
),
|
||||
)
|
||||
|
||||
if not key.startswith(PUBLIC_LINK):
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🔄 Обновить подписку", callback_data=f"update_subscription|{key_name}")
|
||||
InlineKeyboardButton(
|
||||
text="🔄 Обновить подписку",
|
||||
callback_data=f"update_subscription|{key_name}",
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile")
|
||||
)
|
||||
|
||||
keyboard = builder.as_markup()
|
||||
|
||||
@@ -183,7 +263,9 @@ async def process_callback_view_key(callback_query: types.CallbackQuery, session
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("update_subscription|"))
|
||||
async def process_callback_update_subscription(callback_query: types.CallbackQuery, session: Any):
|
||||
async def process_callback_update_subscription(
|
||||
callback_query: types.CallbackQuery, session: Any
|
||||
):
|
||||
tg_id = callback_query.message.chat.id
|
||||
email = callback_query.data.split("|")[1]
|
||||
try:
|
||||
@@ -243,7 +325,9 @@ async def process_callback_update_subscription(callback_query: types.CallbackQue
|
||||
else:
|
||||
await callback_query.message.answer("<b>Ключ не найден в базе данных.</b>")
|
||||
except Exception as e:
|
||||
await handle_error(tg_id, callback_query, f"Ошибка при обновлении подписки: {e}")
|
||||
await handle_error(
|
||||
tg_id, callback_query, f"Ошибка при обновлении подписки: {e}"
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("delete_key|"))
|
||||
@@ -258,7 +342,11 @@ async def process_callback_delete_key(callback_query: types.CallbackQuery):
|
||||
callback_data=f"confirm_delete|{client_id}",
|
||||
)
|
||||
],
|
||||
[types.InlineKeyboardButton(text="❌ Нет, отменить", callback_data="view_keys")],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="❌ Нет, отменить", callback_data="view_keys"
|
||||
)
|
||||
],
|
||||
]
|
||||
)
|
||||
|
||||
@@ -290,39 +378,46 @@ async def process_callback_renew_key(callback_query: types.CallbackQuery, sessio
|
||||
expiry_time = record["expiry_time"]
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=f'📅 1 месяц ({RENEWAL_PLANS["1"]["price"]} руб.)',
|
||||
callback_data=f"renew_plan|1|{client_id}",
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=f'📅 3 месяца ({RENEWAL_PLANS["3"]["price"]} руб.) 5% скидка',
|
||||
text=f'📅 3 месяца ({RENEWAL_PLANS["3"]["price"]} руб.) {DISCOUNTS["3"]}% скидка',
|
||||
callback_data=f"renew_plan|3|{client_id}",
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=f'📅 6 месяцев ({RENEWAL_PLANS["6"]["price"]} руб.) 10% скидка',
|
||||
text=f'📅 6 месяцев ({RENEWAL_PLANS["6"]["price"]} руб.) {DISCOUNTS["6"]}% скидка',
|
||||
callback_data=f"renew_plan|6|{client_id}",
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=f'📅 12 месяцев ({RENEWAL_PLANS["12"]["price"]} руб.) (20% 🔥)',
|
||||
text=f'📅 12 месяцев ({RENEWAL_PLANS["12"]["price"]} руб.) ({DISCOUNTS["12"]}% 🔥)',
|
||||
callback_data=f"renew_plan|12|{client_id}",
|
||||
)
|
||||
)
|
||||
|
||||
back_button = InlineKeyboardButton(text="🔙 Назад", callback_data="view_keys")
|
||||
back_button = InlineKeyboardButton(
|
||||
text="🔙 Назад", callback_data="view_keys"
|
||||
)
|
||||
builder.row(back_button)
|
||||
|
||||
balance = await get_balance(tg_id)
|
||||
|
||||
response_message = PLAN_SELECTION_MSG.format(
|
||||
balance=balance,
|
||||
expiry_date=datetime.utcfromtimestamp(expiry_time / 1000).strftime("%Y-%m-%d %H:%M:%S"),
|
||||
expiry_date=datetime.utcfromtimestamp(expiry_time / 1000).strftime(
|
||||
"%Y-%m-%d %H:%M:%S"
|
||||
),
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
@@ -336,15 +431,21 @@ async def process_callback_renew_key(callback_query: types.CallbackQuery, sessio
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("confirm_delete|"))
|
||||
async def process_callback_confirm_delete(callback_query: types.CallbackQuery, session: Any):
|
||||
async def process_callback_confirm_delete(
|
||||
callback_query: types.CallbackQuery, session: Any
|
||||
):
|
||||
email = callback_query.data.split("|")[1]
|
||||
try:
|
||||
record = await session.fetchrow("SELECT client_id FROM keys WHERE email = $1", email)
|
||||
record = await session.fetchrow(
|
||||
"SELECT client_id FROM keys WHERE email = $1", email
|
||||
)
|
||||
|
||||
if record:
|
||||
client_id = record["client_id"]
|
||||
response_message = "Ключ успешно удален."
|
||||
back_button = types.InlineKeyboardButton(text="Назад", callback_data="view_keys")
|
||||
back_button = types.InlineKeyboardButton(
|
||||
text="Назад", callback_data="view_keys"
|
||||
)
|
||||
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[back_button]])
|
||||
|
||||
await delete_key(client_id)
|
||||
@@ -359,7 +460,9 @@ async def process_callback_confirm_delete(callback_query: types.CallbackQuery, s
|
||||
try:
|
||||
tasks = []
|
||||
for cluster_id, cluster in servers.items():
|
||||
tasks.append(delete_key_from_cluster(cluster_id, email, client_id))
|
||||
tasks.append(
|
||||
delete_key_from_cluster(cluster_id, email, client_id)
|
||||
)
|
||||
|
||||
await asyncio.gather(*tasks)
|
||||
|
||||
@@ -372,7 +475,9 @@ async def process_callback_confirm_delete(callback_query: types.CallbackQuery, s
|
||||
|
||||
else:
|
||||
response_message = "Ключ не найден или уже удален."
|
||||
back_button = types.InlineKeyboardButton(text="Назад", callback_data="view_keys")
|
||||
back_button = types.InlineKeyboardButton(
|
||||
text="Назад", callback_data="view_keys"
|
||||
)
|
||||
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[back_button]])
|
||||
|
||||
await callback_query.message.answer(
|
||||
@@ -384,7 +489,9 @@ async def process_callback_confirm_delete(callback_query: types.CallbackQuery, s
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("renew_plan|"))
|
||||
async def process_callback_renew_plan(callback_query: types.CallbackQuery, session: Any):
|
||||
async def process_callback_renew_plan(
|
||||
callback_query: types.CallbackQuery, session: Any
|
||||
):
|
||||
tg_id = callback_query.message.chat.id
|
||||
plan, client_id = (
|
||||
callback_query.data.split("|")[1],
|
||||
@@ -407,17 +514,27 @@ async def process_callback_renew_plan(callback_query: types.CallbackQuery, sessi
|
||||
current_time = datetime.utcnow().timestamp() * 1000
|
||||
|
||||
if expiry_time <= current_time:
|
||||
new_expiry_time = int(current_time + timedelta(days=days_to_extend).total_seconds() * 1000)
|
||||
new_expiry_time = int(
|
||||
current_time + timedelta(days=days_to_extend).total_seconds() * 1000
|
||||
)
|
||||
else:
|
||||
new_expiry_time = int(expiry_time + timedelta(days=days_to_extend).total_seconds() * 1000)
|
||||
new_expiry_time = int(
|
||||
expiry_time + timedelta(days=days_to_extend).total_seconds() * 1000
|
||||
)
|
||||
|
||||
cost = RENEWAL_PLANS[plan]["price"]
|
||||
|
||||
balance = await get_balance(tg_id)
|
||||
if balance < cost:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="Пополнить баланс", callback_data="pay"))
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="Пополнить баланс", callback_data="pay")
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="👤 Личный кабинет", callback_data="profile"
|
||||
)
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
INSUFFICIENT_FUNDS_MSG,
|
||||
@@ -425,11 +542,17 @@ async def process_callback_renew_plan(callback_query: types.CallbackQuery, sessi
|
||||
)
|
||||
return
|
||||
|
||||
response_message = SUCCESS_RENEWAL_MSG.format(months=RENEWAL_PLANS[plan]["months"])
|
||||
response_message = SUCCESS_RENEWAL_MSG.format(
|
||||
months=RENEWAL_PLANS[plan]["months"]
|
||||
)
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile")
|
||||
)
|
||||
|
||||
await callback_query.message.answer(response_message, reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
response_message, reply_markup=builder.as_markup()
|
||||
)
|
||||
|
||||
servers = await get_servers_from_db()
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@ import base64
|
||||
from datetime import datetime
|
||||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
import asyncpg
|
||||
from aiohttp import web
|
||||
|
||||
from config import DATABASE_URL, TRANSITION_DATE_STR
|
||||
from config import DATABASE_URL, PROJECT_NAME, SUB_MESSAGE, TRANSITION_DATE_STR
|
||||
from database import get_servers_from_db
|
||||
from logger import logger
|
||||
|
||||
@@ -20,7 +20,9 @@ async def fetch_url_content(url, tg_id):
|
||||
logger.info(f"Успешно получен контент с {url} для tg_id: {tg_id}")
|
||||
return base64.b64decode(content).decode("utf-8").split("\n")
|
||||
else:
|
||||
logger.error(f"Не удалось получить {url} для tg_id: {tg_id}, статус: {response.status}")
|
||||
logger.error(
|
||||
f"Не удалось получить {url} для tg_id: {tg_id}, статус: {response.status}"
|
||||
)
|
||||
return []
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при получении {url} для tg_id: {tg_id}: {e}")
|
||||
@@ -29,7 +31,9 @@ async def fetch_url_content(url, tg_id):
|
||||
|
||||
async def combine_unique_lines(urls, tg_id, query_string):
|
||||
all_lines = []
|
||||
logger.info(f"Начинаем объединение подписок для tg_id: {tg_id}, запрос: {query_string}")
|
||||
logger.info(
|
||||
f"Начинаем объединение подписок для tg_id: {tg_id}, запрос: {query_string}"
|
||||
)
|
||||
|
||||
urls_with_query = [f"{url}?{query_string}" for url in urls]
|
||||
logger.info(f"Составлены URL-адреса: {urls_with_query}")
|
||||
@@ -39,7 +43,9 @@ async def combine_unique_lines(urls, tg_id, query_string):
|
||||
all_lines.extend(lines)
|
||||
|
||||
all_lines = list(set(filter(None, all_lines)))
|
||||
logger.info(f"Объединено {len(all_lines)} строк после фильтрации и удаления дубликатов для tg_id: {tg_id}")
|
||||
logger.info(
|
||||
f"Объединено {len(all_lines)} строк после фильтрации и удаления дубликатов для tg_id: {tg_id}"
|
||||
)
|
||||
|
||||
return all_lines
|
||||
|
||||
@@ -50,7 +56,9 @@ transition_timestamp_ms = int(transition_date.timestamp() * 1000)
|
||||
|
||||
transition_timestamp_ms_adjusted = transition_timestamp_ms - (3 * 60 * 60 * 1000)
|
||||
|
||||
logger.info(f"Время перехода (с поправкой на часовой пояс): {transition_timestamp_ms_adjusted}")
|
||||
logger.info(
|
||||
f"Время перехода (с поправкой на часовой пояс): {transition_timestamp_ms_adjusted}"
|
||||
)
|
||||
|
||||
|
||||
async def handle_old_subscription(request):
|
||||
@@ -67,7 +75,9 @@ async def handle_old_subscription(request):
|
||||
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
try:
|
||||
key_info = await conn.fetchrow("SELECT created_at FROM keys WHERE email = $1", email)
|
||||
key_info = await conn.fetchrow(
|
||||
"SELECT created_at, server_id FROM keys WHERE email = $1", email
|
||||
)
|
||||
|
||||
if not key_info:
|
||||
logger.warning(f"Клиент с email {email} не найден в базе.")
|
||||
@@ -77,10 +87,20 @@ async def handle_old_subscription(request):
|
||||
)
|
||||
|
||||
created_at_ms = key_info["created_at"]
|
||||
logger.info(f"Значение created_at для клиента с email {email}: {created_at_ms}")
|
||||
cluster_name = key_info.get("server_id")
|
||||
if not cluster_name:
|
||||
logger.warning(f"У клиента с email {email} отсутствует cluster_name.")
|
||||
return web.Response(
|
||||
text="❌ Устаревшие данные. Обратитесь в поддержку.",
|
||||
status=400,
|
||||
)
|
||||
|
||||
logger.info(f"Значение created_at для клиента с email {email}: {created_at_ms}, кластер: {cluster_name}")
|
||||
|
||||
created_at_datetime = datetime.utcfromtimestamp(created_at_ms / 1000)
|
||||
logger.info(f"Время создания клиента в формате datetime (UTC): {created_at_datetime}")
|
||||
logger.info(
|
||||
f"Время создания клиента в формате datetime (UTC): {created_at_datetime}"
|
||||
)
|
||||
|
||||
if created_at_ms >= transition_timestamp_ms_adjusted:
|
||||
logger.info(f"Клиент с email {email} является новым.")
|
||||
@@ -90,22 +110,28 @@ async def handle_old_subscription(request):
|
||||
)
|
||||
|
||||
servers = await get_servers_from_db()
|
||||
cluster_servers = servers.get(cluster_name, [])
|
||||
logger.info(f"Сервера в кластере: {cluster_servers}")
|
||||
|
||||
urls = []
|
||||
for cluster_name, cluster_servers in servers.items():
|
||||
for server in cluster_servers:
|
||||
server_subscription_url = f"{server['subscription_url']}/{email}"
|
||||
urls.append(server_subscription_url)
|
||||
for server in cluster_servers:
|
||||
server_subscription_url = f"{server['subscription_url']}/{email}"
|
||||
urls.append(server_subscription_url)
|
||||
|
||||
combined_subscriptions = await combine_unique_lines(urls, email, "")
|
||||
|
||||
base64_encoded = base64.b64encode("\n".join(combined_subscriptions).encode("utf-8")).decode("utf-8")
|
||||
base64_encoded = base64.b64encode(
|
||||
"\n".join(combined_subscriptions).encode("utf-8")
|
||||
).decode("utf-8")
|
||||
|
||||
encoded_project_name = f"{PROJECT_NAME} - {SUB_MESSAGE}"
|
||||
headers = {
|
||||
"Content-Type": "text/plain; charset=utf-8",
|
||||
"Content-Disposition": "inline",
|
||||
"profile-update-interval": "7",
|
||||
"profile-title": email,
|
||||
"profile-title": "base64:" + base64.b64encode(
|
||||
encoded_project_name.encode("utf-8")
|
||||
).decode("utf-8"),
|
||||
}
|
||||
|
||||
logger.info(f"Возвращаем объединенные подписки для email: {email}")
|
||||
@@ -115,6 +141,7 @@ async def handle_old_subscription(request):
|
||||
await conn.close()
|
||||
|
||||
|
||||
|
||||
async def handle_new_subscription(request):
|
||||
email = request.match_info.get("email")
|
||||
tg_id = request.match_info.get("tg_id")
|
||||
@@ -130,7 +157,10 @@ async def handle_new_subscription(request):
|
||||
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
try:
|
||||
client_data = await conn.fetchrow("SELECT tg_id FROM keys WHERE email = $1", email)
|
||||
|
||||
client_data = await conn.fetchrow(
|
||||
"SELECT tg_id, server_id FROM keys WHERE email = $1", email
|
||||
)
|
||||
|
||||
if not client_data:
|
||||
logger.warning(f"Клиент с email {email} не найден в базе.")
|
||||
@@ -140,6 +170,7 @@ async def handle_new_subscription(request):
|
||||
)
|
||||
|
||||
stored_tg_id = client_data["tg_id"]
|
||||
cluster_name = client_data["server_id"]
|
||||
|
||||
if str(tg_id) != str(stored_tg_id):
|
||||
logger.warning(f"Неверный tg_id для клиента с email {email}.")
|
||||
@@ -147,29 +178,36 @@ async def handle_new_subscription(request):
|
||||
text="❌ Неверные данные. Получите свой ключ в боте.",
|
||||
status=403,
|
||||
)
|
||||
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
servers = await get_servers_from_db()
|
||||
cluster_servers = servers.get(cluster_name, [])
|
||||
|
||||
urls = []
|
||||
for cluster_name, cluster_servers in servers.items():
|
||||
for server in cluster_servers:
|
||||
server_subscription_url = f"{server['subscription_url']}/{email}"
|
||||
urls.append(server_subscription_url)
|
||||
for server in cluster_servers:
|
||||
server_subscription_url = f"{server['subscription_url']}/{email}"
|
||||
urls.append(server_subscription_url)
|
||||
|
||||
query_string = request.query_string
|
||||
logger.info(f"Извлечен query string: {query_string}")
|
||||
|
||||
combined_subscriptions = await combine_unique_lines(urls, tg_id, query_string)
|
||||
|
||||
base64_encoded = base64.b64encode("\n".join(combined_subscriptions).encode("utf-8")).decode("utf-8")
|
||||
base64_encoded = base64.b64encode(
|
||||
"\n".join(combined_subscriptions).encode("utf-8")
|
||||
).decode("utf-8")
|
||||
|
||||
encoded_project_name = f"{PROJECT_NAME} - {SUB_MESSAGE}"
|
||||
|
||||
headers = {
|
||||
"Content-Type": "text/plain; charset=utf-8",
|
||||
"Content-Disposition": "inline",
|
||||
"profile-update-interval": "7",
|
||||
"profile-title": email,
|
||||
"profile-title": "base64:" + base64.b64encode(
|
||||
encoded_project_name.encode("utf-8")
|
||||
).decode("utf-8"),
|
||||
}
|
||||
|
||||
logger.info(f"Возвращаем объединенные подписки для email: {email}")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import asyncio
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
from py3xui import AsyncApi
|
||||
|
||||
|
||||
+90
-29
@@ -1,12 +1,20 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import asyncpg
|
||||
from aiogram import Bot, Router, types
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
import asyncpg
|
||||
from py3xui import AsyncApi
|
||||
|
||||
from config import ADMIN_PASSWORD, ADMIN_USERNAME, DATABASE_URL, DEV_MODE, RENEWAL_PLANS, TOTAL_GB, TRIAL_TIME
|
||||
from config import (
|
||||
ADMIN_PASSWORD,
|
||||
ADMIN_USERNAME,
|
||||
DATABASE_URL,
|
||||
DEV_MODE,
|
||||
RENEWAL_PLANS,
|
||||
TOTAL_GB,
|
||||
TRIAL_TIME,
|
||||
)
|
||||
from database import (
|
||||
add_notification,
|
||||
check_notification_time,
|
||||
@@ -30,8 +38,12 @@ async def notify_expiring_keys(bot: Bot):
|
||||
logger.info("Подключение к базе данных успешно.")
|
||||
|
||||
current_time = int(datetime.utcnow().timestamp() * 1000)
|
||||
threshold_time_10h = int((datetime.utcnow() + timedelta(hours=10)).timestamp() * 1000)
|
||||
threshold_time_24h = int((datetime.utcnow() + timedelta(days=1)).timestamp() * 1000)
|
||||
threshold_time_10h = int(
|
||||
(datetime.utcnow() + timedelta(hours=10)).timestamp() * 1000
|
||||
)
|
||||
threshold_time_24h = int(
|
||||
(datetime.utcnow() + timedelta(days=1)).timestamp() * 1000
|
||||
)
|
||||
|
||||
logger.info("Начало обработки уведомлений.")
|
||||
|
||||
@@ -60,10 +72,14 @@ async def is_bot_blocked(bot: Bot, chat_id: int) -> bool:
|
||||
try:
|
||||
member = await bot.get_chat_member(chat_id, bot.id)
|
||||
blocked = member.status == "left"
|
||||
logger.info(f"Статус бота для пользователя {chat_id}: {'заблокирован' if blocked else 'активен'}")
|
||||
logger.info(
|
||||
f"Статус бота для пользователя {chat_id}: {'заблокирован' if blocked else 'активен'}"
|
||||
)
|
||||
return blocked
|
||||
except Exception as e:
|
||||
logger.warning(f"Не удалось проверить статус бота для пользователя {chat_id}: {e}")
|
||||
logger.warning(
|
||||
f"Не удалось проверить статус бота для пользователя {chat_id}: {e}"
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
@@ -110,7 +126,9 @@ async def notify_10h_keys(
|
||||
if not await is_bot_blocked(bot, tg_id) and not DEV_MODE:
|
||||
try:
|
||||
keyboard = InlineKeyboardBuilder()
|
||||
keyboard.button(text="🔄 Продлить VPN", callback_data=f'renew_key|{email}')
|
||||
keyboard.button(
|
||||
text="🔄 Продлить VPN", callback_data=f"renew_key|{email}"
|
||||
)
|
||||
keyboard.button(text="💳 Пополнить баланс", callback_data="pay")
|
||||
keyboard.button(text="👤 Личный кабинет", callback_data="profile")
|
||||
keyboard.adjust(1)
|
||||
@@ -118,7 +136,9 @@ async def notify_10h_keys(
|
||||
await bot.send_message(tg_id, message, reply_markup=keyboard)
|
||||
logger.info(f"Уведомление отправлено пользователю {tg_id}.")
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при отправке уведомления пользователю {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при отправке уведомления пользователю {tg_id}: {e}"
|
||||
)
|
||||
continue
|
||||
|
||||
await conn.execute(
|
||||
@@ -177,7 +197,7 @@ async def notify_24h_keys(
|
||||
builder.row(
|
||||
types.InlineKeyboardButton(
|
||||
text="🔄 Продлить VPN",
|
||||
callback_data=f'renew_key|{email}',
|
||||
callback_data=f"renew_key|{email}",
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
@@ -196,14 +216,18 @@ async def notify_24h_keys(
|
||||
await bot.send_message(tg_id, message_24h, reply_markup=keyboard)
|
||||
logger.info(f"Уведомление за 24 часа отправлено пользователю {tg_id}.")
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при отправке уведомления за 24 часа пользователю {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при отправке уведомления за 24 часа пользователю {tg_id}: {e}"
|
||||
)
|
||||
continue
|
||||
|
||||
await conn.execute(
|
||||
"UPDATE keys SET notified_24h = TRUE WHERE client_id = $1",
|
||||
record["client_id"],
|
||||
)
|
||||
logger.info(f"Обновлено поле notified_24h для клиента {record['client_id']}.")
|
||||
logger.info(
|
||||
f"Обновлено поле notified_24h для клиента {record['client_id']}."
|
||||
)
|
||||
|
||||
await asyncio.sleep(1)
|
||||
|
||||
@@ -225,18 +249,27 @@ async def notify_inactive_trial_users(bot: Bot, conn: asyncpg.Connection):
|
||||
logger.info(f"Найдено {len(inactive_trial_users)} неактивных пользователей.")
|
||||
|
||||
for user in inactive_trial_users:
|
||||
tg_id = user['tg_id']
|
||||
username = user.get('username', 'Пользователь')
|
||||
tg_id = user["tg_id"]
|
||||
username = user.get("username", "Пользователь")
|
||||
|
||||
try:
|
||||
can_notify = await check_notification_time(tg_id, 'inactive_trial', hours=24, session=conn)
|
||||
can_notify = await check_notification_time(
|
||||
tg_id, "inactive_trial", hours=24, session=conn
|
||||
)
|
||||
|
||||
if can_notify and not await is_bot_blocked(bot, tg_id):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
types.InlineKeyboardButton(text="🚀 Активировать пробный период", callback_data="create_key")
|
||||
types.InlineKeyboardButton(
|
||||
text="🚀 Активировать пробный период",
|
||||
callback_data="create_key",
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
types.InlineKeyboardButton(
|
||||
text="👤 Личный кабинет", callback_data="profile"
|
||||
)
|
||||
)
|
||||
builder.row(types.InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
keyboard = builder.as_markup()
|
||||
|
||||
message = (
|
||||
@@ -249,10 +282,12 @@ async def notify_inactive_trial_users(bot: Bot, conn: asyncpg.Connection):
|
||||
await bot.send_message(tg_id, message, reply_markup=keyboard)
|
||||
logger.info(f"Отправлено уведомление неактивному пользователю {tg_id}.")
|
||||
|
||||
await add_notification(tg_id, 'inactive_trial', session=conn)
|
||||
await add_notification(tg_id, "inactive_trial", session=conn)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при отправке уведомления неактивному пользователю {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при отправке уведомления неактивному пользователю {tg_id}: {e}"
|
||||
)
|
||||
|
||||
await asyncio.sleep(1)
|
||||
|
||||
@@ -286,20 +321,32 @@ async def process_key(record, bot, conn):
|
||||
f"Время истечения ключа: {expiry_time} (дата: {expiry_date}), Текущее время: {current_date}, Оставшееся время: {time_left}"
|
||||
)
|
||||
keyboard = types.InlineKeyboardMarkup(
|
||||
inline_keyboard=[[types.InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile")]]
|
||||
inline_keyboard=[
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text="👤 Личный кабинет", callback_data="profile"
|
||||
)
|
||||
]
|
||||
]
|
||||
)
|
||||
|
||||
try:
|
||||
if balance >= RENEWAL_PLANS["1"]["price"]:
|
||||
await update_balance(tg_id, -RENEWAL_PLANS["1"]["price"])
|
||||
new_expiry_time = int((datetime.utcnow() + timedelta(days=30)).timestamp() * 1000)
|
||||
new_expiry_time = int(
|
||||
(datetime.utcnow() + timedelta(days=30)).timestamp() * 1000
|
||||
)
|
||||
await update_key_expiry(client_id, new_expiry_time)
|
||||
|
||||
servers = await get_servers_from_db()
|
||||
|
||||
for cluster_id in servers:
|
||||
await renew_key_in_cluster(cluster_id, email, client_id, new_expiry_time, TOTAL_GB)
|
||||
logger.info(f"Ключ для пользователя {tg_id} успешно продлен в кластере {cluster_id}.")
|
||||
await renew_key_in_cluster(
|
||||
cluster_id, email, client_id, new_expiry_time, TOTAL_GB
|
||||
)
|
||||
logger.info(
|
||||
f"Ключ для пользователя {tg_id} успешно продлен в кластере {cluster_id}."
|
||||
)
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -309,10 +356,14 @@ async def process_key(record, bot, conn):
|
||||
""",
|
||||
client_id,
|
||||
)
|
||||
logger.info(f"Флаги notified и notified_24 сброшены для клиента с ID {client_id}.")
|
||||
logger.info(
|
||||
f"Флаги notified и notified_24 сброшены для клиента с ID {client_id}."
|
||||
)
|
||||
try:
|
||||
await bot.send_message(tg_id, text=KEY_RENEWED, reply_markup=keyboard)
|
||||
logger.info(f"Уведомление об успешном продлении отправлено клиенту {tg_id}.")
|
||||
logger.info(
|
||||
f"Уведомление об успешном продлении отправлено клиенту {tg_id}."
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при отправке уведомления клиенту {tg_id}: {e}")
|
||||
|
||||
@@ -320,10 +371,16 @@ async def process_key(record, bot, conn):
|
||||
message_expired = "Ваша подписка истекла и была удалена. Получите новую через личный кабинет"
|
||||
|
||||
try:
|
||||
await bot.send_message(tg_id, text=message_expired, reply_markup=keyboard)
|
||||
logger.info(f"Уведомление об истечении подписки и удалении ключа отправлено пользователю {tg_id}.")
|
||||
await bot.send_message(
|
||||
tg_id, text=message_expired, reply_markup=keyboard
|
||||
)
|
||||
logger.info(
|
||||
f"Уведомление об истечении подписки и удалении ключа отправлено пользователю {tg_id}."
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при отправке уведомления об истечении подписки пользователю {tg_id}: {e}")
|
||||
logger.error(
|
||||
f"Ошибка при отправке уведомления об истечении подписки пользователю {tg_id}: {e}"
|
||||
)
|
||||
|
||||
servers = await get_servers_from_db()
|
||||
|
||||
@@ -343,7 +400,9 @@ async def check_online_users():
|
||||
|
||||
for cluster_id, cluster in servers.items():
|
||||
for server_id, server in enumerate(cluster):
|
||||
xui = AsyncApi(server["api_url"], username=ADMIN_USERNAME, password=ADMIN_PASSWORD)
|
||||
xui = AsyncApi(
|
||||
server["api_url"], username=ADMIN_USERNAME, password=ADMIN_PASSWORD
|
||||
)
|
||||
await xui.login()
|
||||
try:
|
||||
online_users = len(await xui.client.online())
|
||||
@@ -351,4 +410,6 @@ async def check_online_users():
|
||||
f"Сервер '{server['server_name']}' доступен, текущее количество активных пользователей: {online_users}."
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Не удалось проверить пользователей на сервере {server_id}: {e}")
|
||||
logger.error(
|
||||
f"Не удалось проверить пользователей на сервере {server_id}: {e}"
|
||||
)
|
||||
|
||||
+20
-2
@@ -2,7 +2,15 @@ from aiogram import F, Router
|
||||
from aiogram.types import CallbackQuery, InlineKeyboardButton
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
|
||||
from config import CRYPTO_BOT_ENABLE, FREEKASSA_ENABLE, ROBOKASSA_ENABLE, STARS_ENABLE, YOOKASSA_ENABLE
|
||||
from config import (
|
||||
CRYPTO_BOT_ENABLE,
|
||||
DONATIONS_ENABLE,
|
||||
FREEKASSA_ENABLE,
|
||||
ROBOKASSA_ENABLE,
|
||||
STARS_ENABLE,
|
||||
YOOKASSA_ENABLE,
|
||||
YOOMONEY_ENABLE,
|
||||
)
|
||||
|
||||
router = Router()
|
||||
|
||||
@@ -18,6 +26,13 @@ async def handle_pay(callback_query: CallbackQuery):
|
||||
callback_data="pay_yookassa",
|
||||
)
|
||||
)
|
||||
if YOOMONEY_ENABLE:
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="💳 ЮМани: оплата по карте",
|
||||
callback_data="pay_yoomoney",
|
||||
)
|
||||
)
|
||||
if FREEKASSA_ENABLE:
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
@@ -46,8 +61,11 @@ async def handle_pay(callback_query: CallbackQuery):
|
||||
callback_data="pay_robokassa",
|
||||
)
|
||||
)
|
||||
|
||||
builder.row(InlineKeyboardButton(text="🎟️ Активировать купон", callback_data="activate_coupon"))
|
||||
builder.row(InlineKeyboardButton(text="💰 Поддержать проект", callback_data="donate"))
|
||||
if DONATIONS_ENABLE:
|
||||
builder.row(InlineKeyboardButton(text="💰 Поддержать проект", callback_data="donate"))
|
||||
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
|
||||
await callback_query.message.answer(
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
__all__ = ("router",)
|
||||
|
||||
from aiogram import Router
|
||||
|
||||
from config import (
|
||||
CRYPTO_BOT_ENABLE,
|
||||
FREEKASSA_ENABLE,
|
||||
ROBOKASSA_ENABLE,
|
||||
STARS_ENABLE,
|
||||
YOOKASSA_ENABLE,
|
||||
YOOMONEY_ENABLE,
|
||||
)
|
||||
|
||||
from .cryprobot_pay import router as cryprobot_router
|
||||
from .gift import router as gift_router
|
||||
from .robokassa_pay import router as robokassa_router
|
||||
from .stars_pay import router as stars_router
|
||||
from .yookassa_pay import router as yookassa_router
|
||||
from .yoomoney_pay import router as yoomoney_router
|
||||
|
||||
router = Router(name="payments_main_router")
|
||||
|
||||
if YOOKASSA_ENABLE:
|
||||
router.include_router(yookassa_router)
|
||||
if YOOMONEY_ENABLE:
|
||||
router.include_router(yoomoney_router)
|
||||
if ROBOKASSA_ENABLE:
|
||||
router.include_router(robokassa_router)
|
||||
if CRYPTO_BOT_ENABLE:
|
||||
router.include_router(cryprobot_router)
|
||||
if STARS_ENABLE:
|
||||
router.include_router(stars_router)
|
||||
|
||||
router.include_router(gift_router)
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1,179 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from aiocryptopay import AioCryptoPay, Networks
|
||||
from aiogram import F, Router, types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.fsm.state import State, StatesGroup
|
||||
from aiogram.types import InlineKeyboardButton
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
from aiohttp import web
|
||||
|
||||
from config import CRYPTO_BOT_ENABLE, CRYPTO_BOT_TOKEN, RUB_TO_USDT
|
||||
from database import add_connection, add_payment, check_connection_exists, get_key_count, update_balance
|
||||
from handlers.payments.utils import send_payment_success_notification
|
||||
from handlers.texts import PAYMENT_OPTIONS
|
||||
from logger import logger
|
||||
|
||||
router = Router()
|
||||
|
||||
if CRYPTO_BOT_ENABLE:
|
||||
crypto = AioCryptoPay(token=CRYPTO_BOT_TOKEN, network=Networks.MAIN_NET)
|
||||
|
||||
|
||||
class ReplenishBalanceState(StatesGroup):
|
||||
choosing_amount_crypto = State()
|
||||
waiting_for_payment_confirmation_crypto = State()
|
||||
entering_custom_amount_crypto = State()
|
||||
|
||||
|
||||
@router.callback_query(F.data == "pay_cryptobot")
|
||||
async def process_callback_pay_cryptobot(callback_query: types.CallbackQuery, state: FSMContext, session: Any):
|
||||
builder = InlineKeyboardBuilder()
|
||||
for i in range(0, len(PAYMENT_OPTIONS), 2):
|
||||
if i + 1 < len(PAYMENT_OPTIONS):
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i]["text"],
|
||||
callback_data=f'crypto_{PAYMENT_OPTIONS[i]["callback_data"]}',
|
||||
),
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i + 1]["text"],
|
||||
callback_data=f'crypto_{PAYMENT_OPTIONS[i + 1]["callback_data"]}',
|
||||
),
|
||||
)
|
||||
else:
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i]["text"],
|
||||
callback_data=f'crypto_{PAYMENT_OPTIONS[i]["callback_data"]}',
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="💰 Ввести свою сумму",
|
||||
callback_data="enter_custom_amount_crypto",
|
||||
)
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="⬅️ Назад", callback_data="pay"))
|
||||
key_count = await get_key_count(callback_query.message.chat.id)
|
||||
if key_count == 0:
|
||||
exists = await check_connection_exists(callback_query.message.chat.id)
|
||||
if not exists:
|
||||
await add_connection(tg_id=callback_query.message.chat.id, balance=0.0, trial=0, session=session)
|
||||
await callback_query.message.answer(
|
||||
"Выберите сумму пополнения:",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
await state.set_state(ReplenishBalanceState.choosing_amount_crypto)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("crypto_amount|"))
|
||||
async def process_amount_selection(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
data = callback_query.data.split("|", 1)
|
||||
|
||||
if len(data) != 2:
|
||||
await callback_query.message.answer("Неверные данные для выбора суммы.")
|
||||
return
|
||||
|
||||
amount_str = data[1]
|
||||
try:
|
||||
amount = int(amount_str)
|
||||
except ValueError:
|
||||
await callback_query.message.answer("Некорректная сумма.")
|
||||
return
|
||||
|
||||
await state.update_data(amount=amount)
|
||||
await state.set_state(ReplenishBalanceState.waiting_for_payment_confirmation_crypto)
|
||||
|
||||
try:
|
||||
invoice = await crypto.create_invoice(
|
||||
asset="USDT",
|
||||
amount=str(int(amount // RUB_TO_USDT)),
|
||||
description=f"Пополнения баланса на {amount} руб",
|
||||
payload=f"{callback_query.message.chat.id}:{int(amount)}",
|
||||
)
|
||||
|
||||
if hasattr(invoice, "bot_invoice_url"):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="Пополнить", url=invoice.bot_invoice_url))
|
||||
builder.row(InlineKeyboardButton(text="⬅️ Назад", callback_data="pay"))
|
||||
await callback_query.message.answer(
|
||||
text=f"Вы выбрали пополнение на {amount} рублей.",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
else:
|
||||
await callback_query.message.answer("Ошибка при создании платежа.")
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при создании платежа: {e}")
|
||||
|
||||
|
||||
async def cryptobot_webhook(request):
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.info(f"Получены данные вебхука: {data}")
|
||||
if data.get("update_type") == "invoice_paid":
|
||||
await process_crypto_payment(data["payload"])
|
||||
return web.Response(status=200)
|
||||
else:
|
||||
logger.warning(f"Неподдерживаемый тип обновления: {data.get('update_type')}")
|
||||
return web.Response(status=400)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка обработки вебхука: {e}")
|
||||
return web.Response(status=500)
|
||||
|
||||
|
||||
async def process_crypto_payment(payload):
|
||||
if payload["status"] == "paid":
|
||||
custom_payload = payload["payload"]
|
||||
user_id_str, amount_str = custom_payload.split(":")
|
||||
try:
|
||||
user_id = int(user_id_str)
|
||||
amount = int(amount_str)
|
||||
await add_payment(int(user_id), float(amount), "cryptobot")
|
||||
logger.debug(f"Payment succeeded for user_id: {user_id}, amount: {amount}")
|
||||
await update_balance(user_id, amount)
|
||||
await send_payment_success_notification(user_id, amount)
|
||||
except ValueError as e:
|
||||
logger.error(f"Ошибка конвертации user_id или amount: {e}")
|
||||
else:
|
||||
logger.warning(f"Получен неоплаченный инвойс: {payload}")
|
||||
|
||||
|
||||
@router.callback_query(F.data == "enter_custom_amount_crypto")
|
||||
async def process_enter_custom_amount(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
await callback_query.message.answer(text="Введите сумму пополнения:")
|
||||
await state.set_state(ReplenishBalanceState.entering_custom_amount_crypto)
|
||||
|
||||
|
||||
@router.message(ReplenishBalanceState.entering_custom_amount_crypto)
|
||||
async def process_custom_amount_input(message: types.Message, state: FSMContext):
|
||||
if message.text.isdigit():
|
||||
amount = int(message.text)
|
||||
if amount // RUB_TO_USDT <= 0:
|
||||
await message.answer(f"Сумма должна быть больше {RUB_TO_USDT}. Пожалуйста, введите сумму еще раз:")
|
||||
return
|
||||
|
||||
await state.update_data(amount=amount)
|
||||
await state.set_state(ReplenishBalanceState.waiting_for_payment_confirmation_crypto)
|
||||
try:
|
||||
invoice = await crypto.create_invoice(
|
||||
asset="USDT",
|
||||
amount=str(int(amount // RUB_TO_USDT)),
|
||||
description=f"Пополнения баланса на {amount} руб",
|
||||
payload=f"{message.chat.id}:{amount}",
|
||||
)
|
||||
|
||||
if hasattr(invoice, "bot_invoice_url"):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="Пополнить", url=invoice.bot_invoice_url))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="⬅️ Назад", callback_data="pay"),
|
||||
)
|
||||
await message.answer(
|
||||
text=f"Вы выбрали пополнение на {amount} рублей.",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при создании платежа: {e}")
|
||||
else:
|
||||
await message.answer("Некорректная сумма. Пожалуйста, введите сумму еще раз:")
|
||||
@@ -1,183 +0,0 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from aiogram import F, Router, types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.fsm.state import State, StatesGroup
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
from aiohttp import web
|
||||
import requests
|
||||
|
||||
from config import FREEKASSA_API_KEY, FREEKASSA_SHOP_ID
|
||||
from database import add_payment, update_balance
|
||||
from handlers.payments.utils import send_payment_success_notification
|
||||
from handlers.texts import PAYMENT_OPTIONS
|
||||
|
||||
router = Router()
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
|
||||
class ReplenishBalanceState(StatesGroup):
|
||||
choosing_amount_freekassa = State()
|
||||
waiting_for_payment_confirmation_freekassa = State()
|
||||
entering_custom_amount_freekassa = State()
|
||||
|
||||
|
||||
def generate_signature(params, api_key):
|
||||
sorted_params = {k: params[k] for k in sorted(params)}
|
||||
sign_string = "|".join(str(value) for value in sorted_params.values())
|
||||
return hmac.new(api_key.encode(), sign_string.encode(), hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
async def create_payment(user_id, amount, email, ip):
|
||||
payment_id = str(uuid.uuid4())
|
||||
nonce = int(time.time() * 1000)
|
||||
params = {
|
||||
"shopId": FREEKASSA_SHOP_ID,
|
||||
"amount": amount,
|
||||
"currency": "RUB",
|
||||
"paymentId": payment_id,
|
||||
"email": email,
|
||||
"ip": ip,
|
||||
"i": 6,
|
||||
"nonce": nonce,
|
||||
}
|
||||
params["signature"] = generate_signature(params, FREEKASSA_API_KEY)
|
||||
|
||||
try:
|
||||
response = requests.post("https://api.freekassa.com/v1/orders/create", json=params)
|
||||
response_data = response.json()
|
||||
|
||||
logging.debug(f"Ответ от FreeKassa при создании платежа: {response_data}")
|
||||
|
||||
if response_data.get("type") == "success":
|
||||
return response_data["location"]
|
||||
else:
|
||||
logging.error(f"Ошибка создания платежа: {response_data}")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Ошибка запроса к FreeKassa: {e}")
|
||||
return None
|
||||
|
||||
|
||||
async def freekassa_webhook(request):
|
||||
data = await request.json()
|
||||
logging.debug(f"Получен вебхук от FreeKassa: {data}")
|
||||
|
||||
logging.debug(f"Данные вебхука от FreeKassa: {data}")
|
||||
|
||||
if data["status"] == "completed":
|
||||
user_id = data["metadata"]["user_id"]
|
||||
amount = float(data["amount"])
|
||||
await add_payment(int(user_id), float(amount), "freekassa")
|
||||
|
||||
await update_balance(user_id, amount)
|
||||
await send_payment_success_notification(user_id, amount)
|
||||
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
@router.callback_query(lambda c: c.data == "pay_freekassa")
|
||||
async def process_callback_pay_freekassa(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
builder = InlineKeyboardBuilder()
|
||||
for i in range(0, len(PAYMENT_OPTIONS), 2):
|
||||
if i + 1 < len(PAYMENT_OPTIONS):
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i]["text"],
|
||||
callback_data=f'freekassa_{PAYMENT_OPTIONS[i]["callback_data"]}',
|
||||
),
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i + 1]["text"],
|
||||
callback_data=f'freekassa_{PAYMENT_OPTIONS[i + 1]["callback_data"]}',
|
||||
),
|
||||
)
|
||||
else:
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i]["text"],
|
||||
callback_data=f'freekassa_{PAYMENT_OPTIONS[i]["callback_data"]}',
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="💰 Ввести свою сумму",
|
||||
callback_data="enter_custom_amount_freekassa",
|
||||
)
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="⬅️ Назад", callback_data="pay"))
|
||||
|
||||
await callback_query.message.answer(
|
||||
text="Выберите сумму пополнения через FreeKassa:",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
await state.set_state(ReplenishBalanceState.choosing_amount_freekassa)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("freekassa_amount|"))
|
||||
async def process_amount_selection(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
data = callback_query.data.split("|", 1)
|
||||
amount_str = data[1]
|
||||
try:
|
||||
amount = int(amount_str)
|
||||
except ValueError:
|
||||
await callback_query.message.answer("Некорректная сумма.")
|
||||
return
|
||||
|
||||
user_email = f"{callback_query.message.chat.id}@solo.net"
|
||||
user_ip = callback_query.message.chat.id
|
||||
payment_url = await create_payment(callback_query.message.chat.id, amount, user_email, user_ip)
|
||||
|
||||
if payment_url:
|
||||
confirm_keyboard = InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[InlineKeyboardButton(text=f"Оплатить {amount} рублей", url=payment_url)],
|
||||
[InlineKeyboardButton(text="⬅️ Назад", callback_data="pay")],
|
||||
]
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
f"Вы выбрали оплату на {amount} рублей. Перейдите по ссылке для завершения оплаты:",
|
||||
reply_markup=confirm_keyboard,
|
||||
)
|
||||
else:
|
||||
await callback_query.message.answer(
|
||||
"Ошибка при создании платежа. Попробуйте позже.",
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "enter_custom_amount_freekassa")
|
||||
async def process_enter_custom_amount(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
await callback_query.message.answer(text="Введите сумму пополнения:")
|
||||
await state.set_state(ReplenishBalanceState.entering_custom_amount_freekassa)
|
||||
|
||||
|
||||
@router.message(ReplenishBalanceState.entering_custom_amount_freekassa)
|
||||
async def process_custom_amount_input(message: types.Message, state: FSMContext):
|
||||
if message.text.isdigit():
|
||||
amount = int(message.text)
|
||||
if amount <= 0:
|
||||
await message.answer("Сумма должна быть больше нуля. Пожалуйста, введите сумму еще раз:")
|
||||
return
|
||||
|
||||
user_email = f"{message.chat.id}@solo.net"
|
||||
user_ip = message.chat.id
|
||||
payment_url = await create_payment(message.chat.id, amount, user_email, user_ip)
|
||||
|
||||
if payment_url:
|
||||
keyboard = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton("Оплатить", url=payment_url)]])
|
||||
await message.answer(
|
||||
f"Вы выбрали оплату на {amount} рублей. Перейдите по ссылке для завершения оплаты:",
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
else:
|
||||
await message.answer("Ошибка при создании платежа. Попробуйте позже.")
|
||||
|
||||
else:
|
||||
await message.answer("Пожалуйста, введите корректную сумму.")
|
||||
File diff suppressed because it is too large
Load Diff
BIN
Binary file not shown.
@@ -9,8 +9,20 @@ from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
from aiohttp import web
|
||||
from robokassa import HashAlgorithm, Robokassa
|
||||
|
||||
from config import ROBOKASSA_ENABLE, ROBOKASSA_LOGIN, ROBOKASSA_PASSWORD1, ROBOKASSA_PASSWORD2, ROBOKASSA_TEST_MODE
|
||||
from database import add_connection, add_payment, check_connection_exists, get_key_count, update_balance
|
||||
from config import (
|
||||
ROBOKASSA_ENABLE,
|
||||
ROBOKASSA_LOGIN,
|
||||
ROBOKASSA_PASSWORD1,
|
||||
ROBOKASSA_PASSWORD2,
|
||||
ROBOKASSA_TEST_MODE,
|
||||
)
|
||||
from database import (
|
||||
add_connection,
|
||||
add_payment,
|
||||
check_connection_exists,
|
||||
get_key_count,
|
||||
update_balance,
|
||||
)
|
||||
from handlers.payments.utils import send_payment_success_notification
|
||||
from handlers.texts import PAYMENT_OPTIONS
|
||||
from logger import logger
|
||||
@@ -37,7 +49,9 @@ if ROBOKASSA_ENABLE:
|
||||
|
||||
def generate_payment_link(amount, inv_id, description, tg_id):
|
||||
"""Генерация ссылки на оплату."""
|
||||
logger.debug(f"Generating payment link for amount: {amount}, inv_id: {inv_id}, description: {description}")
|
||||
logger.debug(
|
||||
f"Generating payment link for amount: {amount}, inv_id: {inv_id}, description: {description}"
|
||||
)
|
||||
payment_link = robokassa._payment.link.generate_by_script(
|
||||
out_sum=amount,
|
||||
inv_id=inv_id,
|
||||
@@ -49,7 +63,9 @@ def generate_payment_link(amount, inv_id, description, tg_id):
|
||||
|
||||
|
||||
@router.callback_query(F.data == "pay_robokassa")
|
||||
async def process_callback_pay_robokassa(callback_query: types.CallbackQuery, state: FSMContext, session: Any):
|
||||
async def process_callback_pay_robokassa(
|
||||
callback_query: types.CallbackQuery, state: FSMContext, session: Any
|
||||
):
|
||||
tg_id = callback_query.message.chat.id
|
||||
logger.info(f"User {tg_id} initiated Robokassa payment.")
|
||||
|
||||
@@ -98,7 +114,9 @@ async def process_callback_pay_robokassa(callback_query: types.CallbackQuery, st
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("robokassa_amount|"))
|
||||
async def process_amount_selection(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
async def process_amount_selection(
|
||||
callback_query: types.CallbackQuery, state: FSMContext
|
||||
):
|
||||
logger.info(f"Получены данные callback_data: {callback_query.data}")
|
||||
|
||||
data = callback_query.data.split("|")
|
||||
@@ -152,7 +170,9 @@ async def robokassa_webhook(request):
|
||||
shp_id = params.get("shp_id")
|
||||
signature_value = params.get("SignatureValue")
|
||||
|
||||
logger.info(f"OutSum: {amount}, InvId: {inv_id}, shp_id: {shp_id}, SignatureValue: {signature_value}")
|
||||
logger.info(
|
||||
f"OutSum: {amount}, InvId: {inv_id}, shp_id: {shp_id}, SignatureValue: {signature_value}"
|
||||
)
|
||||
|
||||
if not check_payment_signature(params):
|
||||
logger.error("Неверная подпись или данные запроса.")
|
||||
@@ -191,7 +211,9 @@ def check_payment_signature(params):
|
||||
|
||||
logger.info(f"Signature string before hashing: {signature_string}")
|
||||
|
||||
expected_signature = hashlib.md5(signature_string.encode("utf-8")).hexdigest().upper()
|
||||
expected_signature = (
|
||||
hashlib.md5(signature_string.encode("utf-8")).hexdigest().upper()
|
||||
)
|
||||
|
||||
logger.info(f"Expected signature: {expected_signature}")
|
||||
logger.info(f"Received signature: {signature_value}")
|
||||
@@ -200,12 +222,23 @@ def check_payment_signature(params):
|
||||
|
||||
|
||||
@router.callback_query(F.data == "enter_custom_amount_robokassa")
|
||||
async def process_custom_amount_selection(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
async def process_custom_amount_selection(
|
||||
callback_query: types.CallbackQuery, state: FSMContext
|
||||
):
|
||||
tg_id = callback_query.message.chat.id
|
||||
logger.info(f"User {tg_id} chose to enter a custom amount.")
|
||||
|
||||
await callback_query.message.answer(text="Пожалуйста, введите сумму пополнения в рублях (например, 150):")
|
||||
await state.set_state(ReplenishBalanceState.waiting_for_payment_confirmation_robokassa)
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🔙 Назад", callback_data="pay_robokassa"))
|
||||
|
||||
await callback_query.message.answer(
|
||||
"Пожалуйста, введите сумму пополнения.",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
await state.set_state(
|
||||
ReplenishBalanceState.waiting_for_payment_confirmation_robokassa
|
||||
)
|
||||
|
||||
|
||||
@router.message(ReplenishBalanceState.waiting_for_payment_confirmation_robokassa)
|
||||
@@ -239,4 +272,6 @@ async def handle_custom_amount_input(message: types.Message, state: FSMContext):
|
||||
await state.clear()
|
||||
except ValueError as e:
|
||||
logger.error(f"Некорректная сумма от пользователя {tg_id}: {e}")
|
||||
await message.answer(text="Введите корректную сумму в рублях (целое положительное число).")
|
||||
await message.answer(
|
||||
text="Введите корректную сумму в рублях (целое положительное число)."
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1,187 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from aiogram import F, Router, types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.fsm.state import State, StatesGroup
|
||||
from aiogram.types import InlineKeyboardButton, LabeledPrice, PreCheckoutQuery
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
|
||||
from config import RUB_TO_XTR
|
||||
from database import add_connection, add_payment, check_connection_exists, get_key_count, update_balance
|
||||
from handlers.payments.utils import send_payment_success_notification
|
||||
from handlers.texts import PAYMENT_OPTIONS
|
||||
from logger import logger
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class ReplenishBalanceState(StatesGroup):
|
||||
choosing_amount_stars = State()
|
||||
waiting_for_payment_confirmation_stars = State()
|
||||
entering_custom_amount_stars = State()
|
||||
|
||||
|
||||
@router.callback_query(F.data == "pay_stars")
|
||||
async def process_callback_pay_stars(callback_query: types.CallbackQuery, state: FSMContext, session: Any):
|
||||
tg_id = callback_query.message.chat.id
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="🤖 Бот для покупки звезд", url="https://t.me/PremiumBot"))
|
||||
|
||||
for i in range(0, len(PAYMENT_OPTIONS), 2):
|
||||
if i + 1 < len(PAYMENT_OPTIONS):
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i]["text"],
|
||||
callback_data=f'stars_{PAYMENT_OPTIONS[i]["callback_data"]}',
|
||||
),
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i + 1]["text"],
|
||||
callback_data=f'stars_{PAYMENT_OPTIONS[i + 1]["callback_data"]}',
|
||||
),
|
||||
)
|
||||
else:
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i]["text"],
|
||||
callback_data=f'stars_{PAYMENT_OPTIONS[i]["callback_data"]}',
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="💰 Ввести свою сумму",
|
||||
callback_data="enter_custom_amount_stars",
|
||||
)
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="⬅️ Назад", callback_data="pay"))
|
||||
|
||||
key_count = await get_key_count(tg_id)
|
||||
|
||||
if key_count == 0:
|
||||
exists = await check_connection_exists(tg_id)
|
||||
if not exists:
|
||||
await add_connection(tg_id, balance=0.0, trial=0, session=session)
|
||||
|
||||
try:
|
||||
await callback_query.message.delete()
|
||||
except Exception as e:
|
||||
logger.error(f"Не удалось удалить сообщение: {e}")
|
||||
|
||||
await callback_query.message.answer(
|
||||
text="Выберите сумму пополнения:",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
await state.set_state(ReplenishBalanceState.choosing_amount_stars)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("stars_amount|"))
|
||||
async def process_amount_selection(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
data = callback_query.data.split("|", 1)
|
||||
|
||||
if len(data) != 2:
|
||||
try:
|
||||
await callback_query.message.delete()
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при удалении сообщения: {e}")
|
||||
|
||||
await callback_query.message.answer("Неверные данные для выбора суммы.")
|
||||
return
|
||||
|
||||
amount_str = data[1]
|
||||
try:
|
||||
amount = int(amount_str)
|
||||
except ValueError:
|
||||
try:
|
||||
await callback_query.message.delete()
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при удалении сообщения: {e}")
|
||||
|
||||
await callback_query.message.answer("Некорректная сумма.")
|
||||
return
|
||||
|
||||
await state.update_data(amount=amount)
|
||||
await state.set_state(ReplenishBalanceState.waiting_for_payment_confirmation_stars)
|
||||
|
||||
try:
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="Пополнить", pay=True),
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="⬅️ Назад", callback_data="pay"),
|
||||
)
|
||||
|
||||
await callback_query.message.answer_invoice(
|
||||
title=f"Вы выбрали пополнение на {amount} рублей.",
|
||||
description=f"Вы выбрали пополнение на {amount} рублей.",
|
||||
prices=[LabeledPrice(label="XTR", amount=int(amount // RUB_TO_XTR))],
|
||||
provider_token="",
|
||||
payload=f"{amount}_stars",
|
||||
currency="XTR",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при создании платежа: {e}")
|
||||
await callback_query.message.answer("Произошла ошибка при создании платежа.")
|
||||
|
||||
|
||||
@router.callback_query(F.data == "enter_custom_amount_stars")
|
||||
async def process_enter_custom_amount(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
await callback_query.message.answer(text="Введите сумму пополнения:")
|
||||
await state.set_state(ReplenishBalanceState.entering_custom_amount_stars)
|
||||
|
||||
|
||||
@router.message(ReplenishBalanceState.entering_custom_amount_stars)
|
||||
async def process_custom_amount_input(message: types.Message, state: FSMContext):
|
||||
if message.text.isdigit():
|
||||
amount = int(message.text)
|
||||
if amount // RUB_TO_XTR <= 0:
|
||||
await message.answer(f"Сумма должна быть больше {RUB_TO_XTR}. Пожалуйста, введите сумму еще раз:")
|
||||
return
|
||||
|
||||
await state.update_data(amount=amount)
|
||||
await state.set_state(ReplenishBalanceState.waiting_for_payment_confirmation_stars)
|
||||
try:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="Пополнить", pay=True),
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="⬅️ Назад", callback_data="pay"),
|
||||
)
|
||||
await message.answer_invoice(
|
||||
title=f"Вы выбрали пополнение на {amount} рублей.",
|
||||
description=f"Вы выбрали пополнение на {amount} рублей.",
|
||||
prices=[LabeledPrice(label="XTR", amount=int(amount // RUB_TO_XTR))],
|
||||
provider_token="",
|
||||
payload=f"{amount}_stars",
|
||||
currency="XTR",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при создании платежа: {e}")
|
||||
await message.answer("Произошла ошибка при создании платежа.")
|
||||
else:
|
||||
await message.answer("Некорректная сумма. Пожалуйста, введите сумму еще раз:")
|
||||
|
||||
|
||||
@router.pre_checkout_query()
|
||||
async def on_pre_checkout_query(pre_checkout_query: PreCheckoutQuery):
|
||||
await pre_checkout_query.answer(ok=True)
|
||||
|
||||
|
||||
@router.message(F.successful_payment)
|
||||
async def on_successful_payment(
|
||||
message: types.Message,
|
||||
):
|
||||
try:
|
||||
user_id = int(message.chat.id)
|
||||
amount = float(message.successful_payment.invoice_payload.split("_")[0])
|
||||
logger.debug(f"Payment succeeded for user_id: {user_id}, amount: {amount}")
|
||||
await add_payment(int(user_id), float(amount), "stars")
|
||||
await update_balance(user_id, amount)
|
||||
await send_payment_success_notification(user_id, amount)
|
||||
except ValueError as e:
|
||||
logger.error(f"Ошибка конвертации user_id или amount: {e}")
|
||||
File diff suppressed because it is too large
Load Diff
BIN
Binary file not shown.
@@ -1,18 +0,0 @@
|
||||
from aiogram.types import InlineKeyboardButton
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
|
||||
from bot import bot
|
||||
from logger import logger
|
||||
|
||||
|
||||
async def send_payment_success_notification(user_id: int, amount: float):
|
||||
try:
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
await bot.send_message(
|
||||
chat_id=user_id,
|
||||
text=f"Ваш баланс успешно пополнен на {amount} рублей. Спасибо за оплату!",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при отправке уведомления пользователю {user_id}: {e}")
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1,240 +0,0 @@
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
from aiogram import F, Router, types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.fsm.state import State, StatesGroup
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
from aiohttp import web
|
||||
from yookassa import Configuration, Payment
|
||||
|
||||
from config import YOOKASSA_ENABLE, YOOKASSA_SECRET_KEY, YOOKASSA_SHOP_ID
|
||||
from database import add_connection, add_payment, check_connection_exists, get_key_count, update_balance
|
||||
from handlers.payments.utils import send_payment_success_notification
|
||||
from handlers.texts import PAYMENT_OPTIONS
|
||||
from logger import logger
|
||||
|
||||
router = Router()
|
||||
|
||||
if YOOKASSA_ENABLE:
|
||||
Configuration.account_id = YOOKASSA_SHOP_ID
|
||||
Configuration.secret_key = YOOKASSA_SECRET_KEY
|
||||
logger.debug(f"Account ID: {YOOKASSA_SHOP_ID}")
|
||||
logger.debug(f"Secret Key: {YOOKASSA_SECRET_KEY}")
|
||||
|
||||
|
||||
class ReplenishBalanceState(StatesGroup):
|
||||
choosing_amount_yookassa = State()
|
||||
waiting_for_payment_confirmation_yookassa = State()
|
||||
entering_custom_amount_yookassa = State()
|
||||
|
||||
|
||||
@router.callback_query(F.data == "pay_yookassa")
|
||||
async def process_callback_pay_yookassa(callback_query: types.CallbackQuery, state: FSMContext, session: Any):
|
||||
tg_id = callback_query.message.chat.id
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
|
||||
for i in range(0, len(PAYMENT_OPTIONS), 2):
|
||||
if i + 1 < len(PAYMENT_OPTIONS):
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i]["text"],
|
||||
callback_data=f'yookassa_{PAYMENT_OPTIONS[i]["callback_data"]}',
|
||||
),
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i + 1]["text"],
|
||||
callback_data=f'yookassa_{PAYMENT_OPTIONS[i + 1]["callback_data"]}',
|
||||
),
|
||||
)
|
||||
else:
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text=PAYMENT_OPTIONS[i]["text"],
|
||||
callback_data=f'yookassa_{PAYMENT_OPTIONS[i]["callback_data"]}',
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="💰 Ввести свою сумму",
|
||||
callback_data="enter_custom_amount_yookassa",
|
||||
)
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="⬅️ Назад", callback_data="pay"))
|
||||
|
||||
key_count = await get_key_count(tg_id)
|
||||
|
||||
if key_count == 0:
|
||||
exists = await check_connection_exists(tg_id)
|
||||
if not exists:
|
||||
await add_connection(tg_id, balance=0.0, trial=0, session=session)
|
||||
|
||||
await callback_query.message.answer(
|
||||
text="Выберите сумму пополнения:",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
await state.set_state(ReplenishBalanceState.choosing_amount_yookassa)
|
||||
|
||||
|
||||
@router.callback_query(F.data.startswith("yookassa_amount|"))
|
||||
async def process_amount_selection(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
data = callback_query.data.split("|", 1)
|
||||
|
||||
if len(data) != 2:
|
||||
return
|
||||
|
||||
amount_str = data[1]
|
||||
try:
|
||||
amount = int(amount_str)
|
||||
except ValueError:
|
||||
return
|
||||
|
||||
await state.update_data(amount=amount)
|
||||
await state.set_state(ReplenishBalanceState.waiting_for_payment_confirmation_yookassa)
|
||||
|
||||
# state_data = await state.get_data()
|
||||
customer_name = callback_query.from_user.full_name
|
||||
customer_id = callback_query.message.chat.id
|
||||
|
||||
customer_email = f"{customer_id}@solo.net"
|
||||
|
||||
payment = Payment.create(
|
||||
{
|
||||
"amount": {"value": str(amount), "currency": "RUB"},
|
||||
"confirmation": {
|
||||
"type": "redirect",
|
||||
"return_url": "https://pocomacho.ru/success.html",
|
||||
},
|
||||
"capture": True,
|
||||
"description": "Пополнение баланса",
|
||||
"receipt": {
|
||||
"customer": {
|
||||
"full_name": customer_name,
|
||||
"email": customer_email,
|
||||
"phone": "79000000000",
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"description": "Пополнение баланса",
|
||||
"quantity": "1.00",
|
||||
"amount": {"value": str(amount), "currency": "RUB"},
|
||||
"vat_code": 6,
|
||||
}
|
||||
],
|
||||
},
|
||||
"metadata": {"user_id": customer_id},
|
||||
},
|
||||
uuid.uuid4(),
|
||||
)
|
||||
|
||||
if payment["status"] == "pending":
|
||||
payment_url = payment["confirmation"]["confirmation_url"]
|
||||
|
||||
confirm_keyboard = InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[InlineKeyboardButton(text="Пополнить", url=payment_url)],
|
||||
[InlineKeyboardButton(text="⬅️ Назад", callback_data="pay")],
|
||||
]
|
||||
)
|
||||
|
||||
await callback_query.message.answer(
|
||||
text=f"Вы выбрали пополнение на {amount} рублей.",
|
||||
reply_markup=confirm_keyboard,
|
||||
)
|
||||
else:
|
||||
await callback_query.message.answer("Ошибка при создании платежа.")
|
||||
|
||||
|
||||
async def yookassa_webhook(request):
|
||||
event = await request.json()
|
||||
logger.debug(f"Webhook event received: {event}")
|
||||
if event["event"] == "payment.succeeded":
|
||||
user_id_str = event["object"]["metadata"]["user_id"]
|
||||
amount_str = event["object"]["amount"]["value"]
|
||||
try:
|
||||
user_id = int(user_id_str)
|
||||
amount = float(amount_str)
|
||||
logger.debug(f"Payment succeeded for user_id: {user_id}, amount: {amount}")
|
||||
await add_payment(int(user_id), float(amount), "yookassa")
|
||||
await update_balance(user_id, amount)
|
||||
await send_payment_success_notification(user_id, amount)
|
||||
except ValueError as e:
|
||||
logger.error(f"Ошибка конвертации user_id или amount: {e}")
|
||||
return web.Response(status=400)
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "enter_custom_amount_yookassa")
|
||||
async def process_enter_custom_amount(callback_query: types.CallbackQuery, state: FSMContext):
|
||||
await callback_query.message.answer(text="Введите сумму пополнения:")
|
||||
await state.set_state(ReplenishBalanceState.entering_custom_amount_yookassa)
|
||||
|
||||
|
||||
@router.message(ReplenishBalanceState.entering_custom_amount_yookassa)
|
||||
async def process_custom_amount_input(message: types.Message, state: FSMContext):
|
||||
if message.text.isdigit():
|
||||
amount = int(message.text)
|
||||
if amount <= 0:
|
||||
await message.answer("Сумма должна быть больше нуля. Пожалуйста, введите сумму еще раз:")
|
||||
return
|
||||
|
||||
await state.update_data(amount=amount)
|
||||
await state.set_state(ReplenishBalanceState.waiting_for_payment_confirmation_yookassa)
|
||||
|
||||
try:
|
||||
payment = Payment.create(
|
||||
{
|
||||
"amount": {"value": str(amount), "currency": "RUB"},
|
||||
"confirmation": {
|
||||
"type": "redirect",
|
||||
"return_url": "https://pocomacho.ru/success.html",
|
||||
},
|
||||
"capture": True,
|
||||
"description": "Пополнение баланса",
|
||||
"receipt": {
|
||||
"customer": {
|
||||
"full_name": message.from_user.full_name,
|
||||
"email": f"{message.chat.id}@solo.net",
|
||||
"phone": "79000000000",
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"description": "Пополнение баланса",
|
||||
"quantity": "1.00",
|
||||
"amount": {
|
||||
"value": str(amount),
|
||||
"currency": "RUB",
|
||||
},
|
||||
"vat_code": 6,
|
||||
}
|
||||
],
|
||||
},
|
||||
"metadata": {"user_id": message.chat.id},
|
||||
},
|
||||
uuid.uuid4(),
|
||||
)
|
||||
|
||||
if payment["status"] == "pending":
|
||||
payment_url = payment["confirmation"]["confirmation_url"]
|
||||
|
||||
confirm_keyboard = InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[InlineKeyboardButton(text="Пополнить", url=payment_url)],
|
||||
[InlineKeyboardButton(text="⬅️ Назад", callback_data="pay")],
|
||||
]
|
||||
)
|
||||
|
||||
await message.answer(
|
||||
text=f"Вы выбрали пополнение на {amount} рублей.",
|
||||
reply_markup=confirm_keyboard,
|
||||
)
|
||||
else:
|
||||
await message.answer("Ошибка при создании платежа.")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при создании платежа: {e}")
|
||||
await message.answer("Произошла ошибка при создании платежа.")
|
||||
else:
|
||||
await message.answer("Некорректная сумма. Пожалуйста, введите сумму еще раз:")
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
+74
-32
@@ -7,60 +7,91 @@ from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
|
||||
from config import NEWS_MESSAGE, RENEWAL_PLANS
|
||||
from database import get_balance, get_key_count, get_referral_stats
|
||||
from handlers.buttons.profile import ADD_SUB, GIFTS, INSTRUCTIONS, INVITE, MAIN_MENU, MY_SUBS, PAYMENT, TARRIFS
|
||||
from handlers.texts import get_referral_link, invite_message_send, profile_message_send
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
@router.callback_query(F.data == "profile")
|
||||
async def process_callback_view_profile(callback_query: types.CallbackQuery, state: FSMContext, admin: bool):
|
||||
chat_id = callback_query.message.chat.id
|
||||
username = callback_query.from_user.full_name
|
||||
@router.message(F.text == "/profile")
|
||||
async def process_callback_view_profile(
|
||||
callback_query_or_message: types.Message | types.CallbackQuery, state: FSMContext, admin: bool
|
||||
):
|
||||
if isinstance(callback_query_or_message, types.CallbackQuery):
|
||||
chat_id = callback_query_or_message.message.chat.id
|
||||
username = callback_query_or_message.from_user.full_name
|
||||
is_callback = True
|
||||
elif isinstance(callback_query_or_message, types.Message):
|
||||
chat_id = callback_query_or_message.chat.id
|
||||
username = callback_query_or_message.from_user.full_name
|
||||
is_callback = False
|
||||
|
||||
image_path = os.path.join("img", "pic.jpg")
|
||||
key_count = await get_key_count(chat_id)
|
||||
balance = await get_balance(chat_id)
|
||||
if balance is None:
|
||||
balance = 0
|
||||
|
||||
profile_message = profile_message_send(username, chat_id, balance, key_count)
|
||||
profile_message = profile_message_send(username, chat_id, int(balance), key_count)
|
||||
|
||||
if key_count == 0:
|
||||
profile_message += "\n<pre>🔧 <i>Нажмите кнопку ➕ Устройство, чтобы настроить VPN-подключение</i></pre>"
|
||||
else:
|
||||
profile_message += f"\n<pre>🔧 <i>{NEWS_MESSAGE}</i></pre>"
|
||||
profile_message += f"\n<pre> <i>{NEWS_MESSAGE}</i></pre>"
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="➕ Устройство", callback_data="create_key"),
|
||||
InlineKeyboardButton(text="📱 Мои устройства", callback_data="view_keys"),
|
||||
InlineKeyboardButton(text=ADD_SUB, callback_data="create_key"),
|
||||
InlineKeyboardButton(text=MY_SUBS, callback_data="view_keys"),
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="💳 Пополнить баланс",
|
||||
text=PAYMENT,
|
||||
callback_data="pay",
|
||||
)
|
||||
)
|
||||
builder.row()
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="👥 Пригласить друзей", callback_data="invite"),
|
||||
InlineKeyboardButton(text="📘 Инструкции", callback_data="instructions"),
|
||||
InlineKeyboardButton(text=INVITE, callback_data="invite"),
|
||||
InlineKeyboardButton(text=GIFTS, callback_data="gifts"),
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text=TARRIFS, callback_data="view_tariffs"),
|
||||
InlineKeyboardButton(text=INSTRUCTIONS, callback_data="instructions"),
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="💡 Тарифы", callback_data="view_tariffs"))
|
||||
if admin:
|
||||
builder.row(InlineKeyboardButton(text="🔧 Администратор", callback_data="admin"))
|
||||
builder.row(InlineKeyboardButton(text="⬅️ Главное меню", callback_data="start"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="🔧 Администратор", callback_data="admin")
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text=MAIN_MENU, callback_data="start"))
|
||||
|
||||
if os.path.isfile(image_path):
|
||||
with open(image_path, "rb") as image_file:
|
||||
await callback_query.message.answer_photo(
|
||||
photo=BufferedInputFile(image_file.read(), filename="pic.jpg"),
|
||||
caption=profile_message,
|
||||
if is_callback:
|
||||
await callback_query_or_message.message.answer_photo(
|
||||
photo=BufferedInputFile(image_file.read(), filename="pic.jpg"),
|
||||
caption=profile_message,
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
else:
|
||||
await callback_query_or_message.answer_photo(
|
||||
photo=BufferedInputFile(image_file.read(), filename="pic.jpg"),
|
||||
caption=profile_message,
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
else:
|
||||
if is_callback:
|
||||
await callback_query_or_message.message.answer(
|
||||
text=profile_message,
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
else:
|
||||
await callback_query.message.answer(
|
||||
text=profile_message,
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
else:
|
||||
await callback_query_or_message.answer(
|
||||
text=profile_message,
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@router.callback_query(F.data == "view_tariffs")
|
||||
@@ -68,19 +99,30 @@ async def view_tariffs_handler(callback_query: types.CallbackQuery):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
|
||||
await callback_query.message.answer(
|
||||
"<b>🚀 Доступные тарифы VPN:</b>\n\n"
|
||||
+ "\n".join(
|
||||
[
|
||||
f"{months} {'месяц' if months == '1' else 'месяца' if int(months) in [2, 3, 4] else 'месяцев'}: "
|
||||
f"{RENEWAL_PLANS[months]['price']} "
|
||||
f"{'💳' if months == '1' else '🌟' if months == '3' else '🔥' if months == '6' else '🚀'} рублей"
|
||||
for months in sorted(RENEWAL_PLANS.keys(), key=int)
|
||||
]
|
||||
),
|
||||
reply_markup=builder.as_markup(),
|
||||
image_path = os.path.join("img", "tariffs.jpg")
|
||||
|
||||
tariffs_message = "<b>🚀 Доступные тарифы VPN:</b>\n\n" + "\n".join(
|
||||
[
|
||||
f"{months} {'месяц' if months == '1' else 'месяца' if int(months) in [2, 3, 4] else 'месяцев'}: "
|
||||
f"{RENEWAL_PLANS[months]['price']} "
|
||||
f"{'💳' if months == '1' else '🌟' if months == '3' else '🔥' if months == '6' else '🚀'} рублей"
|
||||
for months in sorted(RENEWAL_PLANS.keys(), key=int)
|
||||
]
|
||||
)
|
||||
|
||||
if os.path.isfile(image_path):
|
||||
with open(image_path, "rb") as image_file:
|
||||
await callback_query.message.answer_photo(
|
||||
photo=BufferedInputFile(image_file.read(), filename="tariffs.jpg"),
|
||||
caption=tariffs_message,
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
else:
|
||||
await callback_query.message.answer(
|
||||
text=tariffs_message,
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "invite")
|
||||
async def invite_handler(callback_query: types.CallbackQuery):
|
||||
|
||||
+155
-22
@@ -4,49 +4,165 @@ from typing import Any
|
||||
from aiogram import F, Router
|
||||
from aiogram.filters import Command
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.types import BufferedInputFile, CallbackQuery, InlineKeyboardButton, Message
|
||||
from aiogram.types import (
|
||||
BufferedInputFile,
|
||||
CallbackQuery,
|
||||
InlineKeyboardButton,
|
||||
Message,
|
||||
)
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
|
||||
from config import CHANNEL_URL, CONNECT_ANDROID, CONNECT_IOS, DOWNLOAD_ANDROID, DOWNLOAD_IOS, SUPPORT_CHAT_URL
|
||||
from config import (
|
||||
CHANNEL_EXISTS,
|
||||
CHANNEL_URL,
|
||||
CONNECT_ANDROID,
|
||||
CONNECT_IOS,
|
||||
DONATIONS_ENABLE,
|
||||
DOWNLOAD_ANDROID,
|
||||
DOWNLOAD_IOS,
|
||||
SUPPORT_CHAT_URL,
|
||||
)
|
||||
from database import add_connection, add_referral, check_connection_exists, get_trial, use_trial
|
||||
from handlers.keys.key_management import create_key
|
||||
from handlers.keys.trial_key import create_trial_key
|
||||
from handlers.texts import INSTRUCTIONS_TRIAL, WELCOME_TEXT, get_about_vpn
|
||||
from logger import logger
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
@router.callback_query(F.data == "start")
|
||||
async def handle_start_callback_query(callback_query: CallbackQuery, state: FSMContext, session: Any, admin: bool):
|
||||
async def handle_start_callback_query(
|
||||
callback_query: CallbackQuery, state: FSMContext, session: Any, admin: bool
|
||||
):
|
||||
await start_command(callback_query.message, state, session, admin)
|
||||
|
||||
|
||||
@router.message(Command("start"))
|
||||
async def start_command(message: Message, state: FSMContext, session: Any, admin: bool):
|
||||
"""Обрабатывает команду /start, включает логику рефералов и подарков."""
|
||||
logger.info(f"Вызвана функция start_command для пользователя {message.chat.id}")
|
||||
|
||||
await state.clear()
|
||||
|
||||
if message.text:
|
||||
try:
|
||||
referrer_tg_id = int(message.text.split("referral_")[1])
|
||||
await add_referral(message.chat.id, referrer_tg_id, session)
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
connection_exists = await check_connection_exists(message.chat.id)
|
||||
if not connection_exists:
|
||||
await add_connection(tg_id=message.chat.id, session=session)
|
||||
connection_exists = await check_connection_exists(message.chat.id)
|
||||
logger.info(f"Проверка существования подключения: {connection_exists}")
|
||||
|
||||
|
||||
if not connection_exists:
|
||||
await add_connection(tg_id=message.chat.id, session=session)
|
||||
logger.info(f"Пользователь {message.chat.id} успешно добавлен в базу данных.")
|
||||
|
||||
if "gift_" in message.text:
|
||||
logger.info(f"Обнаружена ссылка на подарок: {message.text}")
|
||||
parts = message.text.split("gift_")[1].split("_")
|
||||
gift_id = parts[0]
|
||||
|
||||
recipient_tg_id = message.chat.id
|
||||
|
||||
gift_info = await session.fetchrow(
|
||||
"SELECT * FROM gifts WHERE gift_id = $1 AND is_used = FALSE", gift_id
|
||||
)
|
||||
|
||||
if gift_info is None:
|
||||
logger.warning(f"Подарок с ID {gift_id} уже был использован или не существует.")
|
||||
await message.answer("Этот подарок уже был использован или не существует.")
|
||||
return await show_start_menu(message, admin, session)
|
||||
|
||||
if gift_info['sender_tg_id'] == recipient_tg_id:
|
||||
logger.warning(
|
||||
f"Пользователь {recipient_tg_id} попытался активировать подарок, который был отправлен им самим."
|
||||
)
|
||||
await message.answer("❌ Вы не можете получить подарок от самого себя.")
|
||||
return await show_start_menu(message, admin, session)
|
||||
|
||||
selected_months = gift_info['selected_months']
|
||||
expiry_time = gift_info['expiry_time']
|
||||
expiry_time_naive = expiry_time.replace(tzinfo=None)
|
||||
logger.info(f"Подарок с ID {gift_id} успешно найден для пользователя {recipient_tg_id}.")
|
||||
|
||||
await create_key(recipient_tg_id, expiry_time_naive, state, session, message)
|
||||
logger.info(f"Ключ создан для пользователя {recipient_tg_id} на срок {selected_months} месяцев.")
|
||||
|
||||
await session.execute(
|
||||
"UPDATE gifts SET is_used = TRUE, recipient_tg_id = $1 WHERE gift_id = $2",
|
||||
recipient_tg_id,
|
||||
gift_id,
|
||||
)
|
||||
|
||||
await message.answer(
|
||||
f"🎉 Ваш подарок на {selected_months} {'месяц' if selected_months == 1 else 'месяца' if selected_months in [2, 3, 4] else 'месяцев'} активирован!"
|
||||
)
|
||||
logger.info(f"Подарок на {selected_months} месяцев активирован для пользователя {recipient_tg_id}.")
|
||||
return
|
||||
|
||||
elif "referral_" in message.text:
|
||||
try:
|
||||
referrer_tg_id = int(message.text.split("referral_")[1])
|
||||
|
||||
if connection_exists:
|
||||
logger.info(
|
||||
f"Пользователь {message.chat.id} уже зарегистрирован и не может стать рефералом."
|
||||
)
|
||||
await message.answer("❌ Вы уже зарегистрированы и не можете использовать реферальную ссылку.")
|
||||
return await show_start_menu(message, admin, session)
|
||||
|
||||
if referrer_tg_id == message.chat.id:
|
||||
logger.warning(f"Пользователь {message.chat.id} попытался стать рефералом самого себя.")
|
||||
await message.answer("❌ Вы не можете быть рефералом самого себя.")
|
||||
return await show_start_menu(message, admin, session)
|
||||
|
||||
existing_referral = await session.fetchrow(
|
||||
"SELECT * FROM referrals WHERE referred_tg_id = $1", message.chat.id
|
||||
)
|
||||
|
||||
if existing_referral:
|
||||
logger.info(f"Реферал с ID {message.chat.id} уже существует.")
|
||||
return await show_start_menu(message, admin, session)
|
||||
|
||||
await add_referral(message.chat.id, referrer_tg_id, session)
|
||||
logger.info(f"Реферал {message.chat.id} использовал ссылку от пользователя {referrer_tg_id}")
|
||||
return await show_start_menu(message, admin, session)
|
||||
|
||||
except (ValueError, IndexError) as e:
|
||||
logger.error(f"Ошибка при обработке реферальной ссылки: {e}")
|
||||
return
|
||||
|
||||
else:
|
||||
logger.info(f"Пользователь {message.chat.id} зашел без реферальной ссылки или подарка.")
|
||||
|
||||
await show_start_menu(message, admin, session)
|
||||
|
||||
except (ValueError, IndexError) as e:
|
||||
logger.error(f"Ошибка при обработке сообщения пользователя {message.chat.id}: {e}")
|
||||
await message.answer("❌ Произошла ошибка. Пожалуйста, попробуйте снова.")
|
||||
else:
|
||||
await show_start_menu(message, admin, session)
|
||||
|
||||
|
||||
async def show_start_menu(message: Message, admin: bool, session: Any):
|
||||
"""Функция для отображения стандартного меню"""
|
||||
logger.info(f"Показываю главное меню для пользователя {message.chat.id}")
|
||||
trial_status = await get_trial(message.chat.id, session)
|
||||
image_path = os.path.join("img", "pic.jpg")
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
|
||||
if trial_status == 0:
|
||||
builder.row(InlineKeyboardButton(text="🔗 Подключить VPN", callback_data="connect_vpn"))
|
||||
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="📞 Техническая поддержка", url=SUPPORT_CHAT_URL),
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="📢 Официальный канал", url=CHANNEL_URL),
|
||||
InlineKeyboardButton(text="📞 Поддержка", url=SUPPORT_CHAT_URL),
|
||||
InlineKeyboardButton(text="📢 Канал", url=CHANNEL_URL),
|
||||
)
|
||||
|
||||
if admin:
|
||||
builder.row(InlineKeyboardButton(text="🔧 Администратор", callback_data="admin"))
|
||||
|
||||
builder.row(InlineKeyboardButton(text="🌐 О нашем VPN", callback_data="about_vpn"))
|
||||
|
||||
if os.path.isfile(image_path):
|
||||
@@ -98,22 +214,39 @@ async def handle_connect_vpn(callback_query: CallbackQuery, session: Any):
|
||||
url=f'{CONNECT_ANDROID}{trial_key_info["key"]}',
|
||||
),
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="💻 Windows/Linux", callback_data=f"connect_pc|{email}"))
|
||||
builder.row(InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile"))
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="💻 Компьютеры", callback_data=f"connect_pc|{email}"
|
||||
),
|
||||
InlineKeyboardButton(
|
||||
text="📺 Андроид TV", callback_data=f"connect_tv|{email}"
|
||||
)
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="👤 Личный кабинет", callback_data="profile")
|
||||
)
|
||||
|
||||
await callback_query.message.answer(key_message, reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
key_message, reply_markup=builder.as_markup()
|
||||
)
|
||||
|
||||
|
||||
@router.callback_query(F.data == "about_vpn")
|
||||
async def handle_about_vpn(callback_query: CallbackQuery):
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(InlineKeyboardButton(text="💰 Поддержать проект", callback_data="donate"))
|
||||
|
||||
if DONATIONS_ENABLE:
|
||||
builder.row(InlineKeyboardButton(text="💰 Поддержать проект", callback_data="donate"))
|
||||
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="📞 Техническая поддержка", url=SUPPORT_CHAT_URL),
|
||||
)
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="📢 Официальный канал", url=CHANNEL_URL),
|
||||
)
|
||||
if CHANNEL_EXISTS:
|
||||
builder.row(
|
||||
InlineKeyboardButton(text="📢 Официальный канал", url=CHANNEL_URL),
|
||||
)
|
||||
builder.row(InlineKeyboardButton(text="⬅️ Назад", callback_data="start"))
|
||||
|
||||
await callback_query.message.answer(get_about_vpn("3.2.2-Release"), reply_markup=builder.as_markup())
|
||||
await callback_query.message.answer(
|
||||
get_about_vpn("3.2.3-minor"), reply_markup=builder.as_markup()
|
||||
)
|
||||
|
||||
+6
-3
@@ -1,6 +1,5 @@
|
||||
import random
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
import asyncpg
|
||||
|
||||
@@ -68,7 +67,9 @@ async def get_least_loaded_cluster() -> str:
|
||||
return least_loaded_cluster
|
||||
|
||||
|
||||
async def handle_error(tg_id: int, callback_query: Optional[object] = None, message: str = "") -> None:
|
||||
async def handle_error(
|
||||
tg_id: int, callback_query: object | None = None, message: str = ""
|
||||
) -> None:
|
||||
"""
|
||||
Обрабатывает ошибку, отправляя сообщение пользователю.
|
||||
|
||||
@@ -80,7 +81,9 @@ async def handle_error(tg_id: int, callback_query: Optional[object] = None, mess
|
||||
try:
|
||||
if callback_query and hasattr(callback_query, "message"):
|
||||
try:
|
||||
await bot.delete_message(chat_id=tg_id, message_id=callback_query.message.message_id)
|
||||
await bot.delete_message(
|
||||
chat_id=tg_id, message_id=callback_query.message.message_id
|
||||
)
|
||||
except Exception as delete_error:
|
||||
logger.warning(f"Не удалось удалить сообщение: {delete_error}")
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -1,10 +1,16 @@
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import timedelta
|
||||
|
||||
from loguru import logger
|
||||
|
||||
logger.remove()
|
||||
log_folder = "logs"
|
||||
|
||||
if not os.path.exists(log_folder):
|
||||
os.makedirs(log_folder)
|
||||
|
||||
logger.remove()
|
||||
|
||||
level_mapping = {
|
||||
50: "CRITICAL",
|
||||
@@ -27,7 +33,6 @@ logging.basicConfig(handlers=[InterceptHandler()], level=0)
|
||||
logging.getLogger("httpcore").setLevel(logging.WARNING)
|
||||
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||
|
||||
# Настройка вывода в консоль
|
||||
logger.add(
|
||||
sys.stderr,
|
||||
level="INFO",
|
||||
@@ -35,13 +40,13 @@ logger.add(
|
||||
colorize=True,
|
||||
)
|
||||
|
||||
# Настройка записи в файл
|
||||
log_file_path = os.path.join(log_folder, "logging.log")
|
||||
logger.add(
|
||||
"logging.log",
|
||||
log_file_path,
|
||||
level="DEBUG",
|
||||
format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {module}:{function}:{line} | {message}",
|
||||
rotation="60 minute",
|
||||
retention=24,
|
||||
rotation=timedelta(minutes=60),
|
||||
retention=timedelta(days=3),
|
||||
)
|
||||
|
||||
logger = logger
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from typing import Any, Awaitable, Callable, Dict, Union
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
from aiogram import BaseMiddleware
|
||||
from aiogram.types import TelegramObject
|
||||
@@ -9,16 +10,16 @@ from config import ADMIN_ID
|
||||
class AdminMiddleware(BaseMiddleware):
|
||||
async def __call__(
|
||||
self,
|
||||
handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]],
|
||||
handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
|
||||
event: TelegramObject,
|
||||
data: Dict[str, Any],
|
||||
data: dict[str, Any],
|
||||
) -> Any:
|
||||
data["admin"] = self._check_admin_access(event)
|
||||
return await handler(event, data)
|
||||
|
||||
def _check_admin_access(self, event: TelegramObject) -> bool:
|
||||
try:
|
||||
admin_ids: Union[int, list[int]] = ADMIN_ID
|
||||
admin_ids: int | list[int] = ADMIN_ID
|
||||
if isinstance(admin_ids, list):
|
||||
return event.from_user.id in admin_ids
|
||||
return event.from_user.id == admin_ids
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
from typing import Any, Awaitable, Callable, Dict
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
import asyncpg
|
||||
from aiogram import BaseMiddleware
|
||||
from aiogram.types import TelegramObject
|
||||
import asyncpg
|
||||
|
||||
from config import DATABASE_URL
|
||||
|
||||
@@ -10,9 +11,9 @@ from config import DATABASE_URL
|
||||
class DatabaseMiddleware(BaseMiddleware):
|
||||
async def __call__(
|
||||
self,
|
||||
handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]],
|
||||
handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
|
||||
event: TelegramObject,
|
||||
data: Dict[str, Any],
|
||||
data: dict[str, Any],
|
||||
) -> Any:
|
||||
conn = await asyncpg.connect(DATABASE_URL)
|
||||
try:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from typing import Any, Awaitable, Callable, Dict
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
from aiogram import BaseMiddleware
|
||||
from aiogram.types import CallbackQuery, Message, TelegramObject
|
||||
@@ -7,15 +8,17 @@ from aiogram.types import CallbackQuery, Message, TelegramObject
|
||||
class DeleteMessageMiddleware(BaseMiddleware):
|
||||
async def __call__(
|
||||
self,
|
||||
handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]],
|
||||
handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
|
||||
event: TelegramObject,
|
||||
data: Dict[str, Any],
|
||||
data: dict[str, Any],
|
||||
) -> Any:
|
||||
if isinstance(event, (Message, CallbackQuery)):
|
||||
if isinstance(event, Message):
|
||||
if not event.text == "/start":
|
||||
if not event.text or not event.text.startswith("/start"):
|
||||
try:
|
||||
await event.bot.delete_message(event.chat.id, event.message_id - 1)
|
||||
await event.bot.delete_message(
|
||||
event.chat.id, event.message_id - 1
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
await event.delete()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from typing import Any, Awaitable, Callable, Dict, Optional
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
from aiogram import BaseMiddleware
|
||||
from aiogram.types import CallbackQuery, Message, TelegramObject
|
||||
@@ -9,9 +10,9 @@ from logger import logger
|
||||
class LoggingMiddleware(BaseMiddleware):
|
||||
async def __call__(
|
||||
self,
|
||||
handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]],
|
||||
handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
|
||||
event: TelegramObject,
|
||||
data: Dict[str, Any],
|
||||
data: dict[str, Any],
|
||||
) -> Any:
|
||||
user_info = self._extract_user_info(event)
|
||||
|
||||
@@ -23,7 +24,7 @@ class LoggingMiddleware(BaseMiddleware):
|
||||
)
|
||||
return await handler(event, data)
|
||||
|
||||
def _extract_user_info(self, event: TelegramObject) -> Dict[str, Optional[str]]:
|
||||
def _extract_user_info(self, event: TelegramObject) -> dict[str, str | None]:
|
||||
user_id = None
|
||||
username = None
|
||||
action = None
|
||||
|
||||
+4
-3
@@ -1,4 +1,5 @@
|
||||
from typing import Any, Awaitable, Callable, Dict
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
from aiogram import BaseMiddleware
|
||||
from aiogram.types import TelegramObject, User
|
||||
@@ -9,9 +10,9 @@ from database import upsert_user
|
||||
class UserMiddleware(BaseMiddleware):
|
||||
async def __call__(
|
||||
self,
|
||||
handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]],
|
||||
handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
|
||||
event: TelegramObject,
|
||||
data: Dict[str, Any],
|
||||
data: dict[str, Any],
|
||||
) -> Any:
|
||||
if user := data.get("event_from_user"):
|
||||
await self._process_user(user)
|
||||
|
||||
+16
-26
@@ -1,27 +1,17 @@
|
||||
[tool.black]
|
||||
line-length = 120 # Совпадает с flake8
|
||||
target-version = ['py39','py310','py311'] # Укажите версию Python вашего проекта
|
||||
skip-string-normalization = true # Отключает нормализацию кавычек
|
||||
include = '\.pyi?$' # Включает Python-файлы
|
||||
exclude = '''
|
||||
/(
|
||||
\.git
|
||||
| \.hg
|
||||
| \.mypy_cache
|
||||
| \.tox
|
||||
| \.venv
|
||||
| _build
|
||||
| buck-out
|
||||
| build
|
||||
| dist
|
||||
)/
|
||||
''' # Исключает системные папки
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
target-version = "py310"
|
||||
|
||||
[tool.isort]
|
||||
profile = "black" # Устанавливает совместимость с black
|
||||
line_length = 120
|
||||
multi_line_output = 3 # Формат многострочных импортов
|
||||
include_trailing_comma = true # Совместимость с black
|
||||
force_sort_within_sections = true # Сортировка внутри секций
|
||||
sections = ["FUTURE", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER"]
|
||||
skip_gitignore = true # Учитывать .gitignore
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "W", "I", "N", "UP", "ANN", "ASYNC", "S", "BLE", "FBT", "B", "A", "C4", "DTZ", "T10", "ISC", "ICN", "G", "PIE"]
|
||||
ignore = ["ANN101", "ANN102", "S101",'ANN201','ANN001','BLE001']
|
||||
|
||||
[tool.ruff.format]
|
||||
quote-style = "single"
|
||||
indent-style = "space"
|
||||
|
||||
[tool.darker]
|
||||
src = ["."]
|
||||
revision = "HEAD"
|
||||
diff = false
|
||||
check = false
|
||||
+2
-4
@@ -30,7 +30,5 @@ aiocryptopay
|
||||
py3xui
|
||||
sqlalchemy
|
||||
robokassa
|
||||
flake8
|
||||
black
|
||||
isort
|
||||
pylint
|
||||
ping3
|
||||
ruff
|
||||
+150
-7
@@ -1,13 +1,24 @@
|
||||
import asyncpg
|
||||
import asyncio
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from config import DATABASE_URL
|
||||
import asyncpg
|
||||
from aiogram.types import InlineKeyboardButton
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
from ping3 import ping
|
||||
|
||||
from bot import bot
|
||||
from config import ADMIN_ID, DATABASE_URL
|
||||
from database import get_servers_from_db
|
||||
from logger import logger
|
||||
|
||||
try:
|
||||
from config import CLUSTERS
|
||||
except ImportError:
|
||||
CLUSTERS = None
|
||||
logger.warning("Переменная CLUSTERS не найдена в конфигурации. Добавьте сервера через админ-панель!")
|
||||
logger.warning(
|
||||
"Переменная CLUSTERS не найдена в конфигурации. Добавьте сервера через админ-панель!"
|
||||
)
|
||||
|
||||
|
||||
async def sync_servers_with_db():
|
||||
@@ -16,7 +27,9 @@ async def sync_servers_with_db():
|
||||
Если CLUSTERS не найден, синхронизация не будет выполнена.
|
||||
"""
|
||||
if CLUSTERS is None:
|
||||
logger.info("Конфигурация CLUSTERS не найдена. Синхронизация не будет выполнена.")
|
||||
logger.info(
|
||||
"Конфигурация CLUSTERS не найдена. Синхронизация не будет выполнена."
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -46,12 +59,142 @@ async def sync_servers_with_db():
|
||||
server_info["SUBSCRIPTION"],
|
||||
server_info["INBOUND_ID"],
|
||||
)
|
||||
logger.info(f"Сервер {server_info['name']} из кластера {cluster_name} добавлен в базу данных.")
|
||||
logger.info(
|
||||
f"Сервер {server_info['name']} из кластера {cluster_name} добавлен в базу данных."
|
||||
)
|
||||
else:
|
||||
logger.info(f"Сервер {server_info['name']} из кластера {cluster_name} уже существует.")
|
||||
logger.info(
|
||||
f"Сервер {server_info['name']} из кластера {cluster_name} уже существует."
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при синхронизации серверов: {e}")
|
||||
finally:
|
||||
if 'conn' in locals():
|
||||
if "conn" in locals():
|
||||
await conn.close()
|
||||
|
||||
|
||||
last_ping_times = {}
|
||||
last_notification_times = {}
|
||||
|
||||
|
||||
async def ping_server(server_ip: str) -> bool:
|
||||
"""
|
||||
Функция пинга сервера.
|
||||
Возвращает True, если сервер доступен, иначе False.
|
||||
"""
|
||||
try:
|
||||
logger.debug(f"Пингуем сервер {server_ip}...")
|
||||
response = ping(server_ip, timeout=3)
|
||||
if response is False:
|
||||
logger.warning(f"Сервер {server_ip} не отвечает.")
|
||||
return False
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при пинге сервера {server_ip}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def notify_admin(server_name: str):
|
||||
"""
|
||||
Отправляет уведомление всем администраторам о недоступности сервера.
|
||||
Уведомления отправляются не чаще чем раз в 3 минуты.
|
||||
"""
|
||||
try:
|
||||
current_time = datetime.now()
|
||||
last_notification_time = last_notification_times.get(server_name)
|
||||
|
||||
if last_notification_time and current_time - last_notification_time < timedelta(
|
||||
minutes=3
|
||||
):
|
||||
logger.info(
|
||||
f"Не отправляем уведомление для сервера {server_name}, так как прошло менее 3 минут."
|
||||
)
|
||||
return
|
||||
|
||||
logger.info(
|
||||
f"Отправка уведомлений администратору о недоступности сервера {server_name}..."
|
||||
)
|
||||
|
||||
builder = InlineKeyboardBuilder()
|
||||
builder.row(
|
||||
InlineKeyboardButton(
|
||||
text="Управление сервером", callback_data=f"manage_server|{server_name}"
|
||||
)
|
||||
)
|
||||
|
||||
for admin_id in ADMIN_ID:
|
||||
await bot.send_message(
|
||||
admin_id,
|
||||
(
|
||||
f"❌ <b>Сервер '{server_name}'</b> не отвечает более 3 минут.\n\n"
|
||||
"Проверьте соединение к серверу, подключение к панели или удалите его из таблицы серверов в боте, "
|
||||
"чтобы не выдать подписку к неработающему серверу."
|
||||
),
|
||||
parse_mode="HTML",
|
||||
reply_markup=builder.as_markup(),
|
||||
)
|
||||
logger.info(
|
||||
f"Уведомление отправлено администратору с ID {admin_id} о сервере {server_name}."
|
||||
)
|
||||
|
||||
last_notification_times[server_name] = current_time
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при отправке уведомления администраторам: {e}")
|
||||
|
||||
|
||||
async def check_servers():
|
||||
"""
|
||||
Периодическая проверка серверов с учетом извлечения хоста из `api_url`.
|
||||
"""
|
||||
while True:
|
||||
servers = await get_servers_from_db()
|
||||
current_time = datetime.now()
|
||||
|
||||
logger.info(f"Начинаю проверку серверов: {current_time}")
|
||||
|
||||
for cluster_name, cluster_servers in servers.items():
|
||||
logger.debug(f"Проверка кластеров: {cluster_name}")
|
||||
for server in cluster_servers:
|
||||
original_api_url = server["api_url"]
|
||||
server_name = server["server_name"]
|
||||
|
||||
server_host = extract_host(original_api_url)
|
||||
logger.debug(
|
||||
f"Проверка доступности сервера '{server_name}' с хостом {server_host}"
|
||||
)
|
||||
|
||||
is_online = await ping_server(server_host)
|
||||
|
||||
if is_online:
|
||||
last_ping_times[server_name] = current_time
|
||||
else:
|
||||
last_ping_time = last_ping_times.get(server_name)
|
||||
if last_ping_time and current_time - last_ping_time > timedelta(
|
||||
minutes=3
|
||||
):
|
||||
logger.warning(
|
||||
f"Сервер {server_name} не отвечает более 3 минут. Отправляю уведомление."
|
||||
)
|
||||
await notify_admin(server_name)
|
||||
elif not last_ping_time:
|
||||
last_ping_times[server_name] = current_time
|
||||
logger.info(
|
||||
f"Сервер {server_name} не отвечал ранее, но теперь зарегистрирован."
|
||||
)
|
||||
|
||||
logger.info("Завершена проверка всех серверов.")
|
||||
await asyncio.sleep(30)
|
||||
|
||||
|
||||
def extract_host(api_url: str) -> str:
|
||||
"""
|
||||
Извлекает только хост из `api_url` (без путей, портов и параметров).
|
||||
"""
|
||||
match = re.match(r"(https?://)?([^:/]+)", api_url)
|
||||
if match:
|
||||
host = match.group(2)
|
||||
logger.debug(f"Извлечён хост: {host} из URL: {api_url}")
|
||||
return host
|
||||
logger.error(f"Не удалось извлечь хост из URL: {api_url}")
|
||||
return api_url
|
||||
|
||||
Reference in New Issue
Block a user