Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 162 additions & 0 deletions examples/auto_update_usage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# Enhanced Auto-Update Functionality

This document demonstrates the new enhanced auto-update functionality implemented for issue #48.

## New Commands

### 1. Enhanced Individual Profile Update
- **Command**: `обновить` / `update`
- **Description**: Updates user profile with comprehensive information from VK API
- **Features**:
- Updates user name (first name + last name)
- Auto-detects GitHub profile from VK site field
- Auto-detects programming languages from activities/about sections
- Provides detailed feedback on what was updated

**Example Usage**:
```
User: обновить
Bot: Профиль обновлен!
Обновленные поля: имя, GitHub профиль, языки программирования (Python, JavaScript)

[Shows updated profile info]
```

### 2. Bulk Profile Updates (Admin Only)
- **Command**: `обновить всех` / `update all`
- **Description**: Updates all user profiles in the current chat
- **Requirements**: High karma (50+) or admin privileges
- **Features**:
- Only updates users with auto-update enabled
- Processes all chat members
- Provides summary of updated profiles

**Example Usage**:
```
Admin: обновить всех
Bot: Массовое обновление завершено!
Обработано пользователей: 25
Обновлено профилей: 8
```

### 3. Auto-Update Settings
- **Command**: `автообновление вкл/выкл` / `auto-update on/off`
- **Description**: Controls automatic profile updates for the user
- **Features**:
- Enable/disable periodic auto-updates
- Check current auto-update status

**Example Usage**:
```
User: автообновление вкл
Bot: Автообновление профиля включено.

User: автообновление выкл
Bot: Автообновление профиля отключено.

User: автообновление
Bot: Автообновление профиля сейчас включено.
```

## Automatic Features

### 1. GitHub Profile Detection
The bot automatically detects GitHub profiles from the VK "site" field:
- Supports various GitHub URL formats
- Validates that the GitHub profile exists before updating
- Extracts username from URLs like:
- `https://github.com/username`
- `http://github.com/username`
- `github.com/username`

