-
Notifications
You must be signed in to change notification settings - Fork 0
/
les_59_telegramBot_ORM.py
134 lines (109 loc) · 4.4 KB
/
les_59_telegramBot_ORM.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import asyncio
import logging
import random
import sys
from aiogram import Bot, Dispatcher, types, F
from aiogram.filters import Command
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.types import Message, FSInputFile
from aiogram.fsm.state import State, StatesGroup
from aiogram.utils.keyboard import ReplyKeyboardBuilder
from aiogram.fsm.context import FSMContext
import config
import asyncpg
import os
db_params = {
'dbname': os.getenv('POSTGRES_DB', 'postgres'),
'user': os.getenv('POSTGRES_USER', 'admin'),
'password': os.getenv('POSTGRES_PASSWORD', 'root'),
'host': os.getenv('POSTGRES_HOST', 'localhost'),
'port': os.getenv('POSTGRES_PORT', '5432')
}
def create_db_url(params):
"""Создать строку подключения для PostgreSQL."""
return f"postgresql://{params['user']}:{params['password']}@{params['host']}:{params['port']}/{params['dbname']}"
db_url = create_db_url(db_params)
async def initiate_db():
conn = await asyncpg.connect(db_url)
await conn.execute('''
CREATE TABLE IF NOT EXISTS Users (
id SERIAL PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
age INTEGER NOT NULL,
balance INTEGER NOT NULL DEFAULT 1000
)
''')
await conn.close()
async def add_user(username, email, age):
conn = await asyncpg.connect(db_url)
await conn.execute('''
INSERT INTO Users (username, email, age, balance)
VALUES ($1, $2, $3, $4)
''', username, email, age, 1000)
await conn.close()
async def is_included(username):
"""Проверка, есть ли пользователь в таблице Users."""
conn = await asyncpg.connect(db_url)
result = await conn.fetchval('''
SELECT EXISTS(SELECT 1 FROM Users WHERE username = $1)
''', username)
await conn.close()
return result
API_TOKEN = config.TOKEN
bot = Bot(token=API_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(storage=storage)
async def on_startup(dispatcher):
await initiate_db()
main_menu = ReplyKeyboardBuilder()
main_menu.button(text="Регистрация")
main_menu_markup = main_menu.as_markup(resize_keyboard=True)
@dp.message(Command("start"))
async def send_welcome(message: types.Message):
await message.reply("Добро пожаловать! Выберите действие:", reply_markup=main_menu_markup)
class RegistrationState(StatesGroup):
username = State()
email = State()
age = State()
@dp.message(F.text == "Регистрация")
async def sing_up(message: types.Message, state: FSMContext):
await message.answer("Введите имя пользователя (только латинский алфавит):")
await state.set_state(RegistrationState.username)
@dp.message(RegistrationState.username)
async def set_username(message: types.Message, state: FSMContext):
username = message.text.strip()
if not username.isalpha():
await message.reply("Имя пользователя должно содержать только латинские буквы.")
return
if await is_included(username):
await message.reply("Пользователь существует, введите другое имя.")
else:
await state.update_data(username=username)
await message.reply("Введите свой email:")
await state.set_state(RegistrationState.email)
@dp.message(RegistrationState.email)
async def set_email(message: types.Message, state: FSMContext):
email = message.text.strip()
await state.update_data(email=email)
await message.reply("Введите свой возраст:")
await state.set_state(RegistrationState.age)
@dp.message(RegistrationState.age)
async def set_age(message: types.Message, state: FSMContext):
age_text = message.text.strip()
if not age_text.isdigit():
await message.reply("Возраст должен быть числом.")
return
age = int(age_text)
user_data = await state.get_data()
username = user_data['username']
email = user_data['email']
await add_user(username, email, age)
await message.reply(f"Регистрация завершена! Ваш баланс: 1000")
await state.clear()
async def main():
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
await on_startup(dp)
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())