Skip to content

Commit 12721f8

Browse files
konardclaude
andcommitted
Implement VK User Bot friend request auto-acceptance
- Extended UserBot class with friend request handling methods - Added background monitoring thread with configurable intervals - Integrated friend request monitoring into main bot startup - Added comprehensive error handling for VK API responses - Created test script for functionality verification - Updated documentation with setup and usage instructions - Added configuration options for enabling/disabling feature Resolves #93 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent eab83b5 commit 12721f8

File tree

5 files changed

+241
-1
lines changed

5 files changed

+241
-1
lines changed

python/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,38 @@
162162

163163
Если нужного языка нет в списке, о его добавлении можно попросить [здесь](https://github.com/linksplatform/Bot/issues/15)
164164

165+
## Friend Request Auto-Acceptance
166+
167+
Бот автоматически принимает заявки в друзья при наличии пользовательского токена (`USER_TOKEN`). Эта функция работает в фоновом режиме и проверяет новые заявки в друзья каждые 30 секунд по умолчанию.
168+
169+
### Настройка
170+
171+
1. Установите `USER_TOKEN` в файле `tokens.py` (см. раздел Configure ниже)
172+
2. Убедитесь что в `config.py` установлено `FRIEND_REQUEST_AUTO_ACCEPT = True` (по умолчанию включено)
173+
3. При необходимости измените `FRIEND_REQUEST_CHECK_INTERVAL` в `config.py` для изменения интервала проверки
174+
175+
### Тестирование
176+
177+
Для тестирования функциональности выполните:
178+
```bash
179+
cd python
180+
python3 test_friend_requests.py
181+
```
182+
183+
Эта команда проверит:
184+
- Настройку пользовательского токена
185+
- Получение списка заявок в друзья
186+
- Автоматическое принятие заявок
187+
- Работу мониторинга в фоновом режиме
188+
189+
### Логи
190+
191+
При запуске бота будут выводиться сообщения о:
192+
- Запуске мониторинга заявок в друзья
193+
- Количестве найденных заявок
194+
- Успешном принятии заявок
195+
- Ошибках при работе с API VK
196+
165197
## Prerequisites
166198
* [Git](https://git-scm.com/downloads)
167199
* [Python 3](https://www.python.org/downloads)

python/__main__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,4 +201,12 @@ def get_messages(
201201

202202
if __name__ == '__main__':
203203
vk = Bot(token=BOT_TOKEN, group_id=config.BOT_GROUP_ID, debug=True)
204+
205+
# Start friend request monitoring if enabled and USER_TOKEN is available
206+
if config.FRIEND_REQUEST_AUTO_ACCEPT:
207+
print("Starting VK Bot with friend request auto-acceptance")
208+
vk.userbot.start_friend_request_monitor(check_interval=config.FRIEND_REQUEST_CHECK_INTERVAL)
209+
else:
210+
print("Friend request auto-acceptance is disabled")
211+
204212
vk.start_listen()

python/config.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,5 +153,9 @@
153153
GITHUB_COPILOT_RUN_COMMAND = 'bash -c "./copilot.sh {input_file} {output_file}"'
154154
GITHUB_COPILOT_TIMEOUT = 120 # seconds
155155

156+
# Friend request auto-acceptance settings
157+
FRIEND_REQUEST_AUTO_ACCEPT = True # Enable/disable automatic friend request acceptance
158+
FRIEND_REQUEST_CHECK_INTERVAL = 30 # Check interval in seconds (default: 30)
159+
156160
DEFAULT_PROGRAMMING_LANGUAGES_PATTERN_STRING = "|".join(DEFAULT_PROGRAMMING_LANGUAGES)
157161
GITHUB_COPILOT_LANGUAGES_PATTERN_STRING = "|".join([i for i in GITHUB_COPILOT_LANGUAGES.keys()])

python/test_friend_requests.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
"""Test script for friend request auto-acceptance functionality.
4+
"""
5+
6+
from userbot import UserBot
7+
from tokens import USER_TOKEN
8+
import time
9+
import sys
10+
11+
def main():
12+
"""Test the friend request functionality."""
13+
print("VK User Bot - Friend Request Test")
14+
print("=" * 40)
15+
16+
# Check if USER_TOKEN is configured
17+
if not USER_TOKEN:
18+
print("ERROR: USER_TOKEN is not set in tokens.py")
19+
print("Please configure your VK user token to test friend request functionality.")
20+
print("You can get a user token from:")
21+
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")
22+
sys.exit(1)
23+
24+
userbot = UserBot()
25+
26+
print("1. Testing friend request retrieval...")
27+
pending_requests = userbot.get_friend_requests()
28+
29+
if pending_requests is None:
30+
print("ERROR: Failed to retrieve friend requests (check token permissions)")
31+
return
32+
elif pending_requests == []:
33+
print("✓ No pending friend requests found")
34+
else:
35+
print(f"✓ Found {len(pending_requests)} pending friend request(s): {pending_requests}")
36+
37+
print("\n2. Testing manual check and accept...")
38+
userbot.check_and_accept_friend_requests()
39+
40+
print("\n3. Testing monitoring functionality...")
41+
print("Starting friend request monitor for 30 seconds (check interval: 10 seconds)")
42+
43+
userbot.start_friend_request_monitor(check_interval=10)
44+
45+
try:
46+
# Let it run for 30 seconds
47+
time.sleep(30)
48+
except KeyboardInterrupt:
49+
print("\nInterrupted by user")
50+
51+
print("\nStopping friend request monitor...")
52+
userbot.stop_friend_request_monitor()
53+
54+
print("\n✓ Test completed successfully!")
55+
print("\nTo enable friend request auto-acceptance in the main bot:")
56+
print("1. Set USER_TOKEN in tokens.py")
57+
print("2. Set FRIEND_REQUEST_AUTO_ACCEPT = True in config.py")
58+
print("3. Run the bot with: python3 __main__.py")
59+
60+
if __name__ == '__main__':
61+
main()

python/userbot.py

Lines changed: 136 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,24 @@
22
"""Provides working with VK API as user.
33
"""
44
from typing import NoReturn, List, Dict, Any
5+
import time
6+
import threading
57

68
from exceptions import TooManyMessagesError
79
from tokens import USER_TOKEN
810
from requests import Session
911

1012

1113
class UserBot:
12-
"""Automatically deleting unnecessary messages.
14+
"""Automatically deleting unnecessary messages and handling friend requests.
1315
"""
1416
session = Session()
1517
url = 'https://api.vk.com/method/'
1618
token = USER_TOKEN
19+
20+
def __init__(self):
21+
self._friend_request_checker_active = False
22+
self._friend_request_thread = None
1723

1824
@staticmethod
1925
def delete_messages(
@@ -50,3 +56,132 @@ def execute(data: str) -> Dict[str, Any]:
5056
"""Executes VK Script.
5157
"""
5258
return UserBot.session.post(UserBot.url + 'execute', data=data).json()
59+
60+
@classmethod
61+
def call_method(cls, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
62+
"""Make VK API call with user token.
63+
"""
64+
params['access_token'] = cls.token
65+
params['v'] = '5.131'
66+
response = cls.session.post(cls.url + method, data=params)
67+
return response.json()
68+
69+
def get_friend_requests(self) -> List[int]:
70+
"""Get list of pending friend request user IDs.
71+
"""
72+
if not self.token:
73+
print("Warning: USER_TOKEN not set, cannot check friend requests")
74+
return []
75+
76+
response = self.call_method('friends.getRequests', {
77+
'out': 0, # incoming requests
78+
'count': 1000
79+
})
80+
81+
if 'error' in response:
82+
print(f"Error getting friend requests: {response['error']}")
83+
return []
84+
85+
if 'response' not in response:
86+
return []
87+
88+
return response['response'].get('items', [])
89+
90+
def accept_friend_request(self, user_id: int) -> bool:
91+
"""Accept a friend request from user_id.
92+
93+
Returns:
94+
bool: True if successfully accepted, False otherwise
95+
"""
96+
if not self.token:
97+
print("Warning: USER_TOKEN not set, cannot accept friend requests")
98+
return False
99+
100+
response = self.call_method('friends.add', {'user_id': user_id})
101+
102+
if 'error' in response:
103+
error_code = response['error'].get('error_code', 0)
104+
if error_code == 174:
105+
print(f"Cannot add yourself as friend (user {user_id})")
106+
elif error_code == 175:
107+
print(f"User {user_id} has blocked you")
108+
elif error_code == 176:
109+
print(f"You have blocked user {user_id}")
110+
elif error_code == 177:
111+
print(f"User {user_id} not found")
112+
elif error_code == 242:
113+
print(f"Too many friends, cannot add user {user_id}")
114+
else:
115+
print(f"Error accepting friend request from {user_id}: {response['error']}")
116+
return False
117+
118+
if 'response' in response:
119+
response_code = response['response']
120+
if response_code == 2:
121+
print(f"Successfully accepted friend request from user {user_id}")
122+
return True
123+
elif response_code == 1:
124+
print(f"Friend request sent to user {user_id} (was not pending)")
125+
return True
126+
elif response_code == 4:
127+
print(f"Request resent to user {user_id}")
128+
return True
129+
130+
return False
131+
132+
def check_and_accept_friend_requests(self):
133+
"""Check for pending friend requests and accept them automatically.
134+
"""
135+
try:
136+
pending_requests = self.get_friend_requests()
137+
138+
if pending_requests:
139+
print(f"Found {len(pending_requests)} pending friend request(s)")
140+
141+
for user_id in pending_requests:
142+
print(f"Accepting friend request from user {user_id}")
143+
success = self.accept_friend_request(user_id)
144+
145+
if success:
146+
# Small delay between requests to avoid rate limits
147+
time.sleep(1)
148+
149+
elif pending_requests == []:
150+
pass # No pending requests, no output needed
151+
152+
except Exception as e:
153+
print(f"Error checking friend requests: {e}")
154+
155+
def start_friend_request_monitor(self, check_interval: int = 60):
156+
"""Start monitoring for friend requests in a background thread.
157+
158+
Args:
159+
check_interval: Time in seconds between checks (default: 60)
160+
"""
161+
if not self.token:
162+
print("Warning: USER_TOKEN not set, cannot start friend request monitoring")
163+
return
164+
165+
if self._friend_request_checker_active:
166+
print("Friend request monitor is already running")
167+
return
168+
169+
print(f"Starting friend request monitor (checking every {check_interval} seconds)")
170+
self._friend_request_checker_active = True
171+
172+
def monitor_loop():
173+
while self._friend_request_checker_active:
174+
self.check_and_accept_friend_requests()
175+
time.sleep(check_interval)
176+
177+
self._friend_request_thread = threading.Thread(target=monitor_loop, daemon=True)
178+
self._friend_request_thread.start()
179+
180+
def stop_friend_request_monitor(self):
181+
"""Stop the friend request monitoring thread.
182+
"""
183+
if self._friend_request_checker_active:
184+
print("Stopping friend request monitor")
185+
self._friend_request_checker_active = False
186+
if self._friend_request_thread:
187+
self._friend_request_thread.join(timeout=5)

0 commit comments

Comments
 (0)