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
85 changes: 85 additions & 0 deletions python/MESSAGE_LOGGING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Message Logging Feature

This feature allows the bot to forward all messages from specified main chats to a dedicated logging chat for monitoring and archival purposes.

## Configuration

To enable message logging, edit `config.py` and configure the following variables:

### MAIN_CHATS
List of chat IDs from which messages should be forwarded to the logging chat.

```python
MAIN_CHATS = [
2000000001, # Example main chat ID
2000000011 # Another main chat ID
]
```

### LOGGING_CHAT_ID
The chat ID where all messages from main chats will be forwarded for logging.

```python
LOGGING_CHAT_ID = 2000000020 # Example logging chat ID
```

## How to Find Chat IDs

1. Go to the VK conversation you want to use
2. Look at the URL in your browser address bar
3. For group chats, the URL will look like: `https://vk.com/im?peers=c477`
4. The chat ID is `2000000000 + 477 = 2000000477`

## Message Format

Messages forwarded to the logging chat include:

- **Timestamp**: When the original message was sent
- **Chat title**: Name of the source chat
- **User name**: Who sent the message
- **Message content**: The actual message text
- **Attachments**: List of attachment types (if any)
- **Special indicators**: For forwarded messages and replies

Example logged message:
```
[2024-01-01 12:30:45] Development Chat
John Doe: Hello, how is everyone doing?
Attachments: [photo], [doc]
[Reply to message]
```

## Features

### What Gets Logged
- All text messages from configured main chats
- Information about attachments (type only, not content)
- Indication of forwarded messages
- Indication of replies to other messages
- User names and chat titles for context

### What Doesn't Get Logged
- Messages from non-main chats
- Bot messages (to avoid infinite loops)
- Messages when logging is disabled or misconfigured
- Actual attachment content (for privacy and performance)

### Error Handling
- If logging fails for any reason, an error is printed to console
- The bot continues to function normally even if logging fails
- Invalid configurations are silently ignored

## Security Considerations

- The logging chat should have restricted access
- Only trusted administrators should have access to logged messages
- Consider the privacy implications of logging all messages
- Ensure the logging chat is properly secured against unauthorized access

## Disabling Logging

To disable logging, set either:
- `LOGGING_CHAT_ID = None`
- `MAIN_CHATS = []`

The bot will automatically skip logging when these are not properly configured.
88 changes: 88 additions & 0 deletions python/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ def message_new(
from_id = event["from_id"]
msg_id = event["conversation_message_id"]

# Forward messages from main chats to logging chat
self._forward_message_to_logging_chat(event, peer_id, from_id)

if peer_id in self.messages_to_delete:
peer = CHAT_ID_OFFSET + config.USERBOT_CHATS[peer_id]
new_messages_to_delete = []
Expand Down Expand Up @@ -189,6 +192,91 @@ def get_user_name(
'users.get', dict(user_ids=uid, name_case=name_case)
)['response'][0]["first_name"]

def _forward_message_to_logging_chat(
self,
event: Dict[str, Any],
peer_id: int,
from_id: int
) -> NoReturn:
"""Forwards messages from main chats to logging chat.

:param event: message event data
:param peer_id: chat ID where the message was sent
:param from_id: user ID who sent the message
"""
# Check if logging is enabled and configured
if not config.LOGGING_CHAT_ID or not config.MAIN_CHATS:
return

# Only forward messages from specified main chats
if peer_id not in config.MAIN_CHATS:
return

# Don't forward our own messages to avoid loops
if from_id < 0: # Negative from_id means it's from a group/bot
return

try:
# Get user name for better logging format
user_name = self.get_user_name(from_id) if from_id > 0 else "Unknown"

# Format the original message with metadata
original_text = event.get("text", "")
chat_title = self._get_chat_title(peer_id)
timestamp = datetime.fromtimestamp(event.get("date", 0)).strftime("%Y-%m-%d %H:%M:%S")

# Create formatted log message
log_message = f"[{timestamp}] {chat_title}\n{user_name}: {original_text}"

# Handle attachments
attachments = event.get("attachments", [])
if attachments:
attachment_info = []
for attachment in attachments:
att_type = attachment.get("type", "unknown")
attachment_info.append(f"[{att_type}]")
if attachment_info:
log_message += f"\nAttachments: {', '.join(attachment_info)}"

# Handle forwarded messages
fwd_messages = event.get("fwd_messages", [])
if fwd_messages:
log_message += f"\n[Forwarded {len(fwd_messages)} message(s)]"

# Handle reply to message
reply_message = event.get("reply_message", {})
if reply_message:
log_message += "\n[Reply to message]"

# Send to logging chat
self.send_msg(log_message, config.LOGGING_CHAT_ID)

except Exception as e:
print(f"Error forwarding message to logging chat: {e}")

def _get_chat_title(self, peer_id: int) -> str:
"""Get chat title for better logging format.

:param peer_id: chat ID
:return: chat title or formatted chat ID
"""
try:
# For group chats (peer_id > 2000000000), try to get conversation info
if peer_id > 2000000000:
response = self.call_method(
'messages.getConversationsById',
{'peer_ids': peer_id}
)
if 'response' in response and 'items' in response['response']:
items = response['response']['items']
if items:
chat_settings = items[0].get('chat_settings', {})
title = chat_settings.get('title', f'Chat {peer_id}')
return title
return f'Chat {peer_id}'
except Exception:
return f'Chat {peer_id}'

@staticmethod
def get_messages(
event: Dict[str, Any]
Expand Down
10 changes: 10 additions & 0 deletions python/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@
2000000011
]

# Message logging configuration
# Main chats that should have their messages forwarded to logging chat
MAIN_CHATS = [
# 2000000001, # Add your main chat IDs here
# 2000000011
]

# Chat ID where all messages from main chats will be forwarded for logging
LOGGING_CHAT_ID = None # Set this to your logging chat ID (e.g., 2000000020)

POSITIVE_VOTES_PER_KARMA = 2
NEGATIVE_VOTES_PER_KARMA = 3

Expand Down
Loading
Loading