├── .github
├── FUNDING.yml
└── workflows
│ └── python-app.yml
├── .gitignore
├── requirements.txt
├── Dockerfile
├── .dockerignore
├── states.py
├── config.py
├── payments.py
├── docker-compose.yaml
├── README.md
├── README_ru.md
├── CODE_OF_CONDUCT.md
├── kb.py
├── LICENSE.md
├── db.py
└── main.py
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | custom: ['https://boosty.to/schr1k/donate']
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | venv
2 | .idea
3 | __pycache__
4 | *.log
5 | test_*.py
6 | .env
7 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | aiogram==3.3.0
2 | asyncpg==0.29.0
3 | redis==5.0.1
4 | yookassa==3.0.0
5 | python-dotenv==1.0.0
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.11-alpine
2 |
3 | WORKDIR /app
4 |
5 | COPY . .
6 |
7 | RUN pip install -r requirements.txt
8 |
9 | CMD ["python3.11", "main.py"]
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | .git
2 | .idea
3 | venv
4 | __pycache__
5 | *.log
6 | test_*.py
7 | README.md
8 | .gitignore
9 | .dockerignore
10 | Dockerfile
11 | docker-compose.yaml
12 |
--------------------------------------------------------------------------------
/states.py:
--------------------------------------------------------------------------------
1 | from aiogram.fsm.state import State, StatesGroup
2 |
3 |
4 | class RegState(StatesGroup):
5 | name = State()
6 | sex = State()
7 | age = State()
8 |
9 |
10 | class Chatting(StatesGroup):
11 | msg = State()
12 |
13 |
14 | class NameState(StatesGroup):
15 | name = State()
16 |
17 |
18 | class AgeState(StatesGroup):
19 | age = State()
20 |
21 |
22 | class SexState(StatesGroup):
23 | sex = State()
24 |
25 |
26 | class Search(StatesGroup):
27 | searching = State()
28 |
29 |
30 | class Bug(StatesGroup):
31 | bug = State()
32 |
33 |
34 | class Idea(StatesGroup):
35 | idea = State()
36 |
37 |
--------------------------------------------------------------------------------
/config.py:
--------------------------------------------------------------------------------
1 | import os
2 | from dotenv import load_dotenv
3 |
4 | load_dotenv()
5 |
6 | # Telegram
7 | TOKEN = str(os.getenv('TOKEN'))
8 | BUGS_GROUP_ID = str(os.getenv('BUGS_GROUP_ID'))
9 | IDEAS_GROUP_ID = str(os.getenv('IDEAS_GROUP_ID'))
10 | RETURN_URL = str(os.getenv('RETURN_URL'))
11 |
12 | # Postgres
13 | POSTGRES_USER = str(os.getenv('POSTGRES_USER'))
14 | POSTGRES_PASSWORD = str(os.getenv('POSTGRES_PASSWORD'))
15 | POSTGRES_DB = str(os.getenv('POSTGRES_DB'))
16 | POSTGRES_HOST = str(os.getenv('POSTGRES_HOST'))
17 | POSTGRES_PORT = str(os.getenv('POSTGRES_PORT'))
18 |
19 | # Redis
20 | REDIS_HOST = str(os.getenv('REDIS_HOST'))
21 | REDIS_PORT = str(os.getenv('REDIS_PORT'))
22 | REDIS_DB = str(os.getenv('REDIS_DB'))
23 |
24 | # Yookassa
25 | YOOKASSA_ACCOUNT_ID = int(os.getenv('YOOKASSA_ACCOUNT_ID'))
26 | YOOKASSA_SECRET_KEY = str(os.getenv('YOOKASSA_SECRET_KEY'))
27 |
--------------------------------------------------------------------------------
/.github/workflows/python-app.yml:
--------------------------------------------------------------------------------
1 | name: Python application
2 |
3 | on:
4 | push:
5 | branches: [ "master" ]
6 | pull_request:
7 | branches: [ "master" ]
8 |
9 | permissions:
10 | contents: read
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 | strategy:
17 | matrix:
18 | python-version: ["3.9", "3.10", "3.11", "3.12"]
19 |
20 | steps:
21 | - uses: actions/checkout@v4
22 | - name: Set up Python ${{ matrix.python-version }}
23 | uses: actions/setup-python@v4
24 | with:
25 | python-version: ${{ matrix.python-version }}
26 | - name: Install dependencies
27 | run: |
28 | python -m pip install --upgrade pip
29 | pip install flake8
30 | pip install -r requirements.txt
31 | - name: Lint with flake8
32 | run: |
33 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
34 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
35 |
36 |
--------------------------------------------------------------------------------
/payments.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | from config import RETURN_URL, YOOKASSA_ACCOUNT_ID, YOOKASSA_SECRET_KEY
4 |
5 | from yookassa import Configuration, Payment
6 | import uuid
7 |
8 | Configuration.account_id = YOOKASSA_ACCOUNT_ID
9 | Configuration.secret_key = YOOKASSA_SECRET_KEY
10 |
11 |
12 | def get_payments() -> str:
13 | payments = Payment.list()
14 | return payments.json()
15 |
16 |
17 | def create_payment(amount: int, description: str) -> tuple[str, str]:
18 | idempotence_key = str(uuid.uuid4())
19 | payment = Payment.create({
20 | "amount": {
21 | "value": float(str(amount)),
22 | "currency": "RUB"
23 | },
24 | "confirmation": {
25 | "type": "redirect",
26 | "return_url": RETURN_URL
27 | },
28 | "description": description
29 | }, idempotence_key)
30 | return payment.confirmation.confirmation_url, payment.id
31 |
32 |
33 | def get_payment_status(payment_id: str) -> str:
34 | payment = Payment.find_one(payment_id)
35 | return json.loads(payment.json())['status']
36 |
37 |
38 | def confirm_payment(payment_id: str) -> str:
39 | idempotence_key = str(uuid.uuid4())
40 | response = Payment.capture(
41 | payment_id,
42 | {},
43 | idempotence_key
44 | )
45 | return response.json()
46 |
--------------------------------------------------------------------------------
/docker-compose.yaml:
--------------------------------------------------------------------------------
1 | services:
2 | postgres:
3 | container_name:
4 | postgres
5 | image:
6 | postgres:alpine
7 | ports:
8 | - ${POSTGRES_PORT}
9 | restart:
10 | unless-stopped
11 | volumes:
12 | - postgres-data:/var/lib/postgresql/data
13 | env_file:
14 | .env
15 | healthcheck:
16 | test: ["CMD-SHELL", "sh -c 'pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}'"]
17 | interval: 10s
18 | timeout: 5s
19 | retries: 5
20 | start_period: 10s
21 | deploy:
22 | resources:
23 | limits:
24 | cpus: "0.1"
25 | memory: 100mb
26 | redis:
27 | container_name:
28 | redis
29 | image:
30 | redis:alpine
31 | ports:
32 | - ${REDIS_PORT}
33 | restart:
34 | unless-stopped
35 | volumes:
36 | - redis-data:/var/lib/redis/data
37 | env_file:
38 | .env
39 | healthcheck:
40 | test: ["CMD-SHELL", "redis-cli PING | grep PONG"]
41 | interval: 10s
42 | timeout: 5s
43 | retries: 5
44 | start_period: 10s
45 | deploy:
46 | resources:
47 | limits:
48 | cpus: "0.1"
49 | memory: 100mb
50 | bot:
51 | container_name:
52 | bot
53 | build:
54 | context:
55 | .
56 | dockerfile:
57 | Dockerfile
58 | restart:
59 | unless-stopped
60 | depends_on:
61 | - redis
62 | - postgres
63 | deploy:
64 | resources:
65 | limits:
66 | cpus: "0.2"
67 | memory: 200mb
68 | volumes:
69 | postgres-data:
70 | redis-data:
71 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | > Readme на русском доступно [здесь](./README_ru.md).
2 |
3 | ## Overview:
4 | * Project is **completely asynchronous** thanks to [aiogram](https://github.com/aiogram/aiogram), [asyncpg](https://github.com/MagicStack/asyncpg) and [redis asyncio](https://github.com/redis/redis-py).
5 | * It's easy to test and debug because 2 levels of logging are provided.
6 | * The [yookassa](https://yookassa.ru/developers?lang=en) **test** API is integrated.
7 |
8 | ### Setup:
9 | 1. Telegram:
10 | * Create new bot via [BotFather](https://t.me/BotFather).
11 | * Create groups (not channels) for bug reports and ideas, add your bot to them and give him admin rights (to get group id forward a message from it to this [bot](https://t.me/getmyid_bot)).
12 |
13 | 2. Create yookassa [test shop](https://yookassa.ru/my/boarding?shopMenuAction=createShop).
14 |
15 | 3. Create .env file with following structure ([dotenv guide](https://dev.to/jakewitcher/using-env-files-for-environment-variables-in-python-applications-55a1)):
16 |
17 | ```dotenv
18 | # Telegram
19 | TOKEN='token from BotFather'
20 | BUGS_GROUP_ID='group id' # starts with "-"
21 | IDEAS_GROUP_ID='group id' # starts with "-"
22 | RETURN_URL='link to your bot' # needed for yookassa
23 |
24 | # Postgres
25 | POSTGRES_USER='postgres'
26 | POSTGRES_PASSWORD='postgres'
27 | POSTGRES_DB='AnonChat'
28 | POSTGRES_HOST='localhost' # change it to container name if you use docker
29 | POSTGRES_PORT='5432'
30 |
31 | # Redis
32 | REDIS_DB='1'
33 | REDIS_HOST='localhost' # change it to container name if you use docker
34 | REDIS_PORT='6379'
35 |
36 | # Yookassa
37 | YOOKASSA_ACCOUNT_ID='yookassa shop id' # note that this value should be int
38 | YOOKASSA_SECRET_KEY='yookassa api token'
39 | ```
40 |
41 | ### Running:
42 | The easiest way is to run project via [docker](https://docs.docker.com/).
43 | 1. Make sure you have installed [docker](https://docs.docker.com/get-docker/).
44 |
45 | 2. Build the project (it may take some time):
46 | ```bash
47 | docker compose build
48 | ```
49 |
50 | 3. Run the project:
51 | ```bash
52 | docker compose up
53 | ```
54 |
55 | That's all! [Docker compose file](./docker-compose.yaml) will install and configure everything.
56 |
57 | ---
58 | Alternatively you can run it manually:
59 | 1. Create venv:
60 | ```bash
61 | python -m venv venv
62 | ```
63 |
64 | 2. Activate venv:
65 |
66 | * On Windows:
67 | ```bash
68 | venv\Scripts\activate
69 | ```
70 | * On Linux and macOS:
71 | ```bash
72 | source venv/bin/activate
73 | ```
74 |
75 | 3. Install dependencies:
76 | ```bash
77 | pip install -r requirements.txt
78 | ```
79 |
80 | 4. Install [Redis](https://redis.io/docs/getting-started/installation/).
81 |
82 | 5. Install [Postgres](https://www.postgresql.org/download/) (if you changed user or password during installation make sure to also change it in [.env file](./.env)).
83 |
84 | 6. Run the project:
85 | ```bash
86 | python main.py
87 | ```
88 |
89 | ---
90 | Feel free to [ask questions](https://github.com/schr1k/AnonChat_2.0/discussions/categories/q-a) and [share your ideas](https://github.com/schr1k/AnonChat_2.0/discussions/categories/ideas).
91 |
92 | Plans on the project are [here](https://github.com/users/schr1k/projects/3).
--------------------------------------------------------------------------------
/README_ru.md:
--------------------------------------------------------------------------------
1 | > Readme on english is available [here](./README.md).
2 |
3 | ## Обзор:
4 | * Проект **полностью асинхронен** благодаря [aiogram](https://github.com/aiogram/aiogram), [asyncpg](https://github.com/MagicStack/asyncpg) и [redis asyncio](https://github.com/redis/redis-py).
5 | * Предусмотренно 2 уровня логирования.
6 | * Подключен **тестовый** магазин [yookassa](https://yookassa.ru/developers?lang=en).
7 |
8 | ### Установка:
9 | 1. Telegram:
10 | * Создайте бота через [BotFather](https://t.me/BotFather).
11 | * Создайте группы (не каналы) для отслеживания багов и идей, добавьте в них вашего бота и сделайте бота админом этих групп (чтобы получить id канала, перешлите любое сообщение оттуда этому [боту](https://t.me/getmyid_bot)).
12 |
13 | 2. Создайте [тестовый магазин](https://yookassa.ru/my/boarding?shopMenuAction=createShop) юкасса.
14 |
15 | 3. Создайте .env файл с такой структурой ([гайд по dotenv](https://dev.to/jakewitcher/using-env-files-for-environment-variables-in-python-applications-55a1)):
16 |
17 | ```dotenv
18 | # Telegram
19 | TOKEN='token from BotFather'
20 | BUGS_GROUP_ID='group id' # начинается на "-"
21 | IDEAS_GROUP_ID='group id' # начинается на "-"
22 | RETURN_URL='link to your bot' # нужно для юкассы
23 |
24 | # Postgres
25 | POSTGRES_USER='postgres'
26 | POSTGRES_PASSWORD='postgres'
27 | POSTGRES_DB='AnonChat'
28 | POSTGRES_HOST='localhost' # измените на название контейнера если вы используете докер
29 | POSTGRES_PORT='5432'
30 |
31 | # Redis
32 | REDIS_DB='1'
33 | REDIS_HOST='localhost' # измените на название контейнера если вы используете докер
34 | REDIS_PORT='6379'
35 |
36 | # Yookassa
37 | YOOKASSA_ACCOUNT_ID='yookassa shop id' # это значение должно быть числом
38 | YOOKASSA_SECRET_KEY='yookassa api token'
39 | ```
40 |
41 | ### Запуск:
42 | Самый простой способ - запустить проект с помощью [docker](https://docs.docker.com/).
43 | 1. Убедитесь, что у вас установлен [docker](https://docs.docker.com/get-docker/).
44 |
45 | 2. Скомпилируйте проект (это займет некоторое время):
46 | ```bash
47 | docker compose build
48 | ```
49 |
50 | 3. Запустите проект:
51 | ```bash
52 | docker compose up
53 | ```
54 |
55 | На этом все! [Docker compose файл](./docker-compose.yaml) установит и настроит все необходимое.
56 |
57 | ---
58 | Также вы можете запустить проект вручную:
59 | 1. Создайте виртуальное окружение:
60 | ```bash
61 | python -m venv venv
62 | ```
63 |
64 | 2. Активируйте виртуальное окружение:
65 |
66 | * Windows:
67 | ```bash
68 | venv\Scripts\activate
69 | ```
70 | * Linux и macOS:
71 | ```bash
72 | source venv/bin/activate
73 | ```
74 |
75 | 3. Установите зависимости:
76 | ```bash
77 | pip install -r requirements.txt
78 | ```
79 |
80 | 4. Установите [Redis](https://redis.io/docs/getting-started/installation/).
81 |
82 | 5. Установите [Postgres](https://www.postgresql.org/download/) (если вы меняли имя пользователя или пароль при установке измените их в [.env файле](./.env)).
83 |
84 | 6. Запустите проект:
85 | ```bash
86 | python main.py
87 | ```
88 |
89 | ---
90 | Вы можете [задать вопрос](https://github.com/schr1k/AnonChat_2.0/discussions/categories/q-a) или [поделиться идеей](https://github.com/schr1k/AnonChat_2.0/discussions/categories/ideas) о проекте.
91 |
92 | Планы по проекту находятся [здесь](https://github.com/users/schr1k/projects/3).
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | https://t.me/schr1k_work.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/kb.py:
--------------------------------------------------------------------------------
1 | from aiogram.types import InlineKeyboardButton
2 | from aiogram.utils.keyboard import InlineKeyboardBuilder
3 |
4 |
5 | # Назад ================================================================================================================
6 | to_main = InlineKeyboardButton(text='🔙 На главную', callback_data='to_main')
7 | to_ref = InlineKeyboardButton(text='🔙 Назад', callback_data='ref')
8 | to_profile = InlineKeyboardButton(text='🔙 Назад', callback_data='profile')
9 | to_settings = InlineKeyboardButton(text='🔙 Назад', callback_data='settings')
10 | to_stats = InlineKeyboardButton(text='🔙 Назад', callback_data='stats')
11 | to_tops = InlineKeyboardButton(text='🔙 Назад', callback_data='tops')
12 | to_vip = InlineKeyboardButton(text='🔙 Назад', callback_data='vip')
13 | to_lobby = InlineKeyboardButton(text='🔙 Назад', callback_data='lobby')
14 | to_buy = InlineKeyboardButton(text='🔙 Назад', callback_data='buy_vip')
15 |
16 |
17 | to_main_kb = InlineKeyboardBuilder().add(to_main).as_markup()
18 | to_ref_kb = InlineKeyboardBuilder().add(to_ref).as_markup()
19 | to_settings_kb = InlineKeyboardBuilder().add(to_settings).as_markup()
20 | to_tops_kb = InlineKeyboardBuilder().add(to_tops).as_markup()
21 | to_lobby_kb = InlineKeyboardBuilder().add(to_lobby).as_markup()
22 | to_buy_kb = InlineKeyboardBuilder().add(to_buy).as_markup()
23 |
24 |
25 | # Отмена ===============================================================================================================
26 | cancel_search = InlineKeyboardButton(text='🚫 Отменить поиск', callback_data='cancel_search')
27 | cancel_search_kb = InlineKeyboardBuilder().add(cancel_search).as_markup()
28 |
29 |
30 | # Лобби ================================================================================================================
31 | rules = InlineKeyboardButton(text='Правила 📖', callback_data='rules')
32 | registrate = InlineKeyboardButton(text='Регистрация ✍️', callback_data='registrate')
33 | lobby_kb = InlineKeyboardBuilder().row(rules, registrate).as_markup()
34 |
35 |
36 | # Главное меню =========================================================================================================
37 | search_man = InlineKeyboardButton(text='Найти ♂️', callback_data='search_man')
38 | search = InlineKeyboardButton(text='Рандом 🔀', callback_data='search')
39 | search_woman = InlineKeyboardButton(text='Найти ♀️', callback_data='search_woman')
40 | vip = InlineKeyboardButton(text='Вип 👑', callback_data='vip')
41 | ref = InlineKeyboardButton(text='Рефералка 💼', callback_data='ref')
42 | profile = InlineKeyboardButton(text='Профиль 👤', callback_data='profile')
43 | main_kb = InlineKeyboardBuilder().row(search_man, search, search_woman).row(vip, ref, profile).as_markup()
44 |
45 |
46 | # Профиль ==============================================================================================================
47 | settings = InlineKeyboardButton(text='⚙️ Настройки', callback_data='settings')
48 | stats = InlineKeyboardButton(text='📈 Статистика', callback_data='stats')
49 | profile_kb = InlineKeyboardBuilder().add(settings).add(stats).add(to_main).adjust(1).as_markup()
50 |
51 |
52 | # Настройки ===========================================================================================================
53 | name = InlineKeyboardButton(text='🅰️ Имя', callback_data='name')
54 | age = InlineKeyboardButton(text='🔞 Возраст', callback_data='age')
55 | sex = InlineKeyboardButton(text='👫 Пол', callback_data='sex')
56 | settings_kb = InlineKeyboardBuilder().add(name).add(age).add(sex).add(to_profile).adjust(1).as_markup()
57 |
58 |
59 | # Рефералка ============================================================================================================
60 | def ref_kb(flag: bool):
61 | trade = InlineKeyboardButton(text='Обменять 💎', callback_data='trade')
62 | on = InlineKeyboardButton(text='Включить уведомления 🔔', callback_data='on')
63 | off = InlineKeyboardButton(text='Выключить уведомления 🔕', callback_data='off')
64 | if flag:
65 | return InlineKeyboardBuilder().add(trade).add(off).add(to_main).adjust(1).as_markup()
66 | else:
67 | return InlineKeyboardBuilder().add(trade).add(on).add(to_main).adjust(1).as_markup()
68 |
69 |
70 | # Статистика ===========================================================================================================
71 | top = InlineKeyboardButton(text='🏆 Рейтинги', callback_data='tops')
72 | statistic_kb = InlineKeyboardBuilder().add(top).add(to_profile).adjust(1).as_markup()
73 |
74 |
75 | # Топы =================================================================================================================
76 | top_messages = InlineKeyboardButton(text='🔝 Топ 5 по сообщениям', callback_data='top_messages')
77 | top_likes = InlineKeyboardButton(text='🔝 Топ 5 по лайкам', callback_data='top_likes')
78 | top_refs = InlineKeyboardButton(text='🔝 Топ 5 по рефам', callback_data='top_refs')
79 | top_kb = InlineKeyboardBuilder().add(top_messages).add(top_likes).add(top_refs).add(to_stats).adjust(1).as_markup()
80 |
81 |
82 | # Вип ==================================================================================================================
83 | free_vip = InlineKeyboardButton(text='🆓 Получить вип бесплатно', callback_data='ref')
84 | buy_vip = InlineKeyboardButton(text='💰 Купить/Продлить вип', callback_data='buy_vip')
85 | vip_kb = InlineKeyboardBuilder().add(free_vip).add(buy_vip).add(to_main).adjust(1).as_markup()
86 |
87 |
88 | # Покупка випа =========================================================================================================
89 | day = InlineKeyboardButton(text='👑 Вип на день - 20₽', callback_data='vip_day')
90 | week = InlineKeyboardButton(text='👑 Вип на неделю - 100₽', callback_data='vip_week')
91 | month = InlineKeyboardButton(text='👑 Вип на месяц - 300₽', callback_data='vip_month')
92 | buy_kb = InlineKeyboardBuilder().add(day).add(week).add(month).add(to_vip).adjust(1).as_markup()
93 |
94 |
95 | # Пол ==================================================================================================================
96 | male = InlineKeyboardButton(text='Мужской ♂️', callback_data='male')
97 | female = InlineKeyboardButton(text='Женский ♀️', callback_data='female')
98 | sex_kb = InlineKeyboardBuilder().row(male, female).as_markup()
99 |
100 |
101 | # Оценка ===============================================================================================================
102 | like = InlineKeyboardButton(text='👍 Лайк', callback_data='like')
103 | dislike = InlineKeyboardButton(text='👎 Дизлайк', callback_data='dislike')
104 | next_dialog = InlineKeyboardButton(text='➡️ Следующий диалог', callback_data='search')
105 | search_kb = InlineKeyboardBuilder().row(like, dislike).row(next_dialog).row(to_main).as_markup()
106 | review_kb = InlineKeyboardBuilder().add(next_dialog).add(to_main).adjust(1).as_markup()
107 |
108 | # Поиск по полу без випа ===============================================================================================
109 | sex_search_no_vip_kb = InlineKeyboardBuilder().add(buy_vip, to_main).adjust(1).as_markup()
110 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | # Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International
2 |
3 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
4 |
5 | **Using Creative Commons Public Licenses**
6 |
7 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
8 |
9 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
10 |
11 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
12 |
13 | ## Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License
14 |
15 | 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-NoDerivatives 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.
16 |
17 | ### Section 1 – Definitions.
18 |
19 | 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.
20 |
21 | b. __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.
22 |
23 | e. __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.
24 |
25 | f. __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.
26 |
27 | h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
28 |
29 | i. __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.
30 |
31 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
32 |
33 | 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.
34 |
35 | 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.
36 |
37 | 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.
38 |
39 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. __Your__ has a corresponding meaning.
40 |
41 | ### Section 2 – Scope.
42 |
43 | a. ___License grant.___
44 |
45 | 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:
46 |
47 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
48 |
49 | B. produce and reproduce, but not Share, Adapted Material for NonCommercial purposes only.
50 |
51 | 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.
52 |
53 | 3. __Term.__ The term of this Public License is specified in Section 6(a).
54 |
55 | 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.
56 |
57 | 5. __Downstream recipients.__
58 |
59 | 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.
60 |
61 | 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.
62 |
63 | 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).
64 |
65 | b. ___Other rights.___
66 |
67 | 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.
68 |
69 | 2. Patent and trademark rights are not licensed under this Public License.
70 |
71 | 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.
72 |
73 | ### Section 3 – License Conditions.
74 |
75 | Your exercise of the Licensed Rights is expressly made subject to the following conditions.
76 |
77 | a. ___Attribution.___
78 |
79 | 1. If You Share the Licensed Material, You must:
80 |
81 | A. retain the following if it is supplied by the Licensor with the Licensed Material:
82 |
83 | 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);
84 |
85 | ii. a copyright notice;
86 |
87 | iii. a notice that refers to this Public License;
88 |
89 | iv. a notice that refers to the disclaimer of warranties;
90 |
91 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
92 |
93 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
94 |
95 | 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.
96 |
97 | For the avoidance of doubt, You do not have permission under this Public License to Share Adapted Material.
98 |
99 | 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.
100 |
101 | 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.
102 |
103 | ### Section 4 – Sui Generis Database Rights.
104 |
105 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
106 |
107 | 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 and provided You do not Share Adapted Material;
108 |
109 | 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
110 |
111 | 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.
112 |
113 | 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.
114 |
115 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability.
116 |
117 | 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.__
118 |
119 | 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.__
120 |
121 | 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.
122 |
123 | ### Section 6 – Term and Termination.
124 |
125 | 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.
126 |
127 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
128 |
129 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
130 |
131 | 2. upon express reinstatement by the Licensor.
132 |
133 | 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.
134 |
135 | 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.
136 |
137 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
138 |
139 | ### Section 7 – Other Terms and Conditions.
140 |
141 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
142 |
143 | 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.
144 |
145 | ### Section 8 – Interpretation.
146 |
147 | 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.
148 |
149 | 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.
150 |
151 | 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.
152 |
153 | 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.
154 |
155 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. The text of the Creative Commons public licenses is dedicated to the public domain under the [CC0 Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/legalcode). Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
156 | >
157 | > Creative Commons may be contacted at [creativecommons.org](http://creativecommons.org).
158 |
--------------------------------------------------------------------------------
/db.py:
--------------------------------------------------------------------------------
1 | import asyncpg
2 |
3 | from config import *
4 |
5 |
6 | class DB:
7 | def __init__(self):
8 | self.pool = None
9 |
10 | async def connect(self):
11 | self.pool = await asyncpg.create_pool(
12 | user=POSTGRES_USER,
13 | password=POSTGRES_PASSWORD,
14 | host=POSTGRES_HOST,
15 | port=POSTGRES_PORT,
16 | database=POSTGRES_DB
17 | )
18 |
19 | # Init table creation ==============================================================================================
20 | async def create_tables(self):
21 | async with self.pool.acquire() as connection:
22 | async with connection.transaction():
23 | await connection.execute('''
24 | CREATE TABLE IF NOT EXISTS users (
25 | id SERIAL PRIMARY KEY,
26 | name VARCHAR,
27 | age VARCHAR,
28 | sex VARCHAR,
29 | tg VARCHAR,
30 | connect_with VARCHAR,
31 | last_connect VARCHAR,
32 | chats INT DEFAULT 0,
33 | messages INT DEFAULT 0,
34 | likes INT DEFAULT 0,
35 | dislikes INT DEFAULT 0,
36 | refs INT DEFAULT 0,
37 | points INT DEFAULT 0,
38 | vip_ends VARCHAR(30),
39 | notifications INT DEFAULT 1
40 | );''')
41 |
42 | await connection.execute('''
43 | CREATE TABLE IF NOT EXISTS queue (
44 | tg VARCHAR,
45 | sex VARCHAR,
46 | op_sex VARCHAR
47 | );''')
48 |
49 | await connection.execute('''
50 | CREATE TABLE IF NOT EXISTS messages (
51 | tg VARCHAR,
52 | username VARCHAR,
53 | message VARCHAR,
54 | stamp VARCHAR
55 | );''')
56 |
57 | # SELECT ===========================================================================================================
58 | async def user_exists(self, tg: str) -> bool:
59 | async with self.pool.acquire() as connection:
60 | async with connection.transaction():
61 | result = await connection.fetchrow(
62 | 'SELECT tg FROM users WHERE tg = $1', tg
63 | )
64 | return False if result is None else True
65 |
66 | async def queue_exists(self, tg: str) -> bool:
67 | async with self.pool.acquire() as connection:
68 | async with connection.transaction():
69 | result = await connection.fetchrow(
70 | 'SELECT * FROM queue WHERE tg = $1', tg
71 | )
72 | return False if result is None else True
73 |
74 | async def count_users(self) -> str:
75 | async with self.pool.acquire() as connection:
76 | async with connection.transaction():
77 | result = await connection.fetchrow(
78 | 'SELECT COUNT(tg) FROM users'
79 | )
80 | return dict(result)['count']
81 |
82 | async def find_chat(self, tg: str):
83 | async with self.pool.acquire() as connection:
84 | async with connection.transaction():
85 | result = await connection.fetchrow(
86 | 'SELECT tg FROM queue WHERE tg <> $1', tg
87 | )
88 | return dict(result)['tg'] if result is not None else None
89 |
90 | async def find_chat_vip(self, tg: str, sex: str, op_sex: str):
91 | async with self.pool.acquire() as connection:
92 | async with connection.transaction():
93 | result = await connection.fetchrow(
94 | 'SELECT tg FROM queue WHERE tg <> $1 AND (op_sex = $2 OR op_sex IS null) AND sex = $3', tg, sex, op_sex
95 | )
96 | return dict(result)['tg'] if result is not None else None
97 |
98 | async def select_name(self, tg: str):
99 | async with self.pool.acquire() as connection:
100 | async with connection.transaction():
101 | result = await connection.fetchrow(
102 | 'SELECT name FROM users WHERE tg = $1', tg
103 | )
104 | return dict(result)['name']
105 |
106 | async def select_age(self, tg: str):
107 | async with self.pool.acquire() as connection:
108 | async with connection.transaction():
109 | result = await connection.fetchrow(
110 | 'SELECT age FROM users WHERE tg = $1',
111 | tg
112 | )
113 | return dict(result)['age']
114 |
115 | async def select_sex(self, tg: str):
116 | async with self.pool.acquire() as connection:
117 | async with connection.transaction():
118 | result = await connection.fetchrow(
119 | 'SELECT sex FROM users WHERE tg = $1', tg
120 | )
121 | return dict(result)['sex']
122 |
123 | async def select_connect_with(self, tg: str) -> str:
124 | async with self.pool.acquire() as connection:
125 | async with connection.transaction():
126 | result = await connection.fetchrow(
127 | 'SELECT connect_with FROM users WHERE tg = $1', tg
128 | )
129 | return dict(result)['connect_with']
130 |
131 | async def select_connect_with_self(self, tg: str):
132 | async with self.pool.acquire() as connection:
133 | async with connection.transaction():
134 | result = await connection.fetchrow(
135 | 'SELECT tg FROM users WHERE connect_with = $1', tg
136 | )
137 | return dict(result)['tg']
138 |
139 | async def select_last_connect(self, tg: str):
140 | async with self.pool.acquire() as connection:
141 | async with connection.transaction():
142 | result = await connection.fetchrow(
143 | 'SELECT last_connect FROM users WHERE tg = $1', tg
144 | )
145 | return dict(result)['last_connect']
146 |
147 | async def select_chats(self, tg: str):
148 | async with self.pool.acquire() as connection:
149 | async with connection.transaction():
150 | result = await connection.fetchrow(
151 | 'SELECT chats FROM users WHERE tg = $1', tg
152 | )
153 | return dict(result)['chats']
154 |
155 | async def select_messages(self, tg: str):
156 | async with self.pool.acquire() as connection:
157 | async with connection.transaction():
158 | result = await connection.fetchrow(
159 | 'SELECT messages FROM users WHERE tg = $1', tg
160 | )
161 | return dict(result)['messages']
162 |
163 | async def select_likes(self, tg: str):
164 | async with self.pool.acquire() as connection:
165 | async with connection.transaction():
166 | result = await connection.fetchrow(
167 | 'SELECT likes FROM users WHERE tg = $1', tg
168 | )
169 | return dict(result)['likes']
170 |
171 | async def select_dislikes(self, tg: str):
172 | async with self.pool.acquire() as connection:
173 | async with connection.transaction():
174 | result = await connection.fetchrow(
175 | 'SELECT dislikes FROM users WHERE tg = $1', tg
176 | )
177 | return dict(result)['dislikes']
178 |
179 | async def select_vip_ends(self, tg: str):
180 | async with self.pool.acquire() as connection:
181 | async with connection.transaction():
182 | result = await connection.fetchrow(
183 | 'SELECT vip_ends FROM users WHERE tg = $1', tg
184 | )
185 | return dict(result)['vip_ends']
186 |
187 | async def select_refs(self, tg: str):
188 | async with self.pool.acquire() as connection:
189 | async with connection.transaction():
190 | result = await connection.fetchrow(
191 | 'SELECT refs FROM users WHERE tg = $1', tg
192 | )
193 | return dict(result)['refs']
194 |
195 | async def select_points(self, tg: str):
196 | async with self.pool.acquire() as connection:
197 | async with connection.transaction():
198 | result = await connection.fetchrow(
199 | 'SELECT points FROM users WHERE tg = $1', tg
200 | )
201 | return dict(result)['points']
202 |
203 | async def select_notifications(self, tg: str):
204 | async with self.pool.acquire() as connection:
205 | async with connection.transaction():
206 | result = await connection.fetchrow(
207 | 'SELECT notifications FROM users WHERE tg = $1', tg
208 | )
209 | return dict(result)['notifications']
210 |
211 | async def top_messages(self):
212 | async with self.pool.acquire() as connection:
213 | async with connection.transaction():
214 | result = await connection.fetch(
215 | 'SELECT name, messages FROM users ORDER BY messages DESC LIMIT 5'
216 | )
217 | top_dict = {}
218 | for number, value in enumerate(list(result)):
219 | top_dict[number + 1] = {'name': dict(value)['name'], 'count': dict(value)['messages']}
220 | return top_dict
221 |
222 | async def top_refs(self):
223 | async with self.pool.acquire() as connection:
224 | async with connection.transaction():
225 | result = await connection.fetch(
226 | 'SELECT name, refs FROM users ORDER BY messages DESC LIMIT 5'
227 | )
228 | top_dict = {}
229 | for number, value in enumerate(list(result)):
230 | top_dict[number + 1] = {'name': dict(value)['name'], 'count': dict(value)['refs']}
231 | return top_dict
232 |
233 | async def top_likes(self):
234 | async with self.pool.acquire() as connection:
235 | async with connection.transaction():
236 | result = await connection.fetch(
237 | 'SELECT name, likes FROM users ORDER BY messages DESC LIMIT 5'
238 | )
239 | top_dict = {}
240 | for number, value in enumerate(list(result)):
241 | top_dict[number + 1] = {'name': dict(value)['name'], 'count': dict(value)['likes']}
242 | return top_dict
243 |
244 | async def count_users(self) -> int:
245 | async with self.pool.acquire() as connection:
246 | async with connection.transaction():
247 | result = await connection.fetchval('SELECT COUNT(tg) FROM users')
248 | return result
249 |
250 | # UPDATE ===========================================================================================================
251 | async def update_name(self, tg: str, name: str):
252 | async with self.pool.acquire() as connection:
253 | async with connection.transaction():
254 | await connection.execute(
255 | 'UPDATE users SET name = $1 WHERE tg = $2', name, tg
256 | )
257 |
258 | async def update_age(self, tg: str, age: str):
259 | async with self.pool.acquire() as connection:
260 | async with connection.transaction():
261 | await connection.execute(
262 | 'UPDATE users SET age = $1 WHERE tg = $2', age, tg
263 | )
264 |
265 | async def update_sex(self, tg: str, sex: str):
266 | async with self.pool.acquire() as connection:
267 | async with connection.transaction():
268 | await connection.execute(
269 | 'UPDATE users SET sex = $1 WHERE tg = $2', sex, tg
270 | )
271 |
272 | async def update_connect_with(self, tg: str, connect_with: str | None):
273 | async with self.pool.acquire() as connection:
274 | async with connection.transaction():
275 | if connect_with != tg:
276 | await connection.execute(
277 | 'UPDATE users SET connect_with = $1 WHERE tg = $2', connect_with, tg
278 | )
279 |
280 | async def update_last_connect(self, tg: str):
281 | async with self.pool.acquire() as connection:
282 | async with connection.transaction():
283 | await connection.execute(
284 | 'UPDATE users SET last_connect = connect_with WHERE tg = $1', tg
285 | )
286 |
287 | async def update_chats(self, tg: str):
288 | async with self.pool.acquire() as connection:
289 | async with connection.transaction():
290 | await connection.execute(
291 | 'UPDATE users SET chats = chats + 1 WHERE tg = $1', tg
292 | )
293 |
294 | async def update_messages(self, tg: str):
295 | async with self.pool.acquire() as connection:
296 | async with connection.transaction():
297 | await connection.execute(
298 | 'UPDATE users SET messages = messages + 1 WHERE tg = $1', tg
299 | )
300 |
301 | async def update_likes(self, tg: str):
302 | async with self.pool.acquire() as connection:
303 | async with connection.transaction():
304 | await connection.execute(
305 | 'UPDATE users SET likes = likes + 1 WHERE tg = $1', tg
306 | )
307 |
308 | async def update_dislikes(self, tg: str):
309 | async with self.pool.acquire() as connection:
310 | async with connection.transaction():
311 | await connection.execute(
312 | 'UPDATE users SET dislikes = dislikes + 1 WHERE tg = $1', tg
313 | )
314 |
315 | async def update_refs(self, tg: str):
316 | async with self.pool.acquire() as connection:
317 | async with connection.transaction():
318 | await connection.execute(
319 | 'UPDATE users SET refs = refs + 1 WHERE tg = $1', tg
320 | )
321 |
322 | async def update_points(self, tg: str, value: int):
323 | async with self.pool.acquire() as connection:
324 | async with connection.transaction():
325 | await connection.execute(
326 | 'UPDATE users SET points = points + $1 WHERE tg = $2', value, tg
327 | )
328 |
329 | async def update_notifications(self, tg: str, value: int):
330 | async with self.pool.acquire() as connection:
331 | async with connection.transaction():
332 | await connection.execute(
333 | 'UPDATE users SET notifications = $1 WHERE tg = $2', value, tg
334 | )
335 |
336 | async def update_vip_ends(self, tg: str, time: str):
337 | async with self.pool.acquire() as connection:
338 | async with connection.transaction():
339 | await connection.execute(
340 | 'UPDATE users SET vip_ends = $1 WHERE tg = $2', time, tg
341 | )
342 |
343 | # INSERT ===========================================================================================================
344 | async def insert_in_users(self, tg: str, name: str, age: str, sex: str, vip_ends: str):
345 | async with self.pool.acquire() as connection:
346 | async with connection.transaction():
347 | await connection.execute(
348 | 'INSERT INTO users (tg, name, age, sex, vip_ends) VALUES($1, $2, $3, $4, $5)', tg, name, age, sex, vip_ends
349 | )
350 |
351 | async def insert_in_queue(self, tg: str, sex: str):
352 | async with self.pool.acquire() as connection:
353 | async with connection.transaction():
354 | await connection.execute(
355 | 'INSERT INTO queue (tg, sex, op_sex) VALUES($1, $2, $3)', tg, sex, None
356 | )
357 |
358 | async def insert_in_queue_vip(self, tg: str, sex: str, op_sex: str):
359 | async with self.pool.acquire() as connection:
360 | async with connection.transaction():
361 | await connection.execute(
362 | 'INSERT INTO queue (tg, sex, op_sex) VALUES($1, $2, $3)', tg, sex, op_sex
363 | )
364 |
365 | async def insert_in_messages(self, tg: str, username: str, message: str, stamp: str):
366 | async with self.pool.acquire() as connection:
367 | async with connection.transaction():
368 | await connection.execute(
369 | 'INSERT INTO messages (tg, username, message, stamp) VALUES ($1, $2, $3, $4)', tg, username, message, stamp
370 | )
371 |
372 | # DELETE ===========================================================================================================
373 | async def delete_from_queue(self, tg: str):
374 | async with self.pool.acquire() as connection:
375 | async with connection.transaction():
376 | await connection.execute(
377 | 'DELETE FROM queue WHERE tg = $1', tg
378 | )
379 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import logging
3 | import sys
4 | from datetime import datetime, timedelta
5 |
6 | from aiogram import Bot, Dispatcher, F
7 | from aiogram.fsm.context import FSMContext
8 | from aiogram.fsm.storage.base import StorageKey
9 | from aiogram.fsm.storage.redis import RedisStorage
10 | from aiogram.types import Message, CallbackQuery
11 | from aiogram.filters.command import Command
12 | from redis.asyncio import Redis
13 |
14 | from config import *
15 | import kb
16 | from states import *
17 | from db import DB
18 | from payments import *
19 |
20 | db = DB()
21 |
22 | redis = Redis(
23 | host=REDIS_HOST,
24 | port=REDIS_PORT,
25 | db=REDIS_DB,
26 | )
27 | storage = RedisStorage(redis)
28 |
29 | bot = Bot(token=TOKEN)
30 | dp = Dispatcher(storage=storage)
31 |
32 | logging.basicConfig(filename="all.log", level=logging.INFO,
33 | format='%(asctime)s - %(levelname)s - %(filename)s function: %(funcName)s line: %(lineno)d - %(message)s')
34 | errors = logging.getLogger("errors")
35 | errors.setLevel(logging.ERROR)
36 | fh = logging.FileHandler("errors.log")
37 | formatter = logging.Formatter(
38 | '%(asctime)s - %(levelname)s - %(filename)s function: %(funcName)s line: %(lineno)d - %(message)s')
39 | fh.setFormatter(formatter)
40 | errors.addHandler(fh)
41 |
42 |
43 | def top(word: str, top_dict: dict) -> str:
44 | st = ''
45 | for i, j in top_dict.items():
46 | st += f'{i}) {j["name"]} — {j["count"]} {word}.\n'
47 | return st
48 |
49 |
50 | # Главная ==============================================================================================================
51 | @dp.message(Command('start'))
52 | async def start(message: Message, state: FSMContext):
53 | try:
54 | await state.clear()
55 | if not await db.user_exists(str(message.from_user.id)):
56 | sp = message.text.split()
57 | if len(sp) > 1:
58 | user_id = sp[1]
59 | await db.update_refs(str(user_id))
60 | await db.update_points(str(user_id), 1)
61 | if bool(await db.select_notifications(user_id)):
62 | await bot.send_message(user_id, 'Кто-то присоединился к боту по вашей ссылке!')
63 | if await db.select_refs(user_id) % 10 == 0:
64 | await bot.send_message(user_id, 'Вы можете отключить уведомления о новых рефах в настройках.')
65 | await message.answer(f'Добро пожаловать в анонимный чат!\n'
66 | f'Перед тем как начать общение необходимо пройти регистрацию.\n'
67 | f'После регистрации вы получите вип на неделю бесплатно!\n'
68 | f'Продолжая пользование ботом вы соглашаетесь с правилами.\n',
69 | reply_markup=kb.lobby_kb, parse_mode='HTML')
70 | else:
71 | await message.answer(f'Привет, {await db.select_name(str(message.from_user.id))}.', reply_markup=kb.main_kb)
72 | except Exception as e:
73 | errors.error(e)
74 |
75 |
76 | @dp.callback_query(F.data == 'to_main')
77 | async def call_start(call: CallbackQuery):
78 | try:
79 | await call.answer()
80 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
81 | text=f'Привет, {await db.select_name(str(call.from_user.id))}.',
82 | reply_markup=kb.main_kb)
83 | except Exception as e:
84 | errors.error(e)
85 |
86 |
87 | # Лобби ================================================================================================================
88 | @dp.callback_query(F.data == 'lobby')
89 | async def lobby(call: CallbackQuery):
90 | try:
91 | await call.answer()
92 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
93 | text=f'Добро пожаловать в анонимный чат!\n'
94 | f'Перед тем как начать общение необходимо пройти регистрацию.\n'
95 | f'После регистрации вы получите вип на неделю бесплатно!\n'
96 | f'Продолжая пользование ботом вы соглашаетесь с правилами.\n',
97 | reply_markup=kb.lobby_kb, parse_mode='HTML')
98 | except Exception as e:
99 | errors.error(e)
100 |
101 |
102 | @dp.message(Command('help'))
103 | async def help(message: Message):
104 | try:
105 | await message.answer(f'/start - В начало')
106 | except Exception as e:
107 | errors.error(e)
108 |
109 |
110 | @dp.message(Command('bug'))
111 | async def bug(message: Message, state: FSMContext):
112 | try:
113 | await message.answer('Опишите ошибку с которой вы столкнулись.')
114 | await state.set_state(Bug.bug)
115 | except Exception as e:
116 | errors.error(e)
117 |
118 |
119 | @dp.message(Bug.bug)
120 | async def set_bug(message: Message, state: FSMContext):
121 | try:
122 | sender = message.from_user.id if message.from_user.username is None else f'@{message.from_user.username}'
123 | await bot.send_message(BUGS_GROUP_ID, f'Отправитель: {sender}.\n'
124 | f'Сообщение: {message.text}.')
125 | await message.answer('Разработчик оповещен о проблеме и скоро ее исправит.\n'
126 | 'Спасибо за помощь!')
127 | await state.clear()
128 | except Exception as e:
129 | errors.error(e)
130 |
131 |
132 | @dp.message(Command('idea'))
133 | async def idea(message: Message, state: FSMContext):
134 | try:
135 | await message.answer('Что вы хотите предложить?')
136 | await state.set_state(Idea.idea)
137 | except Exception as e:
138 | errors.error(e)
139 |
140 |
141 | @dp.message(Idea.idea)
142 | async def set_idea(message: Message, state: FSMContext):
143 | try:
144 | sender = message.from_user.id if message.from_user.username is None else f'@{message.from_user.username}'
145 | await bot.send_message(IDEAS_GROUP_ID, f'Отправитель: {sender}.\n'
146 | f'Сообщение: {message.text}.')
147 | await message.answer('Идея передана разработчику.\n'
148 | 'Спасибо за помощь!')
149 | await state.clear()
150 | except Exception as e:
151 | errors.error(e)
152 |
153 |
154 | # Правила ==============================================================================================================
155 | @dp.callback_query(F.data == 'rules')
156 | async def rules(call: CallbackQuery):
157 | try:
158 | await call.answer()
159 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
160 | text=f'В чате запрещены:\n'
161 | f'1) Любые упоминания психоактивных веществ (наркотиков).\n'
162 | f'2) Обмен, распространение любых 18+ материалов.\n'
163 | f'3) Любая реклама, спам, продажа чего либо.\n'
164 | f'4) Оскорбительное поведение.\n'
165 | f'5) Любые действия, нарушающие правила Telegram.\n',
166 | reply_markup=kb.to_lobby_kb, parse_mode='HTML')
167 | except Exception as e:
168 | errors.error(e)
169 |
170 |
171 | # Регистрация ==========================================================================================================
172 | @dp.callback_query(F.data == 'registrate')
173 | async def registrate(call: CallbackQuery, state: FSMContext):
174 | try:
175 | await call.answer()
176 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
177 | text='Введите ваше имя.')
178 | await state.set_state(RegState.name)
179 | except Exception as e:
180 | errors.error(e)
181 |
182 |
183 | @dp.message(RegState.name)
184 | async def reg_name(message: Message, state: FSMContext):
185 | try:
186 | await state.update_data(name=message.text)
187 | await message.answer('Введите ваш возраст.')
188 | await state.set_state(RegState.age)
189 | except Exception as e:
190 | errors.error(e)
191 |
192 |
193 | @dp.message(RegState.age)
194 | async def reg_age(message: Message, state: FSMContext):
195 | try:
196 | await state.update_data(age=message.text)
197 | await message.answer('Выберите ваш пол.', reply_markup=kb.sex_kb)
198 | await state.set_state(RegState.sex)
199 | except Exception as e:
200 | errors.error(e)
201 |
202 |
203 | @dp.callback_query(RegState.sex, F.data.endswith('male'))
204 | async def reg_sex(call: CallbackQuery, state: FSMContext):
205 | try:
206 | await call.answer()
207 | await state.update_data(sex=call.data)
208 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
209 | text='Регистрация завершена.\nВам выдан вип на 7 дней.', reply_markup=kb.main_kb)
210 | data = await state.get_data()
211 | await db.insert_in_users(str(call.from_user.id), data['name'], data['age'], data['sex'],
212 | (datetime.now() + timedelta(days=7)).strftime('%d.%m.%Y %H:%M'))
213 | await state.clear()
214 | except Exception as e:
215 | errors.error(e)
216 |
217 |
218 | # Профиль ==============================================================================================================
219 | @dp.callback_query(F.data == 'profile')
220 | async def profile(call: CallbackQuery):
221 | try:
222 | await call.answer()
223 | sex = 'Неизвестно'
224 | if await db.select_sex(str(call.from_user.id)) == 'male':
225 | sex = 'Мужской'
226 | elif await db.select_sex(str(call.from_user.id)) == 'female':
227 | sex = 'Женский'
228 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
229 | text=f'🅰️ Имя: {await db.select_name(str(call.from_user.id))}\n'
230 | f'🔞 Возраст: {await db.select_age(str(call.from_user.id))}\n'
231 | f'👫 Пол: {sex}',
232 | reply_markup=kb.profile_kb, parse_mode='HTML')
233 | except Exception as e:
234 | errors.error(e)
235 |
236 |
237 | # Настройки ============================================================================================================
238 | @dp.callback_query(F.data == 'settings')
239 | async def settings(call: CallbackQuery):
240 | try:
241 | await call.answer()
242 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
243 | text='Что вы хотите изменить?', reply_markup=kb.settings_kb)
244 | except Exception as e:
245 | errors.error(e)
246 |
247 |
248 | # Имя ==================================================================================================================
249 | @dp.callback_query(F.data == 'name')
250 | async def edit_name(call: CallbackQuery, state: FSMContext):
251 | try:
252 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
253 | text='Введите свое имя.')
254 | await state.set_state(NameState.name)
255 | except Exception as e:
256 | errors.error(e)
257 |
258 |
259 | @dp.message(NameState.name)
260 | async def set_name(message: Message, state: FSMContext):
261 | try:
262 | await db.update_name(str(message.from_user.id), message.text)
263 | await message.answer(text='Имя сохранено.', reply_markup=kb.to_settings_kb)
264 | await state.clear()
265 | except Exception as e:
266 | errors.error(e)
267 |
268 |
269 | # Возраст ==============================================================================================================
270 | @dp.callback_query(F.data == 'age')
271 | async def edit_age(call: CallbackQuery, state: FSMContext):
272 | try:
273 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
274 | text='Введите свой возраст.')
275 | await state.set_state(AgeState.age)
276 | except Exception as e:
277 | errors.error(e)
278 |
279 |
280 | @dp.message(AgeState.age)
281 | async def set_age(message: Message, state: FSMContext):
282 | try:
283 | await db.update_age(str(message.from_user.id), message.text)
284 | await message.answer('Возраст сохранен.', reply_markup=kb.to_settings_kb)
285 | await state.clear()
286 | except Exception as e:
287 | errors.error(e)
288 |
289 |
290 | # Пол ==================================================================================================================
291 | @dp.callback_query(F.data == 'sex')
292 | async def edit_sex(call: CallbackQuery, state: FSMContext):
293 | try:
294 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
295 | text='Выберите свой пол.', reply_markup=kb.sex_kb)
296 | await state.set_state(SexState.sex)
297 | except Exception as e:
298 | errors.error(e)
299 |
300 |
301 | @dp.callback_query(SexState.sex, F.data.endswith('male'))
302 | async def set_sex(call: CallbackQuery, state: FSMContext):
303 | try:
304 | await call.answer()
305 | await db.update_sex(str(call.from_user.id), call.data)
306 | await bot.send_message(call.from_user.id, 'Пол сохранен.', reply_markup=kb.to_settings_kb)
307 | await state.clear()
308 | except Exception as e:
309 | errors.error(e)
310 |
311 |
312 | # Статистика ===========================================================================================================
313 | @dp.callback_query(F.data == 'stats')
314 | async def stats(call: CallbackQuery):
315 | try:
316 | await call.answer()
317 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
318 | text=f'💬 Чатов: {await db.select_chats(str(call.from_user.id))}\n'
319 | f'⌨️ Сообщений: {await db.select_messages(str(call.from_user.id))}\n'
320 | f'👍 Лайков: {await db.select_likes(str(call.from_user.id))}\n'
321 | f'👎 Дизлайков: {await db.select_dislikes(str(call.from_user.id))}\n'
322 | f'👨💻 Пользователей приглашено: {await db.select_refs(str(call.from_user.id))}',
323 | reply_markup=kb.statistic_kb)
324 | except Exception as e:
325 | errors.error(e)
326 |
327 |
328 | # Рефералка ============================================================================================================
329 | @dp.callback_query(F.data == 'ref')
330 | async def ref(call: CallbackQuery):
331 | try:
332 | await call.answer()
333 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
334 | text=f'Распространяйте свою реферальную ссылку, чтобы получать 💎.\n'
335 | f'1 переход по ссылке = 1 💎.\n'
336 | f'5 💎 = 1 день VIP-статуса 👑.\n'
337 | f'У вас {await db.select_points(str(call.from_user.id))} 💎.\n\n'
338 | f'🆔 Ваша реферальная ссылка:\n'
339 | f'{f"{RETURN_URL}?start=" + str(str(call.from_user.id))}.',
340 | disable_web_page_preview=True,
341 | reply_markup=kb.ref_kb(await db.select_notifications(str(call.from_user.id))))
342 | except Exception as e:
343 | errors.error(e)
344 |
345 |
346 | # Обмен 💎 =============================================================================================================
347 | @dp.callback_query(F.data == 'trade')
348 | async def trade(call: CallbackQuery):
349 | try:
350 | if await db.select_points(str(call.from_user.id)) >= 5:
351 | await db.update_points(str(call.from_user.id), -5)
352 | if await db.select_vip_ends(str(call.from_user.id)) is None:
353 | await db.update_vip_ends((datetime.now() + timedelta(days=1)).strftime('%d.%m.%Y %H:%M'),
354 | str(call.from_user.id))
355 | await call.answer('Успешно!')
356 | else:
357 | await db.update_vip_ends(
358 | (datetime.strptime(await db.select_vip_ends(str(call.from_user.id)), '%d.%m.%Y %H:%M') +
359 | timedelta(days=1)).strftime('%d.%m.%Y %H:%M'), str(call.from_user.id))
360 | await call.answer('Успешно!')
361 | else:
362 | await call.answer('У вас недостаточно баллов.')
363 | except Exception as e:
364 | errors.error(e)
365 |
366 |
367 | # Уведомления ==========================================================================================================
368 | @dp.callback_query(F.data == 'on')
369 | async def notifications_on(call: CallbackQuery):
370 | try:
371 | await call.answer()
372 | await db.update_notifications(str(call.from_user.id), 1)
373 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
374 | text='Уведомления включены.', reply_markup=kb.to_ref_kb)
375 | except Exception as e:
376 | errors.error(e)
377 |
378 |
379 | @dp.callback_query(F.data == 'off')
380 | async def notifications_off(call: CallbackQuery):
381 | try:
382 | await call.answer()
383 | await db.update_notifications(str(call.from_user.id), 0)
384 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
385 | text='Уведомления выключены.', reply_markup=kb.to_ref_kb)
386 | except Exception as e:
387 | errors.error(e)
388 |
389 |
390 | # Топы =================================================================================================================
391 | @dp.callback_query(F.data == 'tops')
392 | async def tops(call: CallbackQuery):
393 | try:
394 | await call.answer()
395 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
396 | text='Ниже представлены рейтинги по разным критериям.', reply_markup=kb.top_kb)
397 | except Exception as e:
398 | errors.error(e)
399 |
400 |
401 | @dp.callback_query(F.data == 'top_messages')
402 | async def top_messages(call: CallbackQuery):
403 | try:
404 | await call.answer()
405 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
406 | text=top('сообщений', await db.top_messages()), reply_markup=kb.to_tops_kb,
407 | parse_mode='HTML')
408 | except Exception as e:
409 | errors.error(e)
410 |
411 |
412 | @dp.callback_query(F.data == 'top_likes')
413 | async def top_likes(call: CallbackQuery):
414 | try:
415 | await call.answer()
416 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
417 | text=top('лайков', await db.top_likes()), reply_markup=kb.to_tops_kb,
418 | parse_mode='HTML')
419 | except Exception as e:
420 | errors.error(e)
421 |
422 |
423 | @dp.callback_query(F.data == 'top_refs')
424 | async def top_refs(call: CallbackQuery):
425 | try:
426 | await call.answer()
427 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
428 | text=top('рефов', await db.top_refs()), reply_markup=kb.to_tops_kb,
429 | parse_mode='HTML')
430 | except Exception as e:
431 | errors.error(e)
432 |
433 |
434 | # Вип ==================================================================================================================
435 | @dp.callback_query(F.data == 'vip')
436 | async def vip(call: CallbackQuery):
437 | try:
438 | await call.answer()
439 | if await db.select_vip_ends(str(call.from_user.id)) is not None:
440 | if datetime.strptime(await db.select_vip_ends(str(call.from_user.id)), '%d.%m.%Y %H:%M') > datetime.now():
441 | delta = datetime.strptime(await db.select_vip_ends(str(call.from_user.id)),
442 | '%d.%m.%Y %H:%M') - datetime.now()
443 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
444 | text=f'Осталось {delta.days} дней, {delta.seconds // 3600} часов, {delta.seconds // 60 % 60} минут Випа.',
445 | reply_markup=kb.vip_kb)
446 | else:
447 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
448 | text=f'Вип дает:\n'
449 | f'1) Поиск по полу.\n'
450 | f'2) Подробная информацию о собеседнике: отзывы, имя, пол, возраст.\n'
451 | f'Сейчас подключены ТЕСТОВЫЕ платежи, то есть деньги НЕ будут списаны, но вип вы получите.',
452 | reply_markup=kb.vip_kb, parse_mode='HTML')
453 | else:
454 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
455 | text=f'Вип дает:\n'
456 | f'1) Поиск по полу.\n'
457 | f'2) Подробная информацию о собеседнике: отзывы, имя, пол, возраст.\n'
458 | f'Сейчас подключены ТЕСТОВЫЕ платежи, то есть деньги НЕ будут списаны, но вип вы получите.',
459 | reply_markup=kb.vip_kb, parse_mode='HTML')
460 | except Exception as e:
461 | errors.error(e)
462 |
463 |
464 | # Купить вип ===========================================================================================================
465 | @dp.callback_query(F.data == 'buy_vip')
466 | async def buy_vip(call: CallbackQuery):
467 | try:
468 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
469 | text='Выберите длительность:', reply_markup=kb.buy_kb)
470 | except Exception as e:
471 | errors.error(e)
472 |
473 |
474 | @dp.callback_query(F.data == 'vip_day')
475 | async def buy_day(call: CallbackQuery):
476 | try:
477 | await call.answer()
478 | url, payment_id = create_payment(20, 'Вип на 1 день')
479 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
480 | text=f'Оплатить 20 рублей', parse_mode='HTML',
481 | reply_markup=kb.to_buy_kb)
482 | c = 0
483 | paid = False
484 | while True:
485 | if get_payment_status(payment_id) == 'waiting_for_capture':
486 | paid = True
487 | break
488 | elif c == 600:
489 | await bot.send_message(call.from_user.id, 'Платеж отменен.\n'
490 | 'Причина: прошло 10 минут с момента создания платежа.',
491 | reply_markup=kb.to_main_kb)
492 | break
493 | else:
494 | await asyncio.sleep(1)
495 | c += 1
496 | if paid:
497 | response = json.loads(confirm_payment(payment_id))
498 | if response['status'] == 'succeeded':
499 | await db.update_vip_ends(str(call.from_user.id), (
500 | datetime.strptime(str(await db.select_vip_ends(str(call.from_user.id))),
501 | '%d.%m.%Y %H:%M') + timedelta(days=1)).strftime('%d.%m.%Y %H:%M'))
502 | await bot.send_message(call.from_user.id, 'Вы успешно приобрели вип на 1 день.\n'
503 | 'Приятного пользования!', reply_markup=kb.to_main_kb)
504 | else:
505 | await bot.send_message(call.from_user.id, 'Произошла ошибка.\n'
506 | 'Деньги будут возвращены вам в течение 24 часов.',
507 | reply_markup=kb.to_main_kb)
508 | except Exception as e:
509 | errors.error(e)
510 |
511 |
512 | @dp.callback_query(F.data == 'vip_week')
513 | async def buy_week(call: CallbackQuery):
514 | try:
515 | await call.answer()
516 | url, payment_id = create_payment(100, 'Вип на 1 неделю')
517 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
518 | text=f'Оплатить 100 рублей', parse_mode='HTML',
519 | reply_markup=kb.to_buy_kb)
520 | c = 0
521 | paid = False
522 | while True:
523 | if get_payment_status(payment_id) == 'waiting_for_capture':
524 | paid = True
525 | break
526 | elif c == 600:
527 | await bot.send_message(call.from_user.id, 'Платеж отменен.\n'
528 | 'Причина: прошло 10 минут с момента создания платежа.',
529 | reply_markup=kb.to_main_kb)
530 | break
531 | else:
532 | await asyncio.sleep(1)
533 | c += 1
534 | if paid:
535 | response = json.loads(confirm_payment(payment_id))
536 | if response['status'] == 'succeeded':
537 | await db.update_vip_ends(str(call.from_user.id),
538 | (datetime.strptime(str(await db.select_vip_ends(str(call.from_user.id))),
539 | '%d.%m.%Y %H:%M') + timedelta(days=7)).strftime(
540 | '%d.%m.%Y %H:%M'))
541 | await bot.send_message(call.from_user.id, 'Вы успешно приобрели вип на 1 неделю.\n'
542 | 'Приятного пользования!', reply_markup=kb.to_main_kb)
543 | else:
544 | await bot.send_message(call.from_user.id, 'Произошла ошибка.\n'
545 | 'Деньги будут возвращены вам в течение 24 часов.',
546 | reply_markup=kb.to_main_kb)
547 | except Exception as e:
548 | errors.error(e)
549 |
550 |
551 | @dp.callback_query(F.data == 'vip_month')
552 | async def buy_month(call: CallbackQuery):
553 | try:
554 | await call.answer()
555 | url, payment_id = create_payment(300, 'Вип на 1 месяц')
556 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
557 | text=f'Оплатить 300 рублей', parse_mode='HTML',
558 | reply_markup=kb.to_buy_kb)
559 | c = 0
560 | paid = False
561 | while True:
562 | if get_payment_status(payment_id) == 'waiting_for_capture':
563 | paid = True
564 | break
565 | elif c == 600:
566 | await bot.send_message(call.from_user.id, 'Платеж отменен.\n'
567 | 'Причина: прошло 10 минут с момента создания платежа.',
568 | reply_markup=kb.to_main_kb)
569 | break
570 | else:
571 | await asyncio.sleep(1)
572 | c += 1
573 | if paid:
574 | response = json.loads(confirm_payment(payment_id))
575 | if response['status'] == 'succeeded':
576 | await db.update_vip_ends(str(call.from_user.id), (
577 | datetime.strptime(str(await db.select_vip_ends(str(call.from_user.id))),
578 | '%d.%m.%Y %H:%M') + timedelta(days=30)).strftime('%d.%m.%Y %H:%M'))
579 | await bot.send_message(call.from_user.id, 'Вы успешно приобрели вип на 1 месяц.\n'
580 | 'Приятного пользования!', reply_markup=kb.to_main_kb)
581 | else:
582 | await bot.send_message(call.from_user.id, 'Произошла ошибка.\n'
583 | 'Деньги будут возвращены вам в течение 24 часов.',
584 | reply_markup=kb.to_main_kb)
585 | except Exception as e:
586 | errors.error(e)
587 |
588 |
589 | # Поиск ================================================================================================================
590 | @dp.callback_query(F.data == 'search')
591 | async def search(call: CallbackQuery, state: FSMContext):
592 | try:
593 | await call.answer()
594 | await db.insert_in_queue(str(call.from_user.id), await db.select_sex(str(call.from_user.id)))
595 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
596 | text='Ищем собеседника... 🔍', reply_markup=kb.cancel_search_kb)
597 | while True:
598 | await asyncio.sleep(0.5)
599 | if await db.find_chat(str(call.from_user.id)) is not None:
600 | await db.update_connect_with(str(call.from_user.id), await db.find_chat(str(call.from_user.id)))
601 | break
602 | while True:
603 | await asyncio.sleep(0.5)
604 | if await db.select_connect_with(str(call.from_user.id)) is not None:
605 | await db.delete_from_queue(str(call.from_user.id))
606 | break
607 | await bot.send_message(call.from_user.id, 'Нашли для тебя собеседника 🥳\n'
608 | '/stop - остановить диалог')
609 | if datetime.strptime(await db.select_vip_ends(str(call.from_user.id)), '%d.%m.%Y %H:%M') > datetime.now():
610 | sex = 'Неизвестно'
611 | user_id = str(await db.select_connect_with(str(call.from_user.id)))
612 | if await db.select_sex(user_id) == 'male':
613 | sex = 'Мужской'
614 | elif await db.select_sex(user_id) == 'female':
615 | sex = 'Женский'
616 | await bot.send_message(call.from_user.id,
617 | f'🅰️ Имя: {await db.select_name(user_id)}\n'
618 | f'🔞 Возраст: {await db.select_age(user_id)}\n'
619 | f'👫 Пол: {sex}\n'
620 | f'👍: {await db.select_likes(user_id)} 👎: {await db.select_dislikes(user_id)}\n', )
621 | await state.set_state(Chatting.msg)
622 | except Exception as e:
623 | errors.error(e)
624 |
625 |
626 | # Поиск ♂️ =============================================================================================================
627 | @dp.callback_query(F.data == 'search_man')
628 | async def search_man(call: CallbackQuery, state: FSMContext):
629 | try:
630 | await call.answer()
631 | if datetime.strptime(await db.select_vip_ends(str(call.from_user.id)), '%d.%m.%Y %H:%M') > datetime.now():
632 | await db.insert_in_queue_vip(str(call.from_user.id), await db.select_sex(str(call.from_user.id)), 'male')
633 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
634 | text='Ищем собеседника... 🔍', reply_markup=kb.cancel_search_kb)
635 | while True:
636 | await asyncio.sleep(0.5)
637 | if await db.find_chat_vip(str(call.from_user.id), await db.select_sex(str(call.from_user.id)),
638 | 'male') is not None:
639 | await db.update_connect_with(
640 | str(call.from_user.id), await db.find_chat_vip(str(call.from_user.id),
641 | await db.select_sex(str(call.from_user.id)),
642 | 'male'))
643 | break
644 | while True:
645 | await asyncio.sleep(0.5)
646 | if await db.select_connect_with(str(call.from_user.id)) is not None:
647 | await db.delete_from_queue(str(call.from_user.id))
648 | break
649 | await bot.send_message(call.from_user.id, 'Нашли для тебя собеседника 🥳\n'
650 | '/stop - остановить диалог')
651 | sex = 'Неизвестно'
652 | user_id = str(await db.select_connect_with(str(call.from_user.id)))
653 | if await db.select_sex(user_id) == 'male':
654 | sex = 'Мужской'
655 | elif await db.select_sex(user_id) == 'female':
656 | sex = 'Женский'
657 | await bot.send_message(call.from_user.id,
658 | f'🅰️ Имя: {await db.select_name(user_id)}\n'
659 | f'🔞 Возраст: {await db.select_age(user_id)}\n'
660 | f'👫 Пол: {sex}\n'
661 | f'👍: {await db.select_likes(user_id)} 👎: {await db.select_dislikes(user_id)}\n')
662 | await state.set_state(Chatting.msg)
663 | else:
664 | await call.answer()
665 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
666 | text='Поиск по полу доступен только для вип-пользователей',
667 | reply_markup=kb.sex_search_no_vip_kb)
668 | except Exception as e:
669 | errors.error(e)
670 |
671 |
672 | # Поиск ♀️ =============================================================================================================
673 | @dp.callback_query(F.data == 'search_woman')
674 | async def search_woman(call: CallbackQuery, state: FSMContext):
675 | try:
676 | await call.answer()
677 | if datetime.strptime(await db.select_vip_ends(str(call.from_user.id)), '%d.%m.%Y %H:%M') > datetime.now():
678 | await db.insert_in_queue_vip(str(call.from_user.id), await db.select_sex(str(call.from_user.id)), 'female')
679 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
680 | text='Ищем собеседника... 🔍', reply_markup=kb.cancel_search_kb)
681 | while True:
682 | await asyncio.sleep(0.5)
683 | if await db.find_chat_vip(str(call.from_user.id), await db.select_sex(str(call.from_user.id)),
684 | 'female') is not None:
685 | await db.update_connect_with(
686 | str(call.from_user.id), await db.find_chat_vip(str(call.from_user.id),
687 | await db.select_sex(str(call.from_user.id)),
688 | 'female'))
689 | break
690 | while True:
691 | await asyncio.sleep(0.5)
692 | if await db.select_connect_with(str(call.from_user.id)) is not None:
693 | await db.delete_from_queue(str(call.from_user.id))
694 | break
695 | await bot.send_message(call.from_user.id, 'Нашли для тебя собеседника 🥳\n'
696 | '/stop - остановить диалог')
697 | sex = 'Неизвестно'
698 | user_id = str(await db.select_connect_with(str(call.from_user.id)))
699 | if await db.select_sex(user_id) == 'male':
700 | sex = 'Мужской'
701 | elif await db.select_sex(user_id) == 'female':
702 | sex = 'Женский'
703 | await bot.send_message(call.from_user.id,
704 | f'🅰️ Имя: {await db.select_name(user_id)}\n'
705 | f'🔞 Возраст: {await db.select_age(user_id)}\n'
706 | f'👫 Пол: {sex}\n'
707 | f'👍: {await db.select_likes(user_id)} 👎: {await db.select_dislikes(user_id)}\n')
708 | await state.set_state(Chatting.msg)
709 | else:
710 | await call.answer()
711 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
712 | text='Поиск по полу доступен только для вип-пользователей',
713 | reply_markup=kb.sex_search_no_vip_kb)
714 | except Exception as e:
715 | errors.error(e)
716 |
717 |
718 | # Отменить поиск =======================================================================================================
719 | @dp.callback_query(F.data == 'cancel_search')
720 | async def cancel_search(call: CallbackQuery):
721 | try:
722 | await call.answer()
723 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
724 | text='Поиск отменен 😥.',
725 | reply_markup=kb.main_kb)
726 | await db.delete_from_queue(str(call.from_user.id))
727 | except Exception as e:
728 | errors.error(e)
729 |
730 |
731 | # Лайк =================================================================================================================
732 | @dp.callback_query(F.data == 'like')
733 | async def like(call: CallbackQuery):
734 | try:
735 | await call.answer()
736 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
737 | text='Спасибо за отзыв!', reply_markup=kb.review_kb)
738 | await db.update_likes(await db.select_last_connect(str(call.from_user.id)))
739 | except Exception as e:
740 | errors.error(e)
741 |
742 |
743 | # Дизлайк ==============================================================================================================
744 | @dp.callback_query(F.data == 'dislike')
745 | async def dislike(call: CallbackQuery):
746 | try:
747 | await call.answer()
748 | await bot.edit_message_text(chat_id=call.from_user.id, message_id=call.message.message_id,
749 | text='Спасибо за отзыв!', reply_markup=kb.review_kb)
750 | await db.update_dislikes(await db.select_last_connect(str(call.from_user.id)))
751 | except Exception as e:
752 | errors.error(e)
753 |
754 |
755 | # Ссылка ===============================================================================================================
756 | @dp.message(Chatting.msg, Command('link'))
757 | async def link(message: Message):
758 | try:
759 | if message.from_user.username is None:
760 | await message.answer('Введите юзернейм в настройках телеграма!')
761 | else:
762 | await bot.send_message(await db.select_connect_with(str(message.from_user.id)),
763 | f'Собеседник отправил свой юзернейм: @{message.from_user.username}.')
764 | await message.answer('Юзернейм отправлен!')
765 | except Exception as e:
766 | errors.error(e)
767 |
768 |
769 | # Остановить диалог ====================================================================================================
770 | @dp.message(Chatting.msg, Command('stop'))
771 | async def stop(message: Message, state: FSMContext):
772 | try:
773 | op_state = FSMContext(
774 | storage=storage,
775 | key=StorageKey(
776 | chat_id=int(await db.select_connect_with(str(message.from_user.id))),
777 | user_id=int(await db.select_connect_with(str(message.from_user.id))),
778 | bot_id=bot.id)
779 | )
780 | await bot.send_message(message.from_user.id,
781 | 'Диалог остановлен 😞\nВы можете оценить собеседника ниже.',
782 | reply_markup=kb.search_kb)
783 | await bot.send_message(await db.select_connect_with(str(message.from_user.id)),
784 | 'Диалог остановлен 😞\nВы можете оценить собеседника ниже.',
785 | reply_markup=kb.search_kb)
786 | await db.update_chats(await db.select_connect_with(str(message.from_user.id)))
787 | await db.update_chats(str(message.from_user.id))
788 | await db.update_last_connect(await db.select_connect_with(str(message.from_user.id)))
789 | await db.update_last_connect(str(message.from_user.id))
790 | await db.update_connect_with(await db.select_connect_with(str(message.from_user.id)), None)
791 | await db.update_connect_with(str(message.from_user.id), None)
792 | await state.clear()
793 | await op_state.clear()
794 | except Exception as e:
795 | errors.error(e)
796 |
797 |
798 | # Общение ==============================================================================================================
799 | @dp.message(Chatting.msg, F.text)
800 | async def chatting_text(message: Message):
801 | try:
802 | await bot.send_message(await db.select_connect_with(str(message.from_user.id)), message.text)
803 | await db.insert_in_messages(str(message.from_user.id), message.from_user.username, message.text,
804 | datetime.now().strftime('%d.%m.%Y %H:%M:%S'))
805 | await db.update_messages(str(message.from_user.id))
806 | except Exception as e:
807 | errors.error(e)
808 |
809 |
810 | # Фото =================================================================================================================
811 | @dp.message(Chatting.msg, F.photo)
812 | async def chatting_photo(message: Message):
813 | try:
814 | await bot.send_photo(await db.select_connect_with(str(message.from_user.id)), message.photo[-1].file_id)
815 | except Exception as e:
816 | errors.error(e)
817 |
818 |
819 | # Видео ================================================================================================================
820 | @dp.message(Chatting.msg, F.video)
821 | async def chatting_video(message: Message):
822 | try:
823 | await bot.send_video(await db.select_connect_with(str(message.from_user.id)), message.video.file_id)
824 | except Exception as e:
825 | errors.error(e)
826 |
827 |
828 | # Гиф ==================================================================================================================
829 | @dp.message(Chatting.msg, F.animation)
830 | async def chatting_animation(message: Message):
831 | try:
832 | await bot.send_animation(await db.select_connect_with(str(message.from_user.id)), message.animation.file_id)
833 | except Exception as e:
834 | errors.error(e)
835 |
836 |
837 | # Стикер ===============================================================================================================
838 | @dp.message(Chatting.msg, F.sticker)
839 | async def chatting_sticker(message: Message):
840 | try:
841 | await bot.send_sticker(await db.select_connect_with(str(message.from_user.id)), message.sticker.file_id)
842 | except Exception as e:
843 | errors.error(e)
844 |
845 |
846 | # Документ =============================================================================================================
847 | @dp.message(Chatting.msg, F.document)
848 | async def chatting_document(message: Message):
849 | try:
850 | await bot.send_document(await db.select_connect_with(str(message.from_user.id)), message.document.file_id)
851 | except Exception as e:
852 | errors.error(e)
853 |
854 |
855 | # Аудио ================================================================================================================
856 | @dp.message(Chatting.msg, F.audio)
857 | async def chatting_audio(message: Message):
858 | try:
859 | await bot.send_audio(await db.select_connect_with(str(message.from_user.id)), message.audio.file_id)
860 | except Exception as e:
861 | errors.error(e)
862 |
863 |
864 | # Гс ===================================================================================================================
865 | @dp.message(Chatting.msg, F.voice)
866 | async def chatting_voice(message: Message):
867 | try:
868 | await bot.send_voice(await db.select_connect_with(str(message.from_user.id)), message.voice.file_id)
869 | except Exception as e:
870 | errors.error(e)
871 |
872 |
873 | # Кружок ===============================================================================================================
874 | @dp.message(Chatting.msg, F.video_note)
875 | async def chatting_video_note(message: Message):
876 | try:
877 | await bot.send_video_note(await db.select_connect_with(str(message.from_user.id)), message.video_note.file_id)
878 | except Exception as e:
879 | errors.error(e)
880 |
881 |
882 | # Остальное ===============================================================================================================
883 | @dp.message(Chatting.msg, F.unknown)
884 | async def chatting_unknown(message):
885 | try:
886 | await message.answer('Этот тип контента пока не поддерживается 😢.')
887 | except Exception as e:
888 | errors.error(e)
889 |
890 |
891 | # id ===================================================================================================================
892 | @dp.message(Command('id'))
893 | async def ids(message: Message):
894 | try:
895 | await message.answer(str(message.from_user.id))
896 | except Exception as e:
897 | errors.error(e)
898 |
899 |
900 | # group id =============================================================================================================
901 | @dp.message(Command('gid'))
902 | async def gids(message: Message):
903 | try:
904 | await message.answer(str(message.chat.id))
905 | except Exception as e:
906 | errors.error(e)
907 |
908 |
909 | # all ==================================================================================================================
910 | @dp.message()
911 | async def all(message: Message):
912 | try:
913 | if str(message.chat.id) not in [BUGS_GROUP_ID, IDEAS_GROUP_ID]:
914 | await message.answer('Команда не распознана. Отправьте /start для выхода в главное меню.')
915 | except Exception as e:
916 | errors.error(e)
917 |
918 |
919 | async def main():
920 | await db.connect()
921 | await db.create_tables()
922 | await dp.start_polling(bot)
923 |
924 |
925 | if __name__ == '__main__':
926 | print(f'Бот запущен ({datetime.now().strftime("%H:%M:%S %d.%m.%Y")}).')
927 | asyncio.run(main())
928 |
--------------------------------------------------------------------------------