mass refactor
This commit is contained in:
84
bin/README.md
Normal file
84
bin/README.md
Normal file
@@ -0,0 +1,84 @@
|
||||
# Автоматическое обновление Telegram Tinder Bot
|
||||
|
||||
Этот документ описывает процесс автоматического обновления бота с помощью созданных скриптов.
|
||||
|
||||
## Скрипт обновления
|
||||
|
||||
Скрипт обновления выполняет следующие действия:
|
||||
|
||||
1. Получает последние изменения из Git-репозитория
|
||||
2. Устанавливает зависимости
|
||||
3. Применяет миграции базы данных
|
||||
4. Собирает проект
|
||||
5. Проверяет наличие файла .env
|
||||
6. Проверяет наличие Docker-сервисов
|
||||
7. При запуске на Ubuntu: проверяет и перезапускает PM2 сервис
|
||||
|
||||
## Подробные инструкции по развертыванию
|
||||
|
||||
Для подробных инструкций по развертыванию бота на сервере Ubuntu 24.04, пожалуйста, обратитесь к файлу `DEPLOY_UBUNTU.md` в корне проекта.
|
||||
|
||||
## Как использовать
|
||||
|
||||
### На Linux/macOS:
|
||||
|
||||
```bash
|
||||
# Обновление с ветки main (по умолчанию)
|
||||
npm run update
|
||||
|
||||
# Обновление с определенной ветки
|
||||
bash ./bin/update.sh develop
|
||||
|
||||
# Обновление с определенной ветки и перезапуском сервиса PM2 (для Ubuntu)
|
||||
bash ./bin/update.sh develop --restart-service
|
||||
```
|
||||
|
||||
### На Windows:
|
||||
|
||||
```powershell
|
||||
# Обновление с ветки main (по умолчанию)
|
||||
npm run update:win
|
||||
|
||||
# Обновление с определенной ветки
|
||||
.\bin\update.bat develop
|
||||
```
|
||||
|
||||
## Добавление прав на выполнение (только для Linux/macOS)
|
||||
|
||||
Если у вас возникают проблемы с запуском скрипта, добавьте права на выполнение:
|
||||
|
||||
```bash
|
||||
chmod +x ./bin/update.sh
|
||||
```
|
||||
|
||||
## Автоматизация обновлений
|
||||
|
||||
Для автоматизации регулярных обновлений вы можете использовать cron (Linux/macOS) или Планировщик заданий (Windows).
|
||||
|
||||
### Пример cron-задания для Ubuntu (ежедневное обновление в 4:00 с перезапуском сервиса):
|
||||
|
||||
```
|
||||
0 4 * * * cd /opt/tg_tinder_bot && ./bin/update.sh --restart-service >> /var/log/tg_bot_update.log 2>&1
|
||||
```
|
||||
|
||||
### Пример cron-задания (ежедневное обновление в 4:00 без перезапуска):
|
||||
|
||||
```
|
||||
0 4 * * * cd /path/to/bot && ./bin/update.sh
|
||||
```
|
||||
|
||||
### Для Windows:
|
||||
|
||||
Создайте задачу в Планировщике заданий, которая запускает:
|
||||
|
||||
```
|
||||
cmd.exe /c "cd /d D:\Projects\tg_tinder_bot && .\bin\update.bat"
|
||||
```
|
||||
|
||||
## Что делать после обновления
|
||||
|
||||
После обновления вы можете:
|
||||
|
||||
1. Запустить бота: `npm run start`
|
||||
2. Запустить бота в режиме разработки: `npm run dev`
|
||||
3. Перезапустить Docker-контейнеры, если используете Docker: `docker-compose down && docker-compose up -d`
|
||||
190
bin/install_ubuntu.sh
Normal file
190
bin/install_ubuntu.sh
Normal file
@@ -0,0 +1,190 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Script for installing Telegram Tinder Bot on Ubuntu
|
||||
# This script automates the deployment process on a fresh Ubuntu server
|
||||
# Usage: ./bin/install_ubuntu.sh [--with-nginx] [--with-ssl domain.com]
|
||||
|
||||
set -e # Exit immediately if a command exits with a non-zero status
|
||||
|
||||
# Define colors for pretty output
|
||||
GREEN='\033[0;32m'
|
||||
BLUE='\033[0;34m'
|
||||
YELLOW='\033[0;33m'
|
||||
RED='\033[0;31m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Default settings
|
||||
INSTALL_NGINX=false
|
||||
INSTALL_SSL=false
|
||||
DOMAIN=""
|
||||
|
||||
# Parse command line arguments
|
||||
for arg in "$@"; do
|
||||
if [[ "$arg" == "--with-nginx" ]]; then
|
||||
INSTALL_NGINX=true
|
||||
elif [[ "$arg" == "--with-ssl" ]]; then
|
||||
INSTALL_SSL=true
|
||||
# Next argument should be domain
|
||||
shift
|
||||
DOMAIN="$1"
|
||||
if [[ -z "$DOMAIN" || "$DOMAIN" == --* ]]; then
|
||||
echo -e "${RED}Error: Domain name required after --with-ssl${NC}"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
shift
|
||||
done
|
||||
|
||||
echo -e "${BLUE}========================================${NC}"
|
||||
echo -e "${BLUE} Telegram Tinder Bot Ubuntu Installer ${NC}"
|
||||
echo -e "${BLUE}========================================${NC}"
|
||||
|
||||
# Check if running on Ubuntu
|
||||
if [ -f /etc/os-release ]; then
|
||||
source /etc/os-release
|
||||
if [[ "$ID" != "ubuntu" ]]; then
|
||||
echo -e "${RED}Error: This script is designed for Ubuntu. Current OS: $ID${NC}"
|
||||
exit 1
|
||||
else
|
||||
echo -e "${GREEN}Detected Ubuntu ${VERSION_ID}${NC}"
|
||||
fi
|
||||
else
|
||||
echo -e "${RED}Error: Could not detect operating system${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check for root privileges
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
echo -e "${RED}Error: This script must be run as root${NC}"
|
||||
echo -e "Please run: ${YELLOW}sudo $0 $*${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "\n${BLUE}Step 1: Updating system packages...${NC}"
|
||||
apt update && apt upgrade -y
|
||||
echo -e "${GREEN}✓ System packages updated${NC}"
|
||||
|
||||
echo -e "\n${BLUE}Step 2: Installing dependencies...${NC}"
|
||||
apt install -y curl wget git build-essential postgresql postgresql-contrib
|
||||
echo -e "${GREEN}✓ Basic dependencies installed${NC}"
|
||||
|
||||
echo -e "\n${BLUE}Step 3: Installing Node.js...${NC}"
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||
apt install -y nodejs
|
||||
echo -e "${GREEN}✓ Node.js $(node --version) installed${NC}"
|
||||
echo -e "${GREEN}✓ npm $(npm --version) installed${NC}"
|
||||
|
||||
echo -e "\n${BLUE}Step 4: Setting up PostgreSQL...${NC}"
|
||||
systemctl start postgresql
|
||||
systemctl enable postgresql
|
||||
|
||||
echo -e "\n${BLUE}Please enter a strong password for the database user:${NC}"
|
||||
read -s DB_PASSWORD
|
||||
echo
|
||||
|
||||
# Create database and user
|
||||
su - postgres -c "psql -c \"CREATE DATABASE tg_tinder_bot;\""
|
||||
su - postgres -c "psql -c \"CREATE USER tg_bot WITH PASSWORD '$DB_PASSWORD';\""
|
||||
su - postgres -c "psql -c \"GRANT ALL PRIVILEGES ON DATABASE tg_tinder_bot TO tg_bot;\""
|
||||
echo -e "${GREEN}✓ PostgreSQL configured${NC}"
|
||||
|
||||
echo -e "\n${BLUE}Step 5: Setting up application directory...${NC}"
|
||||
mkdir -p /opt/tg_tinder_bot
|
||||
chown $SUDO_USER:$SUDO_USER /opt/tg_tinder_bot
|
||||
echo -e "${GREEN}✓ Application directory created${NC}"
|
||||
|
||||
echo -e "\n${BLUE}Step 6: Installing PM2...${NC}"
|
||||
npm install -g pm2
|
||||
echo -e "${GREEN}✓ PM2 installed${NC}"
|
||||
|
||||
echo -e "\n${BLUE}Step 7: Please enter your Telegram Bot Token:${NC}"
|
||||
read BOT_TOKEN
|
||||
|
||||
echo -e "\n${BLUE}Step 8: Creating environment file...${NC}"
|
||||
cat > /opt/tg_tinder_bot/.env << EOL
|
||||
# Bot settings
|
||||
BOT_TOKEN=${BOT_TOKEN}
|
||||
LOG_LEVEL=info
|
||||
|
||||
# Database settings
|
||||
DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
DB_USER=tg_bot
|
||||
DB_PASSWORD=${DB_PASSWORD}
|
||||
DB_NAME=tg_tinder_bot
|
||||
EOL
|
||||
chmod 600 /opt/tg_tinder_bot/.env
|
||||
chown $SUDO_USER:$SUDO_USER /opt/tg_tinder_bot/.env
|
||||
echo -e "${GREEN}✓ Environment file created${NC}"
|
||||
|
||||
echo -e "\n${BLUE}Step 9: Setting up systemd service...${NC}"
|
||||
cat > /etc/systemd/system/tg-tinder-bot.service << EOL
|
||||
[Unit]
|
||||
Description=Telegram Tinder Bot
|
||||
After=network.target postgresql.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=${SUDO_USER}
|
||||
WorkingDirectory=/opt/tg_tinder_bot
|
||||
ExecStart=/usr/bin/node dist/bot.js
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
StandardOutput=syslog
|
||||
StandardError=syslog
|
||||
SyslogIdentifier=tg-tinder-bot
|
||||
Environment=NODE_ENV=production
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOL
|
||||
echo -e "${GREEN}✓ Systemd service created${NC}"
|
||||
|
||||
if [ "$INSTALL_NGINX" = true ]; then
|
||||
echo -e "\n${BLUE}Step 10: Installing and configuring Nginx...${NC}"
|
||||
apt install -y nginx
|
||||
|
||||
# Create Nginx configuration
|
||||
cat > /etc/nginx/sites-available/tg_tinder_bot << EOL
|
||||
server {
|
||||
listen 80;
|
||||
server_name ${DOMAIN:-_};
|
||||
|
||||
location / {
|
||||
proxy_pass http://localhost:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade \$http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host \$host;
|
||||
proxy_cache_bypass \$http_upgrade;
|
||||
}
|
||||
}
|
||||
EOL
|
||||
|
||||
# Enable site
|
||||
ln -sf /etc/nginx/sites-available/tg_tinder_bot /etc/nginx/sites-enabled/
|
||||
nginx -t && systemctl restart nginx
|
||||
echo -e "${GREEN}✓ Nginx configured${NC}"
|
||||
|
||||
if [ "$INSTALL_SSL" = true ] && [ ! -z "$DOMAIN" ]; then
|
||||
echo -e "\n${BLUE}Step 11: Setting up SSL with Certbot...${NC}"
|
||||
apt install -y certbot python3-certbot-nginx
|
||||
certbot --nginx --non-interactive --agree-tos --email admin@${DOMAIN} -d ${DOMAIN}
|
||||
echo -e "${GREEN}✓ SSL certificate installed${NC}"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo -e "\n${BLUE}Step 12: Clone your repository${NC}"
|
||||
echo -e "Now you should clone your repository to /opt/tg_tinder_bot"
|
||||
echo -e "Example: ${YELLOW}git clone https://your-git-repo-url.git /opt/tg_tinder_bot${NC}"
|
||||
echo -e "Then run the update script: ${YELLOW}cd /opt/tg_tinder_bot && ./bin/update.sh${NC}"
|
||||
|
||||
echo -e "\n${GREEN}========================================${NC}"
|
||||
echo -e "${GREEN} Installation completed! ${NC}"
|
||||
echo -e "${GREEN}========================================${NC}"
|
||||
echo -e "Next steps:"
|
||||
echo -e "1. Clone your repository to ${YELLOW}/opt/tg_tinder_bot${NC}"
|
||||
echo -e "2. Run the update script to set up the application"
|
||||
echo -e "3. Start the service with: ${YELLOW}sudo systemctl start tg-tinder-bot${NC}"
|
||||
echo -e "4. Enable auto-start with: ${YELLOW}sudo systemctl enable tg-tinder-bot${NC}"
|
||||
echo -e "5. Check status with: ${YELLOW}sudo systemctl status tg-tinder-bot${NC}"
|
||||
81
bin/setup.sh
Normal file
81
bin/setup.sh
Normal file
@@ -0,0 +1,81 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Telegram Tinder Bot Setup Script
|
||||
|
||||
echo "🚀 Setting up Telegram Tinder Bot..."
|
||||
|
||||
# Check if Node.js is installed
|
||||
if ! command -v node &> /dev/null; then
|
||||
echo "❌ Node.js is not installed. Please install Node.js 16 or higher."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if PostgreSQL is installed
|
||||
if ! command -v psql &> /dev/null; then
|
||||
echo "⚠️ PostgreSQL is not installed. You can install it or use Docker."
|
||||
read -p "Do you want to use Docker for PostgreSQL? (y/n): " use_docker
|
||||
if [[ $use_docker =~ ^[Yy]$ ]]; then
|
||||
echo "📦 Using Docker for PostgreSQL..."
|
||||
DOCKER_MODE=true
|
||||
else
|
||||
echo "❌ Please install PostgreSQL manually."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Install dependencies
|
||||
echo "📦 Installing dependencies..."
|
||||
npm install
|
||||
|
||||
# Check if .env file exists
|
||||
if [ ! -f .env ]; then
|
||||
echo "📄 Creating .env file from template..."
|
||||
cp .env.example .env
|
||||
echo "✅ .env file created. Please edit it with your configuration."
|
||||
else
|
||||
echo "✅ .env file already exists."
|
||||
fi
|
||||
|
||||
# Build the project
|
||||
echo "🔨 Building the project..."
|
||||
npm run build
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "✅ Project built successfully!"
|
||||
else
|
||||
echo "❌ Build failed. Please check the errors above."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create necessary directories
|
||||
echo "📁 Creating directories..."
|
||||
mkdir -p logs uploads
|
||||
|
||||
if [ "$DOCKER_MODE" = true ]; then
|
||||
echo "🐳 Starting database with Docker..."
|
||||
docker-compose up -d db
|
||||
echo "⏳ Waiting for database to be ready..."
|
||||
sleep 10
|
||||
|
||||
echo "🗄️ Initializing database..."
|
||||
docker-compose exec db psql -U postgres -d telegram_tinder_bot -f /docker-entrypoint-initdb.d/init.sql
|
||||
else
|
||||
echo "🗄️ Setting up database..."
|
||||
echo "Please run the following commands to set up your database:"
|
||||
echo "1. Create database: createdb telegram_tinder_bot"
|
||||
echo "2. Run migrations: psql -d telegram_tinder_bot -f src/database/migrations/init.sql"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "🎉 Setup completed!"
|
||||
echo ""
|
||||
echo "Next steps:"
|
||||
echo "1. Edit .env file with your Telegram Bot Token and database credentials"
|
||||
echo "2. Get your bot token from @BotFather on Telegram"
|
||||
echo "3. Configure your database connection"
|
||||
echo "4. Run 'npm start' to start the bot"
|
||||
echo ""
|
||||
echo "For development: npm run dev"
|
||||
echo "For production: npm run start:prod"
|
||||
echo ""
|
||||
echo "📚 Check README.md for detailed instructions."
|
||||
27
bin/start_bot.bat
Normal file
27
bin/start_bot.bat
Normal file
@@ -0,0 +1,27 @@
|
||||
@echo off
|
||||
REM Скрипт для запуска Telegram Tinder Bot в производственном режиме на Windows
|
||||
REM Запускает собранный JavaScript из dist/bot.js
|
||||
|
||||
echo 🚀 Запуск Telegram Tinder Bot в производственном режиме...
|
||||
|
||||
REM Добавляем Node.js в PATH, если нужно
|
||||
set PATH=%PATH%;C:\Program Files\nodejs
|
||||
|
||||
REM Переходим в корневую директорию проекта
|
||||
cd /d %~dp0..
|
||||
|
||||
REM Проверяем, существует ли собранный файл
|
||||
if not exist ".\dist\bot.js" (
|
||||
echo ❌ Ошибка: Собранный файл не найден. Сначала выполните 'npm run build'.
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM Устанавливаем переменную окружения для производственного режима
|
||||
set NODE_ENV=production
|
||||
|
||||
REM Запускаем бот
|
||||
echo 🤖 Запуск Telegram Tinder Bot...
|
||||
node .\dist\bot.js
|
||||
|
||||
REM Если скрипт дойдет до этой точки, значит бот завершил работу
|
||||
echo 👋 Бот был остановлен.
|
||||
24
bin/start_bot.sh
Normal file
24
bin/start_bot.sh
Normal file
@@ -0,0 +1,24 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Скрипт для запуска бота в производственном режиме
|
||||
# Запускает собранный JavaScript из dist/bot.js
|
||||
|
||||
# Переходим в корневую директорию проекта (предполагается, что скрипт находится в bin/)
|
||||
PROJECT_DIR="$(dirname "$(dirname "$(readlink -f "$0")")")"
|
||||
cd "$PROJECT_DIR" || { echo "❌ Error: Could not change directory to $PROJECT_DIR"; exit 1; }
|
||||
|
||||
# Проверяем, существует ли собранный файл
|
||||
if [ ! -f "./dist/bot.js" ]; then
|
||||
echo "❌ Error: Built file not found. Please run 'npm run build' first."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Устанавливаем переменную окружения для производственного режима
|
||||
export NODE_ENV=production
|
||||
|
||||
# Запускаем бот
|
||||
echo "🚀 Starting Telegram Tinder Bot in production mode..."
|
||||
node ./dist/bot.js
|
||||
|
||||
# Если скрипт дойдет до этой точки, значит бот завершил работу
|
||||
echo "👋 Bot has been stopped."
|
||||
18
bin/tg-tinder-bot.service
Normal file
18
bin/tg-tinder-bot.service
Normal file
@@ -0,0 +1,18 @@
|
||||
[Unit]
|
||||
Description=Telegram Tinder Bot
|
||||
After=network.target postgresql.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=ubuntu
|
||||
WorkingDirectory=/opt/tg_tinder_bot
|
||||
ExecStart=/usr/bin/node dist/bot.js
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
StandardOutput=syslog
|
||||
StandardError=syslog
|
||||
SyslogIdentifier=tg-tinder-bot
|
||||
Environment=NODE_ENV=production
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
113
bin/update.bat
Normal file
113
bin/update.bat
Normal file
@@ -0,0 +1,113 @@
|
||||
@echo off
|
||||
REM Script for updating the Telegram Tinder Bot on Windows
|
||||
REM This script updates the code from Git, applies migrations, and prepares the bot for running
|
||||
REM Usage: .\bin\update.bat [branch]
|
||||
REM If branch is not specified, 'main' is used
|
||||
|
||||
setlocal enableextensions enabledelayedexpansion
|
||||
|
||||
echo ========================================
|
||||
echo Telegram Tinder Bot Updater
|
||||
echo ========================================
|
||||
|
||||
REM Get the branch name from the command line arguments
|
||||
set BRANCH=%1
|
||||
if "%BRANCH%"=="" set BRANCH=main
|
||||
echo Updating from branch: %BRANCH%
|
||||
|
||||
REM Store the current directory
|
||||
set CURRENT_DIR=%CD%
|
||||
set SCRIPT_DIR=%~dp0
|
||||
set PROJECT_DIR=%SCRIPT_DIR%..
|
||||
|
||||
REM Navigate to the project directory
|
||||
cd /d %PROJECT_DIR%
|
||||
echo Working directory: %PROJECT_DIR%
|
||||
|
||||
REM Check if we're in a git repository
|
||||
if not exist .git (
|
||||
echo Error: Not a git repository
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Step 1: Pulling latest changes from Git repository...
|
||||
REM Save any local changes
|
||||
git stash save "Auto-stash before update: %DATE% %TIME%"
|
||||
|
||||
REM Fetch all branches
|
||||
git fetch --all
|
||||
|
||||
REM Check if the branch exists
|
||||
git rev-parse --verify %BRANCH% >nul 2>&1
|
||||
if %ERRORLEVEL% NEQ 0 (
|
||||
git rev-parse --verify origin/%BRANCH% >nul 2>&1
|
||||
if %ERRORLEVEL% NEQ 0 (
|
||||
echo Error: Branch '%BRANCH%' does not exist locally or remotely
|
||||
exit /b 1
|
||||
)
|
||||
)
|
||||
|
||||
REM Checkout the specified branch
|
||||
git checkout %BRANCH%
|
||||
|
||||
REM Pull the latest changes
|
||||
git pull origin %BRANCH%
|
||||
echo ✓ Successfully pulled latest changes
|
||||
|
||||
echo.
|
||||
echo Step 2: Installing dependencies...
|
||||
call npm ci
|
||||
echo ✓ Dependencies installed
|
||||
|
||||
echo.
|
||||
echo Step 3: Running database migrations...
|
||||
REM Check if migrations directory exists
|
||||
if exist migrations (
|
||||
echo Applying database migrations...
|
||||
call npm run migrate:up
|
||||
echo ✓ Migrations applied successfully
|
||||
) else (
|
||||
echo ⚠ No migrations directory found, running database initialization script...
|
||||
call npm run init:db
|
||||
echo ✓ Database initialized
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Step 4: Building the project...
|
||||
call npm run build
|
||||
echo ✓ Project built successfully
|
||||
|
||||
echo.
|
||||
echo Step 5: Checking for .env file...
|
||||
if exist .env (
|
||||
echo ✓ .env file exists
|
||||
) else (
|
||||
echo ⚠ .env file not found
|
||||
if exist .env.example (
|
||||
echo Creating .env from .env.example
|
||||
copy .env.example .env
|
||||
echo ⚠ Please update the .env file with your configuration!
|
||||
) else (
|
||||
echo Error: .env.example file not found
|
||||
exit /b 1
|
||||
)
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Step 6: Checking for services...
|
||||
REM Check if Docker is being used
|
||||
if exist docker-compose.yml (
|
||||
echo Docker Compose configuration found
|
||||
echo You might want to restart containers with: docker-compose down ^&^& docker-compose up -d
|
||||
)
|
||||
|
||||
echo.
|
||||
echo ========================================
|
||||
echo Update completed successfully!
|
||||
echo ========================================
|
||||
echo To start the bot, run: npm run start
|
||||
echo For development mode: npm run dev
|
||||
|
||||
REM Return to the original directory
|
||||
cd /d %CURRENT_DIR%
|
||||
155
bin/update.sh
Normal file
155
bin/update.sh
Normal file
@@ -0,0 +1,155 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Script for updating the Telegram Tinder Bot
|
||||
# This script updates the code from Git, applies migrations, and prepares the bot for running
|
||||
# Usage: ./bin/update.sh [branch] [--restart-service]
|
||||
# If branch is not specified, 'main' is used
|
||||
# Use --restart-service flag to restart PM2 service after update (for production deployments)
|
||||
|
||||
set -e # Exit immediately if a command exits with a non-zero status
|
||||
|
||||
# Define colors for pretty output
|
||||
GREEN='\033[0;32m'
|
||||
BLUE='\033[0;34m'
|
||||
YELLOW='\033[0;33m'
|
||||
RED='\033[0;31m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
echo -e "${BLUE}========================================${NC}"
|
||||
echo -e "${BLUE} Telegram Tinder Bot Updater ${NC}"
|
||||
echo -e "${BLUE}========================================${NC}"
|
||||
|
||||
# Parse command line arguments
|
||||
BRANCH="main"
|
||||
RESTART_SERVICE=false
|
||||
|
||||
for arg in "$@"; do
|
||||
if [[ "$arg" == "--restart-service" ]]; then
|
||||
RESTART_SERVICE=true
|
||||
elif [[ "$arg" != --* ]]; then
|
||||
BRANCH="$arg"
|
||||
fi
|
||||
done
|
||||
|
||||
echo -e "${YELLOW}Updating from branch: ${BRANCH}${NC}"
|
||||
if [ "$RESTART_SERVICE" = true ]; then
|
||||
echo -e "${YELLOW}Will restart service after update${NC}"
|
||||
fi
|
||||
|
||||
# Store the current directory
|
||||
CURRENT_DIR=$(pwd)
|
||||
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
|
||||
PROJECT_DIR=$(dirname "$SCRIPT_DIR")
|
||||
|
||||
# Check if running on Ubuntu
|
||||
IS_UBUNTU=false
|
||||
if [ -f /etc/os-release ]; then
|
||||
source /etc/os-release
|
||||
if [[ "$ID" == "ubuntu" ]]; then
|
||||
IS_UBUNTU=true
|
||||
echo -e "${BLUE}Detected Ubuntu: ${VERSION_ID}${NC}"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Navigate to the project directory
|
||||
cd "$PROJECT_DIR"
|
||||
echo -e "${BLUE}Working directory: ${PROJECT_DIR}${NC}"
|
||||
|
||||
# Check if we're in a git repository
|
||||
if [ ! -d ".git" ]; then
|
||||
echo -e "${RED}Error: Not a git repository${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "\n${BLUE}Step 1: Pulling latest changes from Git repository...${NC}"
|
||||
# Save any local changes
|
||||
git stash save "Auto-stash before update: $(date)"
|
||||
|
||||
# Fetch all branches
|
||||
git fetch --all
|
||||
|
||||
# Check if the branch exists
|
||||
if ! git rev-parse --verify "$BRANCH" &>/dev/null && ! git rev-parse --verify "origin/$BRANCH" &>/dev/null; then
|
||||
echo -e "${RED}Error: Branch '$BRANCH' does not exist locally or remotely${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Checkout the specified branch
|
||||
git checkout "$BRANCH"
|
||||
|
||||
# Pull the latest changes
|
||||
git pull origin "$BRANCH"
|
||||
echo -e "${GREEN}✓ Successfully pulled latest changes${NC}"
|
||||
|
||||
echo -e "\n${BLUE}Step 2: Installing dependencies...${NC}"
|
||||
npm ci
|
||||
echo -e "${GREEN}✓ Dependencies installed${NC}"
|
||||
|
||||
echo -e "\n${BLUE}Step 3: Running database migrations...${NC}"
|
||||
# Check if migrations directory exists
|
||||
if [ -d "./migrations" ]; then
|
||||
echo "Applying database migrations..."
|
||||
npm run migrate:up
|
||||
echo -e "${GREEN}✓ Migrations applied successfully${NC}"
|
||||
else
|
||||
echo -e "${YELLOW}⚠ No migrations directory found, running database initialization script...${NC}"
|
||||
npm run init:db
|
||||
echo -e "${GREEN}✓ Database initialized${NC}"
|
||||
fi
|
||||
|
||||
echo -e "\n${BLUE}Step 4: Building the project...${NC}"
|
||||
npm run build
|
||||
echo -e "${GREEN}✓ Project built successfully${NC}"
|
||||
|
||||
echo -e "\n${BLUE}Step 5: Checking for .env file...${NC}"
|
||||
if [ -f .env ]; then
|
||||
echo -e "${GREEN}✓ .env file exists${NC}"
|
||||
else
|
||||
echo -e "${YELLOW}⚠ .env file not found${NC}"
|
||||
if [ -f .env.example ]; then
|
||||
echo "Creating .env from .env.example"
|
||||
cp .env.example .env
|
||||
echo -e "${YELLOW}⚠ Please update the .env file with your configuration!${NC}"
|
||||
else
|
||||
echo -e "${RED}Error: .env.example file not found${NC}"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
echo -e "\n${BLUE}Step 6: Checking for services...${NC}"
|
||||
# Check if Docker is being used
|
||||
if [ -f docker-compose.yml ]; then
|
||||
echo "Docker Compose configuration found"
|
||||
echo "You might want to restart containers with: docker-compose down && docker-compose up -d"
|
||||
fi
|
||||
|
||||
# Check for PM2 process on Ubuntu
|
||||
if [ "$IS_UBUNTU" = true ] && command -v pm2 &>/dev/null; then
|
||||
echo -e "\n${BLUE}Step 7: Checking PM2 service...${NC}"
|
||||
if pm2 list | grep -q "tg_tinder_bot"; then
|
||||
echo "PM2 service for tg_tinder_bot found"
|
||||
if [ "$RESTART_SERVICE" = true ]; then
|
||||
echo "Restarting PM2 service..."
|
||||
pm2 restart tg_tinder_bot
|
||||
echo -e "${GREEN}✓ PM2 service restarted${NC}"
|
||||
else
|
||||
echo "To restart the service, run: ${YELLOW}pm2 restart tg_tinder_bot${NC}"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
echo -e "\n${GREEN}========================================${NC}"
|
||||
echo -e "${GREEN} Update completed successfully! ${NC}"
|
||||
echo -e "${GREEN}========================================${NC}"
|
||||
|
||||
if [ "$IS_UBUNTU" = true ] && command -v pm2 &>/dev/null; then
|
||||
echo -e "To start the bot with PM2, run: ${YELLOW}pm2 start dist/bot.js --name tg_tinder_bot${NC}"
|
||||
echo -e "To restart the bot, run: ${YELLOW}pm2 restart tg_tinder_bot${NC}"
|
||||
echo -e "To view logs, run: ${YELLOW}pm2 logs tg_tinder_bot${NC}"
|
||||
else
|
||||
echo -e "To start the bot, run: ${YELLOW}npm run start${NC}"
|
||||
echo -e "For development mode: ${YELLOW}npm run dev${NC}"
|
||||
fi
|
||||
|
||||
# Return to the original directory
|
||||
cd "$CURRENT_DIR"
|
||||
Reference in New Issue
Block a user