mirror of
https://github.com/open-webui/oikb.git
synced 2026-11-23 14:10:45 -05:00
fix: split messaging connectors by day for incremental sync (v0.1.2)
This commit is contained in:
1 parent
08a1bd1859
commit
2fd9319ca5
6 files changed
+163
-65
No files matched your search
@@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
## [0.1.2] - 2025-05-20
|
||||
|
||||
### Changed
|
||||
|
||||
- Messaging connectors (Slack, Discord, Teams) now split messages by day for truly incremental sync. Past days are immutable so their checksums never change.
|
||||
|
||||
## [0.1.1] - 2025-05-20
|
||||
|
||||
### Added
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "oikb"
|
||||
version = "0.1.1"
|
||||
description = "CLI tool for syncing content to Open WebUI Knowledge Bases"
|
||||
version = "0.1.2"
|
||||
description = "Sync anything to Open WebUI Knowledge Bases"
|
||||
readme = "README.md"
|
||||
authors = [
|
||||
{ name = "Tim Baek", email = "tim@openwebui.com" }
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""oikb — Open WebUI Knowledge Base CLI."""
|
||||
|
||||
__version__ = "0.1.1"
|
||||
__version__ = "0.1.2"
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Discord connector — sync channel messages to a Knowledge Base.
|
||||
|
||||
Auth via DISCORD_TOKEN env var (Bot token with Message Content intent).
|
||||
Messages are split by day for incremental sync.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
@@ -15,9 +18,9 @@ from oikb.connectors import BaseConnector, ManifestEntry
|
||||
|
||||
|
||||
class DiscordConnector(BaseConnector):
|
||||
"""Sync messages from a Discord channel."""
|
||||
"""Sync messages from a Discord channel, one file per day."""
|
||||
|
||||
def __init__(self, channel_id: str, token: str | None = None, limit: int = 1000):
|
||||
def __init__(self, channel_id: str, token: str | None = None, limit: int = 5000):
|
||||
self.channel_id = channel_id
|
||||
self.limit = limit
|
||||
self._token = token or os.environ.get("DISCORD_TOKEN")
|
||||
@@ -29,28 +32,51 @@ class DiscordConnector(BaseConnector):
|
||||
headers={"Authorization": f"Bot {self._token}"},
|
||||
timeout=30.0,
|
||||
)
|
||||
self._text: str = ""
|
||||
self._channel_name: str = ""
|
||||
self._daily_texts: dict[str, str] = {}
|
||||
|
||||
def build_manifest(self) -> list[ManifestEntry]:
|
||||
messages = self._fetch_messages()
|
||||
if not messages:
|
||||
return []
|
||||
|
||||
lines = []
|
||||
for msg in reversed(messages):
|
||||
author = msg.get("author", {}).get("username", "unknown")
|
||||
content = msg.get("content", "")
|
||||
ts = msg.get("timestamp", "")
|
||||
lines.append(f"[{ts}] {author}: {content}")
|
||||
|
||||
self._text = "\n".join(lines)
|
||||
checksum = hashlib.sha256(self._text.encode()).hexdigest()[:16]
|
||||
|
||||
# Get channel name.
|
||||
info = self._http.get(f"/channels/{self.channel_id}")
|
||||
name = info.json().get("name", self.channel_id) if info.status_code == 200 else self.channel_id
|
||||
self._channel_name = (
|
||||
info.json().get("name", self.channel_id)
|
||||
if info.status_code == 200
|
||||
else self.channel_id
|
||||
)
|
||||
|
||||
return [ManifestEntry(filename=f"{name}.txt", path="", checksum=checksum, size=len(self._text.encode()))]
|
||||
# Group by day.
|
||||
by_day: dict[str, list[dict]] = defaultdict(list)
|
||||
for msg in messages:
|
||||
ts = msg.get("timestamp", "")[:10] # YYYY-MM-DD from ISO string.
|
||||
if not ts:
|
||||
continue
|
||||
by_day[ts].append(msg)
|
||||
|
||||
entries: list[ManifestEntry] = []
|
||||
for day, day_msgs in sorted(by_day.items()):
|
||||
lines = []
|
||||
for msg in sorted(day_msgs, key=lambda m: m.get("timestamp", "")):
|
||||
author = msg.get("author", {}).get("username", "unknown")
|
||||
content = msg.get("content", "")
|
||||
lines.append(f"[{msg.get('timestamp', '')}] {author}: {content}")
|
||||
|
||||
text = "\n".join(lines)
|
||||
self._daily_texts[day] = text
|
||||
checksum = hashlib.sha256(text.encode()).hexdigest()[:16]
|
||||
|
||||
entries.append(
|
||||
ManifestEntry(
|
||||
filename=f"{self._channel_name}_{day}.txt",
|
||||
path="",
|
||||
checksum=checksum,
|
||||
size=len(text.encode()),
|
||||
)
|
||||
)
|
||||
|
||||
return entries
|
||||
|
||||
def _fetch_messages(self) -> list[dict]:
|
||||
messages: list[dict] = []
|
||||
@@ -69,7 +95,10 @@ class DiscordConnector(BaseConnector):
|
||||
return messages
|
||||
|
||||
def read_file(self, path: str, filename: str) -> bytes:
|
||||
return self._text.encode("utf-8")
|
||||
for day, text in self._daily_texts.items():
|
||||
if day in filename:
|
||||
return text.encode("utf-8")
|
||||
raise FileNotFoundError(f"Day not found: {filename}")
|
||||
|
||||
def close(self) -> None:
|
||||
self._http.close()
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Slack connector — sync channel history to a Knowledge Base.
|
||||
|
||||
Auth via SLACK_TOKEN env var (Bot User OAuth Token with channels:history scope).
|
||||
Messages are split by day for incremental sync — past days never change.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
@@ -15,9 +18,9 @@ from oikb.connectors import BaseConnector, ManifestEntry
|
||||
|
||||
|
||||
class SlackConnector(BaseConnector):
|
||||
"""Sync messages from a Slack channel."""
|
||||
"""Sync messages from a Slack channel, one file per day."""
|
||||
|
||||
def __init__(self, channel_id: str, token: str | None = None, limit: int = 1000):
|
||||
def __init__(self, channel_id: str, token: str | None = None, limit: int = 5000):
|
||||
self.channel_id = channel_id
|
||||
self.limit = limit
|
||||
self._token = token or os.environ.get("SLACK_TOKEN")
|
||||
@@ -29,27 +32,61 @@ class SlackConnector(BaseConnector):
|
||||
headers={"Authorization": f"Bearer {self._token}"},
|
||||
timeout=30.0,
|
||||
)
|
||||
self._messages: list[dict] = []
|
||||
self._channel_name: str = ""
|
||||
self._daily_texts: dict[str, str] = {}
|
||||
|
||||
def build_manifest(self) -> list[ManifestEntry]:
|
||||
self._messages = self._fetch_history()
|
||||
if not self._messages:
|
||||
messages = self._fetch_history()
|
||||
if not messages:
|
||||
return []
|
||||
|
||||
text = self._format_messages(self._messages)
|
||||
checksum = hashlib.sha256(text.encode()).hexdigest()[:16]
|
||||
|
||||
# Get channel name.
|
||||
info = self._http.get("/conversations.info", params={"channel": self.channel_id})
|
||||
name = info.json().get("channel", {}).get("name", self.channel_id) if info.status_code == 200 else self.channel_id
|
||||
self._channel_name = (
|
||||
info.json().get("channel", {}).get("name", self.channel_id)
|
||||
if info.status_code == 200
|
||||
else self.channel_id
|
||||
)
|
||||
|
||||
return [ManifestEntry(filename=f"{name}.txt", path="", checksum=checksum, size=len(text.encode()))]
|
||||
# Group messages by date.
|
||||
by_day: dict[str, list[dict]] = defaultdict(list)
|
||||
for msg in messages:
|
||||
ts = float(msg.get("ts", "0"))
|
||||
day = datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
by_day[day].append(msg)
|
||||
|
||||
entries: list[ManifestEntry] = []
|
||||
for day, day_msgs in sorted(by_day.items()):
|
||||
lines = []
|
||||
for msg in sorted(day_msgs, key=lambda m: m.get("ts", "")):
|
||||
user = msg.get("user", "unknown")
|
||||
text = msg.get("text", "")
|
||||
ts = msg.get("ts", "")
|
||||
lines.append(f"[{ts}] {user}: {text}")
|
||||
|
||||
content = "\n".join(lines)
|
||||
self._daily_texts[day] = content
|
||||
checksum = hashlib.sha256(content.encode()).hexdigest()[:16]
|
||||
|
||||
entries.append(
|
||||
ManifestEntry(
|
||||
filename=f"{self._channel_name}_{day}.txt",
|
||||
path="",
|
||||
checksum=checksum,
|
||||
size=len(content.encode()),
|
||||
)
|
||||
)
|
||||
|
||||
return entries
|
||||
|
||||
def _fetch_history(self) -> list[dict]:
|
||||
messages: list[dict] = []
|
||||
cursor = None
|
||||
while len(messages) < self.limit:
|
||||
params: dict[str, Any] = {"channel": self.channel_id, "limit": min(200, self.limit - len(messages))}
|
||||
params: dict[str, Any] = {
|
||||
"channel": self.channel_id,
|
||||
"limit": min(200, self.limit - len(messages)),
|
||||
}
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
resp = self._http.get("/conversations.history", params=params)
|
||||
@@ -61,17 +98,12 @@ class SlackConnector(BaseConnector):
|
||||
break
|
||||
return messages
|
||||
|
||||
def _format_messages(self, messages: list[dict]) -> str:
|
||||
lines = []
|
||||
for msg in reversed(messages):
|
||||
user = msg.get("user", "unknown")
|
||||
text = msg.get("text", "")
|
||||
ts = msg.get("ts", "")
|
||||
lines.append(f"[{ts}] {user}: {text}")
|
||||
return "\n".join(lines)
|
||||
|
||||
def read_file(self, path: str, filename: str) -> bytes:
|
||||
return self._format_messages(self._messages).encode("utf-8")
|
||||
# Extract date from filename: channel_YYYY-MM-DD.txt
|
||||
for day, text in self._daily_texts.items():
|
||||
if day in filename:
|
||||
return text.encode("utf-8")
|
||||
raise FileNotFoundError(f"Day not found: {filename}")
|
||||
|
||||
def close(self) -> None:
|
||||
self._http.close()
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
Auth via Microsoft Graph API using app credentials.
|
||||
Set TEAMS_TENANT_ID, TEAMS_CLIENT_ID, TEAMS_CLIENT_SECRET env vars.
|
||||
Messages are split by day for incremental sync.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
@@ -16,7 +18,7 @@ from oikb.connectors import BaseConnector, ManifestEntry
|
||||
|
||||
|
||||
class TeamsConnector(BaseConnector):
|
||||
"""Sync messages from a Microsoft Teams channel."""
|
||||
"""Sync messages from a Microsoft Teams channel, one file per day."""
|
||||
|
||||
def __init__(self, team_id: str, channel_id: str,
|
||||
tenant_id: str | None = None, client_id: str | None = None, client_secret: str | None = None):
|
||||
@@ -40,45 +42,74 @@ class TeamsConnector(BaseConnector):
|
||||
headers={"Authorization": f"Bearer {token_resp.json()['access_token']}"},
|
||||
timeout=30.0,
|
||||
)
|
||||
self._text: str = ""
|
||||
self._channel_name: str = ""
|
||||
self._daily_texts: dict[str, str] = {}
|
||||
|
||||
def build_manifest(self) -> list[ManifestEntry]:
|
||||
messages = self._fetch_messages()
|
||||
if not messages:
|
||||
return []
|
||||
|
||||
info = self._http.get(f"/teams/{self.team_id}/channels/{self.channel_id}")
|
||||
self._channel_name = (
|
||||
info.json().get("displayName", self.channel_id)
|
||||
if info.status_code == 200
|
||||
else self.channel_id
|
||||
)
|
||||
|
||||
by_day: dict[str, list[dict]] = defaultdict(list)
|
||||
for msg in messages:
|
||||
ts = msg.get("createdDateTime", "")[:10]
|
||||
if not ts:
|
||||
continue
|
||||
by_day[ts].append(msg)
|
||||
|
||||
entries: list[ManifestEntry] = []
|
||||
for day, day_msgs in sorted(by_day.items()):
|
||||
lines = []
|
||||
for msg in sorted(day_msgs, key=lambda m: m.get("createdDateTime", "")):
|
||||
sender = msg.get("from", {}).get("user", {}).get("displayName", "unknown")
|
||||
body = msg.get("body", {}).get("content", "")
|
||||
lines.append(f"[{msg.get('createdDateTime', '')}] {sender}: {body}")
|
||||
|
||||
text = "\n".join(lines)
|
||||
self._daily_texts[day] = text
|
||||
checksum = hashlib.sha256(text.encode()).hexdigest()[:16]
|
||||
|
||||
entries.append(
|
||||
ManifestEntry(
|
||||
filename=f"{self._channel_name}_{day}.txt",
|
||||
path="",
|
||||
checksum=checksum,
|
||||
size=len(text.encode()),
|
||||
)
|
||||
)
|
||||
|
||||
return entries
|
||||
|
||||
def _fetch_messages(self) -> list[dict]:
|
||||
messages: list[dict] = []
|
||||
url = f"/teams/{self.team_id}/channels/{self.channel_id}/messages"
|
||||
while url and len(messages) < 1000:
|
||||
while url and len(messages) < 5000:
|
||||
resp = self._http.get(url)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
messages.extend(data.get("value", []))
|
||||
url = data.get("@odata.nextLink", "").replace("https://graph.microsoft.com/v1.0", "") if data.get("@odata.nextLink") else None
|
||||
|
||||
if not messages:
|
||||
return []
|
||||
|
||||
lines = []
|
||||
for msg in messages:
|
||||
sender = msg.get("from", {}).get("user", {}).get("displayName", "unknown")
|
||||
body = msg.get("body", {}).get("content", "")
|
||||
ts = msg.get("createdDateTime", "")
|
||||
lines.append(f"[{ts}] {sender}: {body}")
|
||||
|
||||
self._text = "\n".join(lines)
|
||||
checksum = hashlib.sha256(self._text.encode()).hexdigest()[:16]
|
||||
|
||||
info = self._http.get(f"/teams/{self.team_id}/channels/{self.channel_id}")
|
||||
name = info.json().get("displayName", self.channel_id) if info.status_code == 200 else self.channel_id
|
||||
|
||||
return [ManifestEntry(filename=f"{name}.txt", path="", checksum=checksum, size=len(self._text.encode()))]
|
||||
next_link = data.get("@odata.nextLink", "")
|
||||
url = next_link.replace("https://graph.microsoft.com/v1.0", "") if next_link else None
|
||||
return messages
|
||||
|
||||
def read_file(self, path: str, filename: str) -> bytes:
|
||||
return self._text.encode("utf-8")
|
||||
for day, text in self._daily_texts.items():
|
||||
if day in filename:
|
||||
return text.encode("utf-8")
|
||||
raise FileNotFoundError(f"Day not found: {filename}")
|
||||
|
||||
def close(self) -> None:
|
||||
self._http.close()
|
||||
|
||||
|
||||
def parse_teams_source(source: str) -> dict[str, str | None]:
|
||||
"""Parse teams:team-id/channel-id."""
|
||||
source = source.removeprefix("teams:")
|
||||
parts = source.split("/", 1)
|
||||
if len(parts) < 2:
|
||||
|
||||
Reference in new issue
Block a user