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
32 changes: 32 additions & 0 deletions python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,38 @@

Если Π½ΡƒΠΆΠ½ΠΎΠ³ΠΎ языка Π½Π΅Ρ‚ Π² спискС, ΠΎ Π΅Π³ΠΎ Π΄ΠΎΠ±Π°Π²Π»Π΅Π½ΠΈΠΈ ΠΌΠΎΠΆΠ½ΠΎ ΠΏΠΎΠΏΡ€ΠΎΡΠΈΡ‚ΡŒ [здСсь](https://github.com/linksplatform/Bot/issues/15)

## Friend Request Auto-Acceptance

Π‘ΠΎΡ‚ автоматичСски ΠΏΡ€ΠΈΠ½ΠΈΠΌΠ°Π΅Ρ‚ заявки Π² Π΄Ρ€ΡƒΠ·ΡŒΡ ΠΏΡ€ΠΈ Π½Π°Π»ΠΈΡ‡ΠΈΠΈ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒΡΠΊΠΎΠ³ΠΎ Ρ‚ΠΎΠΊΠ΅Π½Π° (`USER_TOKEN`). Π­Ρ‚Π° функция Ρ€Π°Π±ΠΎΡ‚Π°Π΅Ρ‚ Π² Ρ„ΠΎΠ½ΠΎΠ²ΠΎΠΌ Ρ€Π΅ΠΆΠΈΠΌΠ΅ ΠΈ провСряСт Π½ΠΎΠ²Ρ‹Π΅ заявки Π² Π΄Ρ€ΡƒΠ·ΡŒΡ ΠΊΠ°ΠΆΠ΄Ρ‹Π΅ 30 сСкунд ΠΏΠΎ ΡƒΠΌΠΎΠ»Ρ‡Π°Π½ΠΈΡŽ.

### Настройка

1. УстановитС `USER_TOKEN` Π² Ρ„Π°ΠΉΠ»Π΅ `tokens.py` (см. Ρ€Π°Π·Π΄Π΅Π» Configure Π½ΠΈΠΆΠ΅)
2. Π£Π±Π΅Π΄ΠΈΡ‚Π΅ΡΡŒ Ρ‡Ρ‚ΠΎ Π² `config.py` установлСно `FRIEND_REQUEST_AUTO_ACCEPT = True` (ΠΏΠΎ ΡƒΠΌΠΎΠ»Ρ‡Π°Π½ΠΈΡŽ Π²ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΎ)
3. ΠŸΡ€ΠΈ нСобходимости ΠΈΠ·ΠΌΠ΅Π½ΠΈΡ‚Π΅ `FRIEND_REQUEST_CHECK_INTERVAL` Π² `config.py` для измСнСния ΠΈΠ½Ρ‚Π΅Ρ€Π²Π°Π»Π° ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ

### ВСстированиС

Для тСстирования Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΎΠ½Π°Π»ΡŒΠ½ΠΎΡΡ‚ΠΈ Π²Ρ‹ΠΏΠΎΠ»Π½ΠΈΡ‚Π΅:
```bash
cd python
python3 test_friend_requests.py
```

Π­Ρ‚Π° ΠΊΠΎΠΌΠ°Π½Π΄Π° ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΈΡ‚:
- Настройку ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒΡΠΊΠΎΠ³ΠΎ Ρ‚ΠΎΠΊΠ΅Π½Π°
- ΠŸΠΎΠ»ΡƒΡ‡Π΅Π½ΠΈΠ΅ списка заявок Π² Π΄Ρ€ΡƒΠ·ΡŒΡ
- АвтоматичСскоС принятиС заявок
- Π Π°Π±ΠΎΡ‚Ρƒ ΠΌΠΎΠ½ΠΈΡ‚ΠΎΡ€ΠΈΠ½Π³Π° Π² Ρ„ΠΎΠ½ΠΎΠ²ΠΎΠΌ Ρ€Π΅ΠΆΠΈΠΌΠ΅

### Π›ΠΎΠ³ΠΈ

ΠŸΡ€ΠΈ запускС Π±ΠΎΡ‚Π° Π±ΡƒΠ΄ΡƒΡ‚ Π²Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ΡŒΡΡ сообщСния ΠΎ:
- ЗапускС ΠΌΠΎΠ½ΠΈΡ‚ΠΎΡ€ΠΈΠ½Π³Π° заявок Π² Π΄Ρ€ΡƒΠ·ΡŒΡ
- ΠšΠΎΠ»ΠΈΡ‡Π΅ΡΡ‚Π²Π΅ Π½Π°ΠΉΠ΄Π΅Π½Π½Ρ‹Ρ… заявок
- УспСшном принятии заявок
- ΠžΡˆΠΈΠ±ΠΊΠ°Ρ… ΠΏΡ€ΠΈ Ρ€Π°Π±ΠΎΡ‚Π΅ с API VK

## Prerequisites
* [Git](https://git-scm.com/downloads)
* [Python 3](https://www.python.org/downloads)
Expand Down
8 changes: 8 additions & 0 deletions python/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,4 +201,12 @@ def get_messages(

if __name__ == '__main__':
vk = Bot(token=BOT_TOKEN, group_id=config.BOT_GROUP_ID, debug=True)

# Start friend request monitoring if enabled and USER_TOKEN is available
if config.FRIEND_REQUEST_AUTO_ACCEPT:
print("Starting VK Bot with friend request auto-acceptance")
vk.userbot.start_friend_request_monitor(check_interval=config.FRIEND_REQUEST_CHECK_INTERVAL)
else:
print("Friend request auto-acceptance is disabled")

vk.start_listen()
4 changes: 4 additions & 0 deletions python/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,5 +153,9 @@
GITHUB_COPILOT_RUN_COMMAND = 'bash -c "./copilot.sh {input_file} {output_file}"'
GITHUB_COPILOT_TIMEOUT = 120 # seconds

# Friend request auto-acceptance settings
FRIEND_REQUEST_AUTO_ACCEPT = True # Enable/disable automatic friend request acceptance
FRIEND_REQUEST_CHECK_INTERVAL = 30 # Check interval in seconds (default: 30)

DEFAULT_PROGRAMMING_LANGUAGES_PATTERN_STRING = "|".join(DEFAULT_PROGRAMMING_LANGUAGES)
GITHUB_COPILOT_LANGUAGES_PATTERN_STRING = "|".join([i for i in GITHUB_COPILOT_LANGUAGES.keys()])
61 changes: 61 additions & 0 deletions python/test_friend_requests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Test script for friend request auto-acceptance functionality.
"""

from userbot import UserBot
from tokens import USER_TOKEN
import time
import sys

def main():
"""Test the friend request functionality."""
print("VK User Bot - Friend Request Test")
print("=" * 40)

# Check if USER_TOKEN is configured
if not USER_TOKEN:
print("ERROR: USER_TOKEN is not set in tokens.py")
print("Please configure your VK user token to test friend request functionality.")
print("You can get a user token from:")
print("https://oauth.vk.com/authorize?client_id=2685278&scope=1073737727&redirect_uri=https://api.vk.com/blank.html&display=page&response_type=token&revoke=1")
sys.exit(1)

userbot = UserBot()

print("1. Testing friend request retrieval...")
pending_requests = userbot.get_friend_requests()

if pending_requests is None:
print("ERROR: Failed to retrieve friend requests (check token permissions)")
return
elif pending_requests == []:
print("βœ“ No pending friend requests found")
else:
print(f"βœ“ Found {len(pending_requests)} pending friend request(s): {pending_requests}")

print("\n2. Testing manual check and accept...")
userbot.check_and_accept_friend_requests()

print("\n3. Testing monitoring functionality...")
print("Starting friend request monitor for 30 seconds (check interval: 10 seconds)")

userbot.start_friend_request_monitor(check_interval=10)

try:
# Let it run for 30 seconds
time.sleep(30)
except KeyboardInterrupt:
print("\nInterrupted by user")

print("\nStopping friend request monitor...")
userbot.stop_friend_request_monitor()

print("\nβœ“ Test completed successfully!")
print("\nTo enable friend request auto-acceptance in the main bot:")
print("1. Set USER_TOKEN in tokens.py")
print("2. Set FRIEND_REQUEST_AUTO_ACCEPT = True in config.py")
print("3. Run the bot with: python3 __main__.py")

if __name__ == '__main__':
main()
137 changes: 136 additions & 1 deletion python/userbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,24 @@
"""Provides working with VK API as user.
"""
from typing import NoReturn, List, Dict, Any
import time
import threading

from exceptions import TooManyMessagesError
from tokens import USER_TOKEN
from requests import Session


class UserBot:
"""Automatically deleting unnecessary messages.
"""Automatically deleting unnecessary messages and handling friend requests.
"""
session = Session()
url = 'https://api.vk.com/method/'
token = USER_TOKEN

def __init__(self):
self._friend_request_checker_active = False
self._friend_request_thread = None

@staticmethod
def delete_messages(
Expand Down Expand Up @@ -50,3 +56,132 @@ def execute(data: str) -> Dict[str, Any]:
"""Executes VK Script.
"""
return UserBot.session.post(UserBot.url + 'execute', data=data).json()

@classmethod
def call_method(cls, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
"""Make VK API call with user token.
"""
params['access_token'] = cls.token
params['v'] = '5.131'
response = cls.session.post(cls.url + method, data=params)
return response.json()

def get_friend_requests(self) -> List[int]:
"""Get list of pending friend request user IDs.
"""
if not self.token:
print("Warning: USER_TOKEN not set, cannot check friend requests")
return []

response = self.call_method('friends.getRequests', {
'out': 0, # incoming requests
'count': 1000
})

if 'error' in response:
print(f"Error getting friend requests: {response['error']}")
return []

if 'response' not in response:
return []

return response['response'].get('items', [])

def accept_friend_request(self, user_id: int) -> bool:
"""Accept a friend request from user_id.

Returns:
bool: True if successfully accepted, False otherwise
"""
if not self.token:
print("Warning: USER_TOKEN not set, cannot accept friend requests")
return False

response = self.call_method('friends.add', {'user_id': user_id})

if 'error' in response:
error_code = response['error'].get('error_code', 0)
if error_code == 174:
print(f"Cannot add yourself as friend (user {user_id})")
elif error_code == 175:
print(f"User {user_id} has blocked you")
elif error_code == 176:
print(f"You have blocked user {user_id}")
elif error_code == 177:
print(f"User {user_id} not found")
elif error_code == 242:
print(f"Too many friends, cannot add user {user_id}")
else:
print(f"Error accepting friend request from {user_id}: {response['error']}")
return False

if 'response' in response:
response_code = response['response']
if response_code == 2:
print(f"Successfully accepted friend request from user {user_id}")
return True
elif response_code == 1:
print(f"Friend request sent to user {user_id} (was not pending)")
return True
elif response_code == 4:
print(f"Request resent to user {user_id}")
return True

return False

def check_and_accept_friend_requests(self):
"""Check for pending friend requests and accept them automatically.
"""
try:
pending_requests = self.get_friend_requests()

if pending_requests:
print(f"Found {len(pending_requests)} pending friend request(s)")

for user_id in pending_requests:
print(f"Accepting friend request from user {user_id}")
success = self.accept_friend_request(user_id)

if success:
# Small delay between requests to avoid rate limits
time.sleep(1)

elif pending_requests == []:
pass # No pending requests, no output needed

except Exception as e:
print(f"Error checking friend requests: {e}")

def start_friend_request_monitor(self, check_interval: int = 60):
"""Start monitoring for friend requests in a background thread.

Args:
check_interval: Time in seconds between checks (default: 60)
"""
if not self.token:
print("Warning: USER_TOKEN not set, cannot start friend request monitoring")
return

if self._friend_request_checker_active:
print("Friend request monitor is already running")
return

print(f"Starting friend request monitor (checking every {check_interval} seconds)")
self._friend_request_checker_active = True

def monitor_loop():
while self._friend_request_checker_active:
self.check_and_accept_friend_requests()
time.sleep(check_interval)

self._friend_request_thread = threading.Thread(target=monitor_loop, daemon=True)
self._friend_request_thread.start()

def stop_friend_request_monitor(self):
"""Stop the friend request monitoring thread.
"""
if self._friend_request_checker_active:
print("Stopping friend request monitor")
self._friend_request_checker_active = False
if self._friend_request_thread:
self._friend_request_thread.join(timeout=5)
Loading