55 lines
1.8 KiB
Python
55 lines
1.8 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from slack_sdk.errors import SlackApiError
|
||
|
|
from slack_sdk.web.async_client import AsyncWebClient
|
||
|
|
|
||
|
|
from yuxi.channels.adapters.slack.dm_cache import DmChannelCache
|
||
|
|
from yuxi.utils.logging_config import logger
|
||
|
|
|
||
|
|
|
||
|
|
async def resolve_channel_id(
|
||
|
|
client: AsyncWebClient,
|
||
|
|
target: str,
|
||
|
|
dm_cache: DmChannelCache | None = None,
|
||
|
|
) -> str | None:
|
||
|
|
if target.startswith("C") or target.startswith("G") or target.startswith("D"):
|
||
|
|
return target
|
||
|
|
|
||
|
|
if target.startswith("U"):
|
||
|
|
if dm_cache:
|
||
|
|
cached = dm_cache.get(target)
|
||
|
|
if cached:
|
||
|
|
return cached
|
||
|
|
try:
|
||
|
|
result = await client.conversations_open(users=[target])
|
||
|
|
if not result.get("ok"):
|
||
|
|
return None
|
||
|
|
channel_id = result.get("channel", {}).get("id", "")
|
||
|
|
if channel_id and dm_cache:
|
||
|
|
dm_cache.put(target, channel_id)
|
||
|
|
return channel_id
|
||
|
|
except SlackApiError as e:
|
||
|
|
logger.warning(f"Failed to resolve DM channel for user {target}: {e}")
|
||
|
|
return None
|
||
|
|
|
||
|
|
try:
|
||
|
|
result = await client.users_lookupByEmail(email=target)
|
||
|
|
if result.get("ok"):
|
||
|
|
user = result.get("user", {})
|
||
|
|
user_id = user.get("id", "")
|
||
|
|
if user_id:
|
||
|
|
if dm_cache:
|
||
|
|
cached = dm_cache.get(user_id)
|
||
|
|
if cached:
|
||
|
|
return cached
|
||
|
|
conv_result = await client.conversations_open(users=[user_id])
|
||
|
|
if conv_result.get("ok"):
|
||
|
|
channel_id = conv_result.get("channel", {}).get("id", "")
|
||
|
|
if channel_id and dm_cache:
|
||
|
|
dm_cache.put(user_id, channel_id)
|
||
|
|
return channel_id
|
||
|
|
except SlackApiError:
|
||
|
|
pass
|
||
|
|
|
||
|
|
return None
|