get_user_messages
Fetch messages from a specific user in a Slack channel by providing the channel ID and username to retrieve their communication history.
Instructions
Fetch messages by a specific user (given by name) from a Slack channel.
Args:
channel_id: The Slack channel ID.
username: The Slack username or real name of the user.
limit: How many messages to check (optional).
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| channel_id | Yes | ||
| username | Yes | ||
| limit | No |
Implementation Reference
- main.py:98-143 (handler)The core handler function for the 'get_user_messages' tool, decorated with @mcp.tool() for registration. It resolves the user ID from the username by querying the users.list API, fetches recent messages from the specified channel using conversations.history, filters for the user's messages, formats them with timestamps and names using a helper function, and returns a concatenated string.async def get_user_messages(channel_id: str, username: str, limit: int = 10) -> str: """ Fetch messages by a specific user (given by name) from a Slack channel. Args: channel_id: The Slack channel ID. username: The Slack username or real name of the user. limit: How many messages to check (optional). """ # Step 1: Get user list users_data = await make_slack_request("users.list") if not users_data or not users_data.get("ok"): return "❌ Failed to fetch user list." # Step 2: Create a user_map and find the user ID user_map = {} user_id = None for user in users_data["members"]: uid = user.get("id") name = user.get("name") real_name = user.get("real_name") user_map[uid] = real_name or name or uid if name == username or real_name == username: user_id = uid if not user_id: return f"❌ No Slack user found with name '{username}'." # Step 3: Fetch channel messages params = {"channel": channel_id, "limit": limit} data = await make_slack_request("conversations.history", params) if not data or not data.get("ok"): return "❌ Unable to fetch messages." # Step 4: Filter messages by user_id user_msgs = [msg for msg in data.get("messages", []) if msg.get("user") == user_id] if not user_msgs: return f"No messages found from user '{username}' in the channel." # ✅ Step 5: Format messages with user_map return "\n---\n".join(format_slack_message(msg, user_map) for msg in user_msgs)
- main.py:34-40 (helper)Helper function used by get_user_messages to format individual Slack messages into a readable string including timestamp, user name (looked up from map), and message text.def format_slack_message(msg: dict, user_map: dict[str, str]) -> str: """Format Slack message into a readable string with user name.""" user_id = msg.get("user", "unknown user") user_name = user_map.get(user_id, user_id) # fallback to user ID if name not found text = msg.get("text", "") ts = msg.get("ts", "") return f"[{ts}] {user_name}: {text}"
- main.py:19-33 (helper)Shared helper function used by get_user_messages to make authenticated HTTP requests to the Slack API, handling errors and returning JSON response or None.async def make_slack_request(method: str, params: dict[str, Any] | None = None) -> dict[str, Any] | None: """Make a request to the Slack Web API with proper error handling.""" headers = { "Authorization": f"Bearer {SLACK_TOKEN}", "Content-Type": "application/x-www-form-urlencoded" } async with httpx.AsyncClient() as client: try: response = await client.post(f"{SLACK_API_BASE}/{method}", data=params, headers=headers, timeout=10.0) response.raise_for_status() return response.json() except Exception as e: print(f"Slack API error: {e}") return None