Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat: Enhanced Slack configuration and settings persistence

cyhhao7c55035b4777
diff --git a/.env.example b/.env.example
index 2a69a41f6..312c592de 100644
--- a/.env.example
+++ b/.env.example
@@ -20,8 +20,13 @@ SLACK_APP_TOKEN=xapp-your-slack-app-token
SLACK_SIGNING_SECRET=your-signing-secret
# Optional: Default channel for outputs
+# If empty, bot will respond in any channel. If set, bot only responds in this channel.
SLACK_TARGET_CHANNEL=
+# Optional: Require @mention in channels (ignored in DMs)
+# If true, bot only responds when @mentioned in channels. Default: true
+SLACK_REQUIRE_MENTION=true
+
# Claude Configuration
CLAUDE_PERMISSION_MODE=bypassPermissions
CLAUDE_CWD=./_tmp
diff --git a/config/settings.py b/config/settings.py
index fbe7af886..95fcc6c86 100644
--- a/config/settings.py
+++ b/config/settings.py
@@ -57,7 +57,8 @@ class SlackConfig(BaseIMConfig):
bot_token: str
app_token: Optional[str] = None # For Socket Mode
signing_secret: Optional[str] = None # For webhook mode
- target_channel: Optional[str] = None # Default channel for outputs
+ target_channel: Optional[str] = None # If set, only respond in this channel
+ require_mention: bool = True # Require @mention in channels (ignored in DMs)
@classmethod
def from_env(cls) -> 'SlackConfig':
@@ -69,7 +70,8 @@ class SlackConfig(BaseIMConfig):
bot_token=bot_token,
app_token=os.getenv("SLACK_APP_TOKEN"),
signing_secret=os.getenv("SLACK_SIGNING_SECRET"),
- target_channel=os.getenv("SLACK_TARGET_CHANNEL")
+ target_channel=os.getenv("SLACK_TARGET_CHANNEL") or None, # Convert empty string to None
+ require_mention=os.getenv("SLACK_REQUIRE_MENTION", "true").lower() == "true"
)
def validate(self) -> bool:
diff --git a/core/controller.py b/core/controller.py
index 02540ea89..e4748fe28 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -1,7 +1,7 @@
import asyncio
import logging
import os
-from typing import Optional
+from typing import Optional, Union
from config.settings import AppConfig
from modules.im import BaseIMClient, MessageContext, InlineKeyboard, InlineButton, IMFactory
from modules.claude_client import ClaudeClient
@@ -199,7 +199,8 @@ Choose a command below or type any message to add it to the processing queue."""
thread_id = message_data.get('thread_id')
# Get user's CWD from settings if available
- custom_cwd = self.settings_manager.get_custom_cwd(context.user_id)
+ settings_key = self._get_settings_key(context)
+ custom_cwd = self.settings_manager.get_custom_cwd(settings_key)
if custom_cwd:
# Temporarily set the CWD for this execution
original_cwd = self.claude_client.options.cwd
@@ -208,8 +209,9 @@ Choose a command below or type any message to add it to the processing queue."""
# Execute with Claude
async def on_claude_message(claude_msg: str, message_type: str = None):
# Check if this message type should be hidden
- if message_type and self.settings_manager.is_message_type_hidden(context.user_id, message_type):
- logger.info(f"Skipping {message_type} message for user {context.user_id} (hidden in settings)")
+ settings_key = self._get_settings_key(context)
+ if message_type and self.settings_manager.is_message_type_hidden(settings_key, message_type):
+ logger.info(f"Skipping {message_type} message for settings key {settings_key} (hidden in settings)")
return
# Send Claude's formatted output
@@ -289,6 +291,20 @@ Choose a command below or type any message to add it to the processing queue."""
return target_context
+ def _get_settings_key(self, context: MessageContext) -> Union[str, int]:
+ """Get the appropriate settings key based on platform"""
+ if self.config.platform == "slack":
+ # For Slack, use channel_id as the key
+ return context.channel_id
+ else:
+ # For Telegram, use chat_id/channel_id (convert to int)
+ # Note: In Telegram, we use channel_id which is actually the chat_id
+ try:
+ return int(context.channel_id) if context.channel_id else context.channel_id
+ except (ValueError, TypeError):
+ # Fallback to user_id for backward compatibility
+ return int(context.user_id) if context.user_id else context.user_id
+
async def handle_execute(self, context: MessageContext, args: str = ""):
"""Handle manual execute command"""
target_context = self._get_target_context(context)
@@ -333,7 +349,8 @@ Choose a command below or type any message to add it to the processing queue."""
"""Handle cwd command - show current working directory"""
try:
# Check if user has custom CWD in settings
- custom_cwd = self.settings_manager.get_custom_cwd(context.user_id)
+ settings_key = self._get_settings_key(context)
+ custom_cwd = self.settings_manager.get_custom_cwd(settings_key)
current_cwd = custom_cwd if custom_cwd else self.claude_client.options.cwd
absolute_path = os.path.abspath(current_cwd)
@@ -387,7 +404,8 @@ Choose a command below or type any message to add it to the processing queue."""
return
# Save to user settings
- self.settings_manager.set_custom_cwd(context.user_id, absolute_path)
+ settings_key = self._get_settings_key(context)
+ self.settings_manager.set_custom_cwd(settings_key, absolute_path)
logger.info(f"User {context.user_id} changed cwd to: {absolute_path}")
@@ -434,7 +452,8 @@ Choose a command below or type any message to add it to the processing queue."""
async def _handle_settings_traditional(self, context: MessageContext):
"""Handle settings for non-Slack platforms (Telegram, etc)"""
# Get current settings
- user_settings = self.settings_manager.get_user_settings(context.user_id)
+ settings_key = self._get_settings_key(context)
+ user_settings = self.settings_manager.get_user_settings(settings_key)
# Get available message types and display names
message_types = self.settings_manager.get_available_message_types()
@@ -474,12 +493,13 @@ Choose a command below or type any message to add it to the processing queue."""
if trigger_id and hasattr(self.im_client, 'open_settings_modal'):
# We have trigger_id, open modal directly
- user_settings = self.settings_manager.get_user_settings(context.user_id)
+ settings_key = self._get_settings_key(context)
+ user_settings = self.settings_manager.get_user_settings(settings_key)
message_types = self.settings_manager.get_available_message_types()
display_names = self.settings_manager.get_message_type_display_names()
try:
- await self.im_client.open_settings_modal(trigger_id, user_settings, message_types, display_names)
+ await self.im_client.open_settings_modal(trigger_id, user_settings, message_types, display_names, context.channel_id)
except Exception as e:
logger.error(f"Error opening settings modal: {e}")
await self.im_client.send_message(context, "❌ Failed to open settings. Please try again.")
@@ -509,12 +529,13 @@ Choose a command below or type any message to add it to the processing queue."""
if callback_data == "open_settings_modal" and self.config.platform == "slack":
trigger_id = context.platform_specific.get('trigger_id') if context.platform_specific else None
if trigger_id and hasattr(self.im_client, 'open_settings_modal'):
- user_settings = self.settings_manager.get_user_settings(context.user_id)
+ settings_key = self._get_settings_key(context)
+ user_settings = self.settings_manager.get_user_settings(settings_key)
message_types = self.settings_manager.get_available_message_types()
display_names = self.settings_manager.get_message_type_display_names()
try:
- await self.im_client.open_settings_modal(trigger_id, user_settings, message_types, display_names)
+ await self.im_client.open_settings_modal(trigger_id, user_settings, message_types, display_names, context.channel_id)
except Exception as e:
logger.error(f"Error opening settings modal: {e}")
await self.im_client.send_message(context, "❌ Failed to open settings. Please try again.")
@@ -593,10 +614,11 @@ _Tip: All commands work in DMs, channels, and threads!_"""
elif callback_data.startswith("toggle_msg_"):
# Toggle message type visibility
msg_type = callback_data.replace("toggle_msg_", "")
- is_hidden = self.settings_manager.toggle_hidden_message_type(context.user_id, msg_type)
+ settings_key = self._get_settings_key(context)
+ is_hidden = self.settings_manager.toggle_hidden_message_type(settings_key, msg_type)
# Update the keyboard
- user_settings = self.settings_manager.get_user_settings(context.user_id)
+ user_settings = self.settings_manager.get_user_settings(settings_key)
message_types = self.settings_manager.get_available_message_types()
display_names = self.settings_manager.get_message_type_display_names()
@@ -660,19 +682,23 @@ _Tip: All commands work in DMs, channels, and threads!_"""
logger.error(f"Error handling callback query: {e}")
await self.im_client.send_message(context, f"Error: {str(e)}")
- async def handle_settings_update(self, user_id: str, hidden_message_types: list):
+ async def handle_settings_update(self, user_id: str, hidden_message_types: list, channel_id: str = None):
"""Handle settings update from modal submission (Slack)"""
try:
+ # For Slack, we need to use channel_id as the key
+ # The channel_id should be passed from the modal submission context
+ settings_key = channel_id if self.config.platform == "slack" and channel_id else user_id
+
# Get current settings
- user_settings = self.settings_manager.get_user_settings(user_id)
+ user_settings = self.settings_manager.get_user_settings(settings_key)
# Update hidden message types
user_settings.hidden_message_types = hidden_message_types
# Save settings
- self.settings_manager.save_user_settings(user_id, user_settings)
+ self.settings_manager.save_user_settings(settings_key, user_settings)
- logger.info(f"Updated settings for user {user_id}: hidden types = {hidden_message_types}")
+ logger.info(f"Updated settings for key {settings_key}: hidden types = {hidden_message_types}")
# Send confirmation message (if we have a way to reach the user)
# Note: In Slack modals, we don't have direct context to send messages
diff --git a/modules/im/slack.py b/modules/im/slack.py
index bde2ccc24..17a1ef235 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -236,6 +236,15 @@ class SlackBot(BaseIMClient):
if event.get("bot_id"):
return
+ channel_id = event.get("channel")
+
+ # Check if target_channel is configured and message is not in that channel
+ if self.config.target_channel and channel_id != self.config.target_channel:
+ # Check if this is a DM (starts with 'D')
+ if not channel_id.startswith('D'):
+ logger.info(f"Ignoring message from non-target channel: {channel_id}")
+ return
+
# Check if this message contains a bot mention
# If it does, skip processing as it will be handled by app_mention event
text = event.get("text", "")
@@ -244,10 +253,15 @@ class SlackBot(BaseIMClient):
logger.info(f"Skipping message event with bot mention: '{text}'")
return
+ # Check if we require mention in channels (not DMs)
+ if self.config.require_mention and not channel_id.startswith('D'):
+ logger.info(f"Ignoring non-mention message in channel: '{text}'")
+ return
+
# Extract context
context = MessageContext(
user_id=event.get("user"),
- channel_id=event.get("channel"),
+ channel_id=channel_id,
thread_id=event.get("thread_ts"),
message_id=event.get("ts"),
platform_specific={
@@ -256,7 +270,7 @@ class SlackBot(BaseIMClient):
}
)
- # Handle slash commands in regular messages (only in DMs or direct messages)
+ # Handle slash commands in regular messages
if text.startswith("/"):
parts = text.split(maxsplit=1)
command = parts[0][1:] # Remove the /
@@ -273,9 +287,18 @@ class SlackBot(BaseIMClient):
elif event_type == "app_mention":
# Handle @mentions
+ channel_id = event.get("channel")
+
+ # Check if target_channel is configured and mention is not in that channel
+ if self.config.target_channel and channel_id != self.config.target_channel:
+ # Check if this is a DM (starts with 'D')
+ if not channel_id.startswith('D'):
+ logger.info(f"Ignoring mention from non-target channel: {channel_id}")
+ return
+
context = MessageContext(
user_id=event.get("user"),
- channel_id=event.get("channel"),
+ channel_id=channel_id,
thread_id=event.get("thread_ts"),
message_id=event.get("ts"),
platform_specific={
@@ -416,9 +439,12 @@ class SlackBot(BaseIMClient):
# Get the values from selected options
hidden_types = [opt.get("value") for opt in selected_options]
+ # Get channel_id from the view's private_metadata if available
+ channel_id = view.get("private_metadata")
+
# Update settings - need access to settings manager
if hasattr(self, '_on_settings_update'):
- await self._on_settings_update(user_id, hidden_types)
+ await self._on_settings_update(user_id, hidden_types, channel_id)
# Send success message to the user (via DM or channel)
# We need to find the right channel to send the message
@@ -499,7 +525,7 @@ class SlackBot(BaseIMClient):
return formatted
- async def open_settings_modal(self, trigger_id: str, user_settings: Any, message_types: list, display_names: dict):
+ async def open_settings_modal(self, trigger_id: str, user_settings: Any, message_types: list, display_names: dict, channel_id: str = None):
"""Open a modal dialog for settings"""
self._ensure_clients()
@@ -556,6 +582,7 @@ class SlackBot(BaseIMClient):
view = {
"type": "modal",
"callback_id": "settings_modal",
+ "private_metadata": channel_id or "", # Store channel_id for later use
"title": {
"type": "plain_text",
"text": "Settings",
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index c62602a7a..bd6b99ee0 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -92,22 +92,26 @@ class SettingsManager:
self.update_user_settings(user_id, settings)
return is_hidden
- def set_custom_cwd(self, user_id: int, cwd: str):
+ def set_custom_cwd(self, user_id: Union[int, str], cwd: str):
"""Set custom working directory for user"""
settings = self.get_user_settings(user_id)
settings.custom_cwd = cwd
self.update_user_settings(user_id, settings)
- def get_custom_cwd(self, user_id: int) -> Optional[str]:
+ def get_custom_cwd(self, user_id: Union[int, str]) -> Optional[str]:
"""Get custom working directory for user"""
settings = self.get_user_settings(user_id)
return settings.custom_cwd
- def is_message_type_hidden(self, user_id: int, message_type: str) -> bool:
+ def is_message_type_hidden(self, user_id: Union[int, str], message_type: str) -> bool:
"""Check if a message type is hidden for user"""
settings = self.get_user_settings(user_id)
return message_type in settings.hidden_message_types
+ def save_user_settings(self, user_id: Union[int, str], settings: UserSettings):
+ """Save settings for a specific user (alias for update_user_settings)"""
+ self.update_user_settings(user_id, settings)
+
def get_available_message_types(self) -> List[str]:
"""Get list of available message types that can be hidden"""
return [