From eab83b52bd5b7fccd1b96818206650b7e4df4579 Mon Sep 17 00:00:00 2001 From: konard Date: Sat, 13 Sep 2025 13:39:52 +0300 Subject: [PATCH 1/3] Initial commit with task details for issue #93 Adding CLAUDE.md with task information for AI processing. This file will be removed when the task is complete. Issue: https://github.com/linksplatform/Bot/issues/93 --- CLAUDE.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..5bf40091 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,5 @@ +Issue to solve: https://github.com/linksplatform/Bot/issues/93 +Your prepared branch: issue-93-0407119a +Your prepared working directory: /tmp/gh-issue-solver-1757759988253 + +Proceed. \ No newline at end of file From 12721f8a6291289757c69d700ca7fda4492c8ab1 Mon Sep 17 00:00:00 2001 From: konard Date: Sat, 13 Sep 2025 13:47:00 +0300 Subject: [PATCH 2/3] Implement VK User Bot friend request auto-acceptance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- python/README.md | 32 ++++++++ python/__main__.py | 8 ++ python/config.py | 4 + python/test_friend_requests.py | 61 +++++++++++++++ python/userbot.py | 137 ++++++++++++++++++++++++++++++++- 5 files changed, 241 insertions(+), 1 deletion(-) create mode 100755 python/test_friend_requests.py diff --git a/python/README.md b/python/README.md index a50c2d69..2090c82d 100644 --- a/python/README.md +++ b/python/README.md @@ -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) diff --git a/python/__main__.py b/python/__main__.py index cdcbf7f6..18fdf2e1 100644 --- a/python/__main__.py +++ b/python/__main__.py @@ -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() diff --git a/python/config.py b/python/config.py index 1613aec9..5d81ed85 100644 --- a/python/config.py +++ b/python/config.py @@ -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()]) diff --git a/python/test_friend_requests.py b/python/test_friend_requests.py new file mode 100755 index 00000000..3c864cc0 --- /dev/null +++ b/python/test_friend_requests.py @@ -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() \ No newline at end of file diff --git a/python/userbot.py b/python/userbot.py index 74f7bd5d..733b296d 100644 --- a/python/userbot.py +++ b/python/userbot.py @@ -2,6 +2,8 @@ """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 @@ -9,11 +11,15 @@ 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( @@ -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) From ffdad617da5583b966ad15869441459600f821c5 Mon Sep 17 00:00:00 2001 From: konard Date: Sat, 13 Sep 2025 13:48:02 +0300 Subject: [PATCH 3/3] Remove CLAUDE.md - Claude command completed --- CLAUDE.md | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 5bf40091..00000000 --- a/CLAUDE.md +++ /dev/null @@ -1,5 +0,0 @@ -Issue to solve: https://github.com/linksplatform/Bot/issues/93 -Your prepared branch: issue-93-0407119a -Your prepared working directory: /tmp/gh-issue-solver-1757759988253 - -Proceed. \ No newline at end of file