add alembic scripts

This commit is contained in:
harold 2025-07-03 12:26:50 +05:00
parent 696cce8bdf
commit 8bb9b91f50
9 changed files with 372 additions and 17 deletions

View File

@ -161,7 +161,7 @@ cython_debug/
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
/alembic/versions
/migrations/versions
.idea
.env

View File

@ -1,22 +1,93 @@
from groq import AsyncGroq
from telethon.errors import FloodWaitError
from telethon.tl.functions.channels import JoinChannelRequest
import asyncio
from telethon import TelegramClient
from telethon.sessions import StringSession
from src.core.settings.base import settings
# Убедитесь, что переменная окружения GROQ_API_KEY установлена
import time
import openpyxl
import os
# Конфигурация Excel-файла
EXCEL_FILE_PATH = "/home/harold/Documents/chats.xlsx"
SHEET_NAME = 'Чаты' # Имя листа в Excel
LINK_COLUMN = 3 # Номер столбца со ссылками (3 = колонка C)
client = AsyncGroq(
api_key=settings.GROQ.API_KEY,
)
async def main():
# Загрузка групп из Excel
groups = []
try:
# Проверка существования файла
if not os.path.exists(EXCEL_FILE_PATH):
raise FileNotFoundError(f"Excel файл не найден: {EXCEL_FILE_PATH}")
wb = openpyxl.load_workbook(EXCEL_FILE_PATH)
async def create_request_ai(messages: list):
chat_completion = await client.chat.completions.create(
messages=messages,
model="llama-3.3-70b-versatile",
temperature=2,
# Проверка существования листа
if SHEET_NAME not in wb.sheetnames:
raise ValueError(f"Лист '{SHEET_NAME}' не найден в файле")
sheet = wb[SHEET_NAME]
# Чтение данных, пропуская заголовок
for row in range(2, sheet.max_row + 1):
link_cell = sheet.cell(row=row, column=LINK_COLUMN)
if link_cell.value and 't.me/' in link_cell.value:
# Извлекаем username из ссылки
username = link_cell.value.split('t.me/')[-1].split('/')[0].split('?')[0]
groups.append(username)
if not groups:
print("⚠️ В файле не найдено валидных ссылок на Telegram группы")
return
except Exception as e:
print(f"❌ Ошибка при чтении Excel файла: {str(e)}")
return
# Инициализация Telegram клиента
client = TelegramClient(
session=StringSession(settings.ACCOUNT.SESSION),
api_id=settings.ACCOUNT.API_ID,
api_hash=settings.ACCOUNT.API_HASH,
)
print(chat_completion.choices[0].message.content)
await client.start()
# if __name__ == "__main__":
# asyncio.run(create_request())
print(f"\nНайдено {len(groups)} групп в файле. Начинаю подписку...")
success_count = 0
for i, username in enumerate(groups, 1):
try:
# Пытаемся найти группу
group = await client.get_entity(username)
# Подписываемся
await client(JoinChannelRequest(group))
print(f"{i}. ✓ Успешно: @{username}")
success_count += 1
except FloodWaitError as e:
wait_time = e.seconds + 5
print(f"{i}. ⏳ Ожидаем {wait_time} секунд из-за ограничения Telegram")
time.sleep(wait_time)
# Повторяем попытку после ожидания
try:
await client(JoinChannelRequest(username))
print(f"{i}. ✓ Успешно после ожидания: @{username}")
success_count += 1
except Exception as e:
print(f"{i}. ✗ Ошибка повторной попытки для @{username}: {str(e)}")
except Exception as e:
print(f"{i}. ✗ Ошибка в @{username}: {str(e)}")
# Задержка между запросами
time.sleep(2)
print(f"\nПроцесс завершен! Успешно подписано на {success_count} из {len(groups)} групп")
await client.disconnect()
#
#
# if __name__ == '__main__':
# asyncio.run(main())

View File

@ -0,0 +1,117 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = postgresql://%(DB_USER)s:%(DB_PASS)s@%(DB_HOST)s:%(DB_PORT)s/%(DB_NAME)s
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

View File

@ -0,0 +1 @@
Generic single-database configuration with an async dbapi.

View File

@ -0,0 +1,94 @@
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
from src.core.database import Base
from src.core.settings.base import settings
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
config.set_main_option('sqlalchemy.url', settings.POSTGRES.async_connect_url.unicode_string())
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option('sqlalchemy.url')
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={'paramstyle': 'named'},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
"""In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix='sqlalchemy.',
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

View File

@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@ -33,6 +33,26 @@ files = [
pamqp = "3.3.0"
yarl = "*"
[[package]]
name = "alembic"
version = "1.16.2"
description = "A database migration tool for SQLAlchemy."
optional = false
python-versions = ">=3.9"
groups = ["main"]
files = [
{file = "alembic-1.16.2-py3-none-any.whl", hash = "sha256:5f42e9bd0afdbd1d5e3ad856c01754530367debdebf21ed6894e34af52b3bb03"},
{file = "alembic-1.16.2.tar.gz", hash = "sha256:e53c38ff88dadb92eb22f8b150708367db731d58ad7e9d417c9168ab516cbed8"},
]
[package.dependencies]
Mako = "*"
SQLAlchemy = ">=1.4.0"
typing-extensions = ">=4.12"
[package.extras]
tz = ["tzdata"]
[[package]]
name = "annotated-types"
version = "0.7.0"
@ -880,6 +900,26 @@ files = [
pyaes = "1.6.1"
pysocks = "1.7.1"
[[package]]
name = "mako"
version = "1.3.10"
description = "A super-fast templating language that borrows the best ideas from the existing templating languages."
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "mako-1.3.10-py3-none-any.whl", hash = "sha256:baef24a52fc4fc514a0887ac600f9f1cff3d82c61d4d700a1fa84d597b88db59"},
{file = "mako-1.3.10.tar.gz", hash = "sha256:99579a6f39583fa7e5630a28c3c1f440e4e97a414b80372649c0ce338da2ea28"},
]
[package.dependencies]
MarkupSafe = ">=0.9.2"
[package.extras]
babel = ["Babel"]
lingua = ["lingua"]
testing = ["pytest"]
[[package]]
name = "markupsafe"
version = "3.0.2"
@ -1954,4 +1994,4 @@ propcache = ">=0.2.0"
[metadata]
lock-version = "2.1"
python-versions = ">=3.11, <4.0"
content-hash = "99708cc4fde94883d4501ad03427d12d5b88d4b94426cb5a21940b4e5d6249f4"
content-hash = "2eda2ed313011bb0b1c97d9018d87190d2d2ca630cf0eb8a4dca1ea73612ba53"

View File

@ -24,7 +24,8 @@ dependencies = [
"fastapi (>=0.115.12,<0.116.0)",
"uvicorn (>=0.34.2,<0.35.0)",
"emoji (>=2.14.1,<3.0.0)",
"telethon (>=1.40.0,<2.0.0)"
"telethon (>=1.40.0,<2.0.0)",
"alembic (>=1.16.2,<2.0.0)"
]

View File

@ -0,0 +1,7 @@
from telethon.sync import TelegramClient
from telethon.sessions import StringSession
from src.core.settings.base import settings
with TelegramClient(StringSession(), settings.ACCOUNT.API_ID, settings.ACCOUNT.API_HASH) as client:
print(client.session.save())