Compare commits

...

142 Commits

Author SHA1 Message Date
Tyrrrz a46bf9bf11 Update version 2023-11-16 00:43:07 +02:00
Tyrrrz 8dc024d244 Add more comments to the dockerfile 2023-11-16 00:38:18 +02:00
Tyrrrz 9a125db0ea Reformat docker commands 2023-11-15 17:03:36 +02:00
Tyrrrz d9c35f4405 Clean up dockerfile 2023-11-15 15:25:10 +02:00
Tyrrrz 5846129cc6 Use native OpenFolderDialog in GUI 2023-11-14 23:44:29 +02:00
Tyrrrz 6f5f747632 Standardize paths in docker 2023-11-14 23:31:12 +02:00
Tyrrrz 6a71c59b6d Don't need to create a user in Docker anymore with .NET 8 2023-11-14 23:24:28 +02:00
Tyrrrz 73574ade48 Convert some classes to use primary constructors 2023-11-14 22:57:02 +02:00
Tyrrrz 743db67f91 Update references to .NET Runtime 2023-11-14 20:20:35 +02:00
Tyrrrz 5d7a74eece Switch to .NET 8 2023-11-14 20:05:27 +02:00
Tyrrrz 129df42de4 Keep file:/// for absolute paths in HTML exports
Closes #1155
2023-11-13 18:09:09 +02:00
Tyrrrz 6508455f3a Move the tooltip to the correct place 2023-11-12 23:47:16 +02:00
Tyrrrz 50b26c557f Disable "Reuse assets" and "Assets path" options in GUI export setup if "Download assets" is disabled 2023-11-12 23:45:52 +02:00
Tyrrrz b709fc0f15 Update NuGet packages 2023-11-12 23:39:38 +02:00
Tyrrrz c118a0bb94 Fix broken links in docs 2023-11-11 17:49:43 +02:00
Oleksii Holub 1418bec0c7 Update dotnet installation instructions 2023-11-11 17:21:33 +02:00
Oleksii Holub 750fd69a50 Update Docker instructions 2023-11-11 17:10:43 +02:00
Tyrrrz b1297bb7df Set default locale in Docker 2023-11-11 16:56:49 +02:00
Tyrrrz 3189111a0e Install both the iclu-libs and icu-data-full in Docker 2023-11-11 16:52:55 +02:00
Tyrrrz 6ec2c04aa3 Use the full ICU in docker 2023-11-11 16:48:26 +02:00
Tyrrrz 7c014bf64d Add a note about interactivity in the CLI 2023-11-11 16:39:36 +02:00
Tyrrrz c875f8f4f0 Install ICU libs in Docker 2023-11-11 16:27:17 +02:00
Tyrrrz 69e2c337d8 Use alpine images again in Docker 2023-11-11 00:05:27 +02:00
Tyrrrz 77c770acdd Update gitignore file 2023-11-09 13:41:43 +02:00
Tyrrrz 6f8749a105 Update version 2023-11-09 13:11:59 +02:00
Tyrrrz 4896d748aa Update NuGet packages 2023-11-09 13:06:00 +02:00
Tyrrrz 4876ed192a Use ISO 8601 date format in CSV
Closes #1152
2023-11-07 22:16:25 +02:00
Tyrrrz 4f6e6f4f0b Write embed videos in JSON export
Closes #1120
2023-11-07 16:03:39 +02:00
Tyrrrz 8c75f04115 Add labels to the dockerfile 2023-11-07 15:09:31 +02:00
Tyrrrz df04b123cd Reorder props 2023-11-01 15:30:15 +02:00
Tyrrrz 578ed9be17 Prepare for .NET 8 2023-10-31 23:40:41 +02:00
Tyrrrz ebceacc707 Minor workflow cleanup 2023-10-29 23:59:09 +02:00
Tyrrrz eaab5786f2 Workflow improvements 2023-10-29 01:24:47 +03:00
Tyrrrz ebf7d65334 Fix step name in deploy job 2023-10-26 16:15:09 +03:00
Tyrrrz 52a23828ce Update version 2023-10-26 16:06:53 +03:00
Tyrrrz 2edd781e32 Update NuGet packages 2023-10-26 15:59:56 +03:00
Tyrrrz 19cdf47c6e Consolidate some docker jobs 2023-10-26 03:11:07 +03:00
Tyrrrz 65e0a63bda Consistency with other projects 2023-10-26 02:49:26 +03:00
Tyrrrz 692438d10c Reduce repetition in workflows using matrices 2023-10-26 02:45:20 +03:00
Tyrrrz c607c6f307 Fix deploy job 2023-10-26 00:03:55 +03:00
Tyrrrz aae43821e7 Simplify CI workflow 2023-10-24 15:13:30 +03:00
Tyrrrz 7b9a4e1aff Fix closing backticks in docs 2023-10-24 14:32:29 +03:00
LostXOR d8e57f94a8 Add command to fix broken permissions to Linux installation instructions (#1148)
Co-authored-by: Oleksii Holub <1935960+Tyrrrz@users.noreply.github.com>
2023-10-24 00:26:52 +03:00
Tyrrrz 7b7df564ed Allow empty names in interactions 2023-10-22 19:22:51 +03:00
Tyrrrz 80b59d1254 Update version 2023-10-19 18:52:19 +03:00
Tyrrrz 6579563816 Don't unfurl URLs in notify job 2023-10-17 16:18:44 +03:00
Tyrrrz e2971ed3a6 Improve notify job message 2023-10-17 15:01:59 +03:00
Tyrrrz a0a263f074 Improve error message for forum channels
Related to #1144
2023-10-16 17:22:28 +03:00
Tyrrrz 1438fd9f77 Temp fix for the docs link in the readme 2023-10-16 17:12:40 +03:00
Tyrrrz b298b45cf7 Escape markup in CLI 2023-10-13 01:17:13 +03:00
Tyrrrz 8d01c6be35 Improve notify message format 2023-10-12 16:00:47 +03:00
Tyrrrz ce4dbb2616 Update version 2023-10-12 15:43:31 +03:00
Tyrrrz 033d83bc4f More cleanup 2023-10-11 01:20:30 +03:00
Tyrrrz fb6cde38b6 Clean up after last commit 2023-10-10 00:04:57 +03:00
Adam Slatinský 46ede471a9 Remove CDN signature before hashing asset URL (#1138) 2023-10-09 23:58:31 +03:00
Tyrrrz 09f8937d99 Refactor 2023-10-09 16:18:56 +03:00
Adam Slatinský ad2dab2157 Add progress to fetching channels step (#1131) 2023-10-08 23:56:39 +03:00
Tyrrrz c5e426289f Include release link in notify 2023-10-05 22:52:31 +03:00
Tyrrrz b8e5034aea Update version 2023-10-05 14:53:46 +03:00
Tyrrrz 5fc40fe7d5 Fix http action 2023-10-05 14:51:15 +03:00
Tyrrrz f7d94975b2 Retry notify job 2023-10-04 19:57:35 +03:00
Tyrrrz 3eb0421ec6 Update workflow actions 2023-10-04 15:41:48 +03:00
Tyrrrz 57ed5578c9 Optimize message content intent check 2023-10-04 15:24:48 +03:00
Tyrrrz a8895663fe Add check for message content intent 2023-09-30 17:32:21 +03:00
Jacob Pfundstein 89f2084759 Improve and update docs (#1134) 2023-09-29 14:53:52 +03:00
Tyrrrz 9180d51e5e Update version 2023-09-28 19:30:21 +03:00
Tyrrrz a58509fda8 Upgrade to Polly 8 usage 2023-09-28 19:30:12 +03:00
Tyrrrz fbfff4e51f Make tests more resilient 2023-09-28 19:18:52 +03:00
Tyrrrz c466c17793 Update NuGet packages 2023-09-28 16:16:20 +03:00
Tyrrrz 1b2bcf771d Add fallback for progress tasks without name in CLI
Closes #1133
2023-09-26 00:13:22 +03:00
Tyrrrz 99b49f0b8f Allow pack job to run in parallel to test 2023-09-22 14:51:42 +03:00
Tyrrrz 850414b017 Clean up workflow 2023-09-21 20:18:16 +03:00
Tyrrrz 92bf6eab2d Treat all warnings as errors 2023-09-20 21:36:43 +03:00
Oleksii Holub 16d44ce654 Update version 2023-09-15 13:02:35 +03:00
Tyrrrz 5abe74894c Remove Channel.ParentNameWithFallback 2023-09-07 16:36:29 +03:00
Oleksii Holub 59344cedbe Replace the date format option with a locale option (#1130) 2023-09-07 14:34:08 +03:00
Oleksii Holub 53b11d6c49 Update docks for Docker usage 2023-09-07 00:18:29 +03:00
Tyrrrz ccdf082689 Clean up formatting 2023-09-03 22:19:03 +03:00
Tyrrrz 9601e0acea Refactor 2023-09-03 21:46:20 +03:00
Adam Slatinský 9583e2684d Optimize fetching threads (#1125) 2023-09-03 21:18:49 +03:00
Tyrrrz d24550f521 Hide completed tasks in CLI when exporting in parallel
Closes #1124
2023-08-30 18:43:31 +03:00
Tyrrrz c422ac2351 Clean up 2023-08-30 18:43:12 +03:00
Tyrrrz 3740d64601 Optimize thread inclusion UX across GUI and CLI
Related to #1119
2023-08-28 22:08:51 +03:00
Tyrrrz d430f77ae1 Replace --include-threads and --include-archived-threads with a single multi-value option
Related to #1119
2023-08-28 21:52:56 +03:00
Tyrrrz 5f6e51f6fb Show threads in GUI at the bottom of the list, in specialized groups
Related to #1119
2023-08-28 21:31:51 +03:00
Tyrrrz f1c094ac14 Implicitly enable threads if archived threads are enabled in GUI 2023-08-28 21:09:42 +03:00
Tyrrrz 6fb6108610 Be safer when pulling threads using a bot token 2023-08-23 15:58:53 +03:00
Tyrrrz e75a1933f8 Bypass CSharpier in docker build 2023-08-22 21:36:50 +03:00
Tyrrrz 20f58963a6 Use CSharpier 2023-08-22 21:17:19 +03:00
Tyrrrz c410e745b1 Add rudimentary thread support in GUI
Related to #1119
2023-08-22 21:14:34 +03:00
Tyrrrz c29de2c77c Fetch threads more efficiently for user tokens 2023-08-22 19:16:32 +03:00
Tyrrrz 67d41fbdc4 Fix jitter in the GUI when switching from DM guild to any other and back 2023-08-22 17:41:36 +03:00
Tyrrrz 041086267c Short-circuit GetGuildThreadsAsync(...) for DMs 2023-08-22 00:10:04 +03:00
Tyrrrz 47588296a9 Use ValueTask for consistency 2023-08-22 00:08:45 +03:00
Tyrrrz d1a8f466f6 Pull channels lazily in the GUI
Closes #1005
2023-08-22 00:03:29 +03:00
Tyrrrz 758fb26dad Add --include-threads and --include-archived-threads to exportall
Related to #1119
2023-08-21 17:45:12 +03:00
Tyrrrz 8236ba7c4d Add defaults to inits 2023-08-21 17:35:10 +03:00
Tyrrrz eac974cfb1 Add --include-threads and --include-archived-threads to exportguild
Related to #1119
2023-08-21 17:33:22 +03:00
Tyrrrz d1d560fb55 Add --include-vc to the channels command 2023-08-21 17:24:05 +03:00
Tyrrrz 6fba60e570 Print archived threads only if explicitly requested in the channels command 2023-08-21 17:22:44 +03:00
Tyrrrz ac1bd16439 Clean up 2023-08-21 01:05:57 +03:00
Tyrrrz 60389ab002 Add warning about IsBotToken deprecation 2023-08-21 01:03:29 +03:00
Tyrrrz 817d54039b Improve naming of dictionaries 2023-08-20 16:48:39 +03:00
Tyrrrz 0ca42f5a14 Update issue forms 2023-08-18 01:40:01 +03:00
Tyrrrz 193cfd7b1e Update issue forms 2023-08-13 13:40:22 +03:00
Tyrrrz 21293dc7af Update bug report form 2023-08-12 21:55:27 +03:00
Tyrrrz 88dee76690 Update issue forms 2023-08-12 21:44:29 +03:00
Tyrrrz cd5afd07ac Update version 2023-08-11 00:06:15 +03:00
Tyrrrz 55270ad6d3 Switch to MIT license 2023-08-08 22:46:07 +03:00
Tyrrrz e82ad2b9c6 Add comment linking an issue that explains why the EscapedSymbolTextNodeMatcher is used 2023-08-05 18:35:22 +03:00
Tyrrrz dd0a35838d Allow empty lines in repeated single-line quote nodes
Closes #1115
2023-08-05 18:30:11 +03:00
Tyrrrz c9b68427f3 Update NuGet packages 2023-08-05 18:17:06 +03:00
Tyrrrz 1ba0057174 Clean up 2023-07-31 20:22:10 +03:00
Adam Slatinský d00ecf0c37 Export reaction users in JSON format (#1107) 2023-07-31 20:11:47 +03:00
Tyrrrz b224fca6c0 ToHex() should be uppercase by default 2023-07-30 14:54:15 +03:00
Tyrrrz c9447c5c8f Clean up 2023-07-29 20:53:00 +03:00
Tyrrrz de67cfae1c Use invariant culture 2023-07-29 20:47:43 +03:00
Tyrrrz 4efa6094dc Round up the "call lasted for X minutes" value 2023-07-29 20:47:36 +03:00
Tyrrrz 088612a78f Update version 2023-07-29 00:58:32 +03:00
Tyrrrz de531d4a97 Fix category not working in GUI
Closes #1112
2023-07-29 00:57:45 +03:00
Tyrrrz 5fc2fae28a Update version 2023-07-27 23:59:17 +03:00
Tyrrrz ddfbe51cfa Improve error reporting on unexpected HTTP status code 2023-07-25 18:59:05 +03:00
Tyrrrz bcf652edbe Don't throw when parent channel cannot be retrieved
Closes #1108
2023-07-23 16:04:53 +03:00
Tyrrrz 1f5407f032 Update version 2023-07-21 02:03:47 +03:00
Tyrrrz 83a63c2ed7 Update NuGet packages 2023-07-21 02:03:32 +03:00
Tyrrrz f33a0ac0a7 Update Onova 2023-07-18 22:12:26 +03:00
Tyrrrz 779b8984d7 Update readme 2023-07-17 00:47:30 +03:00
Tyrrrz 3e44a2e88d Re-add IHasId to Channel 2023-07-16 23:12:57 +03:00
Tyrrrz b44e6087be Update NuGet packages 2023-07-16 23:09:31 +03:00
Tyrrrz 49b96087d3 Clean up 2023-07-16 23:05:53 +03:00
Tyrrrz e175c93038 Refactor 2023-07-16 22:55:36 +03:00
Tyrrrz 0ee1107638 Make password box un-editable 2023-07-16 21:37:40 +03:00
Tyrrrz 81a6d363d1 Use favicon as avatar for Discord webhooks 2023-07-11 23:53:12 +03:00
Tyrrrz 90d71c5b9e Clean up 2023-07-10 20:40:32 +03:00
Adam Slatinský 5e9c7392db Add export timestamp in JSON format (#1102) 2023-07-09 18:22:09 +03:00
Tyrrrz c4137cf77e Hide token using password box 2023-07-09 18:13:41 +03:00
Tyrrrz 51192425b7 Expect channel parents to be null 2023-07-08 19:21:00 +03:00
William Unsworth 8776a6955b Better support for exporting threads (#1046) 2023-07-07 20:33:17 +03:00
Tyrrrz c69211797f Clean up 2023-07-03 18:35:28 +03:00
Adam Slatinský 768fb88c8c Export role details in JSON format (#1101) 2023-07-03 18:18:30 +03:00
Tyrrrz d4f62387a5 Add CLI option to include or exclude voice channels in exportall and exportguild 2023-06-23 21:23:55 +03:00
Tyrrrz bd4cfcdaf6 Update avatar resolving for users without discriminator 2023-06-21 22:05:08 +03:00
216 changed files with 13837 additions and 12983 deletions
+25 -66
View File
@@ -2,108 +2,67 @@
Docker distribution of DiscordChatExporter provides a way to run the app in a virtualized and isolated environment. Due to the nature of Docker, you also don't need to install any prerequisites otherwise required by DCE. Docker distribution of DiscordChatExporter provides a way to run the app in a virtualized and isolated environment. Due to the nature of Docker, you also don't need to install any prerequisites otherwise required by DCE.
Note that only the CLI flavor of DiscordChatExporter is available for use with Docker. > **Note**:
> Only the CLI flavor of DiscordChatExporter is available for use with Docker.
## Pulling ## Pulling
This will download the [Docker image from the registry](https://hub.docker.com/r/tyrrrz/discordchatexporter) to your computer. You can run this command again to update when a new version is released. This will download the [Docker image from the registry](https://hub.docker.com/r/tyrrrz/discordchatexporter) to your computer. You can run this command again to update when a new version is released.
``` ```console
docker pull tyrrrz/discordchatexporter:stable docker pull tyrrrz/discordchatexporter:stable
``` ```
Note the `:stable` tag. DiscordChatExporter images are tagged according to the following patterns: Note the `:stable` tag. DiscordChatExporter images are tagged according to the following patterns:
- `stable`: Latest stable version release and maps to the latest GitHub release. This tag is updated with release of each new version. Recommended for personal use. - `stable` — latest stable version release. This tag is updated with each release of a new project version. Recommended for personal use.
- `latest`: Built from the latest commit and maps to the latest CI build on GitHub. This tag is updated with each new commit to `master` branch. Not recommended for everyday use, but you can use it if you want to try out some features that haven't been officially released yet. - `x.y.z` (e.g. `2.30.1`) — specific stable version release. This tag is pushed when the corresponding version is released and never updated thereafter. Recommended for use in automation scenarios.
- `x.y.z` (e.g. `2.30.1`): Fixed version release and maps to the corresponding tag on GitHub. This tag is never updated once that version has been released. Recommended for use in various automation scenarios. - `latest` — latest (potentially unstable) build. This tag is updated with each new commit to the `master` branch. Not recommended, unless you want to test a new feature that has not been released in a stable version yet.
You can see all available tags [here](https://hub.docker.com/r/tyrrrz/discordchatexporter/tags?page=1&ordering=name). You can see all available tags [here](https://hub.docker.com/r/tyrrrz/discordchatexporter/tags?ordering=name).
## Usage ## Usage
To run the CLI in Docker and render help text: To run the CLI in Docker and render help text:
``` ```console
docker run --rm tyrrrz/discordchatexporter:stable docker run --rm tyrrrz/discordchatexporter:stable
``` ```
To export a channel: To export a channel:
``` ```console
docker run --rm -v /path/on/machine:/out tyrrrz/discordchatexporter:stable export -t TOKEN -c CHANNELID docker run --rm -v /path/on/machine:/out tyrrrz/discordchatexporter:stable export -t TOKEN -c CHANNELID
``` ```
If you want colored output, real-time progress reporting, and some other stuff, pass `-it` (interactive) option: If you want colored output and real-time progress reporting, pass the `-it` (interactive + pseudo-terminal) option:
``` ```console
docker run --rm -it -v /path/on/machine:/out tyrrrz/discordchatexporter:stable export -t TOKEN -c CHANNELID docker run --rm -it -v /path/on/machine:/out tyrrrz/discordchatexporter:stable export -t TOKEN -c CHANNELID
``` ```
Note the `-v /path/on/machine:/out` option, which instructs Docker to bind the `/out` directory inside the container to a path on your host machine. Replace `/path/on/machine` with the directory you want the files to be saved at. The `-v /path/on/machine:/out` option instructs Docker to bind the `/out` directory inside the container to a path on your host machine. Replace `/path/on/machine` with the directory you want the files to be saved at.
**If you are running SELinux, you will need to add the `:z` option after `/out`, e.g.:** > **Note**:
> If you are running SELinux, you will need to add the `:z` option after `/out`, e.g.:
``` >
docker run --rm -v /path/on/machine:/out:z tyrrrz/discordchatexporter:stable export -t TOKEN -c CHANNELID > ```console
``` > docker run --rm -v /path/on/machine:/out:z tyrrrz/discordchatexporter:stable export -t TOKEN -c CHANNELID
> ```
For more information, refer to the [Docker docs SELinux labels for bind mounts page](https://docs.docker.com/storage/bind-mounts/#configure-the-selinux-label). >
> For more information, refer to the [Docker docs SELinux labels for bind mounts page](https://docs.docker.com/storage/bind-mounts/#configure-the-selinux-label).
You can also use the current working directory as the output directory by specifying: You can also use the current working directory as the output directory by specifying:
- `-v $PWD:/out` in Mac/Linux - `-v $PWD:/out` in Bash
- `-v $pwd.Path:/out` in PowerShell - `-v $pwd.Path:/out` in PowerShell
For more information, please refer to the [Dockerfile](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/Dockerfile) and [Docker documentation](https://docs.docker.com/engine/reference/run/). For more information, please refer to the [Dockerfile](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/DiscordChatExporter.Cli.dockerfile) and [Docker documentation](https://docs.docker.com/engine/reference/run).
To get your Token and Channel IDs, please refer to [this page](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md). To get your Token and Channel IDs, please refer to [this page](Token-and-IDs.md).
## Environment variables ## Environment variables
DiscordChatExpoter CLI accepts environment variables as fallbacks for the `--token` and `--bot` options. DiscordChatExpoter CLI accepts the `DISCORD_TOKEN` environment variable as a fallback for the `--token` option. You can set this variable either with the `--env` Docker option or with a combination of the `--env-file` Docker option and a `.env` file.
- `DISCORD_TOKEN` to set the token Please refer to the [Docker documentation](https://docs.docker.com/engine/reference/commandline/run/#set-environment-variables--e---env---env-file) for more information.
- `DISCORD_TOKEN_BOT` to set whether it's a bot token (`true` or `false`)
You can use these variables either with the `--env` Docker option or with a combination of the `--env-file` Docker option and a `.env` file.
Please refer to the Docker documentation for more information:
- [Docker run - Set environment variables](https://docs.docker.com/engine/reference/commandline/run/#set-environment-variables--e---env---env-file)
## Permission issues with Linux hosts
When bounding volumes between the container and the host, files mirrored from the Docker container will be owned by the Docker user (in most setups this is `root`). Please refer to this [issue comment](https://github.com/Tyrrrz/DiscordChatExporter/issues/800#issuecomment-1030471970) for instructions on how to override this behavior.
## Build Docker images for arm on Raspberry Pi
If you use the Docker image on arm (for example Raspberry Pi), you'd build the image as below.
```bash
$ git clone https://github.com/Tyrrrz/DiscordChatExporter.git
$ cd DiscordChatExporter
$ docker build -f DiscordChatExporter.Cli.dockerfile -t tyrrrz/discordchatexporter:latest .
```
After a while, some images are built like below.
```bash
$ docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
tyrrrz/discordchatexporter latest 7c9ead725177 49 seconds ago 199MB
<none> <none> 57f9f49d05af About a minute ago 678MB
mcr.microsoft.com/dotnet/sdk 5.0 72af6071941e 4 days ago 641MB
mcr.microsoft.com/dotnet/runtime 3.1 6229bebd5a11 4 days ago 197MB
```
Among these, two images (`tyrrrz/discordchatexporter:latest` and `mcr.microsoft.com/dotnet/runtime:3.1`) are required, so you may delete the other two images.
Now you can execute DiscordChatExporter:
```bash
$ docker run --rm tyrrrz/discordchatexporter:latest
```
---
Special thanks to [@simnalamburt](https://github.com/simnalamburt) (dockerize) and [@Nimja](https://github.com/nimja) (better instructions)
+27 -42
View File
@@ -1,69 +1,54 @@
# Install .NET runtime # Install .NET runtime
**.NET v7.0 Runtime** is required by **DiscordChatExporter v2.37 and newer**. **.NET 8.0 Runtime** is required by **DiscordChatExporter**.
If you are using GUI flavor of DiscordChatExporter, the runtime will be installed automatically (since v2.27.1). > **Note**:
If you are using the CLI from Docker, installing the runtime on the host machine is not needed. > Installing the **.NET Runtime** is not required if you running **DiscordChatExporter** using [Docker](Docker.md).
- Install ## Windows
- [Windows and macOS](#windows-and-macos)
- [Linux](#linux)
- [Docker](#docker)
- [Verify installation](#Verify-installation-optional)
## Windows and macOS Both the GUI and the CLI flavors of **DiscordChatExporter** for Windows come with a bootstrapper that should automatically install all the required prerequisites. Simply run the application and follow the presented instructions.
**Download from the direct links:** If, for some reason, you need to install the runtime manually, use one of the download links below:
- [.NET v7.0 Runtime for **Windows x64**](https://dotnet.microsoft.com/download/dotnet/thank-you/runtime-desktop-7.0.1-windows-x64-installer) - [.NET 8.0 Runtime for **Windows x64**](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-8.0.0-windows-x86-installer)
- [.NET v7.0 Runtime for **Windows x86**](https://dotnet.microsoft.com/download/dotnet/thank-you/runtime-desktop-7.0.1-windows-x86-installer) - [.NET 8.0 Runtime for **Windows x86**](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-8.0.0-windows-x64-installer)
- [.NET v7.0 Runtime for **Macs with Apple silicon**](https://dotnet.microsoft.com/download/dotnet/thank-you/runtime-7.0.1-macos-arm64-installer) - [.NET 8.0 Runtime for **Windows arm64**](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-8.0.0-windows-arm64-installer)
- [.NET v7.0 Runtime for **Macs with an Intel processor**](https://dotnet.microsoft.com/download/dotnet/thank-you/runtime-7.0.1-macos-x64-installer)
> **Note**: > **Note**:
> [How can I tell if my computer is running a 32-bit (x86) or a 64-bit (x64) version of Windows?](https://support.microsoft.com/help/15056/windows-32-64-bit-faq) > [How can I tell if my computer is running a 32-bit (x86) or a 64-bit (x64) version of Windows?](https://support.microsoft.com/help/15056/windows-32-64-bit-faq)
## macOS
Use one of the download links below:
- [.NET 8.0 Runtime for **macOS x64**](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-8.0.0-macos-x64-installer)
- [.NET 8.0 Runtime for **macOS arm64**](https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/runtime-8.0.0-macos-arm64-installer)
> **Note**: > **Note**:
> [Is my Mac using an Intel processor or Apple silicon?](https://support.apple.com/HT211814) > [Is my Mac using an Intel processor (x64) or Apple Silicon (arm64)?](https://support.apple.com/HT211814)
**Otherwise:**
[Check out the latest version in this page](https://dotnet.microsoft.com/download/dotnet/7.0).
Look for the download link in the '**.NET Runtime**' section, under **Installers**:
[![](https://i.imgur.com/t3PB3NC.png)](https://dotnet.microsoft.com/download/dotnet/7.0)
## Linux ## Linux
**You only need to install .NET Runtime v7.0** Installing the .NET Runtime works differently depending on which Linux distribution you use. Check out the instructions for your distro:
Check out the instructions for your distro: - [Ubuntu](https://docs.microsoft.com/dotnet/core/install/linux-ubuntu)
- [Debian](https://docs.microsoft.com/dotnet/core/install/linux-debian)
- [Ubuntu](https://docs.microsoft.com/dotnet/core/install/linux-ubuntu#supported-distributions) - [Fedora](https://docs.microsoft.com/dotnet/core/install/linux-fedora)
- [Debian](https://docs.microsoft.com/dotnet/core/install/linux-debian#supported-distributions)
- [Fedora](https://docs.microsoft.com/dotnet/core/install/linux-fedora#supported-distributions)
For other distros, please check the _'Install on Linux'_ menu on the left of [this page](https://docs.microsoft.com/dotnet/core/install/linux). For other distros, please check the _'Install on Linux'_ menu on the left of [this page](https://docs.microsoft.com/dotnet/core/install/linux).
## Docker
Installing .NET Runtime is not needed. Please refer to the [Docker usage instructions](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Docker.md) page for more information.
## Verify installation (optional) ## Verify installation (optional)
You can check which version of **.NET Runtime** is installed by following these instructions: You can check which version of **.NET Runtime** is installed by running the following command in a terminal:
### Step 1
**Windows:** Open Command Prompt (aka `cmd`)
**macOS and Linux:** Open `Terminal`
### Step 2
Run: `dotnet --info`
If **.NET Runtime** is correctly installed, the command will output the following:
```console
dotnet --info
``` ```
If the **.NET Runtime** is correctly installed, the command will output something similar to the following:
```console
.NET runtimes installed: .NET runtimes installed:
Microsoft.NETCore.App 7.0.x [C:\path\to\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 7.0.x [C:\path\to\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 7.0.x [C:\path\to\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 7.0.x [C:\path\to\dotnet\shared\Microsoft.WindowsDesktop.App]
+8 -451
View File
@@ -2,15 +2,16 @@
Welcome to the getting started page! Welcome to the getting started page!
Here you'll learn how to use every **DiscordChatExporter** (DCE for short) feature. Here you'll learn how to use every **DiscordChatExporter** (DCE for short) feature.
For other things you can do with DCE, check out the [Guides](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Readme.md#Guides) section. For other things you can do with DCE, check out the [Guides](Readme.md#guides) section.
If you still have unanswered questions after reading this page or if you have encountered a problem, please visit our [FAQ & Troubleshooting](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Troubleshooting.md) section. If you still have unanswered questions after reading this page or if you have encountered a problem, please visit our [FAQ & Troubleshooting](Troubleshooting.md) section.
The information presented on this page is valid for **all** platforms. The information presented on this page is valid for **all** platforms.
## GUI or CLI? ## GUI or CLI?
![](https://i.imgur.com/j9OTxRB.png) ![GUI vs CLI](https://i.imgur.com/j9OTxRB.png)
**DCE** has two different versions: **DCE** has two different versions:
- **Graphical User Interface** (**GUI**) - it's the preferred version for newcomers as it is easy to use. - **Graphical User Interface** (**GUI**) - it's the preferred version for newcomers as it is easy to use.
@@ -19,449 +20,12 @@ The information presented on this page is valid for **all** platforms.
You can get it by [downloading](https://github.com/Tyrrrz/DiscordChatExporter/releases/latest) the `DiscordChatExporter.CLI.zip` file. You can get it by [downloading](https://github.com/Tyrrrz/DiscordChatExporter/releases/latest) the `DiscordChatExporter.CLI.zip` file.
If you're not comfortable with **Windows'** Command-line (cmd), please choose the GUI. If you're not comfortable with **Windows'** Command-line (cmd), please choose the GUI.
[**macOS**](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/MacOS.md), [**Linux**](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Linux.md) and [**Docker**](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Docker.md) users can only use the CLI version. [**macOS**](MacOS.md), [**Linux**](Linux.md) and [**Docker**](Docker.md) users can only use the CLI version.
**(Skip to [Using the CLI](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#using-the-cli) or [File Formats](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#file-formats))** There are dedicated guides for each version:
## Using the GUI - [Using the GUI](Using-the-GUI.md)
- [Using the CLI](Using-the-CLI.md)
### Video tutorial
[![Video tutorial](https://i.ytimg.com/vi/jjtu0VQXV7I/hqdefault.jpg)](https://youtube.com/watch?v=jjtu0VQXV7I)
> Video by [NoIntro Tutorials](https://youtube.com/channel/UCFezKSxdNKJe77-hYiuXu3Q).
### Guide
1. After extracting the `.zip`, open `DiscordChatExporter.exe`
2. Please refer to the on-screen instructions to get your token, then paste your token in the upper text box and hit ENTER or click the arrow (→).
> **Warning**:
> **Never share your token!**
> A token gives full access to an account, treat it like a password.
<img src="https://i.imgur.com/SuLQ5tZ.png" height="400"/>
3. DCE will display your Direct Messages and a sidebar with your server list. Select the channel you would like to export, then click the ![](https://i.imgur.com/dnTOlDa.png) button to continue.
> **Note**:
> You can export multiple channels at once by holding `CTRL` or `SHIFT` while selecting.
> You can also double-click a channel to export it without clicking the ![](https://i.imgur.com/dnTOlDa.png) button.
<img src="https://i.imgur.com/JHMFRh2.png" height="400"/>
4. In this screen you can customize the following:
- **Export format** - HTML (Dark), HTML (Light), TXT, CSV and JSON
Click the menu button (☰) to see more options:
- **Date range (after/before)** (Optional) - If set, only messages sent in the provided date range will be exported. Only one value (either after or before) is required if you want to use this option.
> **Note**:
> Please note that the time defaults to **12:00 AM** (midnight/00:00). This means that if you choose to export between Sep 17th and Sep 18th, messages from Sep 18th won't be exported.
- **Filter** (Optional) - Special notation for filtering the messages that get included in the export. See [Message filters](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Message-filters.md) for more info.
- **Messages per partition** (Optional) - Split output into partitions, each limited to this number of messages (e.g. 100) or file size (e.g. 10mb). For example, a channel with 36 messages set to be partitioned every 10 messages will output 4 files.
- **Download assets** (Optional) - If this option is set, the export will include additional files such as user avatars, attached files, images, etc.
Only files that are referenced by the export are downloaded, which means that, for example, user avatars will not be downloaded when using the plain text (TXT) export format.
A folder containing the assets will be created along with the exported chat. They must be kept together.
5. Click `EXPORT` to export.
<img src="https://i.imgur.com/KPgMH2D.png" height="400"/><img src="https://i.imgur.com/mtUFojS.png" height="400"/>
### Settings
**Auto-updates**
Perform automatic updates on every launch.
Default: Enabled
> **Note**:
> Keep this option enabled to receive the latest features and bug fixes!
**Dark mode**
Use darker colors in the UI (User Interface).
Default: Disabled
**Save token**
Persist last used token between sessions.
Default: Enabled
**Reuse downloaded assets**
Reuse already downloaded assets to skip redundant requests.
Default: Disabled
**Date format**
You can customize how dates are formatted in the exported files in the settings menu ().
- The default one is `17-Sep-19 11:34 PM` - `dd-MMM-yy hh:mm tt`
- To change it to `09-17-19 11:34 PM` use `MM-dd-yy hh:mm tt`
- To change it to `17/09/2019 23:34` use `dd/MM/yyyy HH:mm`
- To change it to `2019-09-17 23:34:05.6534` use `yyyy-MM-dd HH:mm:ss.ffff`
- To change it to UTC `2019-09-18 04:34:05Z` use `u`
- To display the time zone, add `K`. E.g. to change it to `17-Sep-19 11:34 PM (UTC-05:00)` use `dd-MMM-yy hh:mm tt (UTCK)`
- To change it to Unix time `1568694845` use `unix`
- To change it to Unix time in milliseconds `1568694845653` use `unixms`
More info about .NET date formats [here](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings).
**Parallel limit**
The number of channels can be exported at the same time.
Default: 1
> **Note**:
> Try to keep this number low so that your account doesn't get flagged.
**(Skip to [File Formats](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#file-formats))**
## Using the CLI
> **Note**:
> Make sure you have [.NET Core installed](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Dotnet.md) before attempting to run the commands below.
> **Docker** users, please refer to the [Docker usage instructions](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Docker.md).
1. After extracting the `.zip`, open Command Prompt, aka `cmd` (`Terminal` on **macOS** and **Linux**).
2. Change the current directory to DCE's folder with `cd C:\path\to\directory`, then press ENTER to run the command.
**Windows** users can quickly get the directory's path by clicking the address bar while inside the folder.
![](https://i.imgur.com/XncnhC2.gif)
**macOS** users can select the `.exe`, hit Command+I (⌘I), and copy what's after `Where:` to get the directory
![](https://camo.githubusercontent.com/3c51a904b0099c9f68a4797461d4a7914902fc04/68747470733a2f2f692e696d6775722e636f6d2f323975364e79782e706e67)
You can also drag and drop the folder on **every platform**.
![](https://i.imgur.com/sOpZQAb.gif)
3. Now we're ready to run the commands. The examples on this page follow the Windows file path format, change the file paths according to your system.
Let's do the following to list DCE's options:
Type the following in Command Prompt (Terminal), then press ENTER to run it:
```powershell
dotnet DiscordChatExporter.Cli.dll
```
> **Docker** users, please refer to the [Docker usage instructions](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Docker.md).
### DCE.CLI commands
| Command | Description |
| ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| [export](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#export) | Exports a channel |
| [exportdm](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#exportdm) | Exports all direct message channels |
| [exportguild](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#exportguild) | Exports all channels within the specified server |
| [exportall](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#exportall) | Exports all accessible channels |
| [channels](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#channels) | Outputs the list of channels in the given server |
| [dm](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#dm) | Outputs the list of direct message channels |
| [guilds](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#guilds) | Outputs the list of accessible servers |
| [guide](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#guide) | Explains how to obtain token, guild, and channel ID |
To use the commands, you'll need a token. For the instructions on how to get a token, please refer to [this page](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md), or run `dotnet DiscordChatExporter.Cli.dll guide`.
To get help with a specific command, please run:
```powershell
dotnet DiscordChatExporter.Cli.dll command -h
```
#### `export`
| | Option | Description |
| ------ | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **\*** | [-c](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#basic-usage) | [Channel ID(s)](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#how-to-get-guild-id-or-guild-channel-id) |
| **\*** | [-t](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#basic-usage) | [Authorization token](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | [-o](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#changing-the-output-filename) | Output file or directory path |
| | [-f](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#changing-the-format) | [Output file format](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#file-formats). Default: HtmlDark |
| | [--after](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-ranges) | Only include messages sent after this date |
| | [--before](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-ranges) | Only include messages sent before this date |
| | [-p](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#partitioning) | Split output into partitions, each limited to this number of messages (e.g. 100) or file size (e.g. 10mb) |
| | [--filter](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Message-filters.md) | Special notation for filtering the messages that get included in the export |
| | [--media](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#Downloading-assets) | Download assets referenced by the export (user avatars, attached files, embedded images, etc.). Default: false |
| | [--reuse-media](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#Reuse-assets) | Reuse previously downloaded assets to avoid redundant requests. Default: false. |
| | [--dateformat](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-formats) | Format used when writing dates. |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
With this command you can export Server Channels and Direct Messages.
##### Basic usage
You can quickly export with DCE's default settings by using just `-t token` and `-c channelid`.
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555
```
##### Changing the format
You can change the export format to `HtmlDark`, `HtmlLight`, `PlainText` `Json` or `Csv` with `-f format`. The default format is `HtmlDark`.
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -f Json
```
##### Changing the output filename
You can change the filename by using `-o name.ext`. e.g. for the `HTML` format:
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -o myserver.html
```
##### Changing the output directory
You can change the export directory by using `-o` and providing a path that ends with a slash or does not have a file extension.
If any of the folders in the path have a space in its name, escape them with quotes (").
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -o "C:\Discord Exports"
```
##### Changing the filename and output directory
You can change both the filename and export directory by using `-o directory\name.ext`.
Note that the filename must have an extension, otherwise it will be considered a directory name.
If any of the folders in the path have a space in its name, escape them with quotes (").
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -o "C:\Discord Exports\myserver.html"
```
##### Generating the filename and output directory dynamically
You can use template tokens to generate the output file path based on the guild and channel metadata.
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -o "C:\Discord Exports\%G\%T\%C.html"
```
Assuming you are exporting a channel named `"my-channel"` in the `"Text channels"` category from a server called `"My server"`, you will get the following output file path: `C:\Discord Exports\My server\Text channels\my-channel.html`
Here is the full list of supported template tokens:
- `%g` - guild ID
- `%G` - guild name
- `%t` - category ID
- `%T` - category name
- `%c` - channel ID
- `%C` - channel name
- `%p` - channel position
- `%P` - category position
- `%a` - the "after" date
- `%b` - the "before" date
- `%%` - escapes `%`
##### Partitioning
You can use partitioning to split files after a given number of messages or file size.
For example, a channel with 36 messages set to be partitioned every 10 messages will output 4 files.
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -p 10
```
A 45mb channel set to be partitioned every 20mb will output 3 files.
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -p 20mb
```
##### Downloading assets
If this option is set, the export will include additional files such as user avatars, attached files, images, etc.
Only files that are referenced by the export are downloaded, which means that, for example, user avatars will not be downloaded when using the plain text (TXT) export format.
A folder containing the assets will be created along with the exported chat. They must be kept together.
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --media
```
##### Reuse assets
Previously downloaded assets can be reused to skip redundant downloads as long as the chat is always exported to the same folder. Using this option can speed up future exports. This option requires the `--media` option.
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --media --reuse-media
```
##### Date formats
This setting changes how dates are formatted in the exported files.
- The default one is `17-Sep-19 11:34 PM` - `dd-MMM-yy hh:mm tt`
- To change it to `09-17-19 11:34 PM` use `MM-dd-yy hh:mm tt`
- To change it to `17/09/2019 23:34` use `dd/MM/yyyy HH:mm`
- To change it to `2019-09-17 23:34:05.6534` use `yyyy-MM-dd HH:mm:ss.ffff`
- To change it to UTC `2019-09-18 04:34:05Z` use `u`
- To display the time zone, add `K`. E.g. to change it to `17-Sep-19 11:34 PM (UTC-05:00)` use `dd-MMM-yy hh:mm tt (UTCK)`
- To change it to Unix time `1568694845` use `unix`
- To change it to Unix time in milliseconds `1568694845653` use `unixms`
More info about .NET date formats [here](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings).
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --dateformat "yyyy-MM-dd HH:mm"
```
> Special thanks to [@andrewkolos](https://github.com/andrewkolos) for adding the Unix options
##### Date ranges
**Messages sent before a date**
Use `--before` to export messages sent before the provided date. E.g. messages sent before September 18th, 2019:
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --before 2019-09-18
```
**Messages sent after a date**
Use `--after` to export messages sent after the provided date. E.g. messages sent after September 17th, 2019 11:34 PM:
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --after "2019-09-17 23:34"
```
**Messages sent in a date range**
Use `--before` and `--after` to export messages sent during the provided date range. E.g. messages sent between September 17th, 2019 11:34 PM and September 18th:
```powershell
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --after "2019-09-17 23:34" --before "2019-09-18"
```
You can try different formats like `17-SEP-2019 11:34 PM` or even refine your ranges down to milliseconds `17-SEP-2019 23:45:30.6170`!
Don't forget to quote (") the date if it has spaces!
More info about .NET date formats [here](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings).
#### `exportdm`
| | Option | Description |
| ------ | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **\*** | [-t](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#basic-usage) | [Authorization token](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | --parallel | Limits how many channels can be exported in parallel. Try to keep this number low so that your account doesn't get flagged. Default: 1 |
| | [-o](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#changing-the-output-filename) | Output file or directory path |
| | [-f](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#changing-the-format) | [Output file format](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#file-formats). Default: HtmlDark |
| | [--after](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-ranges) | Only include messages sent after this date |
| | [--before](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-ranges) | Only include messages sent before this date |
| | [-p](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#partitioning) | Split output into partitions, each limited to this number of messages (e.g. 100) or file size (e.g. 10mb) |
| | [--filter](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Message-filters.md) | Special notation for filtering the messages that get included in the export |
| | [--media](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#Downloading-assets) | Download assets referenced by the export (user avatars, attached files, embedded images, etc.). Default: false |
| | [--reuse-media](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#Reuse-assets) | Reuse previously downloaded assets to avoid redundant requests. Default: false. |
| | [--dateformat](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-formats) | Date format used in output |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
This command exports all your Direct Messages.
#### `exportguild`
| | Option | Description |
| ------ | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **\*** | -g | [Server ID](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#how-to-get-guild-id-or-guild-channel-id) |
| **\*** | [-t](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#basic-usage) | [Authorization token](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | --parallel | Limits how many channels can be exported in parallel. Try to keep this number low so that your account doesn't get flagged. Default: 1 |
| | [-o](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#changing-the-output-filename) | Output file or directory path |
| | [-f](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#changing-the-format) | [Output file format](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#file-formats). Default: HtmlDark |
| | [--after](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-ranges) | Only include messages sent after this date |
| | [--before](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-ranges) | Only include messages sent before this date |
| | [-p](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#partitioning) | Split output into partitions, each limited to this number of messages (e.g. 100) or file size (e.g. 10mb) |
| | [--filter](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Message-filters.md) | Special notation for filtering the messages that get included in the export |
| | [--media](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#Downloading-assets) | Download assets referenced by the export (user avatars, attached files, embedded images, etc.). Default: false |
| | [--reuse-media](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#Reuse-assets) | Reuse previously downloaded assets to avoid redundant requests. Default: false. |
| | [--dateformat](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-formats) | Date format used in output |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
This command exports all channels of a Server.
#### `exportall`
| | Option | Description |
| ------ | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **\*** | [-t](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#basic-usage) | [Authorization token](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | --include-dm | Include direct message channels. Default: true |
| | --parallel | Limits how many channels can be exported in parallel. Try to keep this number low so that your account doesn't get flagged. Default: 1 |
| | [-o](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#changing-the-output-filename) | Output file or directory path |
| | [-f](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#changing-the-format) | [Output file format](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#file-formats). Default: HtmlDark |
| | [--after](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-ranges) | Only include messages sent after this date |
| | [--before](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-ranges) | Only include messages sent before this date |
| | [-p](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#partitioning) | Split output into partitions, each limited to this number of messages (e.g. 100) or file size (e.g. 10mb) |
| | [--filter](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Message-filters.md) | Special notation for filtering the messages that get included in the export |
| | [--media](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#Downloading-assets) | Download assets referenced by the export (user avatars, attached files, embedded images, etc.). Default: false |
| | [--reuse-media](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#Reuse-assets) | Reuse previously downloaded assets to avoid redundant requests. Default: false. |
| | [--dateformat](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#date-formats) | Date format used in output |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
This command exports all accessible channels, including server channels and DMs.
To exclude DMs, add the `--include-dm false` option:
```powershell
dotnet DiscordChatExporter.Cli.dll exportall -t "mfa.Ifrn" --include-dm false
```
#### `channels`
| | Option | Description |
| ------ | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **\*** | -g | [Server ID](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#how-to-get-guild-id-or-guild-channel-id) |
| **\*** | [-t](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#basic-usage) | [Authorization token](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
This command outputs the server channels in the following format:
`Channel ID | Channel Name`
To save the output to a file, run the command below. If the file already exists, it will be overwritten.
```powershell
dotnet DiscordChatExporter.Cli.dll channels -t "mfa.Ifrn" -g 21814 > C:\path\to\output.txt
```
#### `dm`
| | Option | Description |
| ------ | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **\*** | [-t](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#basic-usage) | [Authorization token](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
This command outputs the list of Direct Messages.
To save the output to a file, run the command with `> C:\path\…` like the example below. If the file already exists, it will be overwritten.
```powershell
dotnet DiscordChatExporter.Cli.dll dm -t "mfa.Ifrn" > C:\path\to\output.txt
```
#### `guilds`
| | Option | Description |
| ------ | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **\*** | [-t](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#basic-usage) | [Authorization token](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
This command outputs a list of your Server List.
To save the output to a file, run the command with `> C:\path\…` like the example below. If the file already exists, it will be overwritten.
```powershell
dotnet DiscordChatExporter.Cli.dll guilds -t "mfa.Ifrn" > C:\path\to\output.txt
```
#### `guide`
This command explains [how to get your token, guild, and channel IDs](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md).
## File formats ## File formats
@@ -497,10 +61,3 @@ You can open `.json` files with a text editor, such as Notepad.
The CSV format allows for easy parsing of the chat log. Depending on your needs, the JSON format might be better. The CSV format allows for easy parsing of the chat log. Depending on your needs, the JSON format might be better.
You can open `.csv` files with a text editor, such as Notepad, or a spreadsheet app, like Microsoft Excel and Google Sheets. You can open `.csv` files with a text editor, such as Notepad, or a spreadsheet app, like Microsoft Excel and Google Sheets.
**([Back to top](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#getting-started))**
---
Further reading: [.NET date formats](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings)
Special thanks to [@Yudi](https://github.com/Yudi)
+10 -4
View File
@@ -2,7 +2,7 @@
## Installing .NET Runtime ## Installing .NET Runtime
Please follow the [instructions provided here](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Dotnet.md). Please follow the [instructions provided here](Dotnet.md).
## Downloading and using DiscordChatExporter.Cli ## Downloading and using DiscordChatExporter.Cli
@@ -11,10 +11,16 @@ Please follow the [instructions provided here](https://github.com/Tyrrrz/Discord
3. `cd` into the extracted folder. You can do this in Terminal by typing `cd`, then press the SPACE key, drag and drop the extracted folder into the Terminal window, and press the ENTER key. 3. `cd` into the extracted folder. You can do this in Terminal by typing `cd`, then press the SPACE key, drag and drop the extracted folder into the Terminal window, and press the ENTER key.
4. Replace `TOKEN` and `CHANNEL`, then execute this command to export: 4. Replace `TOKEN` and `CHANNEL`, then execute this command to export:
``` ```console
dotnet DiscordChatExporter.Cli.dll export -t TOKEN -c CHANNEL dotnet DiscordChatExporter.Cli.dll export -t TOKEN -c CHANNEL
``` ```
> [How to get Token and Channel IDs](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md). If the above command throws a "Permission denied" error, execute this command to fix the permissions:
There's much more you can do with DCE.CLI! Read the [CLI explained](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#dcecli-commands-) page to get started. ```console
chmod 644 *.dll DiscordChatExporter.*
```
> [How to get Token and Channel IDs](Token-and-IDs.md).
There's much more you can do with DCE.CLI! Read the [CLI explained](Using-the-CLI.md) page to get started.
+4 -4
View File
@@ -4,7 +4,7 @@
## Installing .NET Runtime ## Installing .NET Runtime
Please follow the [instructions provided here](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Dotnet.md). Please follow the [instructions provided here](Dotnet.md).
## Downloading and using DiscordChatExporter.Cli ## Downloading and using DiscordChatExporter.Cli
@@ -13,10 +13,10 @@ Please follow the [instructions provided here](https://github.com/Tyrrrz/Discord
3. In the Terminal window, type `cd` , press the SPACE key, then drag and drop the extracted folder into the window, then press the RETURN key. 3. In the Terminal window, type `cd` , press the SPACE key, then drag and drop the extracted folder into the window, then press the RETURN key.
4. Execute the following command to export, replacing `TOKEN` and `CHANNEL` with your own values: 4. Execute the following command to export, replacing `TOKEN` and `CHANNEL` with your own values:
``` ```console
dotnet DiscordChatExporter.Cli.dll export -t TOKEN -c CHANNEL dotnet DiscordChatExporter.Cli.dll export -t TOKEN -c CHANNEL
``` ```
> [How to get Token and Channel IDs](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md). > [How to get Token and Channel IDs](Token-and-IDs.md).
There's much more you can do with DCE.CLI! Read the [CLI explained](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#dcecli-commands-) page to get started. There's much more you can do with DCE.CLI! Read the [CLI explained](Using-the-CLI.md) page to get started.
+17 -17
View File
@@ -8,79 +8,79 @@ To configure a filter, specify it in advanced export parameters when using the G
- Filter by user - Filter by user
``` ```console
from:Tyrrrz from:Tyrrrz
``` ```
- Filter by user (with discriminator) - Filter by user (with discriminator)
``` ```console
from:Tyrrrz#1234 from:Tyrrrz#1234
``` ```
- Filter by message content (allowed values: `link`, `embed`, `file`, `video`, `image`, `sound`) - Filter by message content (allowed values: `link`, `embed`, `file`, `video`, `image`, `sound`)
``` ```console
has:image has:image
``` ```
- Filter by mentioned user (same rules apply as with `from:` filter) - Filter by mentioned user (same rules apply as with `from:` filter)
``` ```console
mentions:Tyrrrz#1234 mentions:Tyrrrz#1234
``` ```
- Filter by contained text (has word "hello" and word "world" somewhere in the message text): - Filter by contained text (has word "hello" and word "world" somewhere in the message text):
``` ```console
hello world hello world
``` ```
- Filter by contained text (has the string "hello world" somewhere in the message text): - Filter by contained text (has the string "hello world" somewhere in the message text):
``` ```console
"hello world" "hello world"
``` ```
- Combine multiple filters ('and'): - Combine multiple filters ('and'):
``` ```console
from:Tyrrrz has:image from:Tyrrrz has:image
``` ```
- Same thing but with an explicit operator: - Same thing but with an explicit operator:
``` ```console
from:Tyrrrz & has:image from:Tyrrrz & has:image
``` ```
- Combine multiple filters ('or'): - Combine multiple filters ('or'):
``` ```console
from:Tyrrrz | from:"96-LB" from:Tyrrrz | from:"96-LB"
``` ```
- Combine multiple filters using groups: - Combine multiple filters using groups:
``` ```console
(from:Tyrrrz | from:"96-LB") has:image (from:Tyrrrz | from:"96-LB") has:image
``` ```
- Negate a filter: - Negate a filter:
``` ```console
-from:Tyrrrz | -has:image -from:Tyrrrz | -has:image
``` ```
- Negate a grouped filter: - Negate a grouped filter:
``` ```console
-(from:Tyrrrz has:image) -(from:Tyrrrz has:image)
``` ```
- Escape special characters (`-` is escaped below, so it's not parsed as negation operator): - Escape special characters (`-` is escaped below, so it's not parsed as negation operator):
``` ```console
from:96\-LB from:96\-LB
``` ```
@@ -88,18 +88,18 @@ from:96\-LB
In most cases, you will need to enclose your filter in quotes (`"`) to escape characters that may have special meaning in your shell: In most cases, you will need to enclose your filter in quotes (`"`) to escape characters that may have special meaning in your shell:
``` ```console
DiscordChatExporter.Cli export [...] --filter "from:Tyrrrz has:image" DiscordChatExporter.Cli export [...] --filter "from:Tyrrrz has:image"
``` ```
If you need to include quotes inside the filter itself as well, use single quotes (`'`) for those instead: If you need to include quotes inside the filter itself as well, use single quotes (`'`) for those instead:
``` ```console
DiscordChatExporter.Cli export [...] --filter "from:Tyrrrz 'hello world'" DiscordChatExporter.Cli export [...] --filter "from:Tyrrrz 'hello world'"
``` ```
Additionally, negated filters (those that start with `-`) may cause parsing issues even when enclosed in quotes. To avoid this, use the tilde (`~`) character instead of the dash (`-`): Additionally, negated filters (those that start with `-`) may cause parsing issues even when enclosed in quotes. To avoid this, use the tilde (`~`) character instead of the dash (`-`):
``` ```console
DiscordChatExporter.Cli export [...] --filter ~from:Tyrrrz DiscordChatExporter.Cli export [...] --filter ~from:Tyrrrz
``` ```
+16 -16
View File
@@ -2,21 +2,21 @@
## Installation & Usage ## Installation & Usage
- [Get .NET Core Runtime](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Dotnet.md) (Required for CLI; Installed automatically for GUI; Not required in Docker) - [Get .NET Core Runtime](Dotnet.md) (Required for CLI; Installed automatically for GUI; Not required in Docker)
- [Windows](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#gui-or-cli) | [macOS](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/MacOS.md) | [Linux](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Linux.md) | [Docker](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Docker.md) - [Windows](Getting-started.md#gui-or-cli) | [macOS](MacOS.md) | [Linux](Linux.md) | [Docker](Docker.md)
- Getting started: - Getting started:
- [Using the GUI](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#using-the-gui) - [Using the GUI](Using-the-CLI.md)
- [Using the CLI](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#using-the-cli) - [Using the CLI](Using-the-CLI.md)
- [File formats](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#file-formats) - [File formats](Getting-started.md#file-formats)
## Guides ## Guides
- [How to get Token and Channel IDs](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md) - [How to get Token and Channel IDs](Token-and-IDs.md)
- [How to use message filters](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Message-filters.md) - [How to use message filters](Message-filters.md)
- Export scheduling with CLI: - Export scheduling with CLI:
- [Windows](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Scheduling-Windows.md) - [Windows](Scheduling-Windows.md)
- [macOS](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Scheduling-MacOS.md) - [macOS](Scheduling-MacOS.md)
- [Linux](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Scheduling-Linux.md) - [Linux](Scheduling-Linux.md)
## Video tutorial ## Video tutorial
@@ -26,9 +26,9 @@
## FAQ & Troubleshooting ## FAQ & Troubleshooting
- [General questions](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Troubleshooting.md#general) - [General questions](Troubleshooting.md#general)
- [First steps help](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Troubleshooting.md#first-steps) - [First steps help](Troubleshooting.md#first-steps)
- [It's crashing/failing](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Troubleshooting.md#DCE-is-crashingfailing) - [It's crashing/failing](Troubleshooting.md#DCE-is-crashingfailing)
- [.NET Core Runtime is required](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Troubleshooting.md#net-core-runtime-is-required) - [.NET Core Runtime is required](Troubleshooting.md#net-core-runtime-is-required)
- [Errors](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Troubleshooting.md#errors) - [Errors](Troubleshooting.md#errors)
- [**More help**](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Troubleshooting.md) - [**More help**](Troubleshooting.md)
+5 -7
View File
@@ -1,10 +1,8 @@
# Scheduling exports with Cron # Scheduling exports with Cron
Make sure you already have **DiscordChatExporter.CLI** and **.NET Core** properly installed ([instructions here](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Linux.md)). Make sure you already have **DiscordChatExporter.CLI** and **.NET Core** properly installed ([instructions here](Linux.md)).
You can use Cron on macOS, but [this method](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/scheduling-MacOS.md) is preferred. ## Creating the script
---
1. Open Terminal and create a new text file with `nano /path/to/DiscordChatExporter/cron.sh` 1. Open Terminal and create a new text file with `nano /path/to/DiscordChatExporter/cron.sh`
@@ -66,8 +64,8 @@ exit 0
3. Replace: 3. Replace:
- `tokenhere` with your [Token](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md). - `tokenhere` with your [Token](Token-and-IDs.md).
- `channelhere` with a [Channel ID](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md). - `channelhere` with a [Channel ID](Token-and-IDs.md).
- `dceFOLDERpathhere` with DCE's **directory path** (e.g. `/path/to/folder`, NOT `/path/to/folder/DiscordChatExporter.dll`). - `dceFOLDERpathhere` with DCE's **directory path** (e.g. `/path/to/folder`, NOT `/path/to/folder/DiscordChatExporter.dll`).
- `filenamehere` with the exported channel's filename, without spaces. - `filenamehere` with the exported channel's filename, without spaces.
- `dirhere` with the export directory (e.g. /home/user/Documents/Discord\ Exports). - `dirhere` with the export directory (e.g. /home/user/Documents/Discord\ Exports).
@@ -108,7 +106,7 @@ Verify your cron time [here](https://crontab.guru).
--- ---
**Extra information** **Additional information**
The week starts on Sunday. 0 = SUN, 1 = MON ... 7 = SUN. The week starts on Sunday. 0 = SUN, 1 = MON ... 7 = SUN.
+42 -42
View File
@@ -2,7 +2,7 @@
Scheduling on macOS is a bit tricky, but it should work if you follow the instructions accordingly. Scheduling on macOS is a bit tricky, but it should work if you follow the instructions accordingly.
Make sure you already have **DiscordChatExporter.CLI** and **.NET Core** properly installed ([instructions here](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/macOS-usage-instructions.md)). Make sure you already have **DiscordChatExporter.CLI** and **.NET Core** properly installed ([instructions here](MacOS.md)).
## Creating the script ## Creating the script
@@ -70,8 +70,8 @@ exit 0
4. Replace: 4. Replace:
- `tokenhere` with your [Token](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md) - `tokenhere` with your [Token](Token-and-IDs.md)
- `channelhere` with a [Channel ID](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md) - `channelhere` with a [Channel ID](Token-and-IDs.md)
- `dceFOLDERpathhere` with DCE's **directory's path** (e.g. `/Users/user/Desktop/DiscordChatExporterFolder`, NOT `/Users/user/Desktop/DiscordChatExporterFolder/DiscordChatExporter.DLL`) - `dceFOLDERpathhere` with DCE's **directory's path** (e.g. `/Users/user/Desktop/DiscordChatExporterFolder`, NOT `/Users/user/Desktop/DiscordChatExporterFolder/DiscordChatExporter.DLL`)
- `filenamehere` with the exported channel's filename, without spaces - `filenamehere` with the exported channel's filename, without spaces
- `dirhere` with the directory you want the files to be saved at (e.g. `/Users/user/Documents/Discord\ Exports`) - `dirhere` with the directory you want the files to be saved at (e.g. `/Users/user/Documents/Discord\ Exports`)
@@ -88,7 +88,7 @@ After copying and pasting, make sure the file/folder name is not missing. If a f
- `/Users/user/Documents/Discord\ Exports` - Correct ✓ - `/Users/user/Documents/Discord\ Exports` - Correct ✓
- `/Users/user/Desktop/DiscordChatExporter` - Correct ✓ - `/Users/user/Desktop/DiscordChatExporter` - Correct ✓
![](https://i.imgur.com/29u6Nyx.png) ![Screenshot of mac info window](https://i.imgur.com/29u6Nyx.png)
5. Save the file as `filename.sh`, not `.txt` 5. Save the file as `filename.sh`, not `.txt`
6. Open Terminal.app, type `chmod +x`, press the SPACE key, then drag & drop the `filename.sh` into the Terminal window and hit RETURN. You may be prompted for your password, and you won't be able to see it as you type. 6. Open Terminal.app, type `chmod +x`, press the SPACE key, then drag & drop the `filename.sh` into the Terminal window and hit RETURN. You may be prompted for your password, and you won't be able to see it as you type.
@@ -101,13 +101,13 @@ Open TextEdit, make a Plain Text (⇧⌘T) and then paste the following into it:
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"> <plist version="1.0">
<dict> <dict>
<key>Label</key> <key>Label</key>
<string>local.discordchatexporter</string> <string>local.discordchatexporter</string>
<key>Program</key> <key>Program</key>
<string>/path/to/filename.sh</string> <string>/path/to/filename.sh</string>
REPLACEME REPLACEME
</dict> </dict>
</plist> </plist>
``` ```
@@ -138,16 +138,16 @@ The following example is to export every 3600 seconds (1 hour), replace the inte
```xml ```xml
<key>StartCalendarInterval</key> <key>StartCalendarInterval</key>
<dict> <dict>
<key>Weekday</key> <key>Weekday</key>
<integer>0</integer> <integer>0</integer>
<key>Month</key> <key>Month</key>
<integer>0</integer> <integer>0</integer>
<key>Day</key> <key>Day</key>
<integer>0</integer> <integer>0</integer>
<key>Hour</key> <key>Hour</key>
<integer>0</integer> <integer>0</integer>
<key>Minute</key> <key>Minute</key>
<integer>0</integer> <integer>0</integer>
</dict> </dict>
``` ```
@@ -168,17 +168,17 @@ Omitted keys are interpreted as wildcards, for example, if you delete the Minute
Be aware that if you set the day to '31', the script will only run on months that have the 31st day. Be aware that if you set the day to '31', the script will only run on months that have the 31st day.
**Check the examples below ([or skip to step 3 (loading the file)](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/scheduling-MacOS.md#3-loading-the-plist-into-launchctl)):** **Check the examples below ([or skip to step 3 (loading the file)](#3-loading-the-plist-into-launchctl)):**
Export everyday at 5:15 PM: Export everyday at 5:15 PM:
```xml ```xml
<key>StartCalendarInterval</key> <key>StartCalendarInterval</key>
<dict> <dict>
<key>Hour</key> <key>Hour</key>
<integer>17</integer> <integer>17</integer>
<key>Minute</key> <key>Minute</key>
<integer>15</integer> <integer>15</integer>
</dict> </dict>
``` ```
@@ -188,8 +188,8 @@ Every 15 minutes of an hour (xx:15):
```xml ```xml
<key>StartCalendarInterval</key> <key>StartCalendarInterval</key>
<dict> <dict>
<key>Minute</key> <key>Minute</key>
<integer>15</integer> <integer>15</integer>
</dict> </dict>
``` ```
@@ -199,20 +199,20 @@ Every Sunday at midnight and every Wednesday full hour (xx:00). Notice the inclu
```xml ```xml
<key>StartCalendarInterval</key> <key>StartCalendarInterval</key>
<array> <array>
<dict> <dict>
<key>Weekday</key> <key>Weekday</key>
<integer>0</integer> <integer>0</integer>
<key>Hour</key> <key>Hour</key>
<integer>00</integer> <integer>00</integer>
<key>Minute</key> <key>Minute</key>
<integer>00</integer> <integer>00</integer>
</dict> </dict>
<dict> <dict>
<key>Weekday</key> <key>Weekday</key>
<integer>3</integer> <integer>3</integer>
<key>Minute</key> <key>Minute</key>
<integer>00</integer> <integer>00</integer>
</dict> </dict>
</array> </array>
``` ```
+11 -7
View File
@@ -2,10 +2,12 @@
We'll be using [DiscordChatExporter CLI](https://github.com/Tyrrrz/DiscordChatExporter/releases/latest), PowerShell, and Task Scheduler. We'll be using [DiscordChatExporter CLI](https://github.com/Tyrrrz/DiscordChatExporter/releases/latest), PowerShell, and Task Scheduler.
## Creating the script
1. Open a text editor such as Notepad and paste: 1. Open a text editor such as Notepad and paste:
```powershell ```console
# Info: https://github.com/Tyrrrz/DiscordChatExporter/wiki # Info: https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs
$TOKEN = "tokenhere" $TOKEN = "tokenhere"
$CHANNEL = "channelhere" $CHANNEL = "channelhere"
@@ -31,8 +33,8 @@ exit
2. Replace: 2. Replace:
- `tokenhere` with your [Token](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md) - `tokenhere` with your [Token](Token-and-IDs.md)
- `channelhere` with a [Channel ID](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md) - `channelhere` with a [Channel ID](Token-and-IDs.md)
- `exefolderhere` with the .exe **directory's path** (e.g. C:\Users\User\Desktop\DiscordChatExporter) - `exefolderhere` with the .exe **directory's path** (e.g. C:\Users\User\Desktop\DiscordChatExporter)
- `filenamehere` with a filename without spaces - `filenamehere` with a filename without spaces
- `dirhere` with the export directory (e.g. C:\Users\User\Documents\Exports) - `dirhere` with the export directory (e.g. C:\Users\User\Documents\Exports)
@@ -40,7 +42,9 @@ exit
Make sure not to delete the quotes (") Make sure not to delete the quotes (")
3. Save the file as `filename.ps1` not `.txt` 3. Save the file as `filename.ps1`, not as `.txt`
> **Note**: You can also modify the script to use other options, such as `include-threads` or switch to a different command, e. g. `exportguild`.
## Export at Startup ## Export at Startup
@@ -49,14 +53,14 @@ Make sure not to delete the quotes (")
## Scheduling with Task Scheduler ## Scheduling with Task Scheduler
Please notice your computer must be turned on so the exportation can occur. Please note that your computer must be turned on for the export to happen.
1. Press Windows + R, type `taskschd.msc` and press ENTER 1. Press Windows + R, type `taskschd.msc` and press ENTER
2. Select `Task Scheduler Library`, create a Basic Task, and follow the instructions on-screen 2. Select `Task Scheduler Library`, create a Basic Task, and follow the instructions on-screen
<img src="https://i.imgur.com/MHRVGDi.png" height="500"/> <img src="https://i.imgur.com/MHRVGDi.png" height="500"/>
[ ![](https://i.imgur.com/m2DKhA8.png) ](https://i.imgur.com/3gHkF0t.png) ![Screenshot from Task Scheduler](https://i.imgur.com/m2DKhA8.png)
3. At 'Start a Program', write `powershell -file -ExecutionPolicy ByPass -WindowStyle Hidden "C:\path\to\filename.ps1"` in the Program/script text box 3. At 'Start a Program', write `powershell -file -ExecutionPolicy ByPass -WindowStyle Hidden "C:\path\to\filename.ps1"` in the Program/script text box
+38 -4
View File
@@ -14,6 +14,23 @@ Prerequisite step: Navigate to [discord.com](https://discord.com) and login.
#### In Chrome #### In Chrome
##### Using the console
1. <img width="500" align="right" src="https://i.imgur.com/zdDwIT5.jpg" />Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd> (<kbd>⌥</kbd>+<kbd>⌘</kbd>+<kbd>I</kbd> on macOS). Chrome's [DevTools](https://developer.chrome.com/docs/devtools/overview) tools will display.
<br clear="right" />
<br />
2. Click the `Console` tab. The [console](https://developer.chrome.com/docs/devtools/console/) will open.
3. Type
```console
(webpackChunkdiscord_app.push([[''],{},e=>{m=[];for(let c in e.c)m.push(e.c[c])}]),m).find(m=>m?.exports?.default?.getToken!==void 0).exports.default.getToken()
```
into the console and press <kbd>Enter</kbd>. The console will display your user token.
##### Using the network monitor ##### Using the network monitor
1. <img width="500" align="right" src="https://i.imgur.com/zdDwIT5.jpg" />Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd> (<kbd>⌥</kbd>+<kbd>⌘</kbd>+<kbd>I</kbd> on macOS). Chrome's [DevTools](https://developer.chrome.com/docs/devtools/overview) tools will display. 1. <img width="500" align="right" src="https://i.imgur.com/zdDwIT5.jpg" />Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd> (<kbd>⌥</kbd>+<kbd>⌘</kbd>+<kbd>I</kbd> on macOS). Chrome's [DevTools](https://developer.chrome.com/docs/devtools/overview) tools will display.
@@ -90,6 +107,23 @@ Prerequisite step: Navigate to [discord.com](https://discord.com) and login.
#### In Firefox #### In Firefox
##### Using the console
1. <img width="500" align="right" src="https://i.imgur.com/O34nwdG.png" />Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>K</kbd> (<kbd>⌥</kbd>+<kbd>⌘</kbd>+<kbd>K</kbd> on macOS). Firefoxs [web developer tools](https://firefox-source-docs.mozilla.org/devtools-user/) will display at the bottom of the window, and the [web console](https://firefox-source-docs.mozilla.org/devtools-user/console/index.html) will display.
<br clear="right" />
<br />
2. Click the `Console` tab. The [console](https://firefox-source-docs.mozilla.org/devtools-user/console/index.html) will open.
1. Type
```console
(webpackChunkdiscord_app.push([[''],{},e=>{m=[];for(let c in e.c)m.push(e.c[c])}]),m).find(m=>m?.exports?.default?.getToken!==void 0).exports.default.getToken()
```
into the console and press <kbd>Enter</kbd>. The console will display your user token.
##### Using the network monitor ##### Using the network monitor
1. <img width="500" align="right" src="https://i.imgur.com/O34nwdG.png" />Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>E</kbd> (<kbd>⌥</kbd>+<kbd>⌘</kbd>+<kbd>E</kbd> on macOS). Firefoxs [web developer tools](https://firefox-source-docs.mozilla.org/devtools-user/) will display at the bottom of the window, and the [network monitor](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/) will display. 1. <img width="500" align="right" src="https://i.imgur.com/O34nwdG.png" />Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>E</kbd> (<kbd>⌥</kbd>+<kbd>⌘</kbd>+<kbd>E</kbd> on macOS). Firefoxs [web developer tools](https://firefox-source-docs.mozilla.org/devtools-user/) will display at the bottom of the window, and the [network monitor](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/) will display.
@@ -164,7 +198,7 @@ Prerequisite step: Navigate to [discord.com](https://discord.com) and login.
<br clear="right" /> <br clear="right" />
<br /> <br />
### Through the desktop app / Enabling web developer tools ### Through the desktop app / enabling web developer tools
#### By editing the settings file #### By editing the settings file
@@ -198,7 +232,7 @@ Prerequisite step: Navigate to [discord.com](https://discord.com) and login.
4. Launch Discord. 4. Launch Discord.
5. To find your user token, continue [here](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#in-chrome). 5. To find your user token, continue [here](#in-chrome).
#### Via settings menu (BetterDiscord only) #### Via settings menu (BetterDiscord only)
@@ -218,7 +252,7 @@ Prerequisite step: Navigate to [discord.com](https://discord.com) and login.
<br /> <br />
4. Press <kbd>Esc</kbd>. The settings page will close. 4. Press <kbd>Esc</kbd>. The settings page will close.
5. To find your user token, continue [here](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#in-chrome). 5. To find your user token, continue [here](#in-chrome).
## How to get a Bot Token ## How to get a Bot Token
@@ -239,4 +273,4 @@ Prerequisite step: Navigate to [discord.com](https://discord.com) and login.
1. Open Discord Settings 1. Open Discord Settings
2. Go to the **Advanced** section 2. Go to the **Advanced** section
3. Enable **Developer Mode** 3. Enable **Developer Mode**
4. Right-click on the desired server or channel and click Copy Server ID or Copy Channel ID 4. Right-click on the desired server or channel and click **Copy Server ID** or **Copy Channel ID**
+39 -32
View File
@@ -6,7 +6,7 @@ Here you'll find the answers to most of the questions related to **DiscordChatEx
- ❓ If you still have unanswered questions _after_ reading this page, feel free to [create a new discussion](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new). - ❓ If you still have unanswered questions _after_ reading this page, feel free to [create a new discussion](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new).
- 🐞 If you have encountered a problem that's not described here, has not [been discussed before](https://github.com/Tyrrrz/DiscordChatExporter/discussions), and is not a [known issue](https://github.com/Tyrrrz/DiscordChatExporter/issues?q=is%3Aissue), please [create a new discussion](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new) or [open a bug report](https://github.com/Tyrrrz/DiscordChatExporter/issues/new). Don't forget to include your platform (Windows, Mac, Linux, etc.) and a detailed description of your question/problem. - 🐞 If you have encountered a problem that's not described here, has not [been discussed before](https://github.com/Tyrrrz/DiscordChatExporter/discussions), and is not a [known issue](https://github.com/Tyrrrz/DiscordChatExporter/issues?q=is%3Aissue), please [create a new discussion](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new) or [open a bug report](https://github.com/Tyrrrz/DiscordChatExporter/issues/new). Don't forget to include your platform (Windows, Mac, Linux, etc.) and a detailed description of your question/problem.
## General ## General questions
### Token stealer? ### Token stealer?
@@ -20,7 +20,7 @@ A token can be used to log into your account, so treat it like a password and ne
### How can I reset my token? ### How can I reset my token?
Follow the [instructions here](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md). Follow the [instructions here](Token-and-IDs.md).
### Will I get banned if I use this? ### Will I get banned if I use this?
@@ -46,6 +46,10 @@ Yes, and other media too. Export using the "Download media" (`--media`) option.
Yes. Yes.
### Can DCE export multiple formats at once?
No, you can only export one format at a time.
### Can DCE recreate the exported chats in Discord? ### Can DCE recreate the exported chats in Discord?
No, DCE is an exporter. No, DCE is an exporter.
@@ -54,49 +58,52 @@ No, DCE is an exporter.
No, DCE is an exporter. No, DCE is an exporter.
### Can DCE add new messages to an existing export?
No.
## First steps ## First steps
### How can I find my token? ### How can I find my token?
Check the following page: [Obtaining token](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md) Check the following page: [Obtaining token](Token-and-IDs.md)
### When I open DCE a black window pops up quickly or nothing shows up. ### When I open DCE a black window pops up quickly or nothing shows up
If you have [.NET Core Runtime correctly installed](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Dotnet.md), you might have downloaded DCE.CLI, try [downloading the GUI](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#gui-or-cli) instead. If you have [.NET Core Runtime correctly installed](Dotnet.md), you might have downloaded the CLi flavor, try [downloading the GUI](Getting-started.md#gui-or-cli) instead.
### I can't open DCE. It sends me to a Visual Studio webpage.
Check the following page:
[Installation and usage](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Readme.md#installation--usage)
### How do I run DCE on macOS or Linux? ### How do I run DCE on macOS or Linux?
Check the following pages: Check the following pages:
- [macOS usage instructions](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/MacOS.md) - [macOS usage instructions](MacOS.md)
- [Linux usage instructions](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Linux.md) - [Linux usage instructions](Linux.md)
### How can I set DCE to export automatically at certain times? ### How can I set DCE to export automatically at certain times?
Check the following pages to learn how to schedule **DiscordChatExporter.CLI** runs (advanced): Check the following pages to learn how to schedule **DiscordChatExporter.CLI** runs (advanced):
- [Windows scheduling](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/scheduling-windows.md) - [Windows scheduling](Scheduling-Windows.md)
- [macOS scheduling](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/scheduling-MacOS.md) - [macOS scheduling](Scheduling-MacOS.md)
- [Linux scheduling](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/scheduling-Linux.md) - [Linux scheduling](Scheduling-Linux.md)
### The exported file is too large, I can't open it! ### The exported file is too large, I can't open it
Try opening it with a different program, try partitioning or use a different file format, like `PlainText`. Try opening it with a different program, try partitioning or use a different file format, like `PlainText`.
### DCE is crashing/failing. ### DCE is crashing/failing
Check the following page: [Installing .NET Core Runtime](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Dotnet.md) Check the following page: [Installing .NET Core Runtime](Dotnet.md)
If you already have .NET Core installed, please check if your problem is a [known issue](https://github.com/Tyrrrz/DiscordChatExporter/issues?q=is%3Aissue) before [opening a bug report](https://github.com/Tyrrrz/DiscordChatExporter/issues/new). If you already have .NET Core installed, please check if your problem is a [known issue](https://github.com/Tyrrrz/DiscordChatExporter/issues?q=is%3Aissue) before [opening a bug report](https://github.com/Tyrrrz/DiscordChatExporter/issues/new).
### .NET Core Runtime is required. ### .NET Core Runtime is required
Check the following page: [Installing .NET Core Runtime](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Dotnet.md) Check the following page: [Installing .NET Core Runtime](Dotnet.md)
### I see messages in the export, but they have no content
Your bot is missing the 'Message Content Intent'. Go to the [Discord Developer Portal](https://discord.com/developers/applications), navigate to the 'Bot' section and enable it.
## CLI ## CLI
@@ -104,54 +111,54 @@ Check the following page: [Installing .NET Core Runtime](https://github.com/Tyrr
Check the following page: Check the following page:
- [Using the CLI](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Getting-started.md#using-the-cli) - [Using the CLI](Using-the-CLI.md)
If you're using **Docker**, please refer to the [Docker Usage Instructions](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Docker.md) instead. If you're using **Docker**, please refer to the [Docker Usage Instructions](Docker.md) instead.
### Where can I find the 'Channel IDs'? ### Where can I find the 'Channel IDs'?
Check the following page: Check the following page:
- [Obtaining Channel IDs](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md) - [Obtaining Channel IDs](Token-and-IDs.md)
### I can't find Docker exported chats ### I can't find Docker exported chats
Check the following page: Check the following page:
- [Docker usage instructions](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/docker) - [Docker usage instructions](Docker.md)
### I can't export Direct Messages ### I can't export Direct Messages
Make sure you're [copying the DM Channel ID](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md#how-to-get-a-direct-message-channel-id), not the person's user ID. Make sure you're [copying the DM Channel ID](Token-and-IDs.md#how-to-get-a-direct-message-channel-id), not the person's user ID.
## Errors ## Errors
``` ```console
DiscordChatExporter.Domain.Exceptions.DiscordChatExporterException: Authentication token is invalid. DiscordChatExporter.Domain.Exceptions.DiscordChatExporterException: Authentication token is invalid.
... ...
``` ```
↳ Make sure the provided token is correct. ↳ Make sure the provided token is correct.
``` ```console
DiscordChatExporter.Domain.Exceptions.DiscordChatExporterException: Requested resource does not exist. DiscordChatExporter.Domain.Exceptions.DiscordChatExporterException: Requested resource does not exist.
``` ```
↳ Check your channel ID, it might be invalid. [Read this if you need help](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs/Token-and-IDs.md). ↳ Check your channel ID, it might be invalid. [Read this if you need help](Token-and-IDs.md).
``` ```console
DiscordChatExporter.Domain.Exceptions.DiscordChatExporterException: Access is forbidden. DiscordChatExporter.Domain.Exceptions.DiscordChatExporterException: Access is forbidden.
``` ```
↳ This means you don't have access to the channel. ↳ This means you don't have access to the channel.
``` ```console
The application to execute does not exist: The application to execute does not exist:
``` ```
↳ The `DiscordChatExporter.Cli.dll` file is missing. Keep the `.exe` and all the `.dll` files together. If you didn't move the files, try unzipping again. ↳ The `DiscordChatExporter.Cli.dll` file is missing. Keep the `.exe` and all the `.dll` files together. If you didn't move the files, try unzipping again.
``` ```console
System.Net.WebException: Error: TrustFailure ... Invalid certificate received from server. System.Net.WebException: Error: TrustFailure ... Invalid certificate received from server.
... ...
``` ```
@@ -167,5 +174,5 @@ If it still doesn't work, try mozroots: `mozroots --import --ask-remove`
--- ---
> ❓ If you still have unanswered questions, feel free to [create a new discussion](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new). > ❓ If you still have unanswered questions, feel free to [create a new discussion](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new).
>
> 🐞 If you have encountered a problem that's not described here, has not [been discussed before](https://github.com/Tyrrrz/DiscordChatExporter/discussions), and is not a [known issue](https://github.com/Tyrrrz/DiscordChatExporter/issues?q=is%3Aissue), please [create a new discussion](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new) or [open a bug report](https://github.com/Tyrrrz/DiscordChatExporter/issues/new). > 🐞 If you have encountered a problem that's not described here, has not [been discussed before](https://github.com/Tyrrrz/DiscordChatExporter/discussions), and is not a [known issue](https://github.com/Tyrrrz/DiscordChatExporter/issues?q=is%3Aissue), please [create a new discussion](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new) or [open a bug report](https://github.com/Tyrrrz/DiscordChatExporter/issues/new).
+402
View File
@@ -0,0 +1,402 @@
# Using the CLI
## Guide
> **Note**:
> Make sure you have [.NET Core installed](Dotnet.md) before attempting to run the commands below.
> **Docker** users, please refer to the [Docker usage instructions](Docker.md).
## Step 1
After extracting the `.zip`, open Command Prompt, aka `cmd` (`Terminal` on **macOS** and **Linux**).
## Step 2
Change the current directory to DCE's folder with `cd C:\path\to\directory`, then press ENTER to run the command.
**Windows** users can quickly get the directory's path by clicking the address bar while inside the folder.
![Copy path from Explorer](https://i.imgur.com/XncnhC2.gif)
**macOS** users can select the `.exe`, hit Command+I (⌘I), and copy what's after `Where:` to get the directory
![Mac info panel](https://camo.githubusercontent.com/3c51a904b0099c9f68a4797461d4a7914902fc04/68747470733a2f2f692e696d6775722e636f6d2f323975364e79782e706e67)
You can also drag and drop the folder on **every platform**.
![Drag and drop folder](https://i.imgur.com/sOpZQAb.gif)
## Step 3
Now we're ready to run the commands. The examples on this page follow the Windows file path format, change the file
paths according to your system.
Type the following in Command Prompt (Terminal), then press ENTER to run it. This will list DCE's options.
```console
dotnet DiscordChatExporter.Cli.dll
```
> **Docker** users, please refer to the [Docker usage instructions](Docker.md).
## CLI commands
| Command | Description |
|-----------------------------|-----------------------------------------------------|
| [export](#export) | Exports a channel |
| [exportdm](#exportdm) | Exports all direct message channels |
| [exportguild](#exportguild) | Exports all channels within the specified server |
| [exportall](#exportall) | Exports all accessible channels |
| [channels](#channels) | Outputs the list of channels in the given server |
| [dm](#dm) | Outputs the list of direct message channels |
| [guilds](#guilds) | Outputs the list of accessible servers |
| [guide](#guide) | Explains how to obtain token, guild, and channel ID |
To use the commands, you'll need a token. For the instructions on how to get a token, please refer
to [this page](Token-and-IDs.md), or run `dotnet DiscordChatExporter.Cli.dll guide`.
To get help with a specific command, please run:
```console
dotnet DiscordChatExporter.Cli.dll command -h
```
### `export`
With this command, you can export **server channels** and **direct messages**.
| | Option | Description |
|--------|---------------------------------------|----------------------------------------------------------------------------------------------------------------|
| **\*** | [-c](#basic-usage) | [Channel ID(s)](Token-and-IDs.md#how-to-get-guild-id-or-guild-channel-id) |
| **\*** | [-t](#basic-usage) | [Authorization token](Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | [-o](#changing-the-output-filename) | Output file or directory path |
| | [-f](#changing-the-format) | [Output file format](Getting-started.md#file-formats). Default: HtmlDark |
| | [--after](#date-ranges) | Only include messages sent after this date |
| | [--before](#date-ranges) | Only include messages sent before this date |
| | [-p](#partitioning) | Split output into partitions, each limited to this number of messages (e.g. 100) or file size (e.g. 10mb) |
| | [--filter](Message-filters.md) | Special notation for filtering the messages that get included in the export |
| | [--media](#downloading-assets) | Download assets referenced by the export (user avatars, attached files, embedded images, etc.). Default: false |
| | [--reuse-media](#reuse-assets) | Reuse previously downloaded assets to avoid redundant requests. Default: false |
| | [--media-dir](#downloading-assets) | Directory to store assets from all exported channels in the same place |
| | [--locale](#changing-the-date-format) | Format used when writing dates. Default: en-US |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
#### Basic usage
You can quickly export with DCE's default settings by using just `-t token` and `-c channelid`.
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555
```
#### Changing the format
You can change the export format to `HtmlDark`, `HtmlLight`, `PlainText` `Json` or `Csv` with `-f format`. The default
format is `HtmlDark`.
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -f Json
```
#### Changing the output filename
You can change the filename by using `-o name.ext`. e.g. for the `HTML` format:
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -o myserver.html
```
#### Changing the output directory
You can change the export directory by using `-o` and providing a path that ends with a slash or does not have a file
extension.
If any of the folders in the path have a space in its name, escape them with quotes (").
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -o "C:\Discord Exports"
```
#### Changing the filename and output directory
You can change both the filename and export directory by using `-o directory\name.ext`.
Note that the filename must have an extension, otherwise it will be considered a directory name.
If any of the folders in the path have a space in its name, escape them with quotes (").
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -o "C:\Discord Exports\myserver.html"
```
#### Generating the filename and output directory dynamically
You can use template tokens to generate the output file path based on the guild and channel metadata.
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -o "C:\Discord Exports\%G\%T\%C.html"
```
Assuming you are exporting a channel named `"my-channel"` in the `"Text channels"` category from a server
called `"My server"`, you will get the following output file
path: `C:\Discord Exports\My server\Text channels\my-channel.html`
Here is the full list of supported template tokens:
- `%g` - guild ID
- `%G` - guild name
- `%t` - category ID
- `%T` - category name
- `%c` - channel ID
- `%C` - channel name
- `%p` - channel position
- `%P` - category position
- `%a` - the "after" date
- `%b` - the "before" date
- `%%` - escapes `%`
#### Partitioning
You can use partitioning to split files after a given number of messages or file size.
For example, a channel with 36 messages set to be partitioned every 10 messages will output 4 files.
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -p 10
```
A 45 MB channel set to be partitioned every 20 MB will output 3 files.
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 -p 20mb
```
#### Downloading assets
If this option is set, the export will include additional files such as user avatars, attached files, images, etc.
Only files that are referenced by the export are downloaded, which means that, for example, user avatars will not be
downloaded when using the plain text (TXT) export format.
A folder containing the assets will be created along with the exported chat. They must be kept together.
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --media
```
#### Reusing assets
Previously downloaded assets can be reused to skip redundant downloads as long as the chat is always exported to the
same folder. Using this option can speed up future exports. This option requires the `--media` option.
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --media --reuse-media
```
#### Changing the media directory
By default, the media directory is created alongside the exported chat. You can change this by using `--media-dir` and
providing a path that ends with a slash. All of the exported media will be stored in this directory.
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --media --media-dir "C:\Discord Media"
```
#### Changing the date format
You can customize how dates are formatted in the exported files by using `--locale` and inserting one of Discord's
locales. The default locale is `en-US`.
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --locale "de-DE"
```
#### Date ranges
**Messages sent before a date**
Use `--before` to export messages sent before the provided date. E.g. messages sent before September 18th, 2019:
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --before 2019-09-18
```
**Messages sent after a date**
Use `--after` to export messages sent after the provided date. E.g. messages sent after September 17th, 2019 11:34 PM:
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --after "2019-09-17 23:34"
```
**Messages sent in a date range**
Use `--before` and `--after` to export messages sent during the provided date range. E.g. messages sent between
September 17th, 2019 11:34 PM and September 18th:
```console
dotnet DiscordChatExporter.Cli.dll export -t "mfa.Ifrn" -c 53555 --after "2019-09-17 23:34" --before "2019-09-18"
```
You can try different formats like `17-SEP-2019 11:34 PM` or even refine your ranges down to
milliseconds `17-SEP-2019 23:45:30.6170`!
Don't forget to quote (") the date if it has spaces!
More info about .NET date
formats [here](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings).
### `exportdm`
This command exports all your **direct messages**.
| | Option | Description |
|--------|---------------------------------------|----------------------------------------------------------------------------------------------------------------|
| **\*** | [-c](#basic-usage) | [Channel ID(s)](Token-and-IDs.md#how-to-get-guild-id-or-guild-channel-id) |
| **\*** | [-t](#basic-usage) | [Authorization token](Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | [-o](#changing-the-output-filename) | Output file or directory path |
| | [-f](#changing-the-format) | [Output file format](Getting-started.md#file-formats). Default: HtmlDark |
| | [--after](#date-ranges) | Only include messages sent after this date |
| | [--before](#date-ranges) | Only include messages sent before this date |
| | [-p](#partitioning) | Split output into partitions, each limited to this number of messages (e.g. 100) or file size (e.g. 10mb) |
| | [--filter](Message-filters.md) | Special notation for filtering the messages that get included in the export |
| | [--media](#downloading-assets) | Download assets referenced by the export (user avatars, attached files, embedded images, etc.). Default: false |
| | [--reuse-media](#reuse-assets) | Reuse previously downloaded assets to avoid redundant requests. Default: false |
| | [--media-dir](#downloading-assets) | Directory to store assets from all exported channels in the same place |
| | [--locale](#changing-the-date-format) | Format used when writing dates. Default: en-US |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
### `exportguild`
This command exports all channels of a **server**.
| | Option | Description |
|--------|-------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **\*** | -g | [Server ID](Token-and-IDs.md#how-to-get-guild-id-or-guild-channel-id) |
| **\*** | [-t](#basic-usage) | [Authorization token](Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | [-o](#changing-the-output-filename) | Output file or directory path |
| | [-f](#changing-the-format) | [Output file format](Getting-started.md#file-formats). Default: HtmlDark |
| | [--after](#date-ranges) | Only include messages sent after this date |
| | [--before](#date-ranges) | Only include messages sent before this date |
| | [-p](#partitioning) | Split output into partitions, each limited to this number of messages (e.g. 100) or file size (e.g. 10mb) |
| | [--filter](Message-filters.md) | Special notation for filtering the messages that get included in the export |
| | [--media](#downloading-assets) | Download assets referenced by the export (user avatars, attached files, embedded images, etc.). Default: false |
| | [--reuse-media](#reuse-assets) | Reuse previously downloaded assets to avoid redundant requests. Default: false |
| | [--media-dir](#downloading-assets) | Directory to store assets from all exported channels in the same place |
| | [--locale](#changing-the-date-format) | Format used when writing dates. Default: en-US |
| | [--include-threads](#including-threads) | Specify whether to include threads (and which type) in the export. By default, threads are not included. It has possible values of `none`, `active`, or `all`, indicating which threads should be included. To include both active and archived threads, use `--include-threads all`. |
| | [--include-vc](#including-voice-channels) | Include voice channels in the export. Default: true |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
#### Including threads
By default, threads are not included in the export. You can change this behavior by using `--include-threads` and
specifying which threads should be included. It has possible values of `none`, `active`, or `all`, indicating which
threads should be included. To include both active and archived threads, use `--include-threads all`.
```console
dotnet DiscordChatExporter.Cli.dll exportguild -t "mfa.Ifrn" -g 21814 --include-threads all
```
#### Including voice channels
By default, voice channels are included in the export. You can change this behavior by using `--include-vc` and
specifying whether to include voice channels in the export. It has possible values of `true` or `false`, to exclude
voice channels, use `--include-vc false`.
```console
dotnet DiscordChatExporter.Cli.dll exportguild -t "mfa.Ifrn" -g 21814 --include-vc false
```
### `exportall`
This command exports **all accessible channels**, including server channels and DMs.
| | Option | Description |
|--------|-------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **\*** | [-t](#basic-usage) | [Authorization token](Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | [-o](#changing-the-output-filename) | Output file or directory path |
| | [-f](#changing-the-format) | [Output file format](Getting-started.md#file-formats). Default: HtmlDark |
| | [--after](#date-ranges) | Only include messages sent after this date |
| | [--before](#date-ranges) | Only include messages sent before this date |
| | [-p](#partitioning) | Split output into partitions, each limited to this number of messages (e.g. 100) or file size (e.g. 10mb) |
| | [--filter](Message-filters.md) | Special notation for filtering the messages that get included in the export |
| | [--media](#downloading-assets) | Download assets referenced by the export (user avatars, attached files, embedded images, etc.). Default: false |
| | [--reuse-media](#reuse-assets) | Reuse previously downloaded assets to avoid redundant requests. Default: false |
| | [--media-dir](#downloading-assets) | Directory to store assets from all exported channels in the same place |
| | [--locale](#changing-the-date-format) | Format used when writing dates. Default: en-US |
| | [--include-threads](#including-threads) | Specify whether to include threads (and which type) in the export. By default, threads are not included. It has possible values of `none`, `active`, or `all`, indicating which threads should be included. To include both active and archived threads, use `--include-threads all`. |
| | [--include-vc](#including-voice-channels) | Include voice channels in the export. Default: true |
| | [--include-dm](#excluding-dms) | Include direct messages in the export. Default: true |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
#### Excluding DMs
To exclude DMs, add the `--include-dm false` option.
```console
dotnet DiscordChatExporter.Cli.dll exportall -t "mfa.Ifrn" --include-dm false
```
### `channels`
This command outputs a **server's channels** in the following format:
`Channel ID | Channel Name`
To save the output to a file, run the command below. If the file already exists, it will be overwritten.
| | Option | Description |
|--------|-------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **\*** | -g | [Server ID](Token-and-IDs.md#how-to-get-guild-id-or-guild-channel-id) |
| **\*** | [-t](#basic-usage) | [Authorization token](Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | [--include-threads](#including-threads) | Specify whether to include threads (and which type) in the output. By default, threads are not included. It has possible values of `none`, `active`, or `all`, indicating which threads should be included. To include both active and archived threads, use `--include-threads all`. |
| | [--include-vc](#including-voice-channels) | Include voice channels in the output. Default: true |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
To save the output to a file, run the command with `> C:\path\…` like the example below. If the file already exists, it
will be overwritten.
```console
dotnet DiscordChatExporter.Cli.dll channels -t "mfa.Ifrn" -g 21814 > C:\path\to\output.txt
```
### `dm`
This command outputs a list of your **direct messages**.
| | Option | Description |
|--------|--------------------|------------------------------------------------------------------------------------------------------|
| **\*** | [-t](#basic-usage) | [Authorization token](Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
To save the output to a file, run the command with `> C:\path\…` like the example below. If the file already exists, it
will be overwritten.
```console
dotnet DiscordChatExporter.Cli.dll dm -t "mfa.Ifrn" > C:\path\to\output.txt
```
### `guilds`
This command outputs a list of your **servers**.
| | Option | Description |
|--------|--------------------|------------------------------------------------------------------------------------------------------|
| **\*** | [-t](#basic-usage) | [Authorization token](Token-and-IDs.md#how-to-get-user-token). Environment variable: `DISCORD_TOKEN` |
| | -h | Shows help text |
> **Note**:
> Options with an asterisk (**\***) are required. The order of the options doesn't matter.
To save the output to a file, run the command with `> C:\path\…` like the example below. If the file already exists, it
will be overwritten.
```console
dotnet DiscordChatExporter.Cli.dll guilds -t "mfa.Ifrn" > C:\path\to\output.txt
```
### `guide`
This command explains [how to get your token, guild, and channel IDs](Token-and-IDs.md).
+97
View File
@@ -0,0 +1,97 @@
# Using the GUI
## Video tutorial
[![Video tutorial](https://i.ytimg.com/vi/jjtu0VQXV7I/hqdefault.jpg)](https://youtube.com/watch?v=jjtu0VQXV7I)
> Video by [NoIntro Tutorials](https://youtube.com/channel/UCFezKSxdNKJe77-hYiuXu3Q).
## Guide
### Step 1
After extracting the `.zip`, open `DiscordChatExporter.exe`
### Step 2
Please refer to the on-screen instructions to get your token, then paste your token in the upper text box and hit ENTER or click the arrow (→).
> **Warning**:
> **Never share your token!**
> A token gives full access to an account, treat it like a password.
<img src="https://i.imgur.com/SuLQ5tZ.png" height="400"/>
### Step 3
DCE will display your Direct Messages and a sidebar with your server list. Select the channel you would like to export, then click the ![Screenshot](https://i.imgur.com/dnTOlDa.png) button to continue.
> **Note**:
> You can export multiple channels at once by holding `CTRL` or `SHIFT` while selecting.
> You can also double-click a channel to export it without clicking the ![Screenshot](https://i.imgur.com/dnTOlDa.png) button.
<img src="https://i.imgur.com/JHMFRh2.png" height="400"/>
### Step 4
In this screen you can customize the following:
- **Output path** - The folder where the exported chat(s) will be saved.
- **Export format** - HTML (Dark), HTML (Light), TXT, CSV and JSON
- **Date range (after/before)** (Optional) - If set, only messages sent in the provided date range will be exported. Only one value (either after or before) is required if you want to use this option.
> **Note**:
> Please note that the time defaults to **12:00 AM** (midnight/00:00). This means that if you choose to export between Sep 17th and Sep 18th, messages from Sep 18th won't be exported.
- **Partition limit** (Optional) - Split output into partitions, each limited to this number of messages (e.g. 100) or file size (e.g. 10mb). For example, a channel with 36 messages set to be partitioned every 10 messages will output 4 files.
- **Message Filter** (Optional) - Special notation for filtering the messages that get included in the export. See [Message filters](Message-filters.md) for more info.
- **Format markdown** (Optional) - Disable markdown processing when exporting. You can use this to produce JSON or plain text exports without unwrapping mentions, custom emoji, and certain other special tokens.
- **Download assets** (Optional) - If this option is set, the export will include additional files such as user avatars, attached files, images, etc. Only files that are referenced by the export are downloaded, which means that, for example, user avatars will not be downloaded when using the plain text (TXT) export format. A folder containing the assets will be created along with the exported chat. They must be kept together.
- **Reuse assets** (Optional) - If this option is set, the export will reuse already downloaded assets to skip redundant requests. This option is only available when **Download assets** is enabled.
- **Assets directory path** (Optional) - If this option is set, the export will use the specified directory to store assets from all exported channels in the same place.
> **Note**:
> You need to scroll down to see all available options.
## Settings
- **Auto-update**
Perform automatic updates on every launch.
Default: Enabled
> **Note**:
> Keep this option enabled to receive the latest features and bug fixes!
- **Dark mode**
Use darker colors in the UI (User Interface).
Default: Disabled
- **Persist token**
Persist last used token between sessions.
Default: Enabled
- **Show threads**
Controls whether threads are shown in the channel list.
Default: none
- **Locale**
Customize how dates are formatted in the exported files.
- **Date format**
Customize how dates are formatted in the exported files in the settings menu ().
- **Parallel limit**
The number of channels that will be exported at the same time.
Default: 1
- **Normalize to UTC**
Convert all dates to UTC before exporting.
> **Note**:
> Try to keep this number low so that your account doesn't get flagged.
+63 -20
View File
@@ -1,4 +1,4 @@
name: 🐞 Bug report name: 🐛 Bug report
description: Report broken functionality. description: Report broken functionality.
labels: [bug] labels: [bug]
@@ -6,26 +6,25 @@ body:
- type: markdown - type: markdown
attributes: attributes:
value: | value: |
🧐 **Guidelines:** - Avoid generic or vague titles such as "Something's not working" or "A couple of problems" — be as descriptive as possible.
- Keep your issue focused on one single problem. If you have multiple bug reports, please create a separate issue for each of them.
- Issues should represent **complete and actionable** work items. If you are unsure about something or have a question, please start a [discussion](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new) instead.
- Remember that **DiscordChatExporter** is an open-source project funded by the community. If you find it useful, **please consider [donating](https://tyrrrz.me/donate) to support its development**.
- Search through [existing issues](https://github.com/Tyrrrz/DiscordChatExporter/issues?q=is%3Aissue) first to ensure that this bug has not been reported before. ___
- Write a descriptive title for your issue. Avoid generic or vague titles such as "Something's not working" or "A couple of problems".
- Keep your issue focused on one single problem. If you have multiple bug reports, please create separate issues for each of them.
- Provide as much context as possible in the details section. Include screenshots, screen recordings, links, references, or anything else you may consider relevant.
- If you want to ask a question instead of reporting a bug, please use [discussions](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new) instead.
- type: input - type: input
attributes: attributes:
label: Version label: Version
description: Which version of DiscordChatExporter does this bug affect? description: Which version of the application does this bug affect? Make sure you're not using an outdated version.
placeholder: ver X.Y.Z placeholder: v1.0.0
validations: validations:
required: true required: true
- type: dropdown - type: dropdown
attributes: attributes:
label: Flavor label: Flavor
description: Does this bug affect the GUI version, the CLI version, or both? description: Which flavor(s) of the application does this bug affect?
multiple: true multiple: true
options: options:
- GUI (Graphical User Interface) - GUI (Graphical User Interface)
@@ -33,10 +32,18 @@ body:
validations: validations:
required: true required: true
- type: input
attributes:
label: Platform
description: Which platform do you experience this bug on?
placeholder: Docker / Windows 11
validations:
required: true
- type: dropdown - type: dropdown
attributes: attributes:
label: Export format label: Export format
description: Does this bug affect specific export format(s)? If not applicable, leave this field blank. description: Which export format(s) do you experience this bug with, if applicable?
multiple: true multiple: true
options: options:
- HTML - HTML
@@ -44,21 +51,57 @@ body:
- JSON - JSON
- CSV - CSV
- type: textarea
attributes:
label: Details
description: Clear and thorough explanation of the bug.
placeholder: I was doing X expecting Y to happen, but Z happened instead.
validations:
required: true
- type: textarea - type: textarea
attributes: attributes:
label: Steps to reproduce label: Steps to reproduce
description: Minimum steps required to reproduce the bug. description: >
Minimum steps required to reproduce the bug, including prerequisites, export settings, or other relevant items.
The information provided in this field must be readily actionable, meaning that anyone should be able to reproduce the bug by following these steps.
If the bug depends on external factors (such as a specific server, channel, or message), then this field must include the server invite and the corresponding link.
placeholder: | placeholder: |
Server invite: https://discord.gg/...
Channel or message link: https://discord.com/channels/.../...
Export settings:
- ...
Application settings:
- ...
Steps:
- Step 1 - Step 1
- Step 2 - Step 2
- Step 3 - Step 3
validations: validations:
required: true required: true
- type: textarea
attributes:
label: Details
description: Clear and thorough explanation of the bug, including any additional information you may find relevant.
placeholder: |
- Expected behavior: ...
- Actual behavior: ...
validations:
required: true
- type: checkboxes
attributes:
label: Checklist
description: Quick list of checks to ensure that everything is in order.
options:
- label: I have looked through existing issues to make sure that this bug has not been reported before
required: true
- label: I have provided a descriptive title for this issue
required: true
- label: I have made sure that that this bug is reproducible on the latest version of the application
required: true
- label: I have provided all the information needed to reproduce this bug as efficiently as possible
required: true
- label: I have sponsored this project
required: false
- type: markdown
attributes:
value: |
If you are struggling to provide actionable reproduction steps, or if something else is preventing you from creating a complete bug report, please start a [discussion](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new) instead.
+4 -4
View File
@@ -3,12 +3,12 @@ contact_links:
- name: ⚠ Feature request - name: ⚠ Feature request
url: https://github.com/Tyrrrz/.github/blob/master/docs/project-status.md url: https://github.com/Tyrrrz/.github/blob/master/docs/project-status.md
about: Sorry, but this project is in maintenance mode and no longer accepts new feature requests. about: Sorry, but this project is in maintenance mode and no longer accepts new feature requests.
- name: 💬 Discord server
url: https://discord.gg/2SUWKFnHSm
about: Chat with the project community.
- name: 📖 Documentation - name: 📖 Documentation
url: https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs url: https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs
about: Find usage guides and frequently asked questions. about: Find usage guides and frequently asked questions.
- name: 🗨 Discussions - name: 🗨 Discussions
url: https://github.com/Tyrrrz/DiscordChatExporter/discussions/new url: https://github.com/Tyrrrz/DiscordChatExporter/discussions/new
about: Ask and answer questions. about: Ask and answer questions.
- name: 💬 Discord server
url: https://discord.gg/2SUWKFnHSm
about: Chat with the project community.
+18 -40
View File
@@ -1,8 +1,12 @@
name: docker name: docker
on: [push, pull_request] on:
push:
pull_request:
jobs: jobs:
# Outputs from this job aren't really used, but it's here to verify that
# the Dockerfile builds correctly on pull requests.
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
@@ -11,37 +15,38 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # 4.1.0
- name: Install Docker Buildx - name: Install Docker Buildx
uses: docker/setup-buildx-action@v2 uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # 3.0.0
- name: Build image - name: Build image
run: > run: >
docker buildx build docker buildx build .
--file DiscordChatExporter.Cli.dockerfile --file DiscordChatExporter.Cli.dockerfile
--platform linux/amd64,linux/arm64 --platform linux/amd64,linux/arm64
--output type=tar,dest=DiscordChatExporter.Cli.Docker.tar --output type=tar,dest=DiscordChatExporter.Cli.Docker.tar
.
- name: Upload artifacts - name: Upload artifacts
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # 3.1.3
with: with:
name: DiscordChatExporter.Cli.Docker name: DiscordChatExporter.Cli.Docker
path: DiscordChatExporter.Cli.Docker.tar path: DiscordChatExporter.Cli.Docker.tar
if-no-files-found: error
deploy-latest: deploy:
if: ${{ github.event_name == 'push' && github.ref_type == 'branch' && github.ref_name == 'master' }} # Deploy to DockerHub only on tag push or master branch push
if: ${{ github.event_name == 'push' && (github.ref_type == 'tag' || github.ref_type == 'branch' && github.ref_name == 'master') }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
contents: read contents: read
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # 4.1.0
- name: Install Docker Buildx - name: Install Docker Buildx
uses: docker/setup-buildx-action@v2 uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # 3.0.0
- name: Login to DockerHub - name: Login to DockerHub
run: > run: >
@@ -50,37 +55,10 @@ jobs:
- name: Build & push image - name: Build & push image
run: > run: >
docker buildx build docker buildx build .
--file DiscordChatExporter.Cli.dockerfile --file DiscordChatExporter.Cli.dockerfile
--platform linux/amd64,linux/arm64 --platform linux/amd64,linux/arm64
--push --push
--tag tyrrrz/discordchatexporter:latest --tag tyrrrz/discordchatexporter:latest
. ${{ github.ref_type == 'tag' && '--tag tyrrrz/discordchatexporter:$GITHUB_REF_NAME' || '' }}
${{ github.ref_type == 'tag' && '--tag tyrrrz/discordchatexporter:stable' || '' }}
deploy-stable:
if: ${{ github.event_name == 'push' && github.ref_type == 'tag' }}
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Install Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to DockerHub
run: >
echo ${{ secrets.DOCKER_TOKEN }} |
docker login --username tyrrrz --password-stdin
- name: Build & push image
run: >
docker buildx build
--file DiscordChatExporter.Cli.dockerfile
--platform linux/amd64,linux/arm64
--push
--tag tyrrrz/discordchatexporter:stable
--tag tyrrrz/discordchatexporter:${{ github.ref_name }}
.
+84 -78
View File
@@ -1,6 +1,13 @@
name: main name: main
on: [push, pull_request] on:
push:
pull_request:
env:
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
DOTNET_NOLOGO: true
DOTNET_CLI_TELEMETRY_OPTOUT: true
jobs: jobs:
test: test:
@@ -8,23 +15,20 @@ jobs:
permissions: permissions:
contents: read contents: read
env:
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
DOTNET_NOLOGO: true
DOTNET_CLI_TELEMETRY_OPTOUT: true
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # 4.1.0
- name: Install .NET - name: Install .NET
uses: actions/setup-dotnet@v2 uses: actions/setup-dotnet@3447fd6a9f9e57506b15f895c5b76d3b197dc7c2 # 3.2.0
with: with:
dotnet-version: 7.0.x dotnet-version: 8.0.x
- name: Run tests - name: Run tests
# Tests need access to secrets, so we can't run them against PRs because of limited trust # Tests need access to secrets, so we can't run them against PRs because of limited trust
if: ${{ github.event_name != 'pull_request' }} if: ${{ github.event_name != 'pull_request' }}
env:
DISCORD_TOKEN: ${{ secrets.DISCORD_TOKEN }}
run: > run: >
dotnet test dotnet test
--configuration Release --configuration Release
@@ -33,107 +37,107 @@ jobs:
-- --
RunConfiguration.CollectSourceInformation=true RunConfiguration.CollectSourceInformation=true
DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover
env:
DISCORD_TOKEN: ${{ secrets.DISCORD_TOKEN }}
- name: Upload coverage - name: Upload coverage
uses: codecov/codecov-action@v3 uses: codecov/codecov-action@eaaf4bedf32dbdc6b720b63067d99c4d77d6047d # 3.1.4
with: with:
token: ${{ secrets.CODECOV_TOKEN }} token: ${{ secrets.CODECOV_TOKEN }}
pack: pack:
needs: test strategy:
matrix:
app:
- DiscordChatExporter.Cli
- DiscordChatExporter.Gui
runs-on: windows-latest runs-on: windows-latest
permissions: permissions:
actions: write actions: write
contents: read contents: read
env:
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
DOTNET_NOLOGO: true
DOTNET_CLI_TELEMETRY_OPTOUT: true
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # 4.1.0
- name: Install .NET - name: Install .NET
uses: actions/setup-dotnet@v2 uses: actions/setup-dotnet@3447fd6a9f9e57506b15f895c5b76d3b197dc7c2 # 3.2.0
with: with:
dotnet-version: 7.0.x dotnet-version: 8.0.x
- name: Publish (CLI) - name: Publish app
run: > run: >
dotnet publish DiscordChatExporter.Cli dotnet publish ${{ matrix.app }}
--output DiscordChatExporter.Cli/publish/ --output ${{ matrix.app }}/bin/publish/
--configuration Release --configuration Release
- name: Publish (GUI) - name: Upload artifacts
uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # 3.1.3
with:
name: ${{ matrix.app }}
path: ${{ matrix.app }}/bin/publish/
if-no-files-found: error
release:
if: ${{ github.event_name == 'push' && github.ref_type == 'tag' }}
needs:
- test
- pack
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Create release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: > run: >
dotnet publish DiscordChatExporter.Gui gh release create ${{ github.ref_name }}
--output DiscordChatExporter.Gui/publish/ --repo ${{ github.event.repository.full_name }}
--configuration Release --title ${{ github.ref_name }}
--notes "[Changelog](${{ github.event.repository.html_url }}/blob/${{ github.ref_name }}/Changelog.md)"
- name: Upload artifacts (CLI) --verify-tag
uses: actions/upload-artifact@v3
with:
name: DiscordChatExporter.Cli
path: DiscordChatExporter.Cli/publish/
- name: Upload artifacts (GUI)
uses: actions/upload-artifact@v3
with:
name: DiscordChatExporter
path: DiscordChatExporter.Gui/publish/
deploy: deploy:
if: ${{ github.event_name == 'push' && github.ref_type == 'tag' }} needs: release
needs: pack
strategy:
matrix:
app:
- DiscordChatExporter.Cli
- DiscordChatExporter.Gui
include:
- app: DiscordChatExporter.Cli
asset: DiscordChatExporter.Cli
- app: DiscordChatExporter.Gui
# GUI asset isn't suffixed, unlike the CLI asset
asset: DiscordChatExporter
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
actions: read actions: read
contents: write contents: write
steps: steps:
- name: Download artifacts (CLI) - name: Download artifacts
uses: actions/download-artifact@v3 uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # 3.0.2
with: with:
name: DiscordChatExporter.Cli name: ${{ matrix.app }}
path: DiscordChatExporter.Cli path: ${{ matrix.app }}/
- name: Download artifacts (GUI) - name: Create package
uses: actions/download-artifact@v3 # Change into the artifacts directory to avoid including the directory itself in the zip archive
with: working-directory: ${{ matrix.app }}/
name: DiscordChatExporter run: zip -r ../${{ matrix.asset }}.zip .
path: DiscordChatExporter.Gui
- name: Create package (CLI) - name: Upload release asset
shell: pwsh
run: >
Compress-Archive
-Path DiscordChatExporter.Cli/*
-DestinationPath DiscordChatExporter.Cli.zip
-Force
- name: Create package (GUI)
shell: pwsh
run: >
Compress-Archive
-Path DiscordChatExporter.Gui/*
-DestinationPath DiscordChatExporter.zip
-Force
- name: Create release
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: > run: >
gh release create "${{ github.ref_name }}" gh release upload ${{ github.ref_name }}
"DiscordChatExporter.Cli.zip" ${{ matrix.asset }}.zip
"DiscordChatExporter.zip" --repo ${{ github.event.repository.full_name }}
--repo "${{ github.event.repository.full_name }}"
--title "${{ github.ref_name }}"
--notes "[Changelog](${{ github.event.repository.html_url }}/blob/${{ github.ref_name }}/Changelog.md)"
--verify-tag
notify: notify:
needs: deploy needs: deploy
@@ -143,7 +147,7 @@ jobs:
steps: steps:
- name: Notify Discord - name: Notify Discord
uses: tyrrrz/action-http-request@v1 uses: tyrrrz/action-http-request@64c70c67f5ebc54d4c7ea09cbe3553322778afd5 # 1.1.2
with: with:
url: ${{ secrets.DISCORD_WEBHOOK }} url: ${{ secrets.DISCORD_WEBHOOK }}
method: POST method: POST
@@ -151,5 +155,7 @@ jobs:
Content-Type: application/json; charset=UTF-8 Content-Type: application/json; charset=UTF-8
body: | body: |
{ {
"content": "**${{ github.event.repository.name }}** new version released!\nVersion: `${{ github.ref_name }}`\nChangelog: <${{ github.event.repository.html_url }}/blob/${{ github.ref_name }}/Changelog.md>" "avatar_url": "https://raw.githubusercontent.com/${{ github.event.repository.full_name }}/${{ github.ref_name }}/favicon.png",
} "content": "**${{ github.event.repository.name }}** v${{ github.ref_name }} has been released!\n🔗 [Download](<${{ github.event.repository.html_url }}/releases/tag/${{ github.ref_name }}>) • [Changelog](<${{ github.event.repository.html_url }}/blob/${{ github.ref_name }}/Changelog.md>)"
}
retry-count: 5
+6 -17
View File
@@ -1,23 +1,12 @@
# User-specific files # User-specific files
.vs/
.idea/
*.suo *.suo
*.user *.user
*.userosscache
*.sln.docstates
.idea/
.vs/
.vscode/
# Build results # Build results
[Dd]ebug/ bin/
[Dd]ebugPublic/ obj/
[Rr]elease/
[Rr]eleases/
[Xx]64/
[Xx]86/
[Bb]uild/
bld/
[Bb]in/
[Oo]bj/
# Coverage # Test results
*.opencover.xml TestResults/
+98 -4
View File
@@ -1,5 +1,99 @@
# Changelog # Changelog
## v2.42.4 (16-Nov-2023)
- General changes:
- Switched from .NET 7.0 to .NET 8.0. If running on Windows, the application should update all required prerequisites automatically. Alternatively, you can download the latest version of the runtime for your system [here](https://dotnet.microsoft.com/download/dotnet/8.0).
- CLI changes:
- Added a message that is displayed when the application is running with the output stream redirected, informing the user that they will not get rich progress reporting in this mode.
- GUI changes:
- Changed the presentation of the "Reuse assets" and "Assets path" options, such that the corresponding controls are now disabled if the "Download assets" option is not enabled.
- HTML changes:
- Fixed an issue where exporting a channel with a custom assets path could result in an HTML output that did not render properly in Firefox.
## v2.42.3 (09-Nov-2023)
- JSON changes:
- Added the `video` field to the embed object, which may contain additional information about an embedded video resource.
- CSV changes:
- Fixed an issue where the `Date` field was incorrectly formatted. Now, the dates follow the `ISO 8601` standard.
## v2.42.2 (26-Oct-2023)
- General changes:
- Fixed an issue where trying to export a channel that contained application interactions with empty command names crashed the application.
## v2.42.1 (19-Oct-2023)
- General changes:
- Improved the error message shown when trying to export a forum channel. Such channels cannot be exported directly, you need to fetch and export their individual threads instead.
- CLI changes:
- Fixed an issue where fetching threads with `[` or `]` in their name crashed the application.
## v2.42 (12-Oct-2023)
- General changes:
- Fixed an issue where the "reuse assets" option did not work as intended due to Discord recently introducing signatures in the CDN URLs. (Thanks [@slatinsky](https://github.com/slatinsky))
- CLI changes:
- Added progress reporting for the "fetching channels" stage of the `exportguild` and `exportall` commands. (Thanks [@slatinsky](https://github.com/slatinsky))
## v2.41.2 (05-Oct-2023)
- General changes:
- Added a check that will trigger an error if the provided bot account does not have the message content intent enabled. Unlike the previous attempt, this approach does not rely on heuristics.
## v2.41.1 (28-Sep-2023)
- CLI changes:
- Fixed an issue where the export failed to export channels with an empty name.
## v2.41 (15-Sep-2023)
- General changes:
- Replaced the "date format" option with a "locale" option. Now, you can choose one of the locales supported by the Discord app, and DiscordChatExporter will infer all the required date, time, and number formats automatically. In GUI, the locale can be selected from the settings window. In CLI, the locale can be specified using the `--locale` option (e.g. `--locale "en-US"`). By default, the current system locale is used.
- Optimized the algorithm for fetching threads to improve performance. (Thanks [@slatinsky](https://github.com/slatinsky))
- GUI changes:
- Improved the initial load time after submitting the token. Now, only the guilds are loaded initially, and the channels are loaded on-demand when the user selects a guild. This should significantly improve performance for accounts with many guilds.
- Added an option to include threads in the channel list, which is configurable in settings. When enabled, threads will appear at the bottom of the list, grouped by the parent channel. Note that pulling threads (especially archived threads) can be a very time-consuming process, depending on the guild size. By default, threads are not included.
- CLI changes:
- Added a warning when using the `--bot` option, informing that it's obsolete and shouldn't be used.
- Changed the `--include-threads` option on the `channels` command from a switch (boolean) option, to an enum (choice) option. It now has possible values of `none`, `active`, or `all`, indicating which threads should be included. To include both active and archived threads, use `--include-threads all`. For backwards compatibility, the `--include-threads` option can still be used as a switch, in which case it will be treated as `--include-threads active`. Note that pulling threads (especially archived threads) can be a very time-consuming process, depending on the guild size.
- Added the `--include-threads` option to the `exportguild` and `exportall` commands. Using this option, you can specify whether to include threads (and which type) in the export. By default, threads are not included.
- Added the `--include-vc` option to the `channels` command. Using this option, you can specify whether to include voice-channel-accompanying text channels in the output. By default, these channels are included.
- Changed the progress reporting behavior of export commands such that tasks are now hidden on completion if parallelization is enabled (i.e. `--parallel` is set to `2` or higher). This should help improve visual clarity when exporting many channels in parallel.
## v2.40.4 (11-Aug-2023)
- HTML changes:
- Fixed an issue where the "call lasted for X minutes" system message was unnecessarily too precise. Now, it's rounded to the nearest minute.
- Fixed an issue where multi-line quote blocks with empty lines in the middle were rendered as separate blocks.
- JSON changes:
- Added the `users` field to the reaction object, containing an array with limited information about the users that reacted with that particular emoji. (Thanks [@slatinsky](https://github.com/slatinsky))
## v2.40.3 (29-Jul-2023)
- GUI changes:
- Fixed an issue where guild categories were rendered with blank names.
## v2.40.2 (27-Jul-2023)
- General changes:
- Improved error reporting on unexpected HTTP errors.
- CLI changes:
- Fixed an issue which caused a crash when trying to export a private (but accessible) channel inside a private (but not accessible) category.
## v2.40.1 (21-Jul-2023)
- General changes:
- Fixed an issue where the fallback avatar (i.e. the avatar used for when the user doesn't have a custom one set) was not resolved properly for users that don't have a discriminator.
- CLI changes:
- Added the `--include-vc` option to the `exportall` and `exportguild` commands, which instructs whether to include voice-channel-accompanying text channels in the export. By default, this is set to `true` to match the previous behavior. To disable the option, use `--include-vc false`.
- GUI changes:
- Replaced the blur effect applied to the token text box with a password mask.
- JSON format changes:
- Added the `exportedAt` field to the export metadata, which contains the timestamp corresponding to when the export was created. (Thanks [@slatinsky](https://github.com/slatinsky))
- Added the `roles` field to the object describing a user. This field contains an array of objects that describe the roles assigned to the user. (Thanks [@slatinsky](https://github.com/slatinsky))
## v2.40 (08-Jun-2023) ## v2.40 (08-Jun-2023)
- General changes: - General changes:
@@ -40,7 +134,7 @@
- Updated the usage guide with additional steps required to retrieve the user token. - Updated the usage guide with additional steps required to retrieve the user token.
- Fixed an issue where certain user mentions were incorrectly rendered as `@Unknown`. - Fixed an issue where certain user mentions were incorrectly rendered as `@Unknown`.
- Fixed an issue where some embed images were rendered using their actual URLs instead of Discord proxy URLs. - Fixed an issue where some embed images were rendered using their actual URLs instead of Discord proxy URLs.
- GUI changes: - GUI changes:
- Added a text box for specifying the output path when exporting channels. It can be used to set an output path that uses template tokens, which previously required hacky workarounds. This text box can be left empty, in which case clicking on the "Export" button will open the file or folder picker dialog, matching the previous behavior. - Added a text box for specifying the output path when exporting channels. It can be used to set an output path that uses template tokens, which previously required hacky workarounds. This text box can be left empty, in which case clicking on the "Export" button will open the file or folder picker dialog, matching the previous behavior.
- Added a notification when the application is updated to a new version, containing the changelog link. - Added a notification when the application is updated to a new version, containing the changelog link.
- Moved the "reuse assets" option from the settings dialog to the export dialog. - Moved the "reuse assets" option from the settings dialog to the export dialog.
@@ -48,7 +142,7 @@
- Minor cosmetic improvements. - Minor cosmetic improvements.
- CLI changes: - CLI changes:
- Changed the behavior of the `export` command when providing IDs of category channels. Now, instead of displaying an error, the command will export all channels contained within the corresponding categories. - Changed the behavior of the `export` command when providing IDs of category channels. Now, instead of displaying an error, the command will export all channels contained within the corresponding categories.
- HTML format changes: - HTML format changes:
- Added proper support for more system notification messages. - Added proper support for more system notification messages.
- Added support for rendering server invites. Now, if the message contains an invite link, the export will show the server icon and include additional information, such as the name of the server and the target channel. - Added support for rendering server invites. Now, if the message contains an invite link, the export will show the server icon and include additional information, such as the name of the server and the target channel.
- Changed the preamble part of the export to show the channel icon when available, instead of the default Discord logo. This is only available for group DM channels. (Thanks [@CanePlayz](https://github.com/CanePlayz)) - Changed the preamble part of the export to show the channel icon when available, instead of the default Discord logo. This is only available for group DM channels. (Thanks [@CanePlayz](https://github.com/CanePlayz))
@@ -96,7 +190,7 @@
## v2.36.1 (24-Sep-2022) ## v2.36.1 (24-Sep-2022)
- Added a check which will trigger an error if the provided bot account does not have the message content intent enabled. Note, however, that this check is based on heuristics which may result in false negatives. - Added a check that will trigger an error if the provided bot account does not have the message content intent enabled. Note, however, that this check is based on heuristics which may result in false negatives.
- Fixed an issue where certain transient HTTP errors were not retried. - Fixed an issue where certain transient HTTP errors were not retried.
- Fixed an issue which caused the export process to fail with the `IndexOutOfRangeException` exception on certain automated messages. - Fixed an issue which caused the export process to fail with the `IndexOutOfRangeException` exception on certain automated messages.
- Fixed an issue which caused the export process to fail on unrecognized embed types. - Fixed an issue which caused the export process to fail on unrecognized embed types.
@@ -543,4 +637,4 @@ Please note that CSV export is most likely not going to receive future updates a
- Added support for user and role mentions. - Added support for user and role mentions.
- Added support for channel mentions. - Added support for channel mentions.
- Fixed text in pre blocks not being wrapped correctly. - Fixed text in pre blocks not being wrapped correctly.
- Added workaround for non-default message types. - Added workaround for non-default message types.
+3 -3
View File
@@ -1,13 +1,13 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<Version>2.40</Version> <Version>2.42.4</Version>
<Company>Tyrrrz</Company> <Company>Tyrrrz</Company>
<Copyright>Copyright (c) Oleksii Holub</Copyright> <Copyright>Copyright (c) Oleksii Holub</Copyright>
<LangVersion>preview</LangVersion> <LangVersion>preview</LangVersion>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<WarningsAsErrors>nullable</WarningsAsErrors> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup> </PropertyGroup>
</Project> </Project>
@@ -8,22 +8,22 @@
<ItemGroup> <ItemGroup>
<Content Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" /> <Content Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" />
<None Include="*.secret" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AngleSharp" Version="1.0.3" /> <PackageReference Include="AngleSharp" Version="1.0.6" />
<PackageReference Include="FluentAssertions" Version="6.11.0" /> <PackageReference Include="coverlet.collector" Version="6.0.0" PrivateAssets="all" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.3.2" PrivateAssets="all" /> <PackageReference Include="CSharpier.MsBuild" Version="0.26.1" PrivateAssets="all" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="GitHubActionsTestLogger" Version="2.3.3" PrivateAssets="all" />
<PackageReference Include="JsonExtensions" Version="1.2.0" /> <PackageReference Include="JsonExtensions" Version="1.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.2" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="ReflectionMagic" Version="4.1.0" /> <PackageReference Include="ReflectionMagic" Version="5.0.0" />
<PackageReference Include="xunit" Version="2.4.2" /> <PackageReference Include="xunit" Version="2.6.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5" PrivateAssets="all" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" PrivateAssets="all" />
<PackageReference Include="coverlet.collector" Version="6.0.0" PrivateAssets="all" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -23,4 +23,4 @@ public static class ChannelIds
public static Snowflake SelfContainedTestCases { get; } = Snowflake.Parse("887441432678379560"); public static Snowflake SelfContainedTestCases { get; } = Snowflake.Parse("887441432678379560");
public static Snowflake StickerTestCases { get; } = Snowflake.Parse("939668868253769729"); public static Snowflake StickerTestCases { get; } = Snowflake.Parse("939668868253769729");
} }
@@ -19,14 +19,16 @@ namespace DiscordChatExporter.Cli.Tests.Infra;
public static class ExportWrapper public static class ExportWrapper
{ {
private static readonly AsyncKeyedLocker<string> Locker = new(o => private static readonly AsyncKeyedLocker<string> Locker =
{ new(o =>
o.PoolSize = 20; {
o.PoolInitialFill = 1; o.PoolSize = 20;
}); o.PoolInitialFill = 1;
});
private static readonly string DirPath = Path.Combine( private static readonly string DirPath = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? Directory.GetCurrentDirectory(), Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
?? Directory.GetCurrentDirectory(),
"ExportCache" "ExportCache"
); );
@@ -36,9 +38,7 @@ public static class ExportWrapper
{ {
Directory.Delete(DirPath, true); Directory.Delete(DirPath, true);
} }
catch (DirectoryNotFoundException) catch (DirectoryNotFoundException) { }
{
}
Directory.CreateDirectory(DirPath); Directory.CreateDirectory(DirPath);
} }
@@ -48,32 +48,31 @@ public static class ExportWrapper
var fileName = channelId.ToString() + '.' + format.GetFileExtension(); var fileName = channelId.ToString() + '.' + format.GetFileExtension();
var filePath = Path.Combine(DirPath, fileName); var filePath = Path.Combine(DirPath, fileName);
// Lock separately for each channel and format using var _ = await Locker.LockAsync(filePath);
using (await Locker.LockAsync(filePath)) using var console = new FakeConsole();
{
// Perform the export only if it hasn't been done before
if (!File.Exists(filePath))
{
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { channelId },
ExportFormat = format,
OutputPath = filePath
}.ExecuteAsync(new FakeConsole());
}
return await File.ReadAllTextAsync(filePath); // Perform the export only if it hasn't been done before
if (!File.Exists(filePath))
{
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { channelId },
ExportFormat = format,
OutputPath = filePath,
Locale = "en-US",
IsUtcNormalizationEnabled = true
}.ExecuteAsync(console);
} }
return await File.ReadAllTextAsync(filePath);
} }
public static async ValueTask<IHtmlDocument> ExportAsHtmlAsync(Snowflake channelId) => Html.Parse( public static async ValueTask<IHtmlDocument> ExportAsHtmlAsync(Snowflake channelId) =>
await ExportAsync(channelId, ExportFormat.HtmlDark) Html.Parse(await ExportAsync(channelId, ExportFormat.HtmlDark));
);
public static async ValueTask<JsonElement> ExportAsJsonAsync(Snowflake channelId) => Json.Parse( public static async ValueTask<JsonElement> ExportAsJsonAsync(Snowflake channelId) =>
await ExportAsync(channelId, ExportFormat.Json) Json.Parse(await ExportAsync(channelId, ExportFormat.Json));
);
public static async ValueTask<string> ExportAsPlainTextAsync(Snowflake channelId) => public static async ValueTask<string> ExportAsPlainTextAsync(Snowflake channelId) =>
await ExportAsync(channelId, ExportFormat.PlainText); await ExportAsync(channelId, ExportFormat.PlainText);
@@ -81,25 +80,26 @@ public static class ExportWrapper
public static async ValueTask<string> ExportAsCsvAsync(Snowflake channelId) => public static async ValueTask<string> ExportAsCsvAsync(Snowflake channelId) =>
await ExportAsync(channelId, ExportFormat.Csv); await ExportAsync(channelId, ExportFormat.Csv);
public static async ValueTask<IReadOnlyList<IElement>> GetMessagesAsHtmlAsync(Snowflake channelId) => public static async ValueTask<IReadOnlyList<IElement>> GetMessagesAsHtmlAsync(
(await ExportAsHtmlAsync(channelId)) Snowflake channelId
.QuerySelectorAll("[data-message-id]") ) => (await ExportAsHtmlAsync(channelId)).QuerySelectorAll("[data-message-id]").ToArray();
.ToArray();
public static async ValueTask<IReadOnlyList<JsonElement>> GetMessagesAsJsonAsync(Snowflake channelId) => public static async ValueTask<IReadOnlyList<JsonElement>> GetMessagesAsJsonAsync(
(await ExportAsJsonAsync(channelId)) Snowflake channelId
.GetProperty("messages") ) => (await ExportAsJsonAsync(channelId)).GetProperty("messages").EnumerateArray().ToArray();
.EnumerateArray()
.ToArray();
public static async ValueTask<IElement> GetMessageAsHtmlAsync(Snowflake channelId, Snowflake messageId) public static async ValueTask<IElement> GetMessageAsHtmlAsync(
Snowflake channelId,
Snowflake messageId
)
{ {
var message = (await GetMessagesAsHtmlAsync(channelId)).SingleOrDefault(e => var message = (await GetMessagesAsHtmlAsync(channelId)).SingleOrDefault(
string.Equals( e =>
e.GetAttribute("data-message-id"), string.Equals(
messageId.ToString(), e.GetAttribute("data-message-id"),
StringComparison.OrdinalIgnoreCase messageId.ToString(),
) StringComparison.OrdinalIgnoreCase
)
); );
if (message is null) if (message is null)
@@ -112,14 +112,18 @@ public static class ExportWrapper
return message; return message;
} }
public static async ValueTask<JsonElement> GetMessageAsJsonAsync(Snowflake channelId, Snowflake messageId) public static async ValueTask<JsonElement> GetMessageAsJsonAsync(
Snowflake channelId,
Snowflake messageId
)
{ {
var message = (await GetMessagesAsJsonAsync(channelId)).SingleOrDefault(j => var message = (await GetMessagesAsJsonAsync(channelId)).SingleOrDefault(
string.Equals( j =>
j.GetProperty("id").GetString(), string.Equals(
messageId.ToString(), j.GetProperty("id").GetString(),
StringComparison.OrdinalIgnoreCase messageId.ToString(),
) StringComparison.OrdinalIgnoreCase
)
); );
if (message.ValueKind == JsonValueKind.Undefined) if (message.ValueKind == JsonValueKind.Undefined)
@@ -131,4 +135,4 @@ public static class ExportWrapper
return message; return message;
} }
} }
@@ -12,6 +12,6 @@ internal static class Secrets
.Build(); .Build();
public static string DiscordToken => public static string DiscordToken =>
Configuration["DISCORD_TOKEN"] ?? Configuration["DISCORD_TOKEN"]
throw new InvalidOperationException("Discord token not provided for tests."); ?? throw new InvalidOperationException("Discord token not provided for tests.");
} }
@@ -14,16 +14,18 @@ public class CsvContentSpecs
var document = await ExportWrapper.ExportAsCsvAsync(ChannelIds.DateRangeTestCases); var document = await ExportWrapper.ExportAsCsvAsync(ChannelIds.DateRangeTestCases);
// Assert // Assert
document.Should().ContainAll( document
"tyrrrz", .Should()
"Hello world", .ContainAll(
"Goodbye world", "tyrrrz",
"Foo bar", "Hello world",
"Hurdle Durdle", "Goodbye world",
"One", "Foo bar",
"Two", "Hurdle Durdle",
"Three", "One",
"Yeet" "Two",
); "Three",
"Yeet"
);
} }
} }
@@ -34,8 +34,7 @@ public class DateRangeSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
var timestamps = Json var timestamps = Json.Parse(await File.ReadAllTextAsync(file.Path))
.Parse(await File.ReadAllTextAsync(file.Path))
.GetProperty("messages") .GetProperty("messages")
.EnumerateArray() .EnumerateArray()
.Select(j => j.GetProperty("timestamp").GetDateTimeOffset()) .Select(j => j.GetProperty("timestamp").GetDateTimeOffset())
@@ -43,21 +42,28 @@ public class DateRangeSpecs
timestamps.All(t => t > after).Should().BeTrue(); timestamps.All(t => t > after).Should().BeTrue();
timestamps.Should().BeEquivalentTo(new[] timestamps
{ .Should()
new DateTimeOffset(2021, 07, 24, 13, 49, 13, TimeSpan.Zero), .BeEquivalentTo(
new DateTimeOffset(2021, 07, 24, 14, 52, 38, TimeSpan.Zero), new[]
new DateTimeOffset(2021, 07, 24, 14, 52, 39, TimeSpan.Zero), {
new DateTimeOffset(2021, 07, 24, 14, 52, 40, TimeSpan.Zero), new DateTimeOffset(2021, 07, 24, 13, 49, 13, TimeSpan.Zero),
new DateTimeOffset(2021, 09, 08, 14, 26, 35, TimeSpan.Zero) new DateTimeOffset(2021, 07, 24, 14, 52, 38, TimeSpan.Zero),
}, o => new DateTimeOffset(2021, 07, 24, 14, 52, 39, TimeSpan.Zero),
{ new DateTimeOffset(2021, 07, 24, 14, 52, 40, TimeSpan.Zero),
return o new DateTimeOffset(2021, 09, 08, 14, 26, 35, TimeSpan.Zero)
.Using<DateTimeOffset>(ctx => },
ctx.Subject.Should().BeCloseTo(ctx.Expectation, TimeSpan.FromSeconds(1)) o =>
) {
.WhenTypeIs<DateTimeOffset>(); return o.Using<DateTimeOffset>(
}); ctx =>
ctx.Subject
.Should()
.BeCloseTo(ctx.Expectation, TimeSpan.FromSeconds(1))
)
.WhenTypeIs<DateTimeOffset>();
}
);
} }
[Fact] [Fact]
@@ -78,8 +84,7 @@ public class DateRangeSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
var timestamps = Json var timestamps = Json.Parse(await File.ReadAllTextAsync(file.Path))
.Parse(await File.ReadAllTextAsync(file.Path))
.GetProperty("messages") .GetProperty("messages")
.EnumerateArray() .EnumerateArray()
.Select(j => j.GetProperty("timestamp").GetDateTimeOffset()) .Select(j => j.GetProperty("timestamp").GetDateTimeOffset())
@@ -87,19 +92,26 @@ public class DateRangeSpecs
timestamps.All(t => t < before).Should().BeTrue(); timestamps.All(t => t < before).Should().BeTrue();
timestamps.Should().BeEquivalentTo(new[] timestamps
{ .Should()
new DateTimeOffset(2021, 07, 19, 13, 34, 18, TimeSpan.Zero), .BeEquivalentTo(
new DateTimeOffset(2021, 07, 19, 15, 58, 48, TimeSpan.Zero), new[]
new DateTimeOffset(2021, 07, 19, 17, 23, 58, TimeSpan.Zero) {
}, o => new DateTimeOffset(2021, 07, 19, 13, 34, 18, TimeSpan.Zero),
{ new DateTimeOffset(2021, 07, 19, 15, 58, 48, TimeSpan.Zero),
return o new DateTimeOffset(2021, 07, 19, 17, 23, 58, TimeSpan.Zero)
.Using<DateTimeOffset>(ctx => },
ctx.Subject.Should().BeCloseTo(ctx.Expectation, TimeSpan.FromSeconds(1)) o =>
) {
.WhenTypeIs<DateTimeOffset>(); return o.Using<DateTimeOffset>(
}); ctx =>
ctx.Subject
.Should()
.BeCloseTo(ctx.Expectation, TimeSpan.FromSeconds(1))
)
.WhenTypeIs<DateTimeOffset>();
}
);
} }
[Fact] [Fact]
@@ -122,8 +134,7 @@ public class DateRangeSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
var timestamps = Json var timestamps = Json.Parse(await File.ReadAllTextAsync(file.Path))
.Parse(await File.ReadAllTextAsync(file.Path))
.GetProperty("messages") .GetProperty("messages")
.EnumerateArray() .EnumerateArray()
.Select(j => j.GetProperty("timestamp").GetDateTimeOffset()) .Select(j => j.GetProperty("timestamp").GetDateTimeOffset())
@@ -131,19 +142,26 @@ public class DateRangeSpecs
timestamps.All(t => t < before && t > after).Should().BeTrue(); timestamps.All(t => t < before && t > after).Should().BeTrue();
timestamps.Should().BeEquivalentTo(new[] timestamps
{ .Should()
new DateTimeOffset(2021, 07, 24, 13, 49, 13, TimeSpan.Zero), .BeEquivalentTo(
new DateTimeOffset(2021, 07, 24, 14, 52, 38, TimeSpan.Zero), new[]
new DateTimeOffset(2021, 07, 24, 14, 52, 39, TimeSpan.Zero), {
new DateTimeOffset(2021, 07, 24, 14, 52, 40, TimeSpan.Zero) new DateTimeOffset(2021, 07, 24, 13, 49, 13, TimeSpan.Zero),
}, o => new DateTimeOffset(2021, 07, 24, 14, 52, 38, TimeSpan.Zero),
{ new DateTimeOffset(2021, 07, 24, 14, 52, 39, TimeSpan.Zero),
return o new DateTimeOffset(2021, 07, 24, 14, 52, 40, TimeSpan.Zero)
.Using<DateTimeOffset>(ctx => },
ctx.Subject.Should().BeCloseTo(ctx.Expectation, TimeSpan.FromSeconds(1)) o =>
) {
.WhenTypeIs<DateTimeOffset>(); return o.Using<DateTimeOffset>(
}); ctx =>
ctx.Subject
.Should()
.BeCloseTo(ctx.Expectation, TimeSpan.FromSeconds(1))
)
.WhenTypeIs<DateTimeOffset>();
}
);
} }
} }
@@ -32,8 +32,7 @@ public class FilterSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
Json Json.Parse(await File.ReadAllTextAsync(file.Path))
.Parse(await File.ReadAllTextAsync(file.Path))
.GetProperty("messages") .GetProperty("messages")
.EnumerateArray() .EnumerateArray()
.Select(j => j.GetProperty("content").GetString()) .Select(j => j.GetProperty("content").GetString())
@@ -58,8 +57,7 @@ public class FilterSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
Json Json.Parse(await File.ReadAllTextAsync(file.Path))
.Parse(await File.ReadAllTextAsync(file.Path))
.GetProperty("messages") .GetProperty("messages")
.EnumerateArray() .EnumerateArray()
.Select(j => j.GetProperty("author").GetProperty("name").GetString()) .Select(j => j.GetProperty("author").GetProperty("name").GetString())
@@ -84,8 +82,7 @@ public class FilterSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
Json Json.Parse(await File.ReadAllTextAsync(file.Path))
.Parse(await File.ReadAllTextAsync(file.Path))
.GetProperty("messages") .GetProperty("messages")
.EnumerateArray() .EnumerateArray()
.Select(j => j.GetProperty("content").GetString()) .Select(j => j.GetProperty("content").GetString())
@@ -110,8 +107,7 @@ public class FilterSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
Json Json.Parse(await File.ReadAllTextAsync(file.Path))
.Parse(await File.ReadAllTextAsync(file.Path))
.GetProperty("messages") .GetProperty("messages")
.EnumerateArray() .EnumerateArray()
.Select(j => j.GetProperty("content").GetString()) .Select(j => j.GetProperty("content").GetString())
@@ -136,12 +132,11 @@ public class FilterSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
Json Json.Parse(await File.ReadAllTextAsync(file.Path))
.Parse(await File.ReadAllTextAsync(file.Path))
.GetProperty("messages") .GetProperty("messages")
.EnumerateArray() .EnumerateArray()
.Select(j => j.GetProperty("content").GetString()) .Select(j => j.GetProperty("content").GetString())
.Should() .Should()
.ContainSingle("This has mention"); .ContainSingle("This has mention");
} }
} }
@@ -1,4 +1,5 @@
using System.Linq; using System;
using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using AngleSharp.Dom; using AngleSharp.Dom;
using DiscordChatExporter.Cli.Tests.Infra; using DiscordChatExporter.Cli.Tests.Infra;
@@ -20,18 +21,18 @@ public class HtmlAttachmentSpecs
); );
// Assert // Assert
message.Text().Should().ContainAll( message.Text().Should().ContainAll("Generic file attachment", "Test.txt", "11 bytes");
"Generic file attachment",
"Test.txt",
"11 bytes"
);
message message
.QuerySelectorAll("a") .QuerySelectorAll("a")
.Select(e => e.GetAttribute("href")) .Select(e => e.GetAttribute("href"))
.Should() .Should()
.Contain( .Contain(
"https://cdn.discordapp.com/attachments/885587741654536192/885587844964417596/Test.txt" u =>
u.StartsWith(
"https://cdn.discordapp.com/attachments/885587741654536192/885587844964417596/Test.txt",
StringComparison.Ordinal
)
); );
} }
@@ -52,7 +53,11 @@ public class HtmlAttachmentSpecs
.Select(e => e.GetAttribute("src")) .Select(e => e.GetAttribute("src"))
.Should() .Should()
.Contain( .Contain(
"https://cdn.discordapp.com/attachments/885587741654536192/885654862430359613/bird-thumbnail.png" u =>
u.StartsWith(
"https://cdn.discordapp.com/attachments/885587741654536192/885654862430359613/bird-thumbnail.png",
StringComparison.Ordinal
)
); );
} }
@@ -71,9 +76,11 @@ public class HtmlAttachmentSpecs
message.Text().Should().Contain("Video attachment"); message.Text().Should().Contain("Video attachment");
var videoUrl = message.QuerySelector("video source")?.GetAttribute("src"); var videoUrl = message.QuerySelector("video source")?.GetAttribute("src");
videoUrl.Should().Be( videoUrl
"https://cdn.discordapp.com/attachments/885587741654536192/885655761512968233/file_example_MP4_640_3MG.mp4" .Should()
); .StartWith(
"https://cdn.discordapp.com/attachments/885587741654536192/885655761512968233/file_example_MP4_640_3MG.mp4"
);
} }
[Fact] [Fact]
@@ -91,8 +98,10 @@ public class HtmlAttachmentSpecs
message.Text().Should().Contain("Audio attachment"); message.Text().Should().Contain("Audio attachment");
var audioUrl = message.QuerySelector("audio source")?.GetAttribute("src"); var audioUrl = message.QuerySelector("audio source")?.GetAttribute("src");
audioUrl.Should().Be( audioUrl
"https://cdn.discordapp.com/attachments/885587741654536192/885656175348187146/file_example_MP3_1MG.mp3" .Should()
); .StartWith(
"https://cdn.discordapp.com/attachments/885587741654536192/885656175348187146/file_example_MP3_1MG.mp3"
);
} }
} }
@@ -16,26 +16,32 @@ public class HtmlContentSpecs
var messages = await ExportWrapper.GetMessagesAsHtmlAsync(ChannelIds.DateRangeTestCases); var messages = await ExportWrapper.GetMessagesAsHtmlAsync(ChannelIds.DateRangeTestCases);
// Assert // Assert
messages.Select(e => e.GetAttribute("data-message-id")).Should().Equal( messages
"866674314627121232", .Select(e => e.GetAttribute("data-message-id"))
"866710679758045195", .Should()
"866732113319428096", .Equal(
"868490009366396958", "866674314627121232",
"868505966528835604", "866710679758045195",
"868505969821364245", "866732113319428096",
"868505973294268457", "868490009366396958",
"885169254029213696" "868505966528835604",
); "868505969821364245",
"868505973294268457",
"885169254029213696"
);
messages.SelectMany(e => e.Text()).Should().ContainInOrder( messages
"Hello world", .SelectMany(e => e.Text())
"Goodbye world", .Should()
"Foo bar", .ContainInOrder(
"Hurdle Durdle", "Hello world",
"One", "Goodbye world",
"Two", "Foo bar",
"Three", "Hurdle Durdle",
"Yeet" "One",
); "Two",
"Three",
"Yeet"
);
} }
} }
@@ -21,15 +21,21 @@ public class HtmlEmbedSpecs
); );
// Assert // Assert
message.Text().Should().ContainAll( message
"Embed author", .Text()
"Embed title", .Should()
"Embed description", .ContainAll(
"Field 1", "Value 1", "Embed author",
"Field 2", "Value 2", "Embed title",
"Field 3", "Value 3", "Embed description",
"Embed footer" "Field 1",
); "Value 1",
"Field 2",
"Value 2",
"Field 3",
"Value 3",
"Embed footer"
);
} }
[Fact] [Fact]
@@ -83,7 +89,12 @@ public class HtmlEmbedSpecs
.QuerySelectorAll("source") .QuerySelectorAll("source")
.Select(e => e.GetAttribute("src")) .Select(e => e.GetAttribute("src"))
.WhereNotNull() .WhereNotNull()
.Where(s => s.EndsWith("i_am_currently_feeling_slight_displeasure_of_what_you_have_just_sent_lqrem.mp4")) .Where(
s =>
s.EndsWith(
"i_am_currently_feeling_slight_displeasure_of_what_you_have_just_sent_lqrem.mp4"
)
)
.Should() .Should()
.ContainSingle(); .ContainSingle();
} }
@@ -134,7 +145,7 @@ public class HtmlEmbedSpecs
// Assert // Assert
var iframeUrl = message.QuerySelector("iframe")?.GetAttribute("src"); var iframeUrl = message.QuerySelector("iframe")?.GetAttribute("src");
iframeUrl.Should().Be("https://open.spotify.com/embed/track/1LHZMWefF9502NPfArRfvP"); iframeUrl.Should().StartWith("https://open.spotify.com/embed/track/1LHZMWefF9502NPfArRfvP");
} }
[Fact] [Fact]
@@ -150,7 +161,7 @@ public class HtmlEmbedSpecs
// Assert // Assert
var iframeUrl = message.QuerySelector("iframe")?.GetAttribute("src"); var iframeUrl = message.QuerySelector("iframe")?.GetAttribute("src");
iframeUrl.Should().Be("https://www.youtube.com/embed/qOWW4OlgbvE"); iframeUrl.Should().StartWith("https://www.youtube.com/embed/qOWW4OlgbvE");
} }
[Fact] [Fact]
@@ -193,4 +204,4 @@ public class HtmlEmbedSpecs
// Assert // Assert
message.Text().Should().Contain("DiscordChatExporter TestServer"); message.Text().Should().Contain("DiscordChatExporter TestServer");
} }
} }
@@ -32,8 +32,7 @@ public class HtmlGroupingSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
var messageGroups = Html var messageGroups = Html.Parse(await File.ReadAllTextAsync(file.Path))
.Parse(await File.ReadAllTextAsync(file.Path))
.QuerySelectorAll(".chatlog__message-group"); .QuerySelectorAll(".chatlog__message-group");
messageGroups.Should().HaveCount(2); messageGroups.Should().HaveCount(2);
@@ -59,12 +58,6 @@ public class HtmlGroupingSpecs
.QuerySelectorAll(".chatlog__content") .QuerySelectorAll(".chatlog__content")
.Select(e => e.Text()) .Select(e => e.Text())
.Should() .Should()
.ContainInOrder( .ContainInOrder("Eleventh", "Twelveth", "Thirteenth", "Fourteenth", "Fifteenth");
"Eleventh",
"Twelveth",
"Thirteenth",
"Fourteenth",
"Fifteenth"
);
} }
} }
@@ -1,8 +1,6 @@
using System; using System.Threading.Tasks;
using System.Threading.Tasks;
using AngleSharp.Dom; using AngleSharp.Dom;
using DiscordChatExporter.Cli.Tests.Infra; using DiscordChatExporter.Cli.Tests.Infra;
using DiscordChatExporter.Cli.Tests.Utils;
using DiscordChatExporter.Core.Discord; using DiscordChatExporter.Core.Discord;
using FluentAssertions; using FluentAssertions;
using Xunit; using Xunit;
@@ -14,215 +12,128 @@ public class HtmlMarkdownSpecs
[Fact] [Fact]
public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker() public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker()
{ {
// Date formatting code relies on the local time zone, so we need to set it to a fixed value // Act
TimeZoneInfoEx.SetLocal(TimeSpan.FromHours(+2)); var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323136411078787")
);
try // Assert
{ message.Text().Should().Contain("Default timestamp: 2/12/2023 1:36 PM");
// Act message.InnerHtml.Should().Contain("Sunday, February 12, 2023 1:36 PM");
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323136411078787")
);
// Assert
message.Text().Should().Contain("Default timestamp: 02/12/2023 3:36 PM");
message.InnerHtml.Should().Contain("Sunday, February 12, 2023 3:36 PM");
}
finally
{
TimeZoneInfo.ClearCachedData();
}
} }
[Fact] [Fact]
public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_short_format() public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_short_format()
{ {
// Date formatting code relies on the local time zone, so we need to set it to a fixed value // Act
TimeZoneInfoEx.SetLocal(TimeSpan.FromHours(+2)); var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323205268967596")
);
try // Assert
{ message.Text().Should().Contain("Short time timestamp: 1:36 PM");
// Act message.InnerHtml.Should().Contain("Sunday, February 12, 2023 1:36 PM");
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323205268967596")
);
// Assert
message.Text().Should().Contain("Short time timestamp: 3:36 PM");
message.InnerHtml.Should().Contain("Sunday, February 12, 2023 3:36 PM");
}
finally
{
TimeZoneInfo.ClearCachedData();
}
} }
[Fact] [Fact]
public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_long_format() public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_long_format()
{ {
// Date formatting code relies on the local time zone, so we need to set it to a fixed value // Act
TimeZoneInfoEx.SetLocal(TimeSpan.FromHours(+2)); var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323235342139483")
);
try // Assert
{ message.Text().Should().Contain("Long time timestamp: 1:36:12 PM");
// Act message.InnerHtml.Should().Contain("Sunday, February 12, 2023 1:36 PM");
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323235342139483")
);
// Assert
message.Text().Should().Contain("Long time timestamp: 3:36:12 PM");
message.InnerHtml.Should().Contain("Sunday, February 12, 2023 3:36 PM");
}
finally
{
TimeZoneInfo.ClearCachedData();
}
} }
[Fact] [Fact]
public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_short_date_format() public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_short_date_format()
{ {
// Date formatting code relies on the local time zone, so we need to set it to a fixed value // Act
TimeZoneInfoEx.SetLocal(TimeSpan.FromHours(+2)); var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323326727634984")
);
try // Assert
{ message.Text().Should().Contain("Short date timestamp: 2/12/2023");
// Act message.InnerHtml.Should().Contain("Sunday, February 12, 2023 1:36 PM");
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323326727634984")
);
// Assert
message.Text().Should().Contain("Short date timestamp: 02/12/2023");
message.InnerHtml.Should().Contain("Sunday, February 12, 2023 3:36 PM");
}
finally
{
TimeZoneInfo.ClearCachedData();
}
} }
[Fact] [Fact]
public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_long_date_format() public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_long_date_format()
{ {
// Date formatting code relies on the local time zone, so we need to set it to a fixed value // Act
TimeZoneInfoEx.SetLocal(TimeSpan.FromHours(+2)); var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323350731640863")
);
try // Assert
{ message.Text().Should().Contain("Long date timestamp: Sunday, February 12, 2023");
// Act message.InnerHtml.Should().Contain("Sunday, February 12, 2023 1:36 PM");
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323350731640863")
);
// Assert
message.Text().Should().Contain("Long date timestamp: February 12, 2023");
message.InnerHtml.Should().Contain("Sunday, February 12, 2023 3:36 PM");
}
finally
{
TimeZoneInfo.ClearCachedData();
}
} }
[Fact] [Fact]
public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_full_format() public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_full_format()
{ {
// Date formatting code relies on the local time zone, so we need to set it to a fixed value // Act
TimeZoneInfoEx.SetLocal(TimeSpan.FromHours(+2)); var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323374379118593")
);
try // Assert
{ message.Text().Should().Contain("Full timestamp: Sunday, February 12, 2023 1:36 PM");
// Act message.InnerHtml.Should().Contain("Sunday, February 12, 2023 1:36 PM");
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323374379118593")
);
// Assert
message.Text().Should().Contain("Full timestamp: February 12, 2023 3:36 PM");
message.InnerHtml.Should().Contain("Sunday, February 12, 2023 3:36 PM");
}
finally
{
TimeZoneInfo.ClearCachedData();
}
} }
[Fact] [Fact]
public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_full_long_format() public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_full_long_format()
{ {
// Date formatting code relies on the local time zone, so we need to set it to a fixed value // Act
TimeZoneInfoEx.SetLocal(TimeSpan.FromHours(+2)); var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323409095376947")
);
try // Assert
{ message
// Act .Text()
var message = await ExportWrapper.GetMessageAsHtmlAsync( .Should()
ChannelIds.MarkdownTestCases, .Contain("Full long timestamp: Sunday, February 12, 2023 1:36:12 PM");
Snowflake.Parse("1074323409095376947") message.InnerHtml.Should().Contain("Sunday, February 12, 2023 1:36 PM");
);
// Assert
message.Text().Should().Contain("Full long timestamp: Sunday, February 12, 2023 3:36 PM");
message.InnerHtml.Should().Contain("Sunday, February 12, 2023 3:36 PM");
}
finally
{
TimeZoneInfo.ClearCachedData();
}
} }
[Fact] [Fact]
public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_relative_format() public async Task I_can_export_a_channel_that_contains_a_message_with_a_timestamp_marker_in_the_relative_format()
{ {
// Date formatting code relies on the local time zone, so we need to set it to a fixed value // Act
TimeZoneInfoEx.SetLocal(TimeSpan.FromHours(+2)); var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323436853285004")
);
try // Assert
{ message.Text().Should().Contain("Relative timestamp: 2/12/2023 1:36 PM");
// Act message.InnerHtml.Should().Contain("Sunday, February 12, 2023 1:36 PM");
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074323436853285004")
);
// Assert
message.Text().Should().Contain("Relative timestamp: 02/12/2023 3:36 PM");
message.InnerHtml.Should().Contain("Sunday, February 12, 2023 3:36 PM");
}
finally
{
TimeZoneInfo.ClearCachedData();
}
} }
[Fact] [Fact]
public async Task I_can_export_a_channel_that_contains_a_message_with_an_invalid_timestamp_marker() public async Task I_can_export_a_channel_that_contains_a_message_with_an_invalid_timestamp_marker()
{ {
// Date formatting code relies on the local time zone, so we need to set it to a fixed value // Act
TimeZoneInfoEx.SetLocal(TimeSpan.FromHours(+2)); var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074328534409019563")
);
try // Assert
{ message.Text().Should().Contain("Invalid timestamp: Invalid date");
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MarkdownTestCases,
Snowflake.Parse("1074328534409019563")
);
// Assert
message.Text().Should().Contain("Invalid timestamp: Invalid date");
}
finally
{
TimeZoneInfo.ClearCachedData();
}
} }
} }
@@ -61,4 +61,4 @@ public class HtmlMentionSpecs
// Assert // Assert
message.Text().Should().Contain("Role mention: @Role 1"); message.Text().Should().Contain("Role mention: @Role 1");
} }
} }
@@ -36,9 +36,11 @@ public class HtmlReplySpecs
// Assert // Assert
message.Text().Should().Contain("reply to deleted"); message.Text().Should().Contain("reply to deleted");
message.QuerySelector(".chatlog__reply-link")?.Text().Should().Contain( message
"Original message was deleted or could not be loaded." .QuerySelector(".chatlog__reply-link")
); ?.Text()
.Should()
.Contain("Original message was deleted or could not be loaded.");
} }
[Fact] [Fact]
@@ -54,7 +56,11 @@ public class HtmlReplySpecs
// Assert // Assert
message.Text().Should().Contain("reply to attachment"); message.Text().Should().Contain("reply to attachment");
message.QuerySelector(".chatlog__reply-link")?.Text().Should().Contain("Click to see attachment"); message
.QuerySelector(".chatlog__reply-link")
?.Text()
.Should()
.Contain("Click to see attachment");
} }
[Fact] [Fact]
@@ -84,8 +90,11 @@ public class HtmlReplySpecs
); );
// Assert // Assert
message.Text().Should().Contain("This is a test message from an announcement channel on another server"); message
.Text()
.Should()
.Contain("This is a test message from an announcement channel on another server");
message.Text().Should().Contain("SERVER"); message.Text().Should().Contain("SERVER");
message.QuerySelector(".chatlog__reply-link").Should().BeNull(); message.QuerySelector(".chatlog__reply-link").Should().BeNull();
} }
} }
@@ -19,7 +19,7 @@ public class HtmlStickerSpecs
// Assert // Assert
var stickerUrl = message.QuerySelector("[title='rock'] img")?.GetAttribute("src"); var stickerUrl = message.QuerySelector("[title='rock'] img")?.GetAttribute("src");
stickerUrl.Should().Be("https://cdn.discordapp.com/stickers/904215665597120572.png"); stickerUrl.Should().StartWith("https://cdn.discordapp.com/stickers/904215665597120572.png");
} }
[Fact] [Fact]
@@ -32,7 +32,12 @@ public class HtmlStickerSpecs
); );
// Assert // Assert
var stickerUrl = message.QuerySelector("[title='Yikes'] [data-source]")?.GetAttribute("data-source"); var stickerUrl = message
stickerUrl.Should().Be("https://cdn.discordapp.com/stickers/816087132447178774.json"); .QuerySelector("[title='Yikes'] [data-source]")
?.GetAttribute("data-source");
stickerUrl
.Should()
.StartWith("https://cdn.discordapp.com/stickers/816087132447178774.json");
} }
} }
@@ -24,9 +24,14 @@ public class JsonAttachmentSpecs
var attachments = message.GetProperty("attachments").EnumerateArray().ToArray(); var attachments = message.GetProperty("attachments").EnumerateArray().ToArray();
attachments.Should().HaveCount(1); attachments.Should().HaveCount(1);
attachments[0].GetProperty("url").GetString().Should().Be( attachments[0]
"https://cdn.discordapp.com/attachments/885587741654536192/885587844964417596/Test.txt" .GetProperty("url")
); .GetString()
.Should()
.StartWith(
"https://cdn.discordapp.com/attachments/885587741654536192/885587844964417596/Test.txt"
);
attachments[0].GetProperty("fileName").GetString().Should().Be("Test.txt"); attachments[0].GetProperty("fileName").GetString().Should().Be("Test.txt");
attachments[0].GetProperty("fileSizeBytes").GetInt64().Should().Be(11); attachments[0].GetProperty("fileSizeBytes").GetInt64().Should().Be(11);
} }
@@ -46,9 +51,14 @@ public class JsonAttachmentSpecs
var attachments = message.GetProperty("attachments").EnumerateArray().ToArray(); var attachments = message.GetProperty("attachments").EnumerateArray().ToArray();
attachments.Should().HaveCount(1); attachments.Should().HaveCount(1);
attachments[0].GetProperty("url").GetString().Should().Be( attachments[0]
"https://cdn.discordapp.com/attachments/885587741654536192/885654862430359613/bird-thumbnail.png" .GetProperty("url")
); .GetString()
.Should()
.StartWith(
"https://cdn.discordapp.com/attachments/885587741654536192/885654862430359613/bird-thumbnail.png"
);
attachments[0].GetProperty("fileName").GetString().Should().Be("bird-thumbnail.png"); attachments[0].GetProperty("fileName").GetString().Should().Be("bird-thumbnail.png");
attachments[0].GetProperty("fileSizeBytes").GetInt64().Should().Be(466335); attachments[0].GetProperty("fileSizeBytes").GetInt64().Should().Be(466335);
} }
@@ -68,10 +78,20 @@ public class JsonAttachmentSpecs
var attachments = message.GetProperty("attachments").EnumerateArray().ToArray(); var attachments = message.GetProperty("attachments").EnumerateArray().ToArray();
attachments.Should().HaveCount(1); attachments.Should().HaveCount(1);
attachments[0].GetProperty("url").GetString().Should().Be( attachments[0]
"https://cdn.discordapp.com/attachments/885587741654536192/885655761512968233/file_example_MP4_640_3MG.mp4" .GetProperty("url")
); .GetString()
attachments[0].GetProperty("fileName").GetString().Should().Be("file_example_MP4_640_3MG.mp4"); .Should()
.StartWith(
"https://cdn.discordapp.com/attachments/885587741654536192/885655761512968233/file_example_MP4_640_3MG.mp4"
);
attachments[0]
.GetProperty("fileName")
.GetString()
.Should()
.Be("file_example_MP4_640_3MG.mp4");
attachments[0].GetProperty("fileSizeBytes").GetInt64().Should().Be(3114374); attachments[0].GetProperty("fileSizeBytes").GetInt64().Should().Be(3114374);
} }
@@ -90,10 +110,15 @@ public class JsonAttachmentSpecs
var attachments = message.GetProperty("attachments").EnumerateArray().ToArray(); var attachments = message.GetProperty("attachments").EnumerateArray().ToArray();
attachments.Should().HaveCount(1); attachments.Should().HaveCount(1);
attachments[0].GetProperty("url").GetString().Should().Be( attachments[0]
"https://cdn.discordapp.com/attachments/885587741654536192/885656175348187146/file_example_MP3_1MG.mp3" .GetProperty("url")
); .GetString()
.Should()
.StartWith(
"https://cdn.discordapp.com/attachments/885587741654536192/885656175348187146/file_example_MP3_1MG.mp3"
);
attachments[0].GetProperty("fileName").GetString().Should().Be("file_example_MP3_1MG.mp3"); attachments[0].GetProperty("fileName").GetString().Should().Be("file_example_MP3_1MG.mp3");
attachments[0].GetProperty("fileSizeBytes").GetInt64().Should().Be(1087849); attachments[0].GetProperty("fileSizeBytes").GetInt64().Should().Be(1087849);
} }
} }
@@ -15,26 +15,32 @@ public class JsonContentSpecs
var messages = await ExportWrapper.GetMessagesAsJsonAsync(ChannelIds.DateRangeTestCases); var messages = await ExportWrapper.GetMessagesAsJsonAsync(ChannelIds.DateRangeTestCases);
// Assert // Assert
messages.Select(j => j.GetProperty("id").GetString()).Should().Equal( messages
"866674314627121232", .Select(j => j.GetProperty("id").GetString())
"866710679758045195", .Should()
"866732113319428096", .Equal(
"868490009366396958", "866674314627121232",
"868505966528835604", "866710679758045195",
"868505969821364245", "866732113319428096",
"868505973294268457", "868490009366396958",
"885169254029213696" "868505966528835604",
); "868505969821364245",
"868505973294268457",
"885169254029213696"
);
messages.Select(j => j.GetProperty("content").GetString()).Should().Equal( messages
"Hello world", .Select(j => j.GetProperty("content").GetString())
"Goodbye world", .Should()
"Foo bar", .Equal(
"Hurdle Durdle", "Hello world",
"One", "Goodbye world",
"Two", "Foo bar",
"Three", "Hurdle Durdle",
"Yeet" "One",
); "Two",
"Three",
"Yeet"
);
} }
} }
@@ -52,4 +52,4 @@ public class JsonEmbedSpecs
embedFields[2].GetProperty("value").GetString().Should().Be("Value 3"); embedFields[2].GetProperty("value").GetString().Should().Be("Value 3");
embedFields[2].GetProperty("isInline").GetBoolean().Should().BeTrue(); embedFields[2].GetProperty("isInline").GetBoolean().Should().BeTrue();
} }
} }
@@ -39,7 +39,11 @@ public class JsonMentionSpecs
); );
// Assert // Assert
message.GetProperty("content").GetString().Should().Be("Text channel mention: #mention-tests"); message
.GetProperty("content")
.GetString()
.Should()
.Be("Text channel mention: #mention-tests");
} }
[Fact] [Fact]
@@ -52,7 +56,11 @@ public class JsonMentionSpecs
); );
// Assert // Assert
message.GetProperty("content").GetString().Should().Be("Voice channel mention: #general [voice]"); message
.GetProperty("content")
.GetString()
.Should()
.Be("Voice channel mention: #general [voice]");
} }
[Fact] [Fact]
@@ -67,4 +75,4 @@ public class JsonMentionSpecs
// Assert // Assert
message.GetProperty("content").GetString().Should().Be("Role mention: @Role 1"); message.GetProperty("content").GetString().Should().Be("Role mention: @Role 1");
} }
} }
@@ -19,15 +19,16 @@ public class JsonStickerSpecs
); );
// Assert // Assert
var sticker = message var sticker = message.GetProperty("stickers").EnumerateArray().Single();
.GetProperty("stickers")
.EnumerateArray()
.Single();
sticker.GetProperty("id").GetString().Should().Be("904215665597120572"); sticker.GetProperty("id").GetString().Should().Be("904215665597120572");
sticker.GetProperty("name").GetString().Should().Be("rock"); sticker.GetProperty("name").GetString().Should().Be("rock");
sticker.GetProperty("format").GetString().Should().Be("Apng"); sticker.GetProperty("format").GetString().Should().Be("Apng");
sticker.GetProperty("sourceUrl").GetString().Should().Be("https://cdn.discordapp.com/stickers/904215665597120572.png"); sticker
.GetProperty("sourceUrl")
.GetString()
.Should()
.StartWith("https://cdn.discordapp.com/stickers/904215665597120572.png");
} }
[Fact] [Fact]
@@ -40,14 +41,15 @@ public class JsonStickerSpecs
); );
// Assert // Assert
var sticker = message var sticker = message.GetProperty("stickers").EnumerateArray().Single();
.GetProperty("stickers")
.EnumerateArray()
.Single();
sticker.GetProperty("id").GetString().Should().Be("816087132447178774"); sticker.GetProperty("id").GetString().Should().Be("816087132447178774");
sticker.GetProperty("name").GetString().Should().Be("Yikes"); sticker.GetProperty("name").GetString().Should().Be("Yikes");
sticker.GetProperty("format").GetString().Should().Be("Lottie"); sticker.GetProperty("format").GetString().Should().Be("Lottie");
sticker.GetProperty("sourceUrl").GetString().Should().Be("https://cdn.discordapp.com/stickers/816087132447178774.json"); sticker
.GetProperty("sourceUrl")
.GetString()
.Should()
.StartWith("https://cdn.discordapp.com/stickers/816087132447178774.json");
} }
} }
@@ -31,9 +31,7 @@ public class PartitioningSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
Directory.EnumerateFiles(dir.Path, "output*") Directory.EnumerateFiles(dir.Path, "output*").Should().HaveCount(3);
.Should()
.HaveCount(3);
} }
[Fact] [Fact]
@@ -54,8 +52,6 @@ public class PartitioningSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
Directory.EnumerateFiles(dir.Path, "output*") Directory.EnumerateFiles(dir.Path, "output*").Should().HaveCount(8);
.Should()
.HaveCount(8);
} }
} }
@@ -14,16 +14,18 @@ public class PlainTextContentSpecs
var document = await ExportWrapper.ExportAsPlainTextAsync(ChannelIds.DateRangeTestCases); var document = await ExportWrapper.ExportAsPlainTextAsync(ChannelIds.DateRangeTestCases);
// Assert // Assert
document.Should().ContainAll( document
"tyrrrz", .Should()
"Hello world", .ContainAll(
"Goodbye world", "tyrrrz",
"Foo bar", "Hello world",
"Hurdle Durdle", "Goodbye world",
"One", "Foo bar",
"Two", "Hurdle Durdle",
"Three", "One",
"Yeet" "Two",
); "Three",
"Yeet"
);
} }
} }
@@ -31,8 +31,7 @@ public class SelfContainedSpecs
}.ExecuteAsync(new FakeConsole()); }.ExecuteAsync(new FakeConsole());
// Assert // Assert
Html Html.Parse(await File.ReadAllTextAsync(filePath))
.Parse(await File.ReadAllTextAsync(filePath))
.QuerySelectorAll("body [src]") .QuerySelectorAll("body [src]")
.Select(e => e.GetAttribute("src")!) .Select(e => e.GetAttribute("src")!)
.Select(f => Path.GetFullPath(f, dir.Path)) .Select(f => Path.GetFullPath(f, dir.Path))
@@ -40,4 +39,4 @@ public class SelfContainedSpecs
.Should() .Should()
.BeTrue(); .BeTrue();
} }
} }
+1 -1
View File
@@ -8,4 +8,4 @@ internal static class Html
private static readonly IHtmlParser Parser = new HtmlParser(); private static readonly IHtmlParser Parser = new HtmlParser();
public static IHtmlDocument Parse(string source) => Parser.ParseDocument(source); public static IHtmlDocument Parse(string source) => Parser.ParseDocument(source);
} }
@@ -9,8 +9,7 @@ internal partial class TempDir : IDisposable
{ {
public string Path { get; } public string Path { get; }
public TempDir(string path) => public TempDir(string path) => Path = path;
Path = path;
public void Dispose() public void Dispose()
{ {
@@ -18,9 +17,7 @@ internal partial class TempDir : IDisposable
{ {
Directory.Delete(Path, true); Directory.Delete(Path, true);
} }
catch (DirectoryNotFoundException) catch (DirectoryNotFoundException) { }
{
}
} }
} }
@@ -29,7 +26,8 @@ internal partial class TempDir
public static TempDir Create() public static TempDir Create()
{ {
var dirPath = PathEx.Combine( var dirPath = PathEx.Combine(
PathEx.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? Directory.GetCurrentDirectory(), PathEx.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
?? Directory.GetCurrentDirectory(),
"Temp", "Temp",
Guid.NewGuid().ToString() Guid.NewGuid().ToString()
); );
@@ -38,4 +36,4 @@ internal partial class TempDir
return new TempDir(dirPath); return new TempDir(dirPath);
} }
} }
@@ -9,8 +9,7 @@ internal partial class TempFile : IDisposable
{ {
public string Path { get; } public string Path { get; }
public TempFile(string path) => public TempFile(string path) => Path = path;
Path = path;
public void Dispose() public void Dispose()
{ {
@@ -18,9 +17,7 @@ internal partial class TempFile : IDisposable
{ {
File.Delete(Path); File.Delete(Path);
} }
catch (FileNotFoundException) catch (FileNotFoundException) { }
{
}
} }
} }
@@ -29,17 +26,15 @@ internal partial class TempFile
public static TempFile Create() public static TempFile Create()
{ {
var dirPath = PathEx.Combine( var dirPath = PathEx.Combine(
PathEx.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? Directory.GetCurrentDirectory(), PathEx.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
?? Directory.GetCurrentDirectory(),
"Temp" "Temp"
); );
Directory.CreateDirectory(dirPath); Directory.CreateDirectory(dirPath);
var filePath = PathEx.Combine( var filePath = PathEx.Combine(dirPath, Guid.NewGuid() + ".tmp");
dirPath,
Guid.NewGuid() + ".tmp"
);
return new TempFile(filePath); return new TempFile(filePath);
} }
} }
@@ -1,14 +0,0 @@
using System;
using ReflectionMagic;
namespace DiscordChatExporter.Cli.Tests.Utils;
internal static class TimeZoneInfoEx
{
// https://stackoverflow.com/a/63700512/2205454
public static void SetLocal(TimeZoneInfo timeZone) =>
typeof(TimeZoneInfo).AsDynamicType().s_cachedData._localTimeZone = timeZone;
public static void SetLocal(TimeSpan offset) =>
SetLocal(TimeZoneInfo.CreateCustomTimeZone("test-tz", offset, "test-tz", "test-tz"));
}
+25 -14
View File
@@ -1,18 +1,13 @@
# -- Build # -- Build
# Specify the platform here so that we pull the SDK image matching the host platform, # Specify the platform here so that we pull the SDK image matching the host platform,
# instead of the target platform specified during build by the `--platform` option. # instead of the target platform specified during build by the `--platform` option.
# Use the .NET 8.0 preview because the `--arch` option is only available in that version. FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build
# https://github.com/dotnet/dotnet-docker/issues/4388#issuecomment-1459038566
# TODO: switch images to Alpine once .NET 8.0 is released.
# Currently, the correct preview version is only available on Debian.
# https://github.com/dotnet/dotnet-docker/blob/main/samples/selecting-tags.md
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0-preview AS build
# Expose the target architecture set by the `docker build --platform` option, so that # Expose the target architecture set by the `docker build --platform` option, so that
# we can build the assembly for the correct platform. # we can build the assembly for the correct platform.
ARG TARGETARCH ARG TARGETARCH
WORKDIR /build WORKDIR /tmp/app
COPY favicon.ico . COPY favicon.ico .
COPY NuGet.config . COPY NuGet.config .
@@ -22,24 +17,40 @@ COPY DiscordChatExporter.Cli DiscordChatExporter.Cli
# Publish a self-contained assembly so we can use a slimmer runtime image # Publish a self-contained assembly so we can use a slimmer runtime image
RUN dotnet publish DiscordChatExporter.Cli \ RUN dotnet publish DiscordChatExporter.Cli \
-p:CSharpier_Bypass=true \
--configuration Release \ --configuration Release \
--self-contained \ --self-contained \
--use-current-runtime \ --use-current-runtime \
--arch $TARGETARCH \ --arch $TARGETARCH \
--output publish/ --output DiscordChatExporter.Cli/bin/publish/
# -- Run # -- Run
# Use `runtime-deps` instead of `runtime` because we have a self-contained assembly # Use `runtime-deps` instead of `runtime` because we have a self-contained assembly
FROM --platform=$TARGETPLATFORM mcr.microsoft.com/dotnet/runtime-deps:7.0 AS run FROM --platform=$TARGETPLATFORM mcr.microsoft.com/dotnet/runtime-deps:8.0-alpine AS run
# Create a non-root user to run the app, so that the output files can be accessed by the host LABEL org.opencontainers.image.title="DiscordChatExporter.Cli"
LABEL org.opencontainers.image.description="DiscordChatExporter is an application that can be used to export message history from any Discord channel to a file."
LABEL org.opencontainers.image.authors="tyrrrz.me"
LABEL org.opencontainers.image.url="https://github.com/Tyrrrz/DiscordChatExporter"
LABEL org.opencontainers.image.source="https://github.com/Tyrrrz/DiscordChatExporter/blob/master/DiscordChatExporter.Cli.dockerfile"
LABEL org.opencontainers.image.licenses="MIT"
# Alpine image doesn't come with the ICU libraries pre-installed, so we need to install them manually.
# We need the full ICU data because we allow the user to specify any locale for formatting purposes.
RUN apk add --no-cache icu-libs
RUN apk add --no-cache icu-data-full
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false
ENV LC_ALL=en_US.UTF-8
ENV LANG=en_US.UTF-8
# Use a non-root user to ensure that the files shared with the host are accessible by the host user.
# We can use the default user provided by the base image for this purpose.
# https://github.com/Tyrrrz/DiscordChatExporter/issues/851 # https://github.com/Tyrrrz/DiscordChatExporter/issues/851
RUN adduser --disabled-password --no-create-home dce USER $APP_UID
USER dce
# This directory is exposed to the user for mounting purposes, so it's important that it always # This directory is exposed to the user for mounting purposes, so it's important that it always
# stays the same for backwards compatibility. # stays the same for backwards compatibility.
WORKDIR /out WORKDIR /out
COPY --from=build /build/publish /opt/dce COPY --from=build /tmp/app/DiscordChatExporter.Cli/bin/publish /opt/app
ENTRYPOINT ["/opt/dce/DiscordChatExporter.Cli"] ENTRYPOINT ["/opt/app/DiscordChatExporter.Cli"]
@@ -24,10 +24,41 @@ public abstract class DiscordCommandBase : ICommand
EnvironmentVariable = "DISCORD_TOKEN_BOT", EnvironmentVariable = "DISCORD_TOKEN_BOT",
Description = "This option doesn't do anything. Kept for backwards compatibility." Description = "This option doesn't do anything. Kept for backwards compatibility."
)] )]
public bool IsBotToken { get; init; } public bool IsBotToken { get; init; } = false;
private DiscordClient? _discordClient; private DiscordClient? _discordClient;
protected DiscordClient Discord => _discordClient ??= new DiscordClient(Token); protected DiscordClient Discord => _discordClient ??= new DiscordClient(Token);
public abstract ValueTask ExecuteAsync(IConsole console); public virtual ValueTask ExecuteAsync(IConsole console)
} {
#pragma warning disable CS0618
// Warn if the bot option is used
if (IsBotToken)
{
using (console.WithForegroundColor(ConsoleColor.DarkYellow))
{
console
.Error
.WriteLine(
"Warning: Option --bot is deprecated and should not be used. "
+ "The type of the provided token is now inferred automatically. "
+ "Please update your workflows as this option may be completely removed in a future version."
);
}
}
#pragma warning restore CS0618
// Note about interactivity
if (console.IsOutputRedirected)
{
console
.Output
.WriteLine(
"Note: Output streams are redirected, rich console interactions are disabled. "
+ "If you are running this command in Docker, consider allocating a pseudo-terminal for better user experience (docker run -it ...)."
);
}
return default;
}
}
@@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -15,9 +16,9 @@ using DiscordChatExporter.Core.Exceptions;
using DiscordChatExporter.Core.Exporting; using DiscordChatExporter.Core.Exporting;
using DiscordChatExporter.Core.Exporting.Filtering; using DiscordChatExporter.Core.Exporting.Filtering;
using DiscordChatExporter.Core.Exporting.Partitioning; using DiscordChatExporter.Core.Exporting.Partitioning;
using DiscordChatExporter.Core.Utils;
using DiscordChatExporter.Core.Utils.Extensions; using DiscordChatExporter.Core.Utils.Extensions;
using Gress; using Gress;
using Spectre.Console;
namespace DiscordChatExporter.Cli.Commands.Base; namespace DiscordChatExporter.Cli.Commands.Base;
@@ -28,11 +29,10 @@ public abstract class ExportCommandBase : DiscordCommandBase
[CommandOption( [CommandOption(
"output", "output",
'o', 'o',
Description = Description = "Output file or directory path. "
"Output file or directory path. " + + "Directory path must end with a slash to avoid ambiguity. "
"Directory path must end with a slash to avoid ambiguity. " + + "If a directory is specified, file names will be generated automatically. "
"If a directory is specified, file names will be generated automatically. " + + "Supports template tokens, see the documentation for more info."
"Supports template tokens, see the documentation for more info."
)] )]
public string OutputPath public string OutputPath
{ {
@@ -42,11 +42,7 @@ public abstract class ExportCommandBase : DiscordCommandBase
init => _outputPath = Path.GetFullPath(value); init => _outputPath = Path.GetFullPath(value);
} }
[CommandOption( [CommandOption("format", 'f', Description = "Export format.")]
"format",
'f',
Description = "Export format."
)]
public ExportFormat ExportFormat { get; init; } = ExportFormat.HtmlDark; public ExportFormat ExportFormat { get; init; } = ExportFormat.HtmlDark;
[CommandOption( [CommandOption(
@@ -64,17 +60,15 @@ public abstract class ExportCommandBase : DiscordCommandBase
[CommandOption( [CommandOption(
"partition", "partition",
'p', 'p',
Description = Description = "Split the output into partitions, each limited to the specified "
"Split the output into partitions, each limited to the specified " + + "number of messages (e.g. '100') or file size (e.g. '10mb')."
"number of messages (e.g. '100') or file size (e.g. '10mb')."
)] )]
public PartitionLimit PartitionLimit { get; init; } = PartitionLimit.Null; public PartitionLimit PartitionLimit { get; init; } = PartitionLimit.Null;
[CommandOption( [CommandOption(
"filter", "filter",
Description = Description = "Only include messages that satisfy this filter. "
"Only include messages that satisfy this filter. " + + "See the documentation for more info."
"See the documentation for more info."
)] )]
public MessageFilter MessageFilter { get; init; } = MessageFilter.Null; public MessageFilter MessageFilter { get; init; } = MessageFilter.Null;
@@ -100,15 +94,14 @@ public abstract class ExportCommandBase : DiscordCommandBase
"reuse-media", "reuse-media",
Description = "Reuse previously downloaded assets to avoid redundant requests." Description = "Reuse previously downloaded assets to avoid redundant requests."
)] )]
public bool ShouldReuseAssets { get; init; } public bool ShouldReuseAssets { get; init; } = false;
private readonly string? _assetsDirPath; private readonly string? _assetsDirPath;
[CommandOption( [CommandOption(
"media-dir", "media-dir",
Description = Description = "Download assets to this directory. "
"Download assets to this directory. " + + "If not specified, the asset directory path will be derived from the output path."
"If not specified, the asset directory path will be derived from the output path."
)] )]
public string? AssetsDirPath public string? AssetsDirPath
{ {
@@ -118,12 +111,19 @@ public abstract class ExportCommandBase : DiscordCommandBase
init => _assetsDirPath = value is not null ? Path.GetFullPath(value) : null; init => _assetsDirPath = value is not null ? Path.GetFullPath(value) : null;
} }
[Obsolete("This option doesn't do anything. Kept for backwards compatibility.")]
[CommandOption( [CommandOption(
"dateformat", "dateformat",
Description = "Format used when writing dates." Description = "This option doesn't do anything. Kept for backwards compatibility."
)] )]
public string DateFormat { get; init; } = "MM/dd/yyyy h:mm tt"; public string DateFormat { get; init; } = "MM/dd/yyyy h:mm tt";
[CommandOption("locale", Description = "Locale to use when formatting dates and numbers.")]
public string Locale { get; init; } = CultureInfo.CurrentCulture.Name;
[CommandOption("utc", Description = "Normalize all timestamps to UTC+0.")]
public bool IsUtcNormalizationEnabled { get; init; } = false;
[CommandOption( [CommandOption(
"fuck-russia", "fuck-russia",
EnvironmentVariable = "FUCK_RUSSIA", EnvironmentVariable = "FUCK_RUSSIA",
@@ -131,28 +131,24 @@ public abstract class ExportCommandBase : DiscordCommandBase
// Use a converter to accept '1' as 'true' to reuse the existing environment variable // Use a converter to accept '1' as 'true' to reuse the existing environment variable
Converter = typeof(TruthyBooleanBindingConverter) Converter = typeof(TruthyBooleanBindingConverter)
)] )]
public bool IsUkraineSupportMessageDisabled { get; init; } public bool IsUkraineSupportMessageDisabled { get; init; } = false;
private ChannelExporter? _channelExporter; private ChannelExporter? _channelExporter;
protected ChannelExporter Exporter => _channelExporter ??= new ChannelExporter(Discord); protected ChannelExporter Exporter => _channelExporter ??= new ChannelExporter(Discord);
protected async ValueTask ExecuteAsync(IConsole console, IReadOnlyList<Channel> channels) protected async ValueTask ExportAsync(IConsole console, IReadOnlyList<Channel> channels)
{ {
// Asset reuse can only be enabled if the download assets option is set // Asset reuse can only be enabled if the download assets option is set
// https://github.com/Tyrrrz/DiscordChatExporter/issues/425 // https://github.com/Tyrrrz/DiscordChatExporter/issues/425
if (ShouldReuseAssets && !ShouldDownloadAssets) if (ShouldReuseAssets && !ShouldDownloadAssets)
{ {
throw new CommandException( throw new CommandException("Option --reuse-media cannot be used without --media.");
"Option --reuse-media cannot be used without --media."
);
} }
// Assets directory can only be specified if the download assets option is set // Assets directory can only be specified if the download assets option is set
if (!string.IsNullOrWhiteSpace(AssetsDirPath) && !ShouldDownloadAssets) if (!string.IsNullOrWhiteSpace(AssetsDirPath) && !ShouldDownloadAssets)
{ {
throw new CommandException( throw new CommandException("Option --media-dir cannot be used without --media.");
"Option --media-dir cannot be used without --media."
);
} }
// Make sure the user does not try to export multiple channels into one file. // Make sure the user does not try to export multiple channels into one file.
@@ -161,100 +157,116 @@ public abstract class ExportCommandBase : DiscordCommandBase
// https://github.com/Tyrrrz/DiscordChatExporter/issues/917 // https://github.com/Tyrrrz/DiscordChatExporter/issues/917
var isValidOutputPath = var isValidOutputPath =
// Anything is valid when exporting a single channel // Anything is valid when exporting a single channel
channels.Count <= 1 || channels.Count <= 1
// When using template tokens, assume the user knows what they're doing // When using template tokens, assume the user knows what they're doing
OutputPath.Contains('%') || || OutputPath.Contains('%')
// Otherwise, require an existing directory or an unambiguous directory path // Otherwise, require an existing directory or an unambiguous directory path
Directory.Exists(OutputPath) || PathEx.IsDirectoryPath(OutputPath); || Directory.Exists(OutputPath)
|| Path.EndsInDirectorySeparator(OutputPath);
if (!isValidOutputPath) if (!isValidOutputPath)
{ {
throw new CommandException( throw new CommandException(
"Attempted to export multiple channels, but the output path is neither a directory nor a template. " + "Attempted to export multiple channels, but the output path is neither a directory nor a template. "
"If the provided output path is meant to be treated as a directory, make sure it ends with a slash." + "If the provided output path is meant to be treated as a directory, make sure it ends with a slash."
); );
} }
// Export // Export
var cancellationToken = console.RegisterCancellationHandler(); var cancellationToken = console.RegisterCancellationHandler();
var errors = new ConcurrentDictionary<Channel, string>(); var errorsByChannel = new ConcurrentDictionary<Channel, string>();
await console.Output.WriteLineAsync($"Exporting {channels.Count} channel(s)..."); await console.Output.WriteLineAsync($"Exporting {channels.Count} channel(s)...");
await console.CreateProgressTicker().StartAsync(async progressContext => await console
{ .CreateProgressTicker()
await Parallel.ForEachAsync( .HideCompleted(
channels, // When exporting multiple channels in parallel, hide the completed tasks
new ParallelOptions // because it gets hard to visually parse them as they complete out of order.
{ // https://github.com/Tyrrrz/DiscordChatExporter/issues/1124
MaxDegreeOfParallelism = Math.Max(1, ParallelLimit), ParallelLimit > 1
CancellationToken = cancellationToken )
}, .StartAsync(async ctx =>
async (channel, innerCancellationToken) => {
{ await Parallel.ForEachAsync(
try channels,
new ParallelOptions
{ {
await progressContext.StartTaskAsync( MaxDegreeOfParallelism = Math.Max(1, ParallelLimit),
$"{channel.Category.Name} / {channel.Name}", CancellationToken = cancellationToken
async progress => },
{ async (channel, innerCancellationToken) =>
var guild = await Discord.GetGuildAsync(channel.GuildId, innerCancellationToken);
var request = new ExportRequest(
guild,
channel,
OutputPath,
AssetsDirPath,
ExportFormat,
After,
Before,
PartitionLimit,
MessageFilter,
ShouldFormatMarkdown,
ShouldDownloadAssets,
ShouldReuseAssets,
DateFormat
);
await Exporter.ExportChannelAsync(
request,
progress.ToPercentageBased(),
innerCancellationToken
);
}
);
}
catch (DiscordChatExporterException ex) when (!ex.IsFatal)
{ {
errors[channel] = ex.Message; try
{
await ctx.StartTaskAsync(
Markup.Escape(channel.GetHierarchicalName()),
async progress =>
{
var guild = await Discord.GetGuildAsync(
channel.GuildId,
innerCancellationToken
);
var request = new ExportRequest(
guild,
channel,
OutputPath,
AssetsDirPath,
ExportFormat,
After,
Before,
PartitionLimit,
MessageFilter,
ShouldFormatMarkdown,
ShouldDownloadAssets,
ShouldReuseAssets,
Locale,
IsUtcNormalizationEnabled
);
await Exporter.ExportChannelAsync(
request,
progress.ToPercentageBased(),
innerCancellationToken
);
}
);
}
catch (DiscordChatExporterException ex) when (!ex.IsFatal)
{
errorsByChannel[channel] = ex.Message;
}
} }
} );
); });
});
// Print the result // Print the result
using (console.WithForegroundColor(ConsoleColor.White)) using (console.WithForegroundColor(ConsoleColor.White))
{ {
await console.Output.WriteLineAsync( await console
$"Successfully exported {channels.Count - errors.Count} channel(s)." .Output
); .WriteLineAsync(
$"Successfully exported {channels.Count - errorsByChannel.Count} channel(s)."
);
} }
// Print errors // Print errors
if (errors.Any()) if (errorsByChannel.Any())
{ {
await console.Output.WriteLineAsync(); await console.Output.WriteLineAsync();
using (console.WithForegroundColor(ConsoleColor.Red)) using (console.WithForegroundColor(ConsoleColor.Red))
{ {
await console.Error.WriteLineAsync( await console
$"Failed to export {errors.Count} channel(s):" .Error
); .WriteLineAsync(
$"Failed to export {errorsByChannel.Count} the following channel(s):"
);
} }
foreach (var (channel, error) in errors) foreach (var (channel, error) in errorsByChannel)
{ {
await console.Error.WriteAsync($"{channel.Category.Name} / {channel.Name}: "); await console.Error.WriteAsync($"{channel.GetHierarchicalName()}: ");
using (console.WithForegroundColor(ConsoleColor.Red)) using (console.WithForegroundColor(ConsoleColor.Red))
await console.Error.WriteLineAsync(error); await console.Error.WriteLineAsync(error);
} }
@@ -264,11 +276,11 @@ public abstract class ExportCommandBase : DiscordCommandBase
// Fail the command only if ALL channels failed to export. // Fail the command only if ALL channels failed to export.
// If only some channels failed to export, it's okay. // If only some channels failed to export, it's okay.
if (errors.Count >= channels.Count) if (errorsByChannel.Count >= channels.Count)
throw new CommandException("Export failed."); throw new CommandException("Export failed.");
} }
protected async ValueTask ExecuteAsync(IConsole console, IReadOnlyList<Snowflake> channelIds) protected async ValueTask ExportAsync(IConsole console, IReadOnlyList<Snowflake> channelIds)
{ {
var cancellationToken = console.RegisterCancellationHandler(); var cancellationToken = console.RegisterCancellationHandler();
@@ -282,15 +294,15 @@ public abstract class ExportCommandBase : DiscordCommandBase
var channel = await Discord.GetChannelAsync(channelId, cancellationToken); var channel = await Discord.GetChannelAsync(channelId, cancellationToken);
// Unwrap categories // Unwrap categories
if (channel.Kind == ChannelKind.GuildCategory) if (channel.IsCategory)
{ {
var guildChannels = var guildChannels =
channelsByGuild.GetValueOrDefault(channel.GuildId) ?? channelsByGuild.GetValueOrDefault(channel.GuildId)
await Discord.GetGuildChannelsAsync(channel.GuildId, cancellationToken); ?? await Discord.GetGuildChannelsAsync(channel.GuildId, cancellationToken);
foreach (var guildChannel in guildChannels) foreach (var guildChannel in guildChannels)
{ {
if (guildChannel.Category.Id == channel.Id) if (guildChannel.Parent?.Id == channel.Id)
channels.Add(guildChannel); channels.Add(guildChannel);
} }
@@ -303,26 +315,62 @@ public abstract class ExportCommandBase : DiscordCommandBase
} }
} }
await ExecuteAsync(console, channels); await ExportAsync(console, channels);
} }
public override ValueTask ExecuteAsync(IConsole console) public override async ValueTask ExecuteAsync(IConsole console)
{ {
// Support Ukraine callout // Support Ukraine callout
if (!IsUkraineSupportMessageDisabled) if (!IsUkraineSupportMessageDisabled)
{ {
console.Output.WriteLine("┌────────────────────────────────────────────────────────────────────┐"); console
console.Output.WriteLine("│ Thank you for supporting Ukraine <3 │"); .Output
console.Output.WriteLine("│ │"); .WriteLine(
console.Output.WriteLine("│ As Russia wages a genocidal war against my country, │"); "┌────────────────────────────────────────────────────────────────────┐"
console.Output.WriteLine("│ I'm grateful to everyone who continues to │"); );
console.Output.WriteLine("│ stand with Ukraine in our fight for freedom. │"); console
console.Output.WriteLine("│ │"); .Output
console.Output.WriteLine("│ Learn more: https://tyrrrz.me/ukraine │"); .WriteLine(
console.Output.WriteLine("└────────────────────────────────────────────────────────────────────┘"); "│ Thank you for supporting Ukraine <3 │"
);
console
.Output
.WriteLine(
"│ │"
);
console
.Output
.WriteLine(
"│ As Russia wages a genocidal war against my country, │"
);
console
.Output
.WriteLine(
"│ I'm grateful to everyone who continues to │"
);
console
.Output
.WriteLine(
"│ stand with Ukraine in our fight for freedom. │"
);
console
.Output
.WriteLine(
"│ │"
);
console
.Output
.WriteLine(
"│ Learn more: https://tyrrrz.me/ukraine │"
);
console
.Output
.WriteLine(
"└────────────────────────────────────────────────────────────────────┘"
);
console.Output.WriteLine(""); console.Output.WriteLine("");
} }
return default; await base.ExecuteAsync(console);
} }
} }
@@ -0,0 +1,22 @@
using System;
using CliFx.Extensibility;
using DiscordChatExporter.Cli.Commands.Shared;
namespace DiscordChatExporter.Cli.Commands.Converters;
internal class ThreadInclusionModeBindingConverter : BindingConverter<ThreadInclusionMode>
{
public override ThreadInclusionMode Convert(string? rawValue)
{
// Empty or unset value is treated as 'active' to match the previous behavior
if (string.IsNullOrWhiteSpace(rawValue))
return ThreadInclusionMode.Active;
// Boolean 'true' is treated as 'active', boolean 'false' is treated as 'none'
if (bool.TryParse(rawValue, out var boolValue))
return boolValue ? ThreadInclusionMode.Active : ThreadInclusionMode.None;
// Otherwise, fall back to regular enum parsing
return Enum.Parse<ThreadInclusionMode>(rawValue, true);
}
}
@@ -1,5 +1,4 @@
using System; using System.Globalization;
using System.Globalization;
using CliFx.Extensibility; using CliFx.Extensibility;
namespace DiscordChatExporter.Cli.Commands.Converters; namespace DiscordChatExporter.Cli.Commands.Converters;
@@ -8,19 +7,15 @@ internal class TruthyBooleanBindingConverter : BindingConverter<bool>
{ {
public override bool Convert(string? rawValue) public override bool Convert(string? rawValue)
{ {
// Null is still considered true, to match the base behavior // Empty or unset value is treated as 'true', to match the regular boolean behavior
if (rawValue is null) if (string.IsNullOrWhiteSpace(rawValue))
return true; return true;
if (string.IsNullOrWhiteSpace(rawValue)) // Number '1' is treated as 'true', other numbers are treated as 'false'
return false; if (int.TryParse(rawValue, CultureInfo.InvariantCulture, out var intValue))
return intValue == 1;
if (bool.TryParse(rawValue, out var boolValue)) // Otherwise, fall back to regular boolean parsing
return boolValue; return bool.Parse(rawValue);
if (int.TryParse(rawValue, CultureInfo.InvariantCulture, out var intValue) && intValue == 0)
return false;
return true;
} }
} }
@@ -1,38 +1,43 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO.Compression; using System.Linq;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using CliFx.Attributes; using CliFx.Attributes;
using CliFx.Exceptions;
using CliFx.Infrastructure; using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands.Base; using DiscordChatExporter.Cli.Commands.Base;
using DiscordChatExporter.Core.Discord; using DiscordChatExporter.Cli.Commands.Converters;
using DiscordChatExporter.Cli.Commands.Shared;
using DiscordChatExporter.Cli.Utils.Extensions;
using DiscordChatExporter.Core.Discord.Data; using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Discord.Dump;
using DiscordChatExporter.Core.Exceptions; using DiscordChatExporter.Core.Exceptions;
using JsonExtensions.Reading; using Spectre.Console;
namespace DiscordChatExporter.Cli.Commands; namespace DiscordChatExporter.Cli.Commands;
[Command("exportall", Description = "Exports all accessible channels.")] [Command("exportall", Description = "Exports all accessible channels.")]
public class ExportAllCommand : ExportCommandBase public class ExportAllCommand : ExportCommandBase
{ {
[CommandOption( [CommandOption("include-dm", Description = "Include direct message channels.")]
"include-dm",
Description = "Include direct message channels."
)]
public bool IncludeDirectChannels { get; init; } = true; public bool IncludeDirectChannels { get; init; } = true;
[CommandOption( [CommandOption("include-guilds", Description = "Include guild channels.")]
"include-guilds",
Description = "Include guild channels."
)]
public bool IncludeGuildChannels { get; init; } = true; public bool IncludeGuildChannels { get; init; } = true;
[CommandOption("include-vc", Description = "Include voice channels.")]
public bool IncludeVoiceChannels { get; init; } = true;
[CommandOption(
"include-threads",
Description = "Which types of threads should be included.",
Converter = typeof(ThreadInclusionModeBindingConverter)
)]
public ThreadInclusionMode ThreadInclusionMode { get; init; } = ThreadInclusionMode.None;
[CommandOption( [CommandOption(
"data-package", "data-package",
Description = Description = "Path to the personal data package (ZIP file) requested from Discord. "
"Path to the personal data package (ZIP file) requested from Discord. " + + "If provided, only channels referenced in the dump will be exported."
"If provided, only channels referenced in the dump will be exported."
)] )]
public string? DataPackageFilePath { get; init; } public string? DataPackageFilePath { get; init; }
@@ -46,13 +51,84 @@ public class ExportAllCommand : ExportCommandBase
// Pull from the API // Pull from the API
if (string.IsNullOrWhiteSpace(DataPackageFilePath)) if (string.IsNullOrWhiteSpace(DataPackageFilePath))
{ {
await console.Output.WriteLineAsync("Fetching channels...");
await foreach (var guild in Discord.GetUserGuildsAsync(cancellationToken)) await foreach (var guild in Discord.GetUserGuildsAsync(cancellationToken))
{ {
await foreach (var channel in Discord.GetGuildChannelsAsync(guild.Id, cancellationToken)) // Regular channels
await console
.Output
.WriteLineAsync($"Fetching channels for guild '{guild.Name}'...");
var fetchedChannelsCount = 0;
await console
.CreateStatusTicker()
.StartAsync(
"...",
async ctx =>
{
await foreach (
var channel in Discord.GetGuildChannelsAsync(
guild.Id,
cancellationToken
)
)
{
if (channel.IsCategory)
continue;
if (!IncludeVoiceChannels && channel.IsVoice)
continue;
channels.Add(channel);
ctx.Status(
Markup.Escape($"Fetched '{channel.GetHierarchicalName()}'.")
);
fetchedChannelsCount++;
}
}
);
await console.Output.WriteLineAsync($"Fetched {fetchedChannelsCount} channel(s).");
// Threads
if (ThreadInclusionMode != ThreadInclusionMode.None)
{ {
channels.Add(channel); await console
.Output
.WriteLineAsync($"Fetching threads for guild '{guild.Name}'...");
var fetchedThreadsCount = 0;
await console
.CreateStatusTicker()
.StartAsync(
"...",
async ctx =>
{
await foreach (
var thread in Discord.GetGuildThreadsAsync(
guild.Id,
ThreadInclusionMode == ThreadInclusionMode.All,
Before,
After,
cancellationToken
)
)
{
channels.Add(thread);
ctx.Status(
Markup.Escape($"Fetched '{thread.GetHierarchicalName()}'.")
);
fetchedThreadsCount++;
}
}
);
await console
.Output
.WriteLineAsync($"Fetched {fetchedThreadsCount} thread(s).");
} }
} }
} }
@@ -60,44 +136,74 @@ public class ExportAllCommand : ExportCommandBase
else else
{ {
await console.Output.WriteLineAsync("Extracting channels..."); await console.Output.WriteLineAsync("Extracting channels...");
using var archive = ZipFile.OpenRead(DataPackageFilePath);
var entry = archive.GetEntry("messages/index.json"); var dump = await DataDump.LoadAsync(DataPackageFilePath, cancellationToken);
if (entry is null) var inaccessibleChannels = new List<DataDumpChannel>();
throw new CommandException("Could not find channel index inside the data package.");
await using var stream = entry.Open(); await console
using var document = await JsonDocument.ParseAsync(stream, default, cancellationToken); .CreateStatusTicker()
.StartAsync(
"...",
async ctx =>
{
foreach (var dumpChannel in dump.Channels)
{
ctx.Status(
Markup.Escape(
$"Fetching '{dumpChannel.Name}' ({dumpChannel.Id})..."
)
);
foreach (var property in document.RootElement.EnumerateObjectOrEmpty()) try
{
var channel = await Discord.GetChannelAsync(
dumpChannel.Id,
cancellationToken
);
channels.Add(channel);
}
catch (DiscordChatExporterException)
{
inaccessibleChannels.Add(dumpChannel);
}
}
}
);
await console.Output.WriteLineAsync($"Fetched {channels} channel(s).");
// Print inaccessible channels
if (inaccessibleChannels.Any())
{ {
var channelId = Snowflake.Parse(property.Name); await console.Output.WriteLineAsync();
var channelName = property.Value.GetString();
// Null items refer to deleted channels using (console.WithForegroundColor(ConsoleColor.Red))
if (channelName is null)
continue;
await console.Output.WriteLineAsync($"Fetching channel '{channelName}' ({channelId})...");
try
{ {
var channel = await Discord.GetChannelAsync(channelId, cancellationToken); await console
channels.Add(channel); .Error
} .WriteLineAsync("Failed to access the following channel(s):");
catch (DiscordChatExporterException)
{
await console.Error.WriteLineAsync($"Channel '{channelName}' ({channelId}) is inaccessible.");
} }
foreach (var dumpChannel in inaccessibleChannels)
await console.Error.WriteLineAsync($"{dumpChannel.Name} ({dumpChannel.Id})");
await console.Error.WriteLineAsync();
} }
} }
// Filter out unwanted channels // Filter out unwanted channels
if (!IncludeDirectChannels) if (!IncludeDirectChannels)
channels.RemoveAll(c => c.Kind.IsDirect()); channels.RemoveAll(c => c.IsDirect);
if (!IncludeGuildChannels) if (!IncludeGuildChannels)
channels.RemoveAll(c => c.Kind.IsGuild()); channels.RemoveAll(c => c.IsGuild);
if (!IncludeVoiceChannels)
channels.RemoveAll(c => c.IsVoice);
if (ThreadInclusionMode == ThreadInclusionMode.None)
channels.RemoveAll(c => c.IsThread);
if (ThreadInclusionMode != ThreadInclusionMode.All)
channels.RemoveAll(c => c is { IsThread: true, IsArchived: true });
await base.ExecuteAsync(console, channels); await ExportAsync(console, channels);
} }
} }
@@ -14,15 +14,14 @@ public class ExportChannelsCommand : ExportCommandBase
[CommandOption( [CommandOption(
"channel", "channel",
'c', 'c',
Description = Description = "Channel ID(s). "
"Channel ID(s). " + + "If provided with category ID(s), all channels inside those categories will be exported."
"If provided with category ID(s), all channels inside those categories will be exported."
)] )]
public required IReadOnlyList<Snowflake> ChannelIds { get; init; } public required IReadOnlyList<Snowflake> ChannelIds { get; init; }
public override async ValueTask ExecuteAsync(IConsole console) public override async ValueTask ExecuteAsync(IConsole console)
{ {
await base.ExecuteAsync(console); await base.ExecuteAsync(console);
await base.ExecuteAsync(console, ChannelIds); await ExportAsync(console, ChannelIds);
} }
} }
@@ -17,8 +17,11 @@ public class ExportDirectMessagesCommand : ExportCommandBase
var cancellationToken = console.RegisterCancellationHandler(); var cancellationToken = console.RegisterCancellationHandler();
await console.Output.WriteLineAsync("Fetching channels..."); await console.Output.WriteLineAsync("Fetching channels...");
var channels = await Discord.GetGuildChannelsAsync(Guild.DirectMessages.Id, cancellationToken); var channels = await Discord.GetGuildChannelsAsync(
Guild.DirectMessages.Id,
cancellationToken
);
await base.ExecuteAsync(console, channels); await ExportAsync(console, channels);
} }
} }
@@ -1,36 +1,106 @@
using System.Linq; using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using CliFx.Attributes; using CliFx.Attributes;
using CliFx.Infrastructure; using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands.Base; using DiscordChatExporter.Cli.Commands.Base;
using DiscordChatExporter.Cli.Commands.Converters;
using DiscordChatExporter.Cli.Commands.Shared;
using DiscordChatExporter.Cli.Utils.Extensions;
using DiscordChatExporter.Core.Discord; using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Discord.Data; using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Utils.Extensions; using Spectre.Console;
namespace DiscordChatExporter.Cli.Commands; namespace DiscordChatExporter.Cli.Commands;
[Command("exportguild", Description = "Exports all channels within the specified guild.")] [Command("exportguild", Description = "Exports all channels within the specified guild.")]
public class ExportGuildCommand : ExportCommandBase public class ExportGuildCommand : ExportCommandBase
{ {
[CommandOption( [CommandOption("guild", 'g', Description = "Guild ID.")]
"guild",
'g',
Description = "Guild ID."
)]
public required Snowflake GuildId { get; init; } public required Snowflake GuildId { get; init; }
[CommandOption("include-vc", Description = "Include voice channels.")]
public bool IncludeVoiceChannels { get; init; } = true;
[CommandOption(
"include-threads",
Description = "Which types of threads should be included.",
Converter = typeof(ThreadInclusionModeBindingConverter)
)]
public ThreadInclusionMode ThreadInclusionMode { get; init; } = ThreadInclusionMode.None;
public override async ValueTask ExecuteAsync(IConsole console) public override async ValueTask ExecuteAsync(IConsole console)
{ {
await base.ExecuteAsync(console); await base.ExecuteAsync(console);
var cancellationToken = console.RegisterCancellationHandler(); var cancellationToken = console.RegisterCancellationHandler();
var channels = new List<Channel>();
// Regular channels
await console.Output.WriteLineAsync("Fetching channels..."); await console.Output.WriteLineAsync("Fetching channels...");
var channels = (await Discord.GetGuildChannelsAsync(GuildId, cancellationToken)) var fetchedChannelsCount = 0;
.Where(c => c.Kind != ChannelKind.GuildCategory) await console
.ToArray(); .CreateStatusTicker()
.StartAsync(
"...",
async ctx =>
{
await foreach (
var channel in Discord.GetGuildChannelsAsync(GuildId, cancellationToken)
)
{
if (channel.IsCategory)
continue;
await base.ExecuteAsync(console, channels); if (!IncludeVoiceChannels && channel.IsVoice)
continue;
channels.Add(channel);
ctx.Status(Markup.Escape($"Fetched '{channel.GetHierarchicalName()}'."));
fetchedChannelsCount++;
}
}
);
await console.Output.WriteLineAsync($"Fetched {fetchedChannelsCount} channel(s).");
// Threads
if (ThreadInclusionMode != ThreadInclusionMode.None)
{
await console.Output.WriteLineAsync("Fetching threads...");
var fetchedThreadsCount = 0;
await console
.CreateStatusTicker()
.StartAsync(
"...",
async ctx =>
{
await foreach (
var thread in Discord.GetGuildThreadsAsync(
GuildId,
ThreadInclusionMode == ThreadInclusionMode.All,
Before,
After,
cancellationToken
)
)
{
channels.Add(thread);
ctx.Status(Markup.Escape($"Fetched '{thread.GetHierarchicalName()}'."));
fetchedThreadsCount++;
}
}
);
await console.Output.WriteLineAsync($"Fetched {fetchedThreadsCount} thread(s).");
}
await ExportAsync(console, channels);
} }
} }
@@ -4,6 +4,8 @@ using System.Threading.Tasks;
using CliFx.Attributes; using CliFx.Attributes;
using CliFx.Infrastructure; using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands.Base; using DiscordChatExporter.Cli.Commands.Base;
using DiscordChatExporter.Cli.Commands.Converters;
using DiscordChatExporter.Cli.Commands.Shared;
using DiscordChatExporter.Core.Discord; using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Discord.Data; using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Utils.Extensions; using DiscordChatExporter.Core.Utils.Extensions;
@@ -13,26 +15,29 @@ namespace DiscordChatExporter.Cli.Commands;
[Command("channels", Description = "Get the list of channels in a guild.")] [Command("channels", Description = "Get the list of channels in a guild.")]
public class GetChannelsCommand : DiscordCommandBase public class GetChannelsCommand : DiscordCommandBase
{ {
[CommandOption( [CommandOption("guild", 'g', Description = "Guild ID.")]
"guild",
'g',
Description = "Guild ID."
)]
public required Snowflake GuildId { get; init; } public required Snowflake GuildId { get; init; }
[CommandOption("include-vc", Description = "Include voice channels.")]
public bool IncludeVoiceChannels { get; init; } = true;
[CommandOption( [CommandOption(
"include-threads", "include-threads",
Description = "Include threads in the output." Description = "Which types of threads should be included.",
Converter = typeof(ThreadInclusionModeBindingConverter)
)] )]
public bool IncludeThreads { get; init; } public ThreadInclusionMode ThreadInclusionMode { get; init; } = ThreadInclusionMode.None;
public override async ValueTask ExecuteAsync(IConsole console) public override async ValueTask ExecuteAsync(IConsole console)
{ {
await base.ExecuteAsync(console);
var cancellationToken = console.RegisterCancellationHandler(); var cancellationToken = console.RegisterCancellationHandler();
var channels = (await Discord.GetGuildChannelsAsync(GuildId, cancellationToken)) var channels = (await Discord.GetGuildChannelsAsync(GuildId, cancellationToken))
.Where(c => c.Kind != ChannelKind.GuildCategory) .Where(c => !c.IsCategory)
.OrderBy(c => c.Category.Position) .Where(c => IncludeVoiceChannels || !c.IsVoice)
.OrderBy(c => c.Parent?.Position)
.ThenBy(c => c.Name) .ThenBy(c => c.Name)
.ToArray(); .ToArray();
@@ -41,40 +46,53 @@ public class GetChannelsCommand : DiscordCommandBase
.OrderDescending() .OrderDescending()
.FirstOrDefault(); .FirstOrDefault();
var threads = IncludeThreads var threads =
? (await Discord.GetGuildThreadsAsync(GuildId, cancellationToken)).OrderBy(c => c.Name).ToArray() ThreadInclusionMode != ThreadInclusionMode.None
: Array.Empty<ChannelThread>(); ? (
await Discord.GetGuildThreadsAsync(
GuildId,
ThreadInclusionMode == ThreadInclusionMode.All,
null,
null,
cancellationToken
)
)
.OrderBy(c => c.Name)
.ToArray()
: Array.Empty<Channel>();
foreach (var channel in channels) foreach (var channel in channels)
{ {
// Channel ID // Channel ID
await console.Output.WriteAsync( await console
channel.Id.ToString().PadRight(channelIdMaxLength, ' ') .Output
); .WriteAsync(channel.Id.ToString().PadRight(channelIdMaxLength, ' '));
// Separator // Separator
using (console.WithForegroundColor(ConsoleColor.DarkGray)) using (console.WithForegroundColor(ConsoleColor.DarkGray))
await console.Output.WriteAsync(" | "); await console.Output.WriteAsync(" | ");
// Channel category / name // Channel name
using (console.WithForegroundColor(ConsoleColor.White)) using (console.WithForegroundColor(ConsoleColor.White))
await console.Output.WriteLineAsync($"{channel.Category.Name} / {channel.Name}"); await console.Output.WriteLineAsync(channel.GetHierarchicalName());
var channelThreads = threads.Where(t => t.ParentId == channel.Id).ToArray(); var channelThreads = threads.Where(t => t.Parent?.Id == channel.Id).ToArray();
var channelThreadIdMaxLength = channelThreads var channelThreadIdMaxLength = channelThreads
.Select(t => t.Id.ToString().Length) .Select(t => t.Id.ToString().Length)
.OrderDescending() .OrderDescending()
.FirstOrDefault(); .FirstOrDefault();
foreach (var thread in channelThreads) foreach (var channelThread in channelThreads)
{ {
// Indent // Indent
await console.Output.WriteAsync(" * "); await console.Output.WriteAsync(" * ");
// Thread ID // Thread ID
await console.Output.WriteAsync( await console
thread.Id.ToString().PadRight(channelThreadIdMaxLength, ' ') .Output
); .WriteAsync(
channelThread.Id.ToString().PadRight(channelThreadIdMaxLength, ' ')
);
// Separator // Separator
using (console.WithForegroundColor(ConsoleColor.DarkGray)) using (console.WithForegroundColor(ConsoleColor.DarkGray))
@@ -82,7 +100,7 @@ public class GetChannelsCommand : DiscordCommandBase
// Thread name // Thread name
using (console.WithForegroundColor(ConsoleColor.White)) using (console.WithForegroundColor(ConsoleColor.White))
await console.Output.WriteAsync($"Thread / {thread.Name}"); await console.Output.WriteAsync($"Thread / {channelThread.Name}");
// Separator // Separator
using (console.WithForegroundColor(ConsoleColor.DarkGray)) using (console.WithForegroundColor(ConsoleColor.DarkGray))
@@ -90,8 +108,10 @@ public class GetChannelsCommand : DiscordCommandBase
// Thread status // Thread status
using (console.WithForegroundColor(ConsoleColor.White)) using (console.WithForegroundColor(ConsoleColor.White))
await console.Output.WriteLineAsync(thread.IsActive ? "Active" : "Archived"); await console
.Output
.WriteLineAsync(channelThread.IsArchived ? "Archived" : "Active");
} }
} }
} }
} }
@@ -14,10 +14,13 @@ public class GetDirectChannelsCommand : DiscordCommandBase
{ {
public override async ValueTask ExecuteAsync(IConsole console) public override async ValueTask ExecuteAsync(IConsole console)
{ {
await base.ExecuteAsync(console);
var cancellationToken = console.RegisterCancellationHandler(); var cancellationToken = console.RegisterCancellationHandler();
var channels = (await Discord.GetGuildChannelsAsync(Guild.DirectMessages.Id, cancellationToken)) var channels = (
.Where(c => c.Kind != ChannelKind.GuildCategory) await Discord.GetGuildChannelsAsync(Guild.DirectMessages.Id, cancellationToken)
)
.OrderByDescending(c => c.LastMessageId) .OrderByDescending(c => c.LastMessageId)
.ThenBy(c => c.Name) .ThenBy(c => c.Name)
.ToArray(); .ToArray();
@@ -30,17 +33,17 @@ public class GetDirectChannelsCommand : DiscordCommandBase
foreach (var channel in channels) foreach (var channel in channels)
{ {
// Channel ID // Channel ID
await console.Output.WriteAsync( await console
channel.Id.ToString().PadRight(channelIdMaxLength, ' ') .Output
); .WriteAsync(channel.Id.ToString().PadRight(channelIdMaxLength, ' '));
// Separator // Separator
using (console.WithForegroundColor(ConsoleColor.DarkGray)) using (console.WithForegroundColor(ConsoleColor.DarkGray))
await console.Output.WriteAsync(" | "); await console.Output.WriteAsync(" | ");
// Channel category / name // Channel name
using (console.WithForegroundColor(ConsoleColor.White)) using (console.WithForegroundColor(ConsoleColor.White))
await console.Output.WriteLineAsync($"{channel.Category.Name} / {channel.Name}"); await console.Output.WriteLineAsync(channel.GetHierarchicalName());
} }
} }
} }
@@ -14,6 +14,8 @@ public class GetGuildsCommand : DiscordCommandBase
{ {
public override async ValueTask ExecuteAsync(IConsole console) public override async ValueTask ExecuteAsync(IConsole console)
{ {
await base.ExecuteAsync(console);
var cancellationToken = console.RegisterCancellationHandler(); var cancellationToken = console.RegisterCancellationHandler();
var guilds = (await Discord.GetUserGuildsAsync(cancellationToken)) var guilds = (await Discord.GetUserGuildsAsync(cancellationToken))
@@ -30,9 +32,7 @@ public class GetGuildsCommand : DiscordCommandBase
foreach (var guild in guilds) foreach (var guild in guilds)
{ {
// Guild ID // Guild ID
await console.Output.WriteAsync( await console.Output.WriteAsync(guild.Id.ToString().PadRight(guildIdMaxLength, ' '));
guild.Id.ToString().PadRight(guildIdMaxLength, ' ')
);
// Separator // Separator
using (console.WithForegroundColor(ConsoleColor.DarkGray)) using (console.WithForegroundColor(ConsoleColor.DarkGray))
@@ -43,4 +43,4 @@ public class GetGuildsCommand : DiscordCommandBase
await console.Output.WriteLineAsync(guild.Name); await console.Output.WriteLineAsync(guild.Name);
} }
} }
} }
@@ -15,14 +15,20 @@ public class GuideCommand : ICommand
using (console.WithForegroundColor(ConsoleColor.White)) using (console.WithForegroundColor(ConsoleColor.White))
console.Output.WriteLine("To get user token:"); console.Output.WriteLine("To get user token:");
console.Output.WriteLine(" * Automating user accounts is technically against TOS — USE AT YOUR OWN RISK!"); console
.Output
.WriteLine(
" * Automating user accounts is technically against TOS — USE AT YOUR OWN RISK!"
);
console.Output.WriteLine(" 1. Open Discord in your web browser and login"); console.Output.WriteLine(" 1. Open Discord in your web browser and login");
console.Output.WriteLine(" 2. Open any server or direct message channel"); console.Output.WriteLine(" 2. Open any server or direct message channel");
console.Output.WriteLine(" 3. Press Ctrl+Shift+I to show developer tools"); console.Output.WriteLine(" 3. Press Ctrl+Shift+I to show developer tools");
console.Output.WriteLine(" 4. Navigate to the Network tab"); console.Output.WriteLine(" 4. Navigate to the Network tab");
console.Output.WriteLine(" 5. Press Ctrl+R to reload"); console.Output.WriteLine(" 5. Press Ctrl+R to reload");
console.Output.WriteLine(" 6. Switch between random channels to trigger network requests"); console.Output.WriteLine(" 6. Switch between random channels to trigger network requests");
console.Output.WriteLine(" 7. Search for a request containing \"messages?limit=50\" or similar"); console
.Output
.WriteLine(" 7. Search for a request containing \"messages?limit=50\" or similar");
console.Output.WriteLine(" 8. Select the Headers tab on the right"); console.Output.WriteLine(" 8. Select the Headers tab on the right");
console.Output.WriteLine(" 9. Scroll down to the Request Headers section"); console.Output.WriteLine(" 9. Scroll down to the Request Headers section");
console.Output.WriteLine(" 10. Copy the value of the \"authorization\" header"); console.Output.WriteLine(" 10. Copy the value of the \"authorization\" header");
@@ -36,7 +42,11 @@ public class GuideCommand : ICommand
console.Output.WriteLine(" 2. Open your application's settings"); console.Output.WriteLine(" 2. Open your application's settings");
console.Output.WriteLine(" 3. Navigate to the Bot section on the left"); console.Output.WriteLine(" 3. Navigate to the Bot section on the left");
console.Output.WriteLine(" 4. Under Token click Copy"); console.Output.WriteLine(" 4. Under Token click Copy");
console.Output.WriteLine(" * Your bot needs to have Message Content Intent enabled to read messages"); console
.Output
.WriteLine(
" * Your bot needs to have Message Content Intent enabled to read messages"
);
console.Output.WriteLine(); console.Output.WriteLine();
// Guild or channel ID // Guild or channel ID
@@ -47,15 +57,23 @@ public class GuideCommand : ICommand
console.Output.WriteLine(" 2. Open Settings"); console.Output.WriteLine(" 2. Open Settings");
console.Output.WriteLine(" 3. Go to Advanced section"); console.Output.WriteLine(" 3. Go to Advanced section");
console.Output.WriteLine(" 4. Enable Developer Mode"); console.Output.WriteLine(" 4. Enable Developer Mode");
console.Output.WriteLine(" 5. Right-click on the desired guild or channel and click Copy Server ID or Copy Channel ID"); console
.Output
.WriteLine(
" 5. Right-click on the desired guild or channel and click Copy Server ID or Copy Channel ID"
);
console.Output.WriteLine(); console.Output.WriteLine();
// Docs link // Docs link
using (console.WithForegroundColor(ConsoleColor.White)) using (console.WithForegroundColor(ConsoleColor.White))
console.Output.WriteLine("If you have questions or issues, please refer to the documentation:"); console
.Output
.WriteLine("If you have questions or issues, please refer to the documentation:");
using (console.WithForegroundColor(ConsoleColor.DarkCyan)) using (console.WithForegroundColor(ConsoleColor.DarkCyan))
console.Output.WriteLine("https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs"); console
.Output
.WriteLine("https://github.com/Tyrrrz/DiscordChatExporter/blob/master/.docs");
return default; return default;
} }
} }
@@ -0,0 +1,8 @@
namespace DiscordChatExporter.Cli.Commands.Shared;
public enum ThreadInclusionMode
{
None,
Active,
All
}
@@ -7,6 +7,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="CliFx" Version="2.3.4" /> <PackageReference Include="CliFx" Version="2.3.4" />
<PackageReference Include="CSharpier.MsBuild" Version="0.26.1" PrivateAssets="all" />
<PackageReference Include="Deorcify" Version="1.0.2" PrivateAssets="all" /> <PackageReference Include="Deorcify" Version="1.0.2" PrivateAssets="all" />
<PackageReference Include="DotnetRuntimeBootstrapper" Version="2.5.1" PrivateAssets="all" /> <PackageReference Include="DotnetRuntimeBootstrapper" Version="2.5.1" PrivateAssets="all" />
<PackageReference Include="Gress" Version="2.1.1" /> <PackageReference Include="Gress" Version="2.1.1" />
+1 -4
View File
@@ -1,6 +1,3 @@
using CliFx; using CliFx;
return await new CliApplicationBuilder() return await new CliApplicationBuilder().AddCommandsFromThisAssembly().Build().RunAsync(args);
.AddCommandsFromThisAssembly()
.Build()
.RunAsync(args);
@@ -8,34 +8,44 @@ namespace DiscordChatExporter.Cli.Utils.Extensions;
internal static class ConsoleExtensions internal static class ConsoleExtensions
{ {
public static IAnsiConsole CreateAnsiConsole(this IConsole console) => public static IAnsiConsole CreateAnsiConsole(this IConsole console) =>
AnsiConsole.Create(new AnsiConsoleSettings AnsiConsole.Create(
{ new AnsiConsoleSettings
Ansi = AnsiSupport.Detect, {
ColorSystem = ColorSystemSupport.Detect, Ansi = AnsiSupport.Detect,
Out = new AnsiConsoleOutput(console.Output) ColorSystem = ColorSystemSupport.Detect,
}); Out = new AnsiConsoleOutput(console.Output)
}
public static Progress CreateProgressTicker(this IConsole console) => console
.CreateAnsiConsole()
.Progress()
.AutoClear(false)
.AutoRefresh(true)
.HideCompleted(false)
.Columns(
new TaskDescriptionColumn {Alignment = Justify.Left},
new ProgressBarColumn(),
new PercentageColumn()
); );
public static Status CreateStatusTicker(this IConsole console) =>
console.CreateAnsiConsole().Status().AutoRefresh(true);
public static Progress CreateProgressTicker(this IConsole console) =>
console
.CreateAnsiConsole()
.Progress()
.AutoClear(false)
.AutoRefresh(true)
.HideCompleted(false)
.Columns(
new TaskDescriptionColumn { Alignment = Justify.Left },
new ProgressBarColumn(),
new PercentageColumn()
);
public static async ValueTask StartTaskAsync( public static async ValueTask StartTaskAsync(
this ProgressContext progressContext, this ProgressContext context,
string description, string description,
Func<ProgressTask, ValueTask> performOperationAsync) Func<ProgressTask, ValueTask> performOperationAsync
)
{ {
var progressTask = progressContext.AddTask( // Description cannot be empty
// Don't recognize random square brackets as style tags // https://github.com/Tyrrrz/DiscordChatExporter/issues/1133
Markup.Escape(description), var actualDescription = !string.IsNullOrWhiteSpace(description) ? description : "...";
new ProgressTaskSettings {MaxValue = 1}
var progressTask = context.AddTask(
actualDescription,
new ProgressTaskSettings { MaxValue = 1 }
); );
try try
@@ -48,4 +58,4 @@ internal static class ConsoleExtensions
progressTask.StopTask(); progressTask.StopTask();
} }
} }
} }
@@ -0,0 +1,28 @@
using System.Text.Json;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/application#application-object
public partial record Application(Snowflake Id, string Name, ApplicationFlags Flags)
{
public bool IsMessageContentIntentEnabled =>
Flags.HasFlag(ApplicationFlags.GatewayMessageContent)
|| Flags.HasFlag(ApplicationFlags.GatewayMessageContentLimited);
}
public partial record Application
{
public static Application Parse(JsonElement json)
{
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var name = json.GetProperty("name").GetNonWhiteSpaceString();
var flags =
json.GetPropertyOrNull("flags")?.GetInt32OrNull()?.Pipe(x => (ApplicationFlags)x)
?? ApplicationFlags.None;
return new Application(id, name, flags);
}
}
@@ -0,0 +1,20 @@
using System;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/application#application-object-application-flags
[Flags]
public enum ApplicationFlags
{
None = 0,
ApplicationAutoModerationRuleCreateBadge = 64,
GatewayPresence = 4096,
GatewayPresenceLimited = 8192,
GatewayGuildMembers = 16384,
GatewayGuildMembersLimited = 32768,
VerificationPendingGuildLimit = 65536,
Embedded = 131072,
GatewayMessageContent = 262144,
GatewayMessageContentLimited = 524288,
ApplicationCommandBadge = 8388608
}
@@ -15,30 +15,31 @@ public partial record Attachment(
string? Description, string? Description,
int? Width, int? Width,
int? Height, int? Height,
FileSize FileSize) : IHasId FileSize FileSize
) : IHasId
{ {
public string FileExtension => Path.GetExtension(FileName); public string FileExtension => Path.GetExtension(FileName);
public bool IsImage => public bool IsImage =>
string.Equals(FileExtension, ".jpg", StringComparison.OrdinalIgnoreCase) || string.Equals(FileExtension, ".jpg", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".jpeg", StringComparison.OrdinalIgnoreCase) || || string.Equals(FileExtension, ".jpeg", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".png", StringComparison.OrdinalIgnoreCase) || || string.Equals(FileExtension, ".png", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".gif", StringComparison.OrdinalIgnoreCase) || || string.Equals(FileExtension, ".gif", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".bmp", StringComparison.OrdinalIgnoreCase) || || string.Equals(FileExtension, ".bmp", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".webp", StringComparison.OrdinalIgnoreCase); || string.Equals(FileExtension, ".webp", StringComparison.OrdinalIgnoreCase);
public bool IsVideo => public bool IsVideo =>
string.Equals(FileExtension, ".gifv", StringComparison.OrdinalIgnoreCase) || string.Equals(FileExtension, ".gifv", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".mp4", StringComparison.OrdinalIgnoreCase) || || string.Equals(FileExtension, ".mp4", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".webm", StringComparison.OrdinalIgnoreCase) || || string.Equals(FileExtension, ".webm", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".mov", StringComparison.OrdinalIgnoreCase); || string.Equals(FileExtension, ".mov", StringComparison.OrdinalIgnoreCase);
public bool IsAudio => public bool IsAudio =>
string.Equals(FileExtension, ".mp3", StringComparison.OrdinalIgnoreCase) || string.Equals(FileExtension, ".mp3", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".wav", StringComparison.OrdinalIgnoreCase) || || string.Equals(FileExtension, ".wav", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".ogg", StringComparison.OrdinalIgnoreCase) || || string.Equals(FileExtension, ".ogg", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".flac", StringComparison.OrdinalIgnoreCase) || || string.Equals(FileExtension, ".flac", StringComparison.OrdinalIgnoreCase)
string.Equals(FileExtension, ".m4a", StringComparison.OrdinalIgnoreCase); || string.Equals(FileExtension, ".m4a", StringComparison.OrdinalIgnoreCase);
public bool IsSpoiler => FileName.StartsWith("SPOILER_", StringComparison.Ordinal); public bool IsSpoiler => FileName.StartsWith("SPOILER_", StringComparison.Ordinal);
} }
@@ -57,4 +58,4 @@ public partial record Attachment
return new Attachment(id, url, fileName, description, width, height, fileSize); return new Attachment(id, url, fileName, description, width, height, fileSize);
} }
} }
@@ -1,4 +1,5 @@
using System.Linq; using System.Collections.Generic;
using System.Linq;
using System.Text.Json; using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common; using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Utils.Extensions; using DiscordChatExporter.Core.Utils.Extensions;
@@ -11,70 +12,104 @@ public partial record Channel(
Snowflake Id, Snowflake Id,
ChannelKind Kind, ChannelKind Kind,
Snowflake GuildId, Snowflake GuildId,
ChannelCategory Category, Channel? Parent,
string Name, string Name,
int? Position, int? Position,
string? IconUrl, string? IconUrl,
string? Topic, string? Topic,
Snowflake? LastMessageId) : IHasId bool IsArchived,
Snowflake? LastMessageId
) : IHasId
{ {
public bool IsDirect => Kind is ChannelKind.DirectTextChat or ChannelKind.DirectGroupTextChat;
public bool IsGuild => !IsDirect;
public bool IsCategory => Kind == ChannelKind.GuildCategory;
public bool IsVoice => Kind is ChannelKind.GuildVoiceChat or ChannelKind.GuildStageVoice; public bool IsVoice => Kind is ChannelKind.GuildVoiceChat or ChannelKind.GuildStageVoice;
public bool IsThread =>
Kind
is ChannelKind.GuildNewsThread
or ChannelKind.GuildPublicThread
or ChannelKind.GuildPrivateThread;
public bool IsEmpty => LastMessageId is null;
public IEnumerable<Channel> GetParents()
{
var current = Parent;
while (current is not null)
{
yield return current;
current = current.Parent;
}
}
public Channel? TryGetRootParent() => GetParents().LastOrDefault();
public string GetHierarchicalName() =>
string.Join(" / ", GetParents().Reverse().Select(c => c.Name).Append(Name));
public bool MayHaveMessagesAfter(Snowflake messageId) => !IsEmpty && messageId < LastMessageId;
public bool MayHaveMessagesBefore(Snowflake messageId) => !IsEmpty && messageId > Id;
} }
public partial record Channel public partial record Channel
{ {
public static Channel Parse(JsonElement json, ChannelCategory? categoryHint = null, int? positionHint = null) public static Channel Parse(JsonElement json, Channel? parent = null, int? positionHint = null)
{ {
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse); var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var kind = (ChannelKind)json.GetProperty("type").GetInt32(); var kind = json.GetProperty("type").GetInt32().Pipe(t => (ChannelKind)t);
var guildId = var guildId =
json.GetPropertyOrNull("guild_id")?.GetNonWhiteSpaceStringOrNull()?.Pipe(Snowflake.Parse) ?? json.GetPropertyOrNull("guild_id")
Guild.DirectMessages.Id; ?.GetNonWhiteSpaceStringOrNull()
?.Pipe(Snowflake.Parse) ?? Guild.DirectMessages.Id;
var category = categoryHint ?? ChannelCategory.CreateDefault(kind);
var name = var name =
// Guild channel // Guild channel
json.GetPropertyOrNull("name")?.GetNonWhiteSpaceStringOrNull() ?? json.GetPropertyOrNull("name")?.GetNonWhiteSpaceStringOrNull()
// DM channel // DM channel
json.GetPropertyOrNull("recipients")? ?? json.GetPropertyOrNull("recipients")
.EnumerateArrayOrNull()? ?.EnumerateArrayOrNull()
.Select(User.Parse) ?.Select(User.Parse)
.Select(u => u.DisplayName) .Select(u => u.DisplayName)
.Pipe(s => string.Join(", ", s)) ?? .Pipe(s => string.Join(", ", s))
// Fallback // Fallback
id.ToString(); ?? id.ToString();
var position = var position = positionHint ?? json.GetPropertyOrNull("position")?.GetInt32OrNull();
positionHint ??
json.GetPropertyOrNull("position")?.GetInt32OrNull();
// Icons can only be set for group DM channels // Icons can only be set for group DM channels
var iconUrl = json var iconUrl = json.GetPropertyOrNull("icon")
.GetPropertyOrNull("icon")? ?.GetNonWhiteSpaceStringOrNull()
.GetNonWhiteSpaceStringOrNull()? ?.Pipe(h => ImageCdn.GetChannelIconUrl(id, h));
.Pipe(h => ImageCdn.GetChannelIconUrl(id, h));
var topic = json.GetPropertyOrNull("topic")?.GetStringOrNull(); var topic = json.GetPropertyOrNull("topic")?.GetStringOrNull();
var lastMessageId = json var isArchived =
.GetPropertyOrNull("last_message_id")? json.GetPropertyOrNull("thread_metadata")
.GetNonWhiteSpaceStringOrNull()? ?.GetPropertyOrNull("archived")
.Pipe(Snowflake.Parse); ?.GetBooleanOrNull() ?? false;
var lastMessageId = json.GetPropertyOrNull("last_message_id")
?.GetNonWhiteSpaceStringOrNull()
?.Pipe(Snowflake.Parse);
return new Channel( return new Channel(
id, id,
kind, kind,
guildId, guildId,
category, parent,
name, name,
position, position,
iconUrl, iconUrl,
topic, topic,
isArchived,
lastMessageId lastMessageId
); );
} }
} }
@@ -1,37 +0,0 @@
using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
public record ChannelCategory(Snowflake Id, string Name, int? Position) : IHasId
{
public static ChannelCategory CreateDefault(ChannelKind channelKind) => new(
Snowflake.Zero,
channelKind switch
{
ChannelKind.GuildTextChat => "Text",
ChannelKind.DirectTextChat => "Private",
ChannelKind.DirectGroupTextChat => "Group",
ChannelKind.GuildNews => "News",
_ => "Default"
},
null
);
public static ChannelCategory Parse(JsonElement json, int? positionHint = null)
{
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var name =
json.GetPropertyOrNull("name")?.GetNonWhiteSpaceStringOrNull() ??
id.ToString();
var position =
positionHint ??
json.GetPropertyOrNull("position")?.GetInt32OrNull();
return new ChannelCategory(id, name, position);
}
}
@@ -16,12 +16,3 @@ public enum ChannelKind
GuildDirectory = 14, GuildDirectory = 14,
GuildForum = 15 GuildForum = 15
} }
public static class ChannelKindExtensions
{
public static bool IsDirect(this ChannelKind kind) =>
kind is ChannelKind.DirectTextChat or ChannelKind.DirectGroupTextChat;
public static bool IsGuild(this ChannelKind kind) =>
!kind.IsDirect();
}
@@ -1,46 +0,0 @@
using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/channel#channel-object-example-thread-channel
public record ChannelThread(
Snowflake Id,
ChannelKind Kind,
Snowflake GuildId,
Snowflake ParentId,
string Name,
bool IsActive,
Snowflake? LastMessageId) : IHasId
{
public static ChannelThread Parse(JsonElement json)
{
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var kind = (ChannelKind)json.GetProperty("type").GetInt32();
var guildId = json.GetProperty("guild_id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var parentId = json.GetProperty("parent_id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var name = json.GetProperty("name").GetNonWhiteSpaceString();
var isActive = !json
.GetPropertyOrNull("thread_metadata")?
.GetPropertyOrNull("archived")?
.GetBooleanOrNull() ?? true;
var lastMessageId = json
.GetPropertyOrNull("last_message_id")?
.GetNonWhiteSpaceStringOrNull()?
.Pipe(Snowflake.Parse);
return new ChannelThread(
id,
kind,
guildId,
parentId,
name,
isActive,
lastMessageId
);
}
}
@@ -41,10 +41,13 @@ public readonly partial record struct FileSize(long TotalBytes)
[ExcludeFromCodeCoverage] [ExcludeFromCodeCoverage]
public override string ToString() => public override string ToString() =>
string.Create(CultureInfo.InvariantCulture, $"{GetLargestWholeNumberValue():0.##} {GetLargestWholeNumberSymbol()}"); string.Create(
CultureInfo.InvariantCulture,
$"{GetLargestWholeNumberValue():0.##} {GetLargestWholeNumberSymbol()}"
);
} }
public partial record struct FileSize public partial record struct FileSize
{ {
public static FileSize FromBytes(long bytes) => new(bytes); public static FileSize FromBytes(long bytes) => new(bytes);
} }
@@ -3,4 +3,4 @@
public interface IHasId public interface IHasId
{ {
Snowflake Id { get; } Snowflake Id { get; }
} }
@@ -1,4 +1,5 @@
using System; using System;
using System.Globalization;
using System.Linq; using System.Linq;
using DiscordChatExporter.Core.Utils.Extensions; using DiscordChatExporter.Core.Utils.Extensions;
@@ -21,7 +22,7 @@ public static class ImageCdn
var twemojiId = string.Join( var twemojiId = string.Join(
"-", "-",
filteredRunes.Select(r => r.Value.ToString("x")) filteredRunes.Select(r => r.Value.ToString("x", CultureInfo.InvariantCulture))
); );
return $"https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/{twemojiId}.svg"; return $"https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/{twemojiId}.svg";
@@ -47,14 +48,19 @@ public static class ImageCdn
? $"https://cdn.discordapp.com/avatars/{userId}/{avatarHash}.gif?size={size}" ? $"https://cdn.discordapp.com/avatars/{userId}/{avatarHash}.gif?size={size}"
: $"https://cdn.discordapp.com/avatars/{userId}/{avatarHash}.png?size={size}"; : $"https://cdn.discordapp.com/avatars/{userId}/{avatarHash}.png?size={size}";
public static string GetFallbackUserAvatarUrl(int discriminator) => public static string GetFallbackUserAvatarUrl(int index = 0) =>
$"https://cdn.discordapp.com/embed/avatars/{discriminator % 5}.png"; $"https://cdn.discordapp.com/embed/avatars/{index}.png";
public static string GetMemberAvatarUrl(Snowflake guildId, Snowflake userId, string avatarHash, int size = 512) => public static string GetMemberAvatarUrl(
Snowflake guildId,
Snowflake userId,
string avatarHash,
int size = 512
) =>
avatarHash.StartsWith("a_", StringComparison.Ordinal) avatarHash.StartsWith("a_", StringComparison.Ordinal)
? $"https://cdn.discordapp.com/guilds/{guildId}/users/{userId}/avatars/{avatarHash}.gif?size={size}" ? $"https://cdn.discordapp.com/guilds/{guildId}/users/{userId}/avatars/{avatarHash}.gif?size={size}"
: $"https://cdn.discordapp.com/guilds/{guildId}/users/{userId}/avatars/{avatarHash}.png?size={size}"; : $"https://cdn.discordapp.com/guilds/{guildId}/users/{userId}/avatars/{avatarHash}.png?size={size}";
public static string GetStickerUrl(Snowflake stickerId, string format = "png") => public static string GetStickerUrl(Snowflake stickerId, string format = "png") =>
$"https://cdn.discordapp.com/stickers/{stickerId}.{format}"; $"https://cdn.discordapp.com/stickers/{stickerId}.{format}";
} }
@@ -21,7 +21,8 @@ public partial record Embed(
EmbedImage? Thumbnail, EmbedImage? Thumbnail,
IReadOnlyList<EmbedImage> Images, IReadOnlyList<EmbedImage> Images,
EmbedVideo? Video, EmbedVideo? Video,
EmbedFooter? Footer) EmbedFooter? Footer
)
{ {
// Embeds can only have one image according to the API model, // Embeds can only have one image according to the API model,
// but the client can render multiple images in some cases. // but the client can render multiple images in some cases.
@@ -41,24 +42,25 @@ public partial record Embed
var title = json.GetPropertyOrNull("title")?.GetStringOrNull(); var title = json.GetPropertyOrNull("title")?.GetStringOrNull();
var kind = var kind =
json.GetPropertyOrNull("type")?.GetStringOrNull()?.ParseEnumOrNull<EmbedKind>() ?? json.GetPropertyOrNull("type")?.GetStringOrNull()?.ParseEnumOrNull<EmbedKind>()
EmbedKind.Rich; ?? EmbedKind.Rich;
var url = json.GetPropertyOrNull("url")?.GetNonWhiteSpaceStringOrNull(); var url = json.GetPropertyOrNull("url")?.GetNonWhiteSpaceStringOrNull();
var timestamp = json.GetPropertyOrNull("timestamp")?.GetDateTimeOffsetOrNull(); var timestamp = json.GetPropertyOrNull("timestamp")?.GetDateTimeOffsetOrNull();
var color = json var color = json.GetPropertyOrNull("color")
.GetPropertyOrNull("color")? ?.GetInt32OrNull()
.GetInt32OrNull()? ?.Pipe(System.Drawing.Color.FromArgb)
.Pipe(System.Drawing.Color.FromArgb)
.ResetAlpha(); .ResetAlpha();
var author = json.GetPropertyOrNull("author")?.Pipe(EmbedAuthor.Parse); var author = json.GetPropertyOrNull("author")?.Pipe(EmbedAuthor.Parse);
var description = json.GetPropertyOrNull("description")?.GetStringOrNull(); var description = json.GetPropertyOrNull("description")?.GetStringOrNull();
var fields = var fields =
json.GetPropertyOrNull("fields")?.EnumerateArrayOrNull()?.Select(EmbedField.Parse).ToArray() ?? json.GetPropertyOrNull("fields")
Array.Empty<EmbedField>(); ?.EnumerateArrayOrNull()
?.Select(EmbedField.Parse)
.ToArray() ?? Array.Empty<EmbedField>();
var thumbnail = json.GetPropertyOrNull("thumbnail")?.Pipe(EmbedImage.Parse); var thumbnail = json.GetPropertyOrNull("thumbnail")?.Pipe(EmbedImage.Parse);
@@ -70,8 +72,10 @@ public partial record Embed
// with this by merging related embeds at the end of the message parsing process. // with this by merging related embeds at the end of the message parsing process.
// https://github.com/Tyrrrz/DiscordChatExporter/issues/695 // https://github.com/Tyrrrz/DiscordChatExporter/issues/695
var images = var images =
json.GetPropertyOrNull("image")?.Pipe(EmbedImage.Parse).ToSingletonEnumerable().ToArray() ?? json.GetPropertyOrNull("image")
Array.Empty<EmbedImage>(); ?.Pipe(EmbedImage.Parse)
.ToSingletonEnumerable()
.ToArray() ?? Array.Empty<EmbedImage>();
var video = json.GetPropertyOrNull("video")?.Pipe(EmbedVideo.Parse); var video = json.GetPropertyOrNull("video")?.Pipe(EmbedVideo.Parse);
@@ -92,4 +96,4 @@ public partial record Embed
footer footer
); );
} }
} }
@@ -4,11 +4,7 @@ using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data.Embeds; namespace DiscordChatExporter.Core.Discord.Data.Embeds;
// https://discord.com/developers/docs/resources/channel#embed-object-embed-author-structure // https://discord.com/developers/docs/resources/channel#embed-object-embed-author-structure
public record EmbedAuthor( public record EmbedAuthor(string? Name, string? Url, string? IconUrl, string? IconProxyUrl)
string? Name,
string? Url,
string? IconUrl,
string? IconProxyUrl)
{ {
public static EmbedAuthor Parse(JsonElement json) public static EmbedAuthor Parse(JsonElement json)
{ {
@@ -19,4 +15,4 @@ public record EmbedAuthor(
return new EmbedAuthor(name, url, iconUrl, iconProxyUrl); return new EmbedAuthor(name, url, iconUrl, iconProxyUrl);
} }
} }
@@ -4,10 +4,7 @@ using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data.Embeds; namespace DiscordChatExporter.Core.Discord.Data.Embeds;
// https://discord.com/developers/docs/resources/channel#embed-object-embed-field-structure // https://discord.com/developers/docs/resources/channel#embed-object-embed-field-structure
public record EmbedField( public record EmbedField(string Name, string Value, bool IsInline)
string Name,
string Value,
bool IsInline)
{ {
public static EmbedField Parse(JsonElement json) public static EmbedField Parse(JsonElement json)
{ {
@@ -17,4 +14,4 @@ public record EmbedField(
return new EmbedField(name, value, isInline); return new EmbedField(name, value, isInline);
} }
} }
@@ -4,10 +4,7 @@ using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data.Embeds; namespace DiscordChatExporter.Core.Discord.Data.Embeds;
// https://discord.com/developers/docs/resources/channel#embed-object-embed-footer-structure // https://discord.com/developers/docs/resources/channel#embed-object-embed-footer-structure
public record EmbedFooter( public record EmbedFooter(string Text, string? IconUrl, string? IconProxyUrl)
string Text,
string? IconUrl,
string? IconProxyUrl)
{ {
public static EmbedFooter Parse(JsonElement json) public static EmbedFooter Parse(JsonElement json)
{ {
@@ -17,4 +14,4 @@ public record EmbedFooter(
return new EmbedFooter(text, iconUrl, iconProxyUrl); return new EmbedFooter(text, iconUrl, iconProxyUrl);
} }
} }
@@ -4,11 +4,7 @@ using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data.Embeds; namespace DiscordChatExporter.Core.Discord.Data.Embeds;
// https://discord.com/developers/docs/resources/channel#embed-object-embed-image-structure // https://discord.com/developers/docs/resources/channel#embed-object-embed-image-structure
public record EmbedImage( public record EmbedImage(string? Url, string? ProxyUrl, int? Width, int? Height)
string? Url,
string? ProxyUrl,
int? Width,
int? Height)
{ {
public static EmbedImage Parse(JsonElement json) public static EmbedImage Parse(JsonElement json)
{ {
@@ -19,4 +15,4 @@ public record EmbedImage(
return new EmbedImage(url, proxyUrl, width, height); return new EmbedImage(url, proxyUrl, width, height);
} }
} }
@@ -8,4 +8,4 @@ public enum EmbedKind
Video, Video,
Gifv, Gifv,
Link Link
} }
@@ -1,14 +1,10 @@
using JsonExtensions.Reading;
using System.Text.Json; using System.Text.Json;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data.Embeds; namespace DiscordChatExporter.Core.Discord.Data.Embeds;
// https://discord.com/developers/docs/resources/channel#embed-object-embed-video-structure // https://discord.com/developers/docs/resources/channel#embed-object-embed-video-structure
public record EmbedVideo( public record EmbedVideo(string? Url, string? ProxyUrl, int? Width, int? Height)
string? Url,
string? ProxyUrl,
int? Width,
int? Height)
{ {
public static EmbedVideo Parse(JsonElement json) public static EmbedVideo Parse(JsonElement json)
{ {
@@ -19,4 +15,4 @@ public record EmbedVideo(
return new EmbedVideo(url, proxyUrl, width, height); return new EmbedVideo(url, proxyUrl, width, height);
} }
} }
@@ -12,7 +12,11 @@ public partial record SpotifyTrackEmbedProjection
private static string? TryParseTrackId(string embedUrl) private static string? TryParseTrackId(string embedUrl)
{ {
// https://open.spotify.com/track/1LHZMWefF9502NPfArRfvP?si=3efac6ce9be04f0a // https://open.spotify.com/track/1LHZMWefF9502NPfArRfvP?si=3efac6ce9be04f0a
var trackId = Regex.Match(embedUrl, @"spotify\.com/track/(.*?)(?:\?|&|/|$)").Groups[1].Value; var trackId = Regex
.Match(embedUrl, @"spotify\.com/track/(.*?)(?:\?|&|/|$)")
.Groups[1]
.Value;
if (!string.IsNullOrWhiteSpace(trackId)) if (!string.IsNullOrWhiteSpace(trackId))
return trackId; return trackId;
@@ -33,4 +37,4 @@ public partial record SpotifyTrackEmbedProjection
return new SpotifyTrackEmbedProjection(trackId); return new SpotifyTrackEmbedProjection(trackId);
} }
} }
@@ -21,4 +21,4 @@ public partial record YouTubeVideoEmbedProjection
return new YouTubeVideoEmbedProjection(videoId); return new YouTubeVideoEmbedProjection(videoId);
} }
} }
+10 -13
View File
@@ -14,12 +14,11 @@ public partial record Emoji(
// Name of a custom emoji (e.g. LUL) or actual representation of a standard emoji (e.g. 🙂) // Name of a custom emoji (e.g. LUL) or actual representation of a standard emoji (e.g. 🙂)
string Name, string Name,
bool IsAnimated, bool IsAnimated,
string ImageUrl) string ImageUrl
)
{ {
// Name of a custom emoji (e.g. LUL) or name of a standard emoji (e.g. slight_smile) // Name of a custom emoji (e.g. LUL) or name of a standard emoji (e.g. slight_smile)
public string Code => Id is not null public string Code => Id is not null ? Name : EmojiIndex.TryGetCode(Name) ?? Name;
? Name
: EmojiIndex.TryGetCode(Name) ?? Name;
} }
public partial record Emoji public partial record Emoji
@@ -39,19 +38,17 @@ public partial record Emoji
public static Emoji Parse(JsonElement json) public static Emoji Parse(JsonElement json)
{ {
var id = json.GetPropertyOrNull("id")?.GetNonWhiteSpaceStringOrNull()?.Pipe(Snowflake.Parse); var id = json.GetPropertyOrNull("id")
?.GetNonWhiteSpaceStringOrNull()
?.Pipe(Snowflake.Parse);
// Names may be missing on custom emoji within reactions // Names may be missing on custom emoji within reactions
var name = json.GetPropertyOrNull("name")?.GetNonWhiteSpaceStringOrNull() ?? "Unknown Emoji"; var name =
json.GetPropertyOrNull("name")?.GetNonWhiteSpaceStringOrNull() ?? "Unknown Emoji";
var isAnimated = json.GetPropertyOrNull("animated")?.GetBooleanOrNull() ?? false; var isAnimated = json.GetPropertyOrNull("animated")?.GetBooleanOrNull() ?? false;
var imageUrl = GetImageUrl(id, name, isAnimated); var imageUrl = GetImageUrl(id, name, isAnimated);
return new Emoji( return new Emoji(id, name, isAnimated, imageUrl);
id,
name,
isAnimated,
imageUrl
);
} }
} }
File diff suppressed because it is too large Load Diff
+12 -12
View File
@@ -6,14 +6,16 @@ using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data; namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/guild#guild-object // https://discord.com/developers/docs/resources/guild#guild-object
public record Guild(Snowflake Id, string Name, string IconUrl) : IHasId public partial record Guild(Snowflake Id, string Name, string IconUrl) : IHasId
{
public bool IsDirect => Id == DirectMessages.Id;
}
public partial record Guild
{ {
// Direct messages are encapsulated within a special pseudo-guild for consistency // Direct messages are encapsulated within a special pseudo-guild for consistency
public static Guild DirectMessages { get; } = new( public static Guild DirectMessages { get; } =
Snowflake.Zero, new(Snowflake.Zero, "Direct Messages", ImageCdn.GetFallbackUserAvatarUrl());
"Direct Messages",
ImageCdn.GetFallbackUserAvatarUrl(0)
);
public static Guild Parse(JsonElement json) public static Guild Parse(JsonElement json)
{ {
@@ -21,12 +23,10 @@ public record Guild(Snowflake Id, string Name, string IconUrl) : IHasId
var name = json.GetProperty("name").GetNonNullString(); var name = json.GetProperty("name").GetNonNullString();
var iconUrl = var iconUrl =
json json.GetPropertyOrNull("icon")
.GetPropertyOrNull("icon")? ?.GetNonWhiteSpaceStringOrNull()
.GetNonWhiteSpaceStringOrNull()? ?.Pipe(h => ImageCdn.GetGuildIconUrl(id, h)) ?? ImageCdn.GetFallbackUserAvatarUrl();
.Pipe(h => ImageCdn.GetGuildIconUrl(id, h)) ??
ImageCdn.GetFallbackUserAvatarUrl(0);
return new Guild(id, name, iconUrl); return new Guild(id, name, iconUrl);
} }
} }
@@ -10,9 +10,9 @@ public record Interaction(Snowflake Id, string Name, User User)
public static Interaction Parse(JsonElement json) public static Interaction Parse(JsonElement json)
{ {
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse); var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var name = json.GetProperty("name").GetNonWhiteSpaceString(); var name = json.GetProperty("name").GetNonNullString(); // may be empty, but not null
var user = json.GetProperty("user").Pipe(User.Parse); var user = json.GetProperty("user").Pipe(User.Parse);
return new Interaction(id, name, user); return new Interaction(id, name, user);
} }
} }
@@ -6,10 +6,7 @@ using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data; namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/invite#invite-object // https://discord.com/developers/docs/resources/invite#invite-object
public record Invite( public record Invite(string Code, Guild Guild, Channel? Channel)
string Code,
Guild Guild,
Channel? Channel)
{ {
public static string? TryGetCodeFromUrl(string url) => public static string? TryGetCodeFromUrl(string url) =>
Regex.Match(url, @"^https?://discord\.gg/(\w+)/?$").Groups[1].Value.NullIfWhiteSpace(); Regex.Match(url, @"^https?://discord\.gg/(\w+)/?$").Groups[1].Value.NullIfWhiteSpace();
@@ -22,4 +19,4 @@ public record Invite(
return new Invite(code, guild, channel); return new Invite(code, guild, channel);
} }
} }
+15 -19
View File
@@ -13,39 +13,35 @@ public partial record Member(
User User, User User,
string? DisplayName, string? DisplayName,
string? AvatarUrl, string? AvatarUrl,
IReadOnlyList<Snowflake> RoleIds) : IHasId IReadOnlyList<Snowflake> RoleIds
) : IHasId
{ {
public Snowflake Id => User.Id; public Snowflake Id => User.Id;
} }
public partial record Member public partial record Member
{ {
public static Member CreateDefault(User user) => new(user, null, null, Array.Empty<Snowflake>()); public static Member CreateFallback(User user) =>
new(user, null, null, Array.Empty<Snowflake>());
public static Member Parse(JsonElement json, Snowflake? guildId = null) public static Member Parse(JsonElement json, Snowflake? guildId = null)
{ {
var user = json.GetProperty("user").Pipe(User.Parse); var user = json.GetProperty("user").Pipe(User.Parse);
var displayName = json.GetPropertyOrNull("nick")?.GetNonWhiteSpaceStringOrNull(); var displayName = json.GetPropertyOrNull("nick")?.GetNonWhiteSpaceStringOrNull();
var roleIds = json var roleIds =
.GetPropertyOrNull("roles")? json.GetPropertyOrNull("roles")
.EnumerateArray() ?.EnumerateArray()
.Select(j => j.GetNonWhiteSpaceString()) .Select(j => j.GetNonWhiteSpaceString())
.Select(Snowflake.Parse) .Select(Snowflake.Parse)
.ToArray() ?? Array.Empty<Snowflake>(); .ToArray() ?? Array.Empty<Snowflake>();
var avatarUrl = guildId is not null var avatarUrl = guildId is not null
? json ? json.GetPropertyOrNull("avatar")
.GetPropertyOrNull("avatar")? ?.GetNonWhiteSpaceStringOrNull()
.GetNonWhiteSpaceStringOrNull()? ?.Pipe(h => ImageCdn.GetMemberAvatarUrl(guildId.Value, user.Id, h))
.Pipe(h => ImageCdn.GetMemberAvatarUrl(guildId.Value, user.Id, h))
: null; : null;
return new Member( return new Member(user, displayName, avatarUrl, roleIds);
user,
displayName,
avatarUrl,
roleIds
);
} }
} }
@@ -27,9 +27,22 @@ public partial record Message(
IReadOnlyList<User> MentionedUsers, IReadOnlyList<User> MentionedUsers,
MessageReference? Reference, MessageReference? Reference,
Message? ReferencedMessage, Message? ReferencedMessage,
Interaction? Interaction) : IHasId Interaction? Interaction
) : IHasId
{ {
public bool IsReplyLike => Kind == MessageKind.Reply || Interaction is not null; public bool IsSystemNotification =>
Kind is >= MessageKind.RecipientAdd and <= MessageKind.ThreadCreated;
public bool IsReply => Kind == MessageKind.Reply;
// App interactions are rendered as replies in the Discord client, but they are not actually replies
public bool IsReplyLike => IsReply || Interaction is not null;
public bool IsEmpty =>
string.IsNullOrWhiteSpace(Content)
&& !Attachments.Any()
&& !Embeds.Any()
&& !Stickers.Any();
public IEnumerable<User> GetReferencedUsers() public IEnumerable<User> GetReferencedUsers()
{ {
@@ -70,22 +83,27 @@ public partial record Message
// Find embeds with the same URL that only contain a single image and nothing else // Find embeds with the same URL that only contain a single image and nothing else
var trailingEmbeds = embeds var trailingEmbeds = embeds
.Skip(i + 1) .Skip(i + 1)
.TakeWhile(e => .TakeWhile(
e.Url == embed.Url && e =>
e.Timestamp is null && e.Url == embed.Url
e.Author is null && && e.Timestamp is null
e.Color is null && && e.Author is null
string.IsNullOrWhiteSpace(e.Description) && && e.Color is null
!e.Fields.Any() && && string.IsNullOrWhiteSpace(e.Description)
e.Images.Count == 1 && && !e.Fields.Any()
e.Footer is null && e.Images.Count == 1
&& e.Footer is null
) )
.ToArray(); .ToArray();
if (trailingEmbeds.Any()) if (trailingEmbeds.Any())
{ {
// Concatenate all images into one embed // Concatenate all images into one embed
var images = embed.Images.Concat(trailingEmbeds.SelectMany(e => e.Images)).ToArray(); var images = embed
.Images
.Concat(trailingEmbeds.SelectMany(e => e.Images))
.ToArray();
normalizedEmbeds.Add(embed with { Images = images }); normalizedEmbeds.Add(embed with { Images = images });
i += trailingEmbeds.Length; i += trailingEmbeds.Length;
@@ -107,43 +125,51 @@ public partial record Message
public static Message Parse(JsonElement json) public static Message Parse(JsonElement json)
{ {
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse); var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var kind = (MessageKind)json.GetProperty("type").GetInt32(); var kind = json.GetProperty("type").GetInt32().Pipe(t => (MessageKind)t);
var flags = (MessageFlags?)json.GetPropertyOrNull("flags")?.GetInt32OrNull() ?? MessageFlags.None;
var author = json.GetProperty("author").Pipe(User.Parse);
var flags =
json.GetPropertyOrNull("flags")?.GetInt32OrNull()?.Pipe(f => (MessageFlags)f)
?? MessageFlags.None;
var author = json.GetProperty("author").Pipe(User.Parse);
var timestamp = json.GetProperty("timestamp").GetDateTimeOffset(); var timestamp = json.GetProperty("timestamp").GetDateTimeOffset();
var editedTimestamp = json.GetPropertyOrNull("edited_timestamp")?.GetDateTimeOffsetOrNull(); var editedTimestamp = json.GetPropertyOrNull("edited_timestamp")?.GetDateTimeOffsetOrNull();
var callEndedTimestamp = json.GetPropertyOrNull("call")
var callEndedTimestamp = json ?.GetPropertyOrNull("ended_timestamp")
.GetPropertyOrNull("call")? ?.GetDateTimeOffsetOrNull();
.GetPropertyOrNull("ended_timestamp")?
.GetDateTimeOffsetOrNull();
var isPinned = json.GetPropertyOrNull("pinned")?.GetBooleanOrNull() ?? false; var isPinned = json.GetPropertyOrNull("pinned")?.GetBooleanOrNull() ?? false;
var content = json.GetPropertyOrNull("content")?.GetStringOrNull() ?? ""; var content = json.GetPropertyOrNull("content")?.GetStringOrNull() ?? "";
var attachments = var attachments =
json.GetPropertyOrNull("attachments")?.EnumerateArrayOrNull()?.Select(Attachment.Parse).ToArray() ?? json.GetPropertyOrNull("attachments")
Array.Empty<Attachment>(); ?.EnumerateArrayOrNull()
?.Select(Attachment.Parse)
.ToArray() ?? Array.Empty<Attachment>();
var embeds = NormalizeEmbeds( var embeds = NormalizeEmbeds(
json.GetPropertyOrNull("embeds")?.EnumerateArrayOrNull()?.Select(Embed.Parse).ToArray() ?? json.GetPropertyOrNull("embeds")?.EnumerateArrayOrNull()?.Select(Embed.Parse).ToArray()
Array.Empty<Embed>() ?? Array.Empty<Embed>()
); );
var stickers = var stickers =
json.GetPropertyOrNull("sticker_items")?.EnumerateArrayOrNull()?.Select(Sticker.Parse).ToArray() ?? json.GetPropertyOrNull("sticker_items")
Array.Empty<Sticker>(); ?.EnumerateArrayOrNull()
?.Select(Sticker.Parse)
.ToArray() ?? Array.Empty<Sticker>();
var reactions = var reactions =
json.GetPropertyOrNull("reactions")?.EnumerateArrayOrNull()?.Select(Reaction.Parse).ToArray() ?? json.GetPropertyOrNull("reactions")
Array.Empty<Reaction>(); ?.EnumerateArrayOrNull()
?.Select(Reaction.Parse)
.ToArray() ?? Array.Empty<Reaction>();
var mentionedUsers = var mentionedUsers =
json.GetPropertyOrNull("mentions")?.EnumerateArrayOrNull()?.Select(User.Parse).ToArray() ?? json.GetPropertyOrNull("mentions")?.EnumerateArrayOrNull()?.Select(User.Parse).ToArray()
Array.Empty<User>(); ?? Array.Empty<User>();
var messageReference = json.GetPropertyOrNull("message_reference")?.Pipe(MessageReference.Parse); var messageReference = json.GetPropertyOrNull("message_reference")
?.Pipe(MessageReference.Parse);
var referencedMessage = json.GetPropertyOrNull("referenced_message")?.Pipe(Parse); var referencedMessage = json.GetPropertyOrNull("referenced_message")?.Pipe(Parse);
var interaction = json.GetPropertyOrNull("interaction")?.Pipe(Interaction.Parse); var interaction = json.GetPropertyOrNull("interaction")?.Pipe(Interaction.Parse);
@@ -167,4 +193,4 @@ public partial record Message
interaction interaction
); );
} }
} }
@@ -15,4 +15,4 @@ public enum MessageFlags
HasThread = 32, HasThread = 32,
Ephemeral = 64, Ephemeral = 64,
Loading = 128 Loading = 128
} }
@@ -14,8 +14,3 @@ public enum MessageKind
ThreadCreated = 18, ThreadCreated = 18,
Reply = 19 Reply = 19
} }
public static class MessageKindExtensions
{
public static bool IsSystemNotification(this MessageKind kind) => (int)kind is >= 1 and <= 18;
}
@@ -9,21 +9,18 @@ public record MessageReference(Snowflake? MessageId, Snowflake? ChannelId, Snowf
{ {
public static MessageReference Parse(JsonElement json) public static MessageReference Parse(JsonElement json)
{ {
var messageId = json var messageId = json.GetPropertyOrNull("message_id")
.GetPropertyOrNull("message_id")? ?.GetNonWhiteSpaceStringOrNull()
.GetNonWhiteSpaceStringOrNull()? ?.Pipe(Snowflake.Parse);
.Pipe(Snowflake.Parse);
var channelId = json var channelId = json.GetPropertyOrNull("channel_id")
.GetPropertyOrNull("channel_id")? ?.GetNonWhiteSpaceStringOrNull()
.GetNonWhiteSpaceStringOrNull()? ?.Pipe(Snowflake.Parse);
.Pipe(Snowflake.Parse);
var guildId = json var guildId = json.GetPropertyOrNull("guild_id")
.GetPropertyOrNull("guild_id")? ?.GetNonWhiteSpaceStringOrNull()
.GetNonWhiteSpaceStringOrNull()? ?.Pipe(Snowflake.Parse);
.Pipe(Snowflake.Parse);
return new MessageReference(messageId, channelId, guildId); return new MessageReference(messageId, channelId, guildId);
} }
} }
@@ -13,4 +13,4 @@ public record Reaction(Emoji Emoji, int Count)
return new Reaction(emoji, count); return new Reaction(emoji, count);
} }
} }
@@ -15,13 +15,12 @@ public record Role(Snowflake Id, string Name, int Position, Color? Color) : IHas
var name = json.GetProperty("name").GetNonNullString(); var name = json.GetProperty("name").GetNonNullString();
var position = json.GetProperty("position").GetInt32(); var position = json.GetProperty("position").GetInt32();
var color = json var color = json.GetPropertyOrNull("color")
.GetPropertyOrNull("color")? ?.GetInt32OrNull()
.GetInt32OrNull()? ?.Pipe(System.Drawing.Color.FromArgb)
.Pipe(System.Drawing.Color.FromArgb)
.ResetAlpha() .ResetAlpha()
.NullIf(c => c.ToRgb() <= 0); .NullIf(c => c.ToRgb() <= 0);
return new Role(id, name, position, color); return new Role(id, name, position, color);
} }
} }
@@ -13,16 +13,19 @@ public record Sticker(Snowflake Id, string Name, StickerFormat Format, string So
{ {
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse); var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var name = json.GetProperty("name").GetNonNullString(); var name = json.GetProperty("name").GetNonNullString();
var format = (StickerFormat)json.GetProperty("format_type").GetInt32(); var format = json.GetProperty("format_type").GetInt32().Pipe(t => (StickerFormat)t);
var sourceUrl = ImageCdn.GetStickerUrl(id, format switch var sourceUrl = ImageCdn.GetStickerUrl(
{ id,
StickerFormat.Png => "png", format switch
StickerFormat.Apng => "png", {
StickerFormat.Lottie => "json", StickerFormat.Png => "png",
_ => throw new InvalidOperationException($"Unknown sticker format '{format}'.") StickerFormat.Apng => "png",
}); StickerFormat.Lottie => "json",
_ => throw new InvalidOperationException($"Unknown sticker format '{format}'.")
}
);
return new Sticker(id, name, format, sourceUrl); return new Sticker(id, name, format, sourceUrl);
} }
} }
@@ -5,4 +5,4 @@ public enum StickerFormat
Png = 1, Png = 1,
Apng = 2, Apng = 2,
Lottie = 3 Lottie = 3
} }
+17 -18
View File
@@ -15,18 +15,16 @@ public partial record User(
int? Discriminator, int? Discriminator,
string Name, string Name,
string DisplayName, string DisplayName,
string AvatarUrl) : IHasId string AvatarUrl
) : IHasId
{ {
public string DiscriminatorFormatted => Discriminator is not null public string DiscriminatorFormatted =>
? $"{Discriminator:0000}" Discriminator is not null ? $"{Discriminator:0000}" : "0000";
: "0000";
// This effectively represents the user's true identity. // This effectively represents the user's true identity.
// In the old system, this is formed from the username and discriminator. // In the old system, this is formed from the username and discriminator.
// In the new system, the username is already the user's unique identifier. // In the new system, the username is already the user's unique identifier.
public string FullName => Discriminator is not null public string FullName => Discriminator is not null ? $"{Name}#{DiscriminatorFormatted}" : Name;
? $"{Name}#{DiscriminatorFormatted}"
: Name;
} }
public partial record User public partial record User
@@ -36,22 +34,23 @@ public partial record User
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse); var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var isBot = json.GetPropertyOrNull("bot")?.GetBooleanOrNull() ?? false; var isBot = json.GetPropertyOrNull("bot")?.GetBooleanOrNull() ?? false;
var discriminator = json var discriminator = json.GetPropertyOrNull("discriminator")
.GetPropertyOrNull("discriminator")? ?.GetNonWhiteSpaceStringOrNull()
.GetNonWhiteSpaceStringOrNull()? ?.Pipe(int.Parse)
.Pipe(int.Parse)
.NullIfDefault(); .NullIfDefault();
var name = json.GetProperty("username").GetNonNullString(); var name = json.GetProperty("username").GetNonNullString();
var displayName = json.GetPropertyOrNull("global_name")?.GetNonWhiteSpaceStringOrNull() ?? name; var displayName =
json.GetPropertyOrNull("global_name")?.GetNonWhiteSpaceStringOrNull() ?? name;
var avatarIndex = discriminator % 5 ?? (int)((id.Value >> 22) % 6);
var avatarUrl = var avatarUrl =
json json.GetPropertyOrNull("avatar")
.GetPropertyOrNull("avatar")? ?.GetNonWhiteSpaceStringOrNull()
.GetNonWhiteSpaceStringOrNull()? ?.Pipe(h => ImageCdn.GetUserAvatarUrl(id, h))
.Pipe(h => ImageCdn.GetUserAvatarUrl(id, h)) ?? ?? ImageCdn.GetFallbackUserAvatarUrl(avatarIndex);
ImageCdn.GetFallbackUserAvatarUrl(discriminator ?? 0);
return new User(id, isBot, discriminator, name, displayName, avatarUrl); return new User(id, isBot, discriminator, name, displayName, avatarUrl);
} }
} }
+375 -144
View File
@@ -30,48 +30,50 @@ public class DiscordClient
private async ValueTask<HttpResponseMessage> GetResponseAsync( private async ValueTask<HttpResponseMessage> GetResponseAsync(
string url, string url,
TokenKind tokenKind, TokenKind tokenKind,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default
)
{ {
return await Http.ResponseResiliencePolicy.ExecuteAsync(async innerCancellationToken => return await Http.ResponseResiliencePipeline.ExecuteAsync(
{ async innerCancellationToken =>
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_baseUri, url));
// Don't validate because the token can have special characters
// https://github.com/Tyrrrz/DiscordChatExporter/issues/828
request.Headers.TryAddWithoutValidation(
"Authorization",
tokenKind == TokenKind.Bot
? $"Bot {_token}"
: _token
);
var response = await Http.Client.SendAsync(
request,
HttpCompletionOption.ResponseHeadersRead,
innerCancellationToken
);
// If this was the last request available before hitting the rate limit,
// wait out the reset time so that future requests can succeed.
// This may add an unnecessary delay in case the user doesn't intend to
// make any more requests, but implementing a smarter solution would
// require properly keeping track of Discord's global/per-route/per-resource
// rate limits and that's just way too much effort.
// https://discord.com/developers/docs/topics/rate-limits
var remainingRequestCount = response
.Headers
.TryGetValue("X-RateLimit-Remaining")?
.Pipe(s => int.Parse(s, CultureInfo.InvariantCulture));
var resetAfterDelay = response
.Headers
.TryGetValue("X-RateLimit-Reset-After")?
.Pipe(s => double.Parse(s, CultureInfo.InvariantCulture))
.Pipe(TimeSpan.FromSeconds);
if (remainingRequestCount <= 0 && resetAfterDelay is not null)
{ {
var delay = using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_baseUri, url));
// Don't validate because the token can have special characters
// https://github.com/Tyrrrz/DiscordChatExporter/issues/828
request
.Headers
.TryAddWithoutValidation(
"Authorization",
tokenKind == TokenKind.Bot ? $"Bot {_token}" : _token
);
var response = await Http.Client.SendAsync(
request,
HttpCompletionOption.ResponseHeadersRead,
innerCancellationToken
);
// If this was the last request available before hitting the rate limit,
// wait out the reset time so that future requests can succeed.
// This may add an unnecessary delay in case the user doesn't intend to
// make any more requests, but implementing a smarter solution would
// require properly keeping track of Discord's global/per-route/per-resource
// rate limits and that's just way too much effort.
// https://discord.com/developers/docs/topics/rate-limits
var remainingRequestCount = response
.Headers
.TryGetValue("X-RateLimit-Remaining")
?.Pipe(s => int.Parse(s, CultureInfo.InvariantCulture));
var resetAfterDelay = response
.Headers
.TryGetValue("X-RateLimit-Reset-After")
?.Pipe(s => double.Parse(s, CultureInfo.InvariantCulture))
.Pipe(TimeSpan.FromSeconds);
if (remainingRequestCount <= 0 && resetAfterDelay is not null)
{
var delay =
// Adding a small buffer to the reset time reduces the chance of getting // Adding a small buffer to the reset time reduces the chance of getting
// rate limited again, because it allows for more requests to be released. // rate limited again, because it allows for more requests to be released.
(resetAfterDelay.Value + TimeSpan.FromSeconds(1)) (resetAfterDelay.Value + TimeSpan.FromSeconds(1))
@@ -79,15 +81,22 @@ public class DiscordClient
// is not actually enforced by the server. So we cap it at a reasonable value. // is not actually enforced by the server. So we cap it at a reasonable value.
.Clamp(TimeSpan.Zero, TimeSpan.FromSeconds(60)); .Clamp(TimeSpan.Zero, TimeSpan.FromSeconds(60));
await Task.Delay(delay, innerCancellationToken); await Task.Delay(delay, innerCancellationToken);
} }
return response; return response;
}, cancellationToken); },
cancellationToken
);
} }
private async ValueTask<TokenKind> GetTokenKindAsync(CancellationToken cancellationToken = default) private async ValueTask<TokenKind> ResolveTokenKindAsync(
CancellationToken cancellationToken = default
)
{ {
if (_resolvedTokenKind is not null)
return _resolvedTokenKind.Value;
// Try authenticating as a user // Try authenticating as a user
using var userResponse = await GetResponseAsync( using var userResponse = await GetResponseAsync(
"users/@me", "users/@me",
@@ -96,7 +105,7 @@ public class DiscordClient
); );
if (userResponse.StatusCode != HttpStatusCode.Unauthorized) if (userResponse.StatusCode != HttpStatusCode.Unauthorized)
return TokenKind.User; return (_resolvedTokenKind = TokenKind.User).Value;
// Try authenticating as a bot // Try authenticating as a bot
using var botResponse = await GetResponseAsync( using var botResponse = await GetResponseAsync(
@@ -106,22 +115,25 @@ public class DiscordClient
); );
if (botResponse.StatusCode != HttpStatusCode.Unauthorized) if (botResponse.StatusCode != HttpStatusCode.Unauthorized)
return TokenKind.Bot; return (_resolvedTokenKind = TokenKind.Bot).Value;
throw DiscordChatExporterException.Unauthorized(); throw new DiscordChatExporterException("Authentication token is invalid.", true);
} }
private async ValueTask<HttpResponseMessage> GetResponseAsync( private async ValueTask<HttpResponseMessage> GetResponseAsync(
string url, string url,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default
{ ) =>
var tokenKind = _resolvedTokenKind ??= await GetTokenKindAsync(cancellationToken); await GetResponseAsync(
return await GetResponseAsync(url, tokenKind, cancellationToken); url,
} await ResolveTokenKindAsync(cancellationToken),
cancellationToken
);
private async ValueTask<JsonElement> GetJsonResponseAsync( private async ValueTask<JsonElement> GetJsonResponseAsync(
string url, string url,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default
)
{ {
using var response = await GetResponseAsync(url, cancellationToken); using var response = await GetResponseAsync(url, cancellationToken);
@@ -129,10 +141,30 @@ public class DiscordClient
{ {
throw response.StatusCode switch throw response.StatusCode switch
{ {
HttpStatusCode.Unauthorized => DiscordChatExporterException.Unauthorized(), HttpStatusCode.Unauthorized
HttpStatusCode.Forbidden => DiscordChatExporterException.Forbidden(), => throw new DiscordChatExporterException(
HttpStatusCode.NotFound => DiscordChatExporterException.NotFound(url), "Authentication token is invalid.",
_ => DiscordChatExporterException.FailedHttpRequest(response) true
),
HttpStatusCode.Forbidden
=> throw new DiscordChatExporterException(
$"Request to '{url}' failed: forbidden."
),
HttpStatusCode.NotFound
=> throw new DiscordChatExporterException(
$"Request to '{url}' failed: not found."
),
_
=> throw new DiscordChatExporterException(
$"""
Request to '{url}' failed: {response.StatusCode.ToString().ToSpaceSeparatedWords().ToLowerInvariant()}.
Response content: {await response.Content.ReadAsStringAsync(cancellationToken)}
""",
true
)
}; };
} }
@@ -141,7 +173,8 @@ public class DiscordClient
private async ValueTask<JsonElement?> TryGetJsonResponseAsync( private async ValueTask<JsonElement?> TryGetJsonResponseAsync(
string url, string url,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default
)
{ {
using var response = await GetResponseAsync(url, cancellationToken); using var response = await GetResponseAsync(url, cancellationToken);
return response.IsSuccessStatusCode return response.IsSuccessStatusCode
@@ -149,16 +182,26 @@ public class DiscordClient
: null; : null;
} }
public async ValueTask<Application> GetApplicationAsync(
CancellationToken cancellationToken = default
)
{
var response = await GetJsonResponseAsync("applications/@me", cancellationToken);
return Application.Parse(response);
}
public async ValueTask<User?> TryGetUserAsync( public async ValueTask<User?> TryGetUserAsync(
Snowflake userId, Snowflake userId,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default
)
{ {
var response = await TryGetJsonResponseAsync($"users/{userId}", cancellationToken); var response = await TryGetJsonResponseAsync($"users/{userId}", cancellationToken);
return response?.Pipe(User.Parse); return response?.Pipe(User.Parse);
} }
public async IAsyncEnumerable<Guild> GetUserGuildsAsync( public async IAsyncEnumerable<Guild> GetUserGuildsAsync(
[EnumeratorCancellation] CancellationToken cancellationToken = default) [EnumeratorCancellation] CancellationToken cancellationToken = default
)
{ {
yield return Guild.DirectMessages; yield return Guild.DirectMessages;
@@ -173,24 +216,25 @@ public class DiscordClient
var response = await GetJsonResponseAsync(url, cancellationToken); var response = await GetJsonResponseAsync(url, cancellationToken);
var isEmpty = true; var count = 0;
foreach (var guildJson in response.EnumerateArray()) foreach (var guildJson in response.EnumerateArray())
{ {
var guild = Guild.Parse(guildJson); var guild = Guild.Parse(guildJson);
yield return guild; yield return guild;
currentAfter = guild.Id; currentAfter = guild.Id;
isEmpty = false; count++;
} }
if (isEmpty) if (count <= 0)
yield break; yield break;
} }
} }
public async ValueTask<Guild> GetGuildAsync( public async ValueTask<Guild> GetGuildAsync(
Snowflake guildId, Snowflake guildId,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default
)
{ {
if (guildId == Guild.DirectMessages.Id) if (guildId == Guild.DirectMessages.Id)
return Guild.DirectMessages; return Guild.DirectMessages;
@@ -201,7 +245,8 @@ public class DiscordClient
public async IAsyncEnumerable<Channel> GetGuildChannelsAsync( public async IAsyncEnumerable<Channel> GetGuildChannelsAsync(
Snowflake guildId, Snowflake guildId,
[EnumeratorCancellation] CancellationToken cancellationToken = default) [EnumeratorCancellation] CancellationToken cancellationToken = default
)
{ {
if (guildId == Guild.DirectMessages.Id) if (guildId == Guild.DirectMessages.Id)
{ {
@@ -211,7 +256,10 @@ public class DiscordClient
} }
else else
{ {
var response = await GetJsonResponseAsync($"guilds/{guildId}/channels", cancellationToken); var response = await GetJsonResponseAsync(
$"guilds/{guildId}/channels",
cancellationToken
);
var channelsJson = response var channelsJson = response
.EnumerateArray() .EnumerateArray()
@@ -219,10 +267,10 @@ public class DiscordClient
.ThenBy(j => j.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse)) .ThenBy(j => j.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse))
.ToArray(); .ToArray();
var categories = channelsJson var parentsById = channelsJson
.Where(j => j.GetProperty("type").GetInt32() == (int)ChannelKind.GuildCategory) .Where(j => j.GetProperty("type").GetInt32() == (int)ChannelKind.GuildCategory)
.Select((j, index) => ChannelCategory.Parse(j, index + 1)) .Select((j, i) => Channel.Parse(j, null, i + 1))
.ToDictionary(j => j.Id.ToString(), StringComparer.Ordinal); .ToDictionary(j => j.Id);
// Discord channel positions are relative, so we need to normalize them // Discord channel positions are relative, so we need to normalize them
// so that the user may refer to them more easily in file name templates. // so that the user may refer to them more easily in file name templates.
@@ -230,30 +278,47 @@ public class DiscordClient
foreach (var channelJson in channelsJson) foreach (var channelJson in channelsJson)
{ {
var parentId = channelJson var parent = channelJson
.GetPropertyOrNull("parent_id")? .GetPropertyOrNull("parent_id")
.GetNonWhiteSpaceStringOrNull(); ?.GetNonWhiteSpaceStringOrNull()
?.Pipe(Snowflake.Parse)
.Pipe(parentsById.GetValueOrDefault);
var category = !string.IsNullOrWhiteSpace(parentId) yield return Channel.Parse(channelJson, parent, position);
? categories.GetValueOrDefault(parentId)
: null;
yield return Channel.Parse(channelJson, category, position);
position++; position++;
} }
} }
} }
public async IAsyncEnumerable<ChannelThread> GetGuildThreadsAsync( public async IAsyncEnumerable<Channel> GetGuildThreadsAsync(
Snowflake guildId, Snowflake guildId,
[EnumeratorCancellation] CancellationToken cancellationToken = default) bool includeArchived = false,
Snowflake? before = null,
Snowflake? after = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default
)
{ {
var tokenKind = _resolvedTokenKind ??= await GetTokenKindAsync(cancellationToken); if (guildId == Guild.DirectMessages.Id)
var channels = await GetGuildChannelsAsync(guildId, cancellationToken); yield break;
var channels = (await GetGuildChannelsAsync(guildId, cancellationToken))
// Categories cannot have threads
.Where(c => !c.IsCategory)
// Voice channels cannot have threads
.Where(c => !c.IsVoice)
// Empty channels cannot have threads
.Where(c => !c.IsEmpty)
// If the 'before' boundary is specified, skip channels that don't have messages
// for that range, because thread-start event should always be accompanied by a message.
// Note that we don't perform a similar check for the 'after' boundary, because
// threads may have messages in range, even if the parent channel doesn't.
.Where(c => before is null || c.MayHaveMessagesBefore(before.Value))
.ToArray();
// User accounts can only fetch threads using the search endpoint // User accounts can only fetch threads using the search endpoint
if (tokenKind == TokenKind.User) if (await ResolveTokenKindAsync(cancellationToken) == TokenKind.User)
{ {
// Active threads
foreach (var channel in channels) foreach (var channel in channels)
{ {
var currentOffset = 0; var currentOffset = 0;
@@ -261,56 +326,157 @@ public class DiscordClient
{ {
var url = new UrlBuilder() var url = new UrlBuilder()
.SetPath($"channels/{channel.Id}/threads/search") .SetPath($"channels/{channel.Id}/threads/search")
.SetQueryParameter("sort_by", "last_message_time")
.SetQueryParameter("sort_order", "desc")
.SetQueryParameter("archived", "false")
.SetQueryParameter("offset", currentOffset.ToString()) .SetQueryParameter("offset", currentOffset.ToString())
.Build(); .Build();
// Can be null on channels that the user cannot access or channels without threads
var response = await TryGetJsonResponseAsync(url, cancellationToken); var response = await TryGetJsonResponseAsync(url, cancellationToken);
if (response is null) if (response is null)
break; break;
foreach (var threadJson in response.Value.GetProperty("threads").EnumerateArray()) var breakOuter = false;
foreach (
var threadJson in response.Value.GetProperty("threads").EnumerateArray()
)
{ {
yield return ChannelThread.Parse(threadJson); var thread = Channel.Parse(threadJson, channel);
// If the 'after' boundary is specified, we can break early,
// because threads are sorted by last message time.
if (after is not null && !thread.MayHaveMessagesAfter(after.Value))
{
breakOuter = true;
break;
}
yield return thread;
currentOffset++; currentOffset++;
} }
if (breakOuter)
break;
if (!response.Value.GetProperty("has_more").GetBoolean()) if (!response.Value.GetProperty("has_more").GetBoolean())
break; break;
} }
} }
// Archived threads
if (includeArchived)
{
foreach (var channel in channels)
{
var currentOffset = 0;
while (true)
{
var url = new UrlBuilder()
.SetPath($"channels/{channel.Id}/threads/search")
.SetQueryParameter("sort_by", "last_message_time")
.SetQueryParameter("sort_order", "desc")
.SetQueryParameter("archived", "true")
.SetQueryParameter("offset", currentOffset.ToString())
.Build();
// Can be null on channels that the user cannot access or channels without threads
var response = await TryGetJsonResponseAsync(url, cancellationToken);
if (response is null)
break;
var breakOuter = false;
foreach (
var threadJson in response.Value.GetProperty("threads").EnumerateArray()
)
{
var thread = Channel.Parse(threadJson, channel);
// If the 'after' boundary is specified, we can break early,
// because threads are sorted by last message time.
if (after is not null && !thread.MayHaveMessagesAfter(after.Value))
{
breakOuter = true;
break;
}
yield return thread;
currentOffset++;
}
if (breakOuter)
break;
if (!response.Value.GetProperty("has_more").GetBoolean())
break;
}
}
}
} }
// Bot accounts can only fetch threads using the threads endpoint // Bot accounts can only fetch threads using the threads endpoint
else else
{ {
// Active threads // Active threads
{ {
var response = await GetJsonResponseAsync($"guilds/{guildId}/threads/active", cancellationToken); var parentsById = channels.ToDictionary(c => c.Id);
var response = await GetJsonResponseAsync(
$"guilds/{guildId}/threads/active",
cancellationToken
);
foreach (var threadJson in response.GetProperty("threads").EnumerateArray()) foreach (var threadJson in response.GetProperty("threads").EnumerateArray())
yield return ChannelThread.Parse(threadJson); {
var parent = threadJson
.GetPropertyOrNull("parent_id")
?.GetNonWhiteSpaceStringOrNull()
?.Pipe(Snowflake.Parse)
.Pipe(parentsById.GetValueOrDefault);
yield return Channel.Parse(threadJson, parent);
}
} }
foreach (var channel in channels) // Archived threads
if (includeArchived)
{ {
// Public archived threads foreach (var channel in channels)
{ {
var response = await GetJsonResponseAsync( // Public archived threads
$"channels/{channel.Id}/threads/archived/public", {
cancellationToken // Can be null on certain channels
); var response = await TryGetJsonResponseAsync(
$"channels/{channel.Id}/threads/archived/public",
cancellationToken
);
foreach (var threadJson in response.GetProperty("threads").EnumerateArray()) if (response is null)
yield return ChannelThread.Parse(threadJson); continue;
}
// Private archived threads foreach (
{ var threadJson in response.Value.GetProperty("threads").EnumerateArray()
var response = await GetJsonResponseAsync( )
$"channels/{channel.Id}/threads/archived/private", yield return Channel.Parse(threadJson, channel);
cancellationToken }
);
foreach (var threadJson in response.GetProperty("threads").EnumerateArray()) // Private archived threads
yield return ChannelThread.Parse(threadJson); {
// Can be null on certain channels
var response = await TryGetJsonResponseAsync(
$"channels/{channel.Id}/threads/archived/private",
cancellationToken
);
if (response is null)
continue;
foreach (
var threadJson in response.Value.GetProperty("threads").EnumerateArray()
)
yield return Channel.Parse(threadJson, channel);
}
} }
} }
} }
@@ -318,7 +484,8 @@ public class DiscordClient
public async IAsyncEnumerable<Role> GetGuildRolesAsync( public async IAsyncEnumerable<Role> GetGuildRolesAsync(
Snowflake guildId, Snowflake guildId,
[EnumeratorCancellation] CancellationToken cancellationToken = default) [EnumeratorCancellation] CancellationToken cancellationToken = default
)
{ {
if (guildId == Guild.DirectMessages.Id) if (guildId == Guild.DirectMessages.Id)
yield break; yield break;
@@ -331,62 +498,62 @@ public class DiscordClient
public async ValueTask<Member?> TryGetGuildMemberAsync( public async ValueTask<Member?> TryGetGuildMemberAsync(
Snowflake guildId, Snowflake guildId,
Snowflake memberId, Snowflake memberId,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default
)
{ {
if (guildId == Guild.DirectMessages.Id) if (guildId == Guild.DirectMessages.Id)
return null; return null;
var response = await TryGetJsonResponseAsync($"guilds/{guildId}/members/{memberId}", cancellationToken); var response = await TryGetJsonResponseAsync(
$"guilds/{guildId}/members/{memberId}",
cancellationToken
);
return response?.Pipe(j => Member.Parse(j, guildId)); return response?.Pipe(j => Member.Parse(j, guildId));
} }
public async ValueTask<Invite?> TryGetGuildInviteAsync( public async ValueTask<Invite?> TryGetInviteAsync(
string code, string code,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default
)
{ {
var response = await TryGetJsonResponseAsync($"invites/{code}", cancellationToken); var response = await TryGetJsonResponseAsync($"invites/{code}", cancellationToken);
return response?.Pipe(Invite.Parse); return response?.Pipe(Invite.Parse);
} }
public async ValueTask<ChannelCategory> GetChannelCategoryAsync(
Snowflake channelId,
CancellationToken cancellationToken = default)
{
try
{
var response = await GetJsonResponseAsync($"channels/{channelId}", cancellationToken);
return ChannelCategory.Parse(response);
}
// In some cases, Discord API returns an empty body when requesting a channel.
// Use an empty channel category as fallback for these cases.
catch (DiscordChatExporterException)
{
return new ChannelCategory(channelId, "Unknown Category", 0);
}
}
public async ValueTask<Channel> GetChannelAsync( public async ValueTask<Channel> GetChannelAsync(
Snowflake channelId, Snowflake channelId,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default
)
{ {
var response = await GetJsonResponseAsync($"channels/{channelId}", cancellationToken); var response = await GetJsonResponseAsync($"channels/{channelId}", cancellationToken);
var parentId = response var parentId = response
.GetPropertyOrNull("parent_id")? .GetPropertyOrNull("parent_id")
.GetNonWhiteSpaceStringOrNull()? ?.GetNonWhiteSpaceStringOrNull()
.Pipe(Snowflake.Parse); ?.Pipe(Snowflake.Parse);
var category = parentId is not null try
? await GetChannelCategoryAsync(parentId.Value, cancellationToken) {
: null; var parent = parentId is not null
? await GetChannelAsync(parentId.Value, cancellationToken)
: null;
return Channel.Parse(response, category); return Channel.Parse(response, parent);
}
// It's possible for the parent channel to be inaccessible, despite the
// child channel being accessible.
// https://github.com/Tyrrrz/DiscordChatExporter/issues/1108
catch (DiscordChatExporterException)
{
return Channel.Parse(response);
}
} }
private async ValueTask<Message?> TryGetLastMessageAsync( private async ValueTask<Message?> TryGetLastMessageAsync(
Snowflake channelId, Snowflake channelId,
Snowflake? before = null, Snowflake? before = null,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default
)
{ {
var url = new UrlBuilder() var url = new UrlBuilder()
.SetPath($"channels/{channelId}/messages") .SetPath($"channels/{channelId}/messages")
@@ -403,7 +570,8 @@ public class DiscordClient
Snowflake? after = null, Snowflake? after = null,
Snowflake? before = null, Snowflake? before = null,
IProgress<Percentage>? progress = null, IProgress<Percentage>? progress = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default) [EnumeratorCancellation] CancellationToken cancellationToken = default
)
{ {
// Get the last message in the specified range, so we can later calculate the // Get the last message in the specified range, so we can later calculate the
// progress based on the difference between message timestamps. // progress based on the difference between message timestamps.
@@ -438,6 +606,24 @@ public class DiscordClient
if (!messages.Any()) if (!messages.Any())
yield break; yield break;
// If all messages are empty, make sure that it's not because the bot account doesn't
// have the Message Content Intent enabled.
// https://github.com/Tyrrrz/DiscordChatExporter/issues/1106#issuecomment-1741548959
if (
messages.All(m => m.IsEmpty)
&& await ResolveTokenKindAsync(cancellationToken) == TokenKind.Bot
)
{
var application = await GetApplicationAsync(cancellationToken);
if (!application.IsMessageContentIntentEnabled)
{
throw new DiscordChatExporterException(
"Bot account does not have the Message Content Intent enabled.",
true
);
}
}
foreach (var message in messages) foreach (var message in messages)
{ {
firstMessage ??= message; firstMessage ??= message;
@@ -452,13 +638,15 @@ public class DiscordClient
var exportedDuration = (message.Timestamp - firstMessage.Timestamp).Duration(); var exportedDuration = (message.Timestamp - firstMessage.Timestamp).Duration();
var totalDuration = (lastMessage.Timestamp - firstMessage.Timestamp).Duration(); var totalDuration = (lastMessage.Timestamp - firstMessage.Timestamp).Duration();
progress.Report(Percentage.FromFraction( progress.Report(
// Avoid division by zero if all messages have the exact same timestamp Percentage.FromFraction(
// (which happens when there's only one message in the channel) // Avoid division by zero if all messages have the exact same timestamp
totalDuration > TimeSpan.Zero // (which happens when there's only one message in the channel)
? exportedDuration / totalDuration totalDuration > TimeSpan.Zero
: 1 ? exportedDuration / totalDuration
)); : 1
)
);
} }
yield return message; yield return message;
@@ -466,4 +654,47 @@ public class DiscordClient
} }
} }
} }
}
public async IAsyncEnumerable<User> GetMessageReactionsAsync(
Snowflake channelId,
Snowflake messageId,
Emoji emoji,
[EnumeratorCancellation] CancellationToken cancellationToken = default
)
{
var reactionName = emoji.Id is not null
// Custom emoji
? emoji.Name + ':' + emoji.Id
// Standard emoji
: emoji.Name;
var currentAfter = Snowflake.Zero;
while (true)
{
var url = new UrlBuilder()
.SetPath(
$"channels/{channelId}/messages/{messageId}/reactions/{Uri.EscapeDataString(reactionName)}"
)
.SetQueryParameter("limit", "100")
.SetQueryParameter("after", currentAfter.ToString())
.Build();
var response = await GetJsonResponseAsync(url, cancellationToken);
var count = 0;
foreach (var userJson in response.EnumerateArray())
{
var user = User.Parse(userJson);
yield return user;
currentAfter = user.Id;
count++;
}
// Each batch can contain up to 100 users.
// If we got fewer, then it's definitely the last batch.
if (count < 100)
yield break;
}
}
}

Some files were not shown because too many files have changed in this diff Show More