-
Notifications
You must be signed in to change notification settings - Fork 6
Update discord_activity tracker app #142
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
leostar0412
wants to merge
3
commits into
cppalliance:develop
Choose a base branch
from
leostar0412:feature/141
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| # Built / downloaded DiscordChatExporter CLI (also listed in repo root .gitignore) | ||
| tools/ | ||
| vendor/ | ||
| # Local overrides (tokens, paths) — never commit secrets | ||
| *.local | ||
| .env.local |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| """Upload Discord markdown exports to a GitHub repo (API upload, no local git required).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| from pathlib import Path | ||
|
|
||
| from django.conf import settings | ||
|
|
||
| from github_ops import get_github_token, upload_folder_to_github | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| DEFAULT_BRANCH = "main" | ||
|
|
||
|
|
||
| def discord_markdown_repo_config() -> tuple[str, str, str] | None: | ||
| """Return (owner, repo, branch) for Markdown upload, or None if not configured.""" | ||
| owner = getattr(settings, "DISCORD_MARKDOWN_REPO_OWNER", "") or "" | ||
| repo = getattr(settings, "DISCORD_MARKDOWN_REPO_NAME", "") or "" | ||
| branch = ( | ||
| getattr(settings, "DISCORD_MARKDOWN_REPO_BRANCH", DEFAULT_BRANCH) | ||
| or DEFAULT_BRANCH | ||
| ).strip() | ||
| owner = owner.strip() | ||
| repo = repo.strip() | ||
| if not owner or not repo: | ||
| return None | ||
| return owner, repo, branch | ||
|
|
||
|
|
||
| def push_discord_markdown_to_github(local_folder: Path) -> bool: | ||
| """ | ||
| Upload all files under local_folder to DISCORD_MARKDOWN_REPO_*. | ||
| Returns True on reported API success. | ||
| """ | ||
| cfg = discord_markdown_repo_config() | ||
| if not cfg: | ||
| logger.error( | ||
| "DISCORD_MARKDOWN_REPO_OWNER / DISCORD_MARKDOWN_REPO_NAME not set; " | ||
| "skipping upload." | ||
| ) | ||
| return False | ||
| owner, repo, branch = cfg | ||
| if not local_folder.is_dir(): | ||
| logger.error("Markdown folder is not a directory: %s", local_folder) | ||
| return False | ||
|
|
||
| logger.info( | ||
| "Uploading Discord markdown from %s to %s/%s@%s", | ||
| local_folder, | ||
| owner, | ||
| repo, | ||
| branch, | ||
| ) | ||
| token = get_github_token(use="write") | ||
| result = upload_folder_to_github( | ||
| local_folder=local_folder, | ||
| owner=owner, | ||
| repo=repo, | ||
| commit_message="chore: update Discord archive markdown", | ||
| branch=branch, | ||
| token=token, | ||
| ) | ||
|
Comment on lines
+56
to
+64
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Preserve the function’s boolean failure contract on token errors.
Suggested fix- token = get_github_token(use="write")
- result = upload_folder_to_github(
- local_folder=local_folder,
- owner=owner,
- repo=repo,
- commit_message="chore: update Discord archive markdown",
- branch=branch,
- token=token,
- )
+ try:
+ token = get_github_token(use="write")
+ result = upload_folder_to_github(
+ local_folder=local_folder,
+ owner=owner,
+ repo=repo,
+ commit_message="chore: update Discord archive markdown",
+ branch=branch,
+ token=token,
+ )
+ except Exception as e:
+ logger.error("Discord markdown upload setup failed: %s", e)
+ return False🤖 Prompt for AI Agents |
||
| if result.get("success"): | ||
| logger.info("Discord markdown upload complete") | ||
| return True | ||
| msg = result.get("message") or "Upload failed" | ||
| logger.error("Discord markdown upload failed: %s", msg) | ||
| return False | ||
151 changes: 151 additions & 0 deletions
151
discord_activity_tracker/management/commands/backfill_discord_json.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| """Import historical DiscordChatExporter JSON (per-day / chunk layout) into the database.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import logging | ||
| from pathlib import Path | ||
|
|
||
| from django.conf import settings | ||
| from django.core.management.base import BaseCommand, CommandError | ||
|
|
||
| from core.utils.datetime_parsing import parse_iso_datetime | ||
| from discord_activity_tracker.sync.backfill_paths import ( | ||
| iter_discussion_json_files, | ||
| json_path_in_date_window, | ||
| ) | ||
| from discord_activity_tracker.sync.chat_exporter import parse_exported_json | ||
| from discord_activity_tracker.sync.importer import persist_exporter_channel_payloads | ||
| from discord_activity_tracker.workspace import get_discussion_export_dir | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = ( | ||
| "Backfill Discord messages from DiscordChatExporter JSON files (e.g. " | ||
| "workspace/discord_activity_tracker/Discussion - c-cpp-discussion/). " | ||
| "Processes one file at a time. Use --dry-run to list files only." | ||
| ) | ||
|
|
||
| def add_arguments(self, parser): | ||
| parser.add_argument( | ||
| "--path", | ||
| type=str, | ||
| default=None, | ||
| help=( | ||
| "Root directory to scan (default: workspace/discord_activity_tracker/" | ||
| "Discussion - c-cpp-discussion/)." | ||
| ), | ||
| ) | ||
| parser.add_argument( | ||
| "--dry-run", | ||
| action="store_true", | ||
| help="List files that would be imported; do not write to the database.", | ||
| ) | ||
| parser.add_argument( | ||
| "--limit", | ||
| type=int, | ||
| default=0, | ||
| metavar="N", | ||
| help="Process at most N JSON files (0 = no limit).", | ||
| ) | ||
| parser.add_argument( | ||
| "--guild-id", | ||
| type=int, | ||
| default=None, | ||
| help="If set, skip JSON whose guild id does not match (default: DISCORD_SERVER_ID).", | ||
| ) | ||
| parser.add_argument( | ||
| "--since", | ||
| "--from-date", | ||
| "--start-time", | ||
| type=str, | ||
| default=None, | ||
| dest="since", | ||
| help="Only include files whose day/chunk range overlaps this date (YYYY-MM-DD or ISO). " | ||
| "Aliases: --from-date, --start-time.", | ||
| ) | ||
| parser.add_argument( | ||
| "--until", | ||
| "--to-date", | ||
| "--end-time", | ||
| type=str, | ||
| default=None, | ||
| dest="until", | ||
| help="Only include files up to this date (same formats as --since). " | ||
| "Aliases: --to-date, --end-time.", | ||
| ) | ||
|
|
||
| def handle(self, *args, **options): | ||
| dry_run = options["dry_run"] | ||
| limit = max(0, int(options["limit"] or 0)) | ||
| path_arg = options["path"] | ||
| root = ( | ||
| Path(path_arg).expanduser().resolve() | ||
| if path_arg | ||
| else get_discussion_export_dir() | ||
| ) | ||
|
|
||
| try: | ||
| since_dt = parse_iso_datetime(options.get("since")) | ||
| until_dt = parse_iso_datetime(options.get("until")) | ||
| except ValueError as e: | ||
| raise CommandError(str(e)) from e | ||
| if since_dt and until_dt and since_dt > until_dt: | ||
| raise CommandError("since must be on or before until") | ||
|
|
||
| cfg_guild = (getattr(settings, "DISCORD_SERVER_ID", "") or "").strip() | ||
| expected = options["guild_id"] | ||
| if expected is None and cfg_guild: | ||
| try: | ||
| expected = int(cfg_guild) | ||
| except ValueError: | ||
| expected = None | ||
|
|
||
| if not root.is_dir(): | ||
| raise CommandError(f"Not a directory: {root}") | ||
|
|
||
| paths = list(iter_discussion_json_files(root)) | ||
| paths = [p for p in paths if json_path_in_date_window(p, since_dt, until_dt)] | ||
| if limit: | ||
| paths = paths[:limit] | ||
|
|
||
| self.stdout.write(f"Found {len(paths)} JSON file(s) under {root}") | ||
| if not paths: | ||
| return | ||
|
|
||
| if dry_run: | ||
| for p in paths: | ||
| self.stdout.write(f" {p.relative_to(root)}") | ||
| self.stdout.write(self.style.WARNING("DRY RUN — no database writes")) | ||
| return | ||
|
|
||
| processed = 0 | ||
| for i, json_path in enumerate(paths, 1): | ||
| try: | ||
| data = parse_exported_json(json_path) | ||
| channel_data = { | ||
| "guild": data.get("guild", {}), | ||
| "channel": data.get("channel", {}), | ||
| "messages": data.get("messages", []), | ||
| } | ||
| ch = channel_data["channel"].get("name", "?") | ||
| n = len(channel_data["messages"]) | ||
| self.stdout.write( | ||
| f" [{i}/{len(paths)}] {json_path.name} #{ch}: {n} msgs" | ||
| ) | ||
| asyncio.run( | ||
| persist_exporter_channel_payloads( | ||
| [channel_data], | ||
| expected_guild_id=expected, | ||
| ) | ||
| ) | ||
| processed += 1 | ||
| except Exception as e: | ||
| logger.exception("Backfill failed for %s: %s", json_path, e) | ||
| self.stdout.write(self.style.WARNING(f" Skip {json_path.name}: {e}")) | ||
|
|
||
| self.stdout.write( | ||
| self.style.SUCCESS(f"✓ Backfill finished ({processed} file(s))") | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Normalize branch fallback after trimming whitespace.
A whitespace-only branch setting currently becomes
""after.strip(), which can cause upload calls to target an invalid branch ref.Suggested fix
🤖 Prompt for AI Agents