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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
support target id list
cyhhao678063b1111f
diff --git a/.env.example b/.env.exampleindex 312c592de..e61c9901a 100644--- a/.env.example+++ b/.env.example@@ -1,12 +1,15 @@# IM Platform Selection-# Options: telegram, slack-IM_PLATFORM=telegram+# Options: slack,telegram+IM_PLATFORM=slack# ============== Telegram Configuration ==============TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here-# Optional: Target chat ID to send all Claude Code outputs-# If set, all outputs will be sent to this chat instead of the original chat+# Optional: Whitelist of allowed chat IDs (comma-separated)+# Examples:+# Empty or []: Only accept private messages (DMs)+# null or omit: Accept all chats+# [123456789,987654321]: Only accept messages from these chat IDsTELEGRAM_TARGET_CHAT_ID=# ============== Slack Configuration ==============@@ -19,13 +22,16 @@ SLACK_APP_TOKEN=xapp-your-slack-app-token# Optional: For webhook mode instead of Socket ModeSLACK_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.+# Optional: Whitelist of allowed channel IDs (comma-separated)+# Examples:+# Empty or []: Only accept direct messages (DMs)+# null or omit: Accept all channels+# [C1234567890,C0987654321]: Only accept messages from these channel IDsSLACK_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+# If true, bot only responds when @mentioned in channels. Default: false+SLACK_REQUIRE_MENTION=false# Claude ConfigurationCLAUDE_PERMISSION_MODE=bypassPermissionsdiff --git a/README.md b/README.mdindex 38b1d97ff..46187914f 100644--- a/README.md+++ b/README.md@@ -37,15 +37,20 @@ Set `IM_PLATFORM` in your `.env` file:### Telegram Configuration- `TELEGRAM_BOT_TOKEN` (required): Your Telegram bot token from @BotFather-- `TELEGRAM_TARGET_CHAT_ID` (optional): Specific chat ID to send all Claude Code outputs+- `TELEGRAM_TARGET_CHAT_ID` (optional): Whitelist of allowed chat IDs+ - Empty or `[]`: Only accept private messages (DMs)+ - `null` or omit: Accept all chats+ - `[123456789,987654321]`: Only accept messages from these chat IDs- Use `/start` command to get your chat ID- - If set, all outputs go to this chat regardless of where commands come from### Slack Configuration- `SLACK_BOT_TOKEN` (required): Your Slack bot token (starts with `xoxb-`)- `SLACK_APP_TOKEN` (required for Socket Mode): App-level token (starts with `xapp-`)-- `SLACK_TARGET_CHANNEL` (optional): Default channel for all outputs+- `SLACK_TARGET_CHANNEL` (optional): Whitelist of allowed channel IDs+ - Empty or `[]`: Only accept direct messages (DMs)+ - `null` or omit: Accept all channels+ - `[C1234567890,C0987654321]`: Only accept messages from these channel IDsFor detailed Slack setup instructions, see [docs/SLACK_SETUP.md](docs/SLACK_SETUP.md).diff --git a/config/settings.py b/config/settings.pyindex 95fcc6c86..a975fffc2 100644--- a/config/settings.py+++ b/config/settings.py@@ -1,7 +1,7 @@import osimport loggingfrom dataclasses import dataclass-from typing import Optional+from typing import Optional, List, Unionfrom modules.im.base import BaseIMConfiglogger = logging.getLogger(__name__)@@ -10,7 +10,7 @@ logger = logging.getLogger(__name__)@dataclassclass TelegramConfig(BaseIMConfig):bot_token: str- target_chat_id: Optional[int] = None # Target chat ID to send all messages+ target_chat_id: Optional[Union[List[int], str]] = None # Whitelist of chat IDs. Empty list = DM only, null/None = accept all@classmethoddef from_env(cls) -> 'TelegramConfig':@@ -21,7 +21,23 @@ class TelegramConfig(BaseIMConfig):target_chat_id = Nonetarget_chat_id_str = os.getenv("TELEGRAM_TARGET_CHAT_ID")if target_chat_id_str:- target_chat_id = int(target_chat_id_str)+ # Handle null string+ if target_chat_id_str.lower() in ['null', 'none']:+ target_chat_id = None+ # Handle empty list+ elif target_chat_id_str.strip() in ['[]', '']:+ target_chat_id = []+ # Handle comma-separated list+ else:+ try:+ # Remove brackets if present and split by comma+ ids_str = target_chat_id_str.strip('[]')+ if ids_str:+ target_chat_id = [int(id.strip()) for id in ids_str.split(',')]+ else:+ target_chat_id = []+ except ValueError:+ raise ValueError(f"Invalid TELEGRAM_TARGET_CHAT_ID format: {target_chat_id_str}")return cls(bot_token=bot_token, target_chat_id=target_chat_id)@@ -57,7 +73,7 @@ class SlackConfig(BaseIMConfig):bot_token: strapp_token: Optional[str] = None # For Socket Modesigning_secret: Optional[str] = None # For webhook mode- target_channel: Optional[str] = None # If set, only respond in this channel+ target_channel: Optional[Union[List[str], str]] = None # Whitelist of channel IDs. Empty list = DM only, null/None = accept allrequire_mention: bool = True # Require @mention in channels (ignored in DMs)@classmethod@@ -70,7 +86,7 @@ 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") or None, # Convert empty string to None+ target_channel=cls._parse_channel_list(os.getenv("SLACK_TARGET_CHANNEL")),require_mention=os.getenv("SLACK_REQUIRE_MENTION", "true").lower() == "true")@@ -83,6 +99,28 @@ class SlackConfig(BaseIMConfig):if self.app_token and not self.app_token.startswith('xapp-'):raise ValueError("Invalid Slack app token format (should start with xapp-)")return True++ @classmethod+ def _parse_channel_list(cls, value: Optional[str]) -> Optional[Union[List[str], str]]:+ """Parse channel list from environment variable"""+ if not value:+ return None++ # Handle null string+ if value.lower() in ['null', 'none']:+ return None++ # Handle empty list+ if value.strip() in ['[]', '']:+ return []++ # Handle comma-separated list+ # Remove brackets if present and split by comma+ ids_str = value.strip('[]')+ if ids_str:+ return [id.strip() for id in ids_str.split(',')]+ else:+ return []@dataclassdiff --git a/core/controller.py b/core/controller.pyindex e4748fe28..eefb46a6b 100644--- a/core/controller.py+++ b/core/controller.py@@ -53,8 +53,17 @@ class Controller:platform_name = self.config.platform.capitalize()# Get user and channel info- user_info = await self.im_client.get_user_info(context.user_id)- channel_info = await self.im_client.get_channel_info(context.channel_id)+ try:+ user_info = await self.im_client.get_user_info(context.user_id)+ except Exception as e:+ logger.warning(f"Failed to get user info: {e}")+ user_info = {'id': context.user_id}++ try:+ channel_info = await self.im_client.get_channel_info(context.channel_id)+ except Exception as e:+ logger.warning(f"Failed to get channel info: {e}")+ channel_info = {'id': context.channel_id, 'name': 'Direct Message' if context.channel_id.startswith('D') else context.channel_id}# For non-Slack platforms, use traditional text messageif self.config.platform != "slack":@@ -283,11 +292,17 @@ Choose a command below or type any message to add it to the processing queue."""platform_specific=context.platform_specific)- # Override channel_id if target is configured- if self.config.platform == "telegram" and self.config.telegram and self.config.telegram.target_chat_id:- target_context.channel_id = str(self.config.telegram.target_chat_id)- elif self.config.platform == "slack" and self.config.slack and self.config.slack.target_channel:- target_context.channel_id = self.config.slack.target_channel+ # Override channel_id if target is configured (only for single target scenarios)+ if self.config.platform == "telegram" and self.config.telegram:+ target_chat_id = self.config.telegram.target_chat_id+ # Only override if it's a single ID (not a list)+ if target_chat_id and not isinstance(target_chat_id, list):+ target_context.channel_id = str(target_chat_id)+ elif self.config.platform == "slack" and self.config.slack:+ target_channel = self.config.slack.target_channel+ # Only override if it's a single ID (not a list)+ if target_channel and not isinstance(target_channel, list):+ target_context.channel_id = target_channelreturn target_contextdiff --git a/docs/SLACK_SETUP.md b/docs/SLACK_SETUP.mdindex 48ba77f9d..cf792cf10 100644--- a/docs/SLACK_SETUP.md+++ b/docs/SLACK_SETUP.md@@ -20,7 +20,9 @@ This guide will walk you through setting up a Slack bot for the Claude Code Remo1. In your app's settings, navigate to **"OAuth & Permissions"** in the sidebar2. Scroll down to **"Scopes"** → **"Bot Token Scopes"**-3. Add the following OAuth scopes:+3. Add ALL the following OAuth scopes to avoid permission issues:++### Essential Scopes (Required)- `channels:history` - View messages in public channels- `channels:read` - View basic information about public channels- `chat:write` - Send messages as bot@@ -28,7 +30,39 @@ This guide will walk you through setting up a Slack bot for the Claude Code Remo- `im:read` - View basic information about direct messages- `im:write` - Send direct messages- `app_mentions:read` - View messages that mention your bot- - `users:read` - View basic information about users (required for welcome messages)+ - `users:read` - View basic information about users+ - `commands` - Use slash commands (automatically added)++### Private Channel Support+ - `groups:read` - View basic information about private channels+ - `groups:history` - View messages in private channels+ - `groups:write` - Send messages to private channels++### Multi-Party DM Support+ - `mpim:read` - View basic information about group DMs+ - `mpim:history` - View messages in group DMs+ - `mpim:write` - Send messages to group DMs++### Enhanced Features+ - `chat:write.public` - Send messages to channels without joining+ - `chat:write.customize` - Send messages with custom username and avatar+ - `files:read` - View files shared in channels (for future file handling)+ - `files:write` - Upload files (for future file upload support)+ - `reactions:read` - View emoji reactions+ - `reactions:write` - Add emoji reactions+ - `users:read.email` - View email addresses (for enhanced user info)+ - `team:read` - View team/workspace information++**Note**: It's better to add all permissions now to avoid reinstalling the app multiple times later. Unused permissions won't affect the bot's performance.++### Quick Permission Checklist+To ensure full functionality, make sure you've added:+- ✅ All Essential Scopes (9 scopes)+- ✅ All Private Channel scopes (3 scopes)+- ✅ All Multi-Party DM scopes (3 scopes)+- ✅ Any Enhanced Features you want (up to 8 additional scopes)++**Total recommended scopes: ~23 scopes** for full functionality without future permission issues.## Step 3: Install App to Workspace@@ -55,12 +89,26 @@ Socket Mode allows your bot to connect without exposing a public URL.1. Go to **"Event Subscriptions"** in the sidebar2. Toggle **"Enable Events"** to On-3. Under **"Subscribe to bot events"**, add:+3. Under **"Subscribe to bot events"**, add ALL these events:++### Message Events- `message.channels` - Messages in public channels+ - `message.groups` - Messages in private channels- `message.im` - Direct messages+ - `message.mpim` - Messages in group DMs- `app_mention` - When someone mentions your bot++### Additional Events (Optional but Recommended)+ - `member_joined_channel` - When bot joins a channel+ - `member_left_channel` - When bot leaves a channel+ - `channel_created` - When a new channel is created+ - `channel_renamed` - When a channel is renamed+ - `team_join` - When a new member joins the workspace+4. Click **"Save Changes"**+**Note**: Adding all events now prevents the need to reconfigure later when expanding bot functionality.+## Step 6: Configure Native Slash Commands (Recommended)Native Slack slash commands provide the best user experience with autocomplete and help text. Here's a detailed step-by-step guide:@@ -312,8 +360,8 @@ IM_PLATFORM=slackSLACK_BOT_TOKEN=xoxb-your-bot-token-hereSLACK_APP_TOKEN=xapp-your-app-token-here-# Optional: Default channel for all outputs-SLACK_TARGET_CHANNEL=C1234567890+# Optional: Whitelist of allowed channel IDs (empty = DM only, null = all channels)+SLACK_TARGET_CHANNEL=[C1234567890,C0987654321]```### Finding Channel IDs@@ -405,10 +453,28 @@ The Slack bot automatically uses threads to organize conversations:3. Check logs for any error messages### Permission errors-1. Ensure all required scopes are added-2. Reinstall the app to workspace after adding scopes+1. Ensure all required scopes are added (including `groups:read` for private channels)+2. **Important**: After adding new scopes, you MUST reinstall the app to workspace:+ - Go to **"OAuth & Permissions"** page+ - Click **"Reinstall to Workspace"** button at the top+ - Review and approve the new permissions3. Verify tokens are correctly set in `.env`+### Private Channel Access Issues+If you see `missing_scope` errors with `groups:read`:+1. Add ALL private channel scopes: `groups:read`, `groups:history`, `groups:write`+2. Click **"Reinstall to Workspace"** (this is mandatory!)+3. Copy the new Bot Token and update your `.env` file+4. Restart the bot+5. Ensure bot is invited to the private channel: `/invite @YourBotName`++### Thread Reply Issues+If you see `cannot_reply_to_message` error:+1. This usually means the bot is trying to reply to a message that doesn't exist or in wrong context+2. Ensure the bot has `channels:history` or `groups:history` permission for the channel type+3. Check that the message timestamp (thread_ts) is valid+4. Verify the bot is a member of the channel where it's trying to reply+### Socket Mode issues1. Ensure `SLACK_APP_TOKEN` is set correctly2. Check that the app-level token has `connections:write` scopediff --git a/modules/im/slack.py b/modules/im/slack.pyindex 17a1ef235..eb9f13428 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -253,6 +253,11 @@ class SlackBot(BaseIMClient):logger.info(f"Skipping message event with bot mention: '{text}'")return+ # Check if channel is authorized based on whitelist+ if not await self._is_authorized_channel(channel_id):+ logger.info(f"Ignoring message from unauthorized channel: {channel_id}")+ 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}'")@@ -289,12 +294,10 @@ class SlackBot(BaseIMClient):# Handle @mentionschannel_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+ # Check if channel is authorized based on whitelist+ if not await self._is_authorized_channel(channel_id):+ logger.info(f"Ignoring mention from unauthorized channel: {channel_id}")+ returncontext = MessageContext(user_id=event.get("user"),@@ -338,6 +341,16 @@ class SlackBot(BaseIMClient):async def _handle_slash_command(self, payload: Dict[str, Any]):"""Handle native Slack slash commands"""command = payload.get("command", "").lstrip("/")+ channel_id = payload.get("channel_id")++ # Check if channel is authorized based on whitelist+ if not await self._is_authorized_channel(channel_id):+ logger.info(f"Ignoring slash command from unauthorized channel: {channel_id}")+ # Send a response to user about unauthorized channel+ response_url = payload.get("response_url")+ if response_url:+ await self.send_slash_response(response_url, "❌ This channel is not authorized to use bot commands.")+ return# Map Slack slash commands to internal commandscommand_mapping = {@@ -698,4 +711,25 @@ class SlackBot(BaseIMClient):return Trueexcept Exception as e:logger.error(f"Error sending slash command response: {e}")- return False\ No newline at end of file+ return False++ async def _is_authorized_channel(self, channel_id: str) -> bool:+ """Check if a channel is authorized based on whitelist configuration"""+ target_channel = self.config.target_channel++ # If None/null, accept all channels+ if target_channel is None:+ return True++ # If empty list, only accept DMs+ if isinstance(target_channel, list) and len(target_channel) == 0:+ # In Slack, DMs start with 'D', group DMs with 'G'+ return channel_id.startswith(('D', 'G'))++ # If list with IDs, check whitelist+ if isinstance(target_channel, list):+ return channel_id in target_channel++ # Should not reach here, but handle gracefully+ logger.warning(f"Unexpected target_channel type: {type(target_channel)}")+ return True\ No newline at end of filediff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex dea2c1481..08fb30dde 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -22,10 +22,18 @@ class TelegramBot(BaseIMClient):async def handle_telegram_message(self, update: Update, tg_context: ContextTypes.DEFAULT_TYPE):"""Handle incoming text messages from Telegram"""+ chat_id = update.effective_chat.id+ chat_type = update.effective_chat.type++ # Check if message is authorized based on whitelist+ if not self._is_authorized_chat(chat_id, chat_type):+ # Silently ignore unauthorized messages+ return+# Create MessageContextcontext = MessageContext(user_id=str(update.effective_user.id),- channel_id=str(update.effective_chat.id),+ channel_id=str(chat_id),message_id=str(update.message.message_id),platform_specific={'update': update, 'tg_context': tg_context})@@ -65,6 +73,14 @@ class TelegramBot(BaseIMClient):"""Wrap a command handler to convert Update to MessageContext"""if command_name not in self.on_command_callbacks:return++ chat_id = update.effective_chat.id+ chat_type = update.effective_chat.type++ # Check if command is authorized based on whitelist+ if not self._is_authorized_chat(chat_id, chat_type):+ # Silently ignore unauthorized commands+ return# Extract argsmessage_text = update.message.text@@ -399,4 +415,24 @@ class TelegramBot(BaseIMClient):"""# Telegram uses standard markdown with double asterisks for bold# Just return the text as-is since it's already in the right format- return text\ No newline at end of file+ return text++ def _is_authorized_chat(self, chat_id: int, chat_type: str) -> bool:+ """Check if a chat is authorized based on whitelist configuration"""+ target_chat_id = self.config.target_chat_id++ # If None/null, accept all chats+ if target_chat_id is None:+ return True++ # If empty list, only accept private chats (DMs)+ if isinstance(target_chat_id, list) and len(target_chat_id) == 0:+ return chat_type == 'private'++ # If list with IDs, check whitelist+ if isinstance(target_chat_id, list):+ return chat_id in target_chat_id++ # Should not reach here, but handle gracefully+ logger.warning(f"Unexpected target_chat_id type: {type(target_chat_id)}")+ return True\ No newline at end of file