### 2. Programming Language Detection
Automatically detects programming languages mentioned in:
- VK "activities" field
- VK "about" field
- Supports 100+ programming languages
- Case-insensitive detection
- Only adds new languages (doesn't remove existing ones)

### 3. Periodic Auto-Updates
- Runs every 6 hours automatically
- Only updates users with auto-update enabled
- Only updates profiles that haven't been updated in 24+ hours
- Processes maximum 10 users per cycle to respect API limits
- Logs all automatic updates

## Data Storage

New user profile fields:
- `auto_update_enabled` (boolean): Controls automatic updates
- `last_auto_update` (timestamp): Tracks when profile was last auto-updated

## Technical Implementation

### New Patterns Added
```python
UPDATE_ALL = recompile(
r'\A\s*(обновить всех|update all)\s*\Z', IGNORECASE)

AUTO_UPDATE = recompile(
r'\A\s*(авто[- ]?обновление|auto[- ]?update)\s+(вкл|on|выкл|off)\s*\Z', IGNORECASE)
```

### Enhanced VK API Usage
The enhanced update uses comprehensive VK API fields:
```python
fields='about,activities,bdate,books,career,city,contacts,education,games,interests,movies,music,personal,quotes,relation,schools,site,tv,universities'
```

### Error Handling
- Graceful handling of VK API errors
- Validation of GitHub profiles before updating
- Protection against API rate limits
- Comprehensive logging for debugging

## Security & Performance

### Admin Protection
- Bulk updates require high karma (50+) or specific user ID
- Only available in group chats, not private messages

### API Rate Limiting
- Periodic updates process maximum 10 users at a time
- 6-hour intervals between automatic update cycles
- Respects VK API rate limits

### Privacy
- Users can disable auto-updates at any time
- Only processes public VK profile information
- No storage of sensitive data

## Migration

Existing users automatically get:
- `auto_update_enabled = True` (opt-in by default)
- `last_auto_update = 0` (eligible for immediate update)

## Examples of Detection

### GitHub Profile Detection
```
VK Site Field: "Check out my code at https://github.com/developer123"
Result: GitHub profile set to "developer123"
```

### Programming Language Detection
```
VK Activities: "Coding in Python, learning JavaScript, love C++"
VK About: "Full-stack developer specializing in web technologies"
Result: Adds "Python", "JavaScript", "C++" to programming languages
```

## Help Message Update

The help command now includes information about auto-update commands:

```
🔄 Команды обновления профиля:
• обновить/update — обновить свой профиль
• обновить всех/update all — массовое обновление (для админов)
• автообновление вкл/выкл — управление автообновлением
```
152 changes: 152 additions & 0 deletions experiments/test_auto_update.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test script for the enhanced auto-update functionality.
This script validates the new auto-update features without requiring VK API tokens.
"""

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'python'))

from modules.data_service import BetterBotBaseDataService
import patterns
from regex import match

def test_patterns():
"""Test the new regex patterns."""
print("=== Testing Patterns ===")

# Test UPDATE pattern (existing)
test_cases = [
("обновить", patterns.UPDATE),
("update", patterns.UPDATE),
("UPDATE", patterns.UPDATE),
]

for test_text, pattern in test_cases:
result = match(pattern, test_text)
print(f"Pattern {pattern.pattern[:30]}... matches '{test_text}': {bool(result)}")

# Test UPDATE_ALL pattern (new)
test_cases = [
("обновить всех", patterns.UPDATE_ALL),
("update all", patterns.UPDATE_ALL),
("UPDATE ALL", patterns.UPDATE_ALL),
]

for test_text, pattern in test_cases:
result = match(pattern, test_text)
print(f"Pattern {pattern.pattern[:30]}... matches '{test_text}': {bool(result)}")

# Test AUTO_UPDATE pattern (new)
test_cases = [
("автообновление вкл", patterns.AUTO_UPDATE),
("auto-update on", patterns.AUTO_UPDATE),
("автообновление выкл", patterns.AUTO_UPDATE),
("auto update off", patterns.AUTO_UPDATE),
]

for test_text, pattern in test_cases:
result = match(pattern, test_text)
print(f"Pattern {pattern.pattern[:30]}... matches '{test_text}': {bool(result)}")
if result:
print(f" Groups: {result.groups()}")

def test_data_service():
"""Test the enhanced data service with new fields."""
print("\n=== Testing Data Service ===")

# Create temporary database
data_service = BetterBotBaseDataService("test_db")

# Test creating a user and checking new fields
user = data_service.get_or_create_user(12345, None)
print(f"Created user: {user.uid}")
print(f"Auto-update enabled: {user.auto_update_enabled}")
print(f"Last auto-update: {user.last_auto_update}")

# Test updating auto-update settings
user.auto_update_enabled = False
user.last_auto_update = 1234567890
data_service.save_user(user)

# Reload user and verify changes
user_reloaded = data_service.get_user(12345)
print(f"Reloaded user auto-update enabled: {user_reloaded.auto_update_enabled}")
print(f"Reloaded user last auto-update: {user_reloaded.last_auto_update}")

# Cleanup
try:
os.remove("test_db.dat")
print("Cleaned up test database")
except:
pass

def test_github_profile_detection():
"""Test GitHub profile URL detection logic."""
print("\n=== Testing GitHub Profile Detection ===")

import re

test_urls = [
"https://github.com/konard",
"http://github.com/test-user",
"github.com/my_username",
"Visit my profile at github.com/developer123/",
"https://github.com/user-name-123",
"not a github url",
"https://gitlab.com/user"
]

for url in test_urls:
github_match = re.search(r'github\.com/([a-zA-Z0-9-_]+)', url)
if github_match:
username = github_match.group(1)
print(f"URL: '{url}' -> GitHub username: '{username}'")
else:
print(f"URL: '{url}' -> No GitHub username found")

def test_programming_language_detection():
"""Test programming language detection logic."""
print("\n=== Testing Programming Language Detection ===")

import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'python'))
import config

test_texts = [
"I love programming in Python and JavaScript",
"Working with C++ and Java daily",
"Learning Rust and Go",
"Expert in C#, PHP, and SQL",
"Just a regular user with no programming languages mentioned"
]

for text in test_texts:
detected = []
text_lower = text.lower()

for lang_pattern in config.DEFAULT_PROGRAMMING_LANGUAGES[:10]: # Test first 10 languages
lang_clean = lang_pattern.replace('\\', '').replace('+', '\+').replace('-', '\-')
if lang_clean.lower() in text_lower:
detected.append(lang_pattern.replace('\\', ''))

print(f"Text: '{text}'")
print(f" Detected languages: {detected}")

if __name__ == "__main__":
print("Testing Enhanced Auto-Update Functionality")
print("=" * 50)

test_patterns()
test_data_service()
test_github_profile_detection()
test_programming_language_detection()

print("\n=== Test Summary ===")
print("✅ Pattern matching tests completed")
print("✅ Data service tests completed")
print("✅ GitHub profile detection tests completed")
print("✅ Programming language detection tests completed")
print("\nAll tests completed successfully!")
Loading
Loading