├── .dockerignore ├── .github └── workflows │ ├── docker_publish.yml │ ├── scan.yml │ └── scan │ └── html.tpl ├── .gitignore ├── .prettierrc ├── .vscode └── settings.json ├── Dockerfile ├── Dockerfile.ubi ├── GlobalSuppressions.cs ├── Helper.cs ├── Json └── SourceGenerationContext.cs ├── LICENSE ├── LiveChatMonitorWorker.cs ├── Models ├── Chat.cs └── Info.cs ├── Program.cs ├── README.md ├── README.zh.md ├── Services ├── DiscordService.cs └── LiveChatDownloadService.cs ├── YoutubeLiveChatToDiscord.csproj ├── YoutubeLiveChatToDiscord.sln ├── appsettings.Development.json ├── appsettings.json ├── assets ├── crown.png ├── gift.png └── wallet.png ├── docker-compose.override.yml ├── docker-compose.yml └── helm-chart ├── .helmignore ├── Chart.yaml ├── templates ├── _helpers.tpl ├── configMap.yaml └── deployment.yaml └── values.yaml /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md 26 | **/helm-chart 27 | **/.github 28 | .dockerignore 29 | .gitignore 30 | -------------------------------------------------------------------------------- /.github/workflows/docker_publish.yml: -------------------------------------------------------------------------------- 1 | name: docker_publish 2 | 3 | # Controls when the action will run. 4 | on: 5 | # Triggers the workflow on push or pull request events but only for the master branch 6 | push: 7 | branches: 8 | - "master" 9 | tags: 10 | - "*" 11 | 12 | # Allows you to run this workflow manually from the Actions tab 13 | workflow_dispatch: 14 | 15 | # Sets the permissions granted to the GITHUB_TOKEN for the actions in this job. 16 | permissions: 17 | contents: read 18 | packages: write 19 | 20 | env: 21 | IMAGE_NAME: youtubelivechattodiscord 22 | 23 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 24 | jobs: 25 | # This workflow contains a single job called "build" 26 | build-and-push: 27 | # The type of runner that the job will run on 28 | runs-on: ubuntu-latest 29 | 30 | # Steps represent a sequence of tasks that will be executed as part of the job 31 | steps: 32 | - name: Checkout 33 | uses: actions/checkout@v4 34 | with: 35 | submodules: true 36 | 37 | - name: Docker meta 38 | id: meta 39 | uses: docker/metadata-action@v5 40 | with: 41 | images: ${{ secrets.DOCKERHUB_USERNAME }}/${{ env.IMAGE_NAME }},ghcr.io/${{ github.repository }},quay.io/${{ github.repository }} 42 | # set latest tag for default branch 43 | tags: | 44 | type=ref,event=branch 45 | type=ref,event=tag 46 | type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', 'master') }} 47 | 48 | - name: Docker meta-ubi 49 | id: meta-ubi 50 | uses: docker/metadata-action@v5 51 | with: 52 | images: ${{ secrets.DOCKERHUB_USERNAME }}/${{ env.IMAGE_NAME }},ghcr.io/${{ github.repository }},quay.io/${{ github.repository }} 53 | # set latest tag for default branch 54 | tags: | 55 | type=raw,value=ubi 56 | 57 | - name: Set up QEMU 58 | uses: docker/setup-qemu-action@v3 59 | 60 | - name: Set up Docker Buildx 61 | uses: docker/setup-buildx-action@v3 62 | 63 | # Create a Access Token and save it as as Actions secret 64 | # https://hub.docker.com/settings/security 65 | # DOCKERHUB_USERNAME 66 | # DOCKERHUB_TOKEN 67 | - name: Login to DockerHub 68 | uses: docker/login-action@v3 69 | with: 70 | username: ${{ secrets.DOCKERHUB_USERNAME }} 71 | password: ${{ secrets.DOCKERHUB_TOKEN }} 72 | 73 | # Create a Access Token with `read:packages` and `write:packages` scopes 74 | # CR_PAT 75 | - name: Login to GitHub Container Registry 76 | uses: docker/login-action@v3 77 | with: 78 | registry: ghcr.io 79 | username: ${{ github.repository_owner }} 80 | password: ${{ github.token }} 81 | 82 | - name: Login to Quay Container Registry 83 | uses: docker/login-action@v3 84 | with: 85 | registry: quay.io 86 | username: ${{ secrets.QUAY_USERNAME }} 87 | password: ${{ secrets.QUAY_TOKEN }} 88 | 89 | - name: Build and push 90 | uses: docker/build-push-action@v5 91 | with: 92 | context: . 93 | file: ./Dockerfile 94 | push: true 95 | target: final 96 | tags: ${{ steps.meta.outputs.tags }} 97 | labels: ${{ steps.meta.outputs.labels }} 98 | platforms: linux/amd64 99 | # Cache to registry instead of gha to avoid the capacity limit. 100 | cache-from: type=registry,ref=ghcr.io/${{ github.repository_owner }}/${{ env.IMAGE_NAME }}:cache 101 | cache-to: type=registry,ref=ghcr.io/${{ github.repository_owner }}/${{ env.IMAGE_NAME }}:cache,mode=max 102 | sbom: true 103 | provenance: true 104 | 105 | - name: Build and push UBI 106 | uses: docker/build-push-action@v5 107 | with: 108 | context: . 109 | file: ./Dockerfile.ubi 110 | push: true 111 | target: final 112 | tags: ${{ steps.meta-ubi.outputs.tags }} 113 | labels: ${{ steps.meta-ubi.outputs.labels }} 114 | platforms: linux/amd64 115 | # Cache to registry instead of gha to avoid the capacity limit. 116 | cache-from: type=registry,ref=ghcr.io/${{ github.repository_owner }}/${{ env.IMAGE_NAME }}:cache 117 | cache-to: type=registry,ref=ghcr.io/${{ github.repository_owner }}/${{ env.IMAGE_NAME }}:cache,mode=max 118 | sbom: true 119 | provenance: true 120 | 121 | # - name: Build and push arm64 122 | # uses: docker/build-push-action@v5 123 | # with: 124 | # context: . 125 | # file: ./Dockerfile 126 | # push: true 127 | # target: final 128 | # tags: ${{ steps.meta.outputs.tags }} 129 | # labels: ${{ steps.meta.outputs.labels }} 130 | # platforms: linux/arm64 131 | 132 | # - name: Build and push UBI arm64 133 | # uses: docker/build-push-action@v5 134 | # with: 135 | # context: . 136 | # file: ./Dockerfile.ubi 137 | # push: true 138 | # target: final 139 | # tags: ${{ steps.meta-ubi.outputs.tags }} 140 | # labels: ${{ steps.meta-ubi.outputs.labels }} 141 | # platforms: linux/arm64 142 | -------------------------------------------------------------------------------- /.github/workflows/scan.yml: -------------------------------------------------------------------------------- 1 | name: scan 2 | 3 | on: 4 | workflow_run: 5 | workflows: [docker_publish] 6 | types: [completed] 7 | 8 | # Allows you to run this workflow manually from the Actions tab 9 | workflow_dispatch: 10 | 11 | jobs: 12 | scan-python: 13 | name: Scan Microsoft official base image 14 | runs-on: ubuntu-latest 15 | if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }} 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v4 19 | with: 20 | sparse-checkout: | 21 | .github/workflows/scan/html.tpl 22 | sparse-checkout-cone-mode: false 23 | 24 | - name: Run Trivy vulnerability scanner for Microsoft official image 25 | uses: aquasecurity/trivy-action@0.30.0 26 | with: 27 | image-ref: "ghcr.io/jim60105/youtubelivechattodiscord:latest" 28 | vuln-type: "os,library" 29 | scanners: vuln 30 | severity: "CRITICAL,HIGH" 31 | format: "template" 32 | template: "@.github/workflows/scan/html.tpl" 33 | output: "trivy-results-microsoft.html" 34 | 35 | - name: Upload Artifact 36 | uses: actions/upload-artifact@v4 37 | with: 38 | name: trivy-results-microsoft 39 | path: trivy-results-microsoft.html 40 | retention-days: 90 41 | 42 | scan-ubi: 43 | name: Scan Red Hat UBI base image 44 | runs-on: ubuntu-latest 45 | if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }} 46 | steps: 47 | - name: Checkout 48 | uses: actions/checkout@v4 49 | with: 50 | sparse-checkout: | 51 | .github/workflows/scan/html.tpl 52 | sparse-checkout-cone-mode: false 53 | 54 | - name: Run Trivy vulnerability scanner for UBI image 55 | uses: aquasecurity/trivy-action@0.30.0 56 | with: 57 | image-ref: "ghcr.io/jim60105/youtubelivechattodiscord:ubi" 58 | vuln-type: "os,library" 59 | scanners: vuln 60 | severity: "CRITICAL,HIGH" 61 | format: "template" 62 | template: "@.github/workflows/scan/html.tpl" 63 | output: "trivy-results-ubi.html" 64 | 65 | - name: Upload Artifact 66 | uses: actions/upload-artifact@v4 67 | with: 68 | name: trivy-results-ubi 69 | path: trivy-results-ubi.html 70 | retention-days: 90 71 | -------------------------------------------------------------------------------- /.github/workflows/scan/html.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | {{- if . }} 7 | 56 | {{- escapeXML ( index . 0 ).Target }} - Trivy Report - {{ now }} 57 | 84 | 85 | 86 |

{{- escapeXML ( index . 0 ).Target }} - Trivy Report - {{ now }}

87 | 88 | {{- range . }} 89 | 90 | {{- if (eq (len .Vulnerabilities) 0) }} 91 | 92 | {{- else }} 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | {{- range .Vulnerabilities }} 102 | 103 | 104 | 105 | 106 | 107 | 108 | 113 | 114 | {{- end }} 115 | {{- end }} 116 | {{- if (eq (len .Misconfigurations ) 0) }} 117 | 118 | {{- else }} 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | {{- range .Misconfigurations }} 127 | 128 | 129 | 130 | 131 | 132 | 138 | 139 | {{- end }} 140 | {{- end }} 141 | {{- end }} 142 |
{{ .Type | toString | escapeXML }}
No Vulnerabilities found
PackageVulnerability IDSeverityInstalled VersionFixed VersionLinks
{{ escapeXML .PkgName }}{{ escapeXML .VulnerabilityID }}{{ escapeXML .Vulnerability.Severity }}{{ escapeXML .InstalledVersion }}{{ escapeXML .FixedVersion }}
No Misconfigurations found
TypeMisconf IDCheckSeverityMessage
{{ escapeXML .Type }}{{ escapeXML .ID }}{{ escapeXML .Title }}{{ escapeXML .Severity }}
143 | {{- else }} 144 | 145 | 146 |

Trivy Returned Empty Report

147 | {{- end }} 148 | 149 | 150 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # Tye 66 | .tye/ 67 | 68 | # ASP.NET Scaffolding 69 | ScaffoldingReadMe.txt 70 | 71 | # StyleCop 72 | StyleCopReport.xml 73 | 74 | # Files built by Visual Studio 75 | *_i.c 76 | *_p.c 77 | *_h.h 78 | *.ilk 79 | *.meta 80 | *.obj 81 | *.iobj 82 | *.pch 83 | *.pdb 84 | *.ipdb 85 | *.pgc 86 | *.pgd 87 | *.rsp 88 | *.sbr 89 | *.tlb 90 | *.tli 91 | *.tlh 92 | *.tmp 93 | *.tmp_proj 94 | *_wpftmp.csproj 95 | *.log 96 | *.vspscc 97 | *.vssscc 98 | .builds 99 | *.pidb 100 | *.svclog 101 | *.scc 102 | 103 | # Chutzpah Test files 104 | _Chutzpah* 105 | 106 | # Visual C++ cache files 107 | ipch/ 108 | *.aps 109 | *.ncb 110 | *.opendb 111 | *.opensdf 112 | *.sdf 113 | *.cachefile 114 | *.VC.db 115 | *.VC.VC.opendb 116 | 117 | # Visual Studio profiler 118 | *.psess 119 | *.vsp 120 | *.vspx 121 | *.sap 122 | 123 | # Visual Studio Trace Files 124 | *.e2e 125 | 126 | # TFS 2012 Local Workspace 127 | $tf/ 128 | 129 | # Guidance Automation Toolkit 130 | *.gpState 131 | 132 | # ReSharper is a .NET coding add-in 133 | _ReSharper*/ 134 | *.[Rr]e[Ss]harper 135 | *.DotSettings.user 136 | 137 | # TeamCity is a build add-in 138 | _TeamCity* 139 | 140 | # DotCover is a Code Coverage Tool 141 | *.dotCover 142 | 143 | # AxoCover is a Code Coverage Tool 144 | .axoCover/* 145 | !.axoCover/settings.json 146 | 147 | # Coverlet is a free, cross platform Code Coverage Tool 148 | coverage*.json 149 | coverage*.xml 150 | coverage*.info 151 | 152 | # Visual Studio code coverage results 153 | *.coverage 154 | *.coveragexml 155 | 156 | # NCrunch 157 | _NCrunch_* 158 | .*crunch*.local.xml 159 | nCrunchTemp_* 160 | 161 | # MightyMoose 162 | *.mm.* 163 | AutoTest.Net/ 164 | 165 | # Web workbench (sass) 166 | .sass-cache/ 167 | 168 | # Installshield output folder 169 | [Ee]xpress/ 170 | 171 | # DocProject is a documentation generator add-in 172 | DocProject/buildhelp/ 173 | DocProject/Help/*.HxT 174 | DocProject/Help/*.HxC 175 | DocProject/Help/*.hhc 176 | DocProject/Help/*.hhk 177 | DocProject/Help/*.hhp 178 | DocProject/Help/Html2 179 | DocProject/Help/html 180 | 181 | # Click-Once directory 182 | publish/ 183 | 184 | # Publish Web Output 185 | *.[Pp]ublish.xml 186 | *.azurePubxml 187 | # Note: Comment the next line if you want to checkin your web deploy settings, 188 | # but database connection strings (with potential passwords) will be unencrypted 189 | *.pubxml 190 | *.publishproj 191 | 192 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 193 | # checkin your Azure Web App publish settings, but sensitive information contained 194 | # in these scripts will be unencrypted 195 | PublishScripts/ 196 | 197 | # NuGet Packages 198 | *.nupkg 199 | # NuGet Symbol Packages 200 | *.snupkg 201 | # The packages folder can be ignored because of Package Restore 202 | **/[Pp]ackages/* 203 | # except build/, which is used as an MSBuild target. 204 | !**/[Pp]ackages/build/ 205 | # Uncomment if necessary however generally it will be regenerated when needed 206 | #!**/[Pp]ackages/repositories.config 207 | # NuGet v3's project.json files produces more ignorable files 208 | *.nuget.props 209 | *.nuget.targets 210 | 211 | # Microsoft Azure Build Output 212 | csx/ 213 | *.build.csdef 214 | 215 | # Microsoft Azure Emulator 216 | ecf/ 217 | rcf/ 218 | 219 | # Windows Store app package directories and files 220 | AppPackages/ 221 | BundleArtifacts/ 222 | Package.StoreAssociation.xml 223 | _pkginfo.txt 224 | *.appx 225 | *.appxbundle 226 | *.appxupload 227 | 228 | # Visual Studio cache files 229 | # files ending in .cache can be ignored 230 | *.[Cc]ache 231 | # but keep track of directories ending in .cache 232 | !?*.[Cc]ache/ 233 | 234 | # Others 235 | ClientBin/ 236 | ~$* 237 | *~ 238 | *.dbmdl 239 | *.dbproj.schemaview 240 | *.jfm 241 | *.pfx 242 | *.publishsettings 243 | orleans.codegen.cs 244 | 245 | # Including strong name files can present a security risk 246 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 247 | #*.snk 248 | 249 | # Since there are multiple workflows, uncomment next line to ignore bower_components 250 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 251 | #bower_components/ 252 | 253 | # RIA/Silverlight projects 254 | Generated_Code/ 255 | 256 | # Backup & report files from converting an old project file 257 | # to a newer Visual Studio version. Backup files are not needed, 258 | # because we have git ;-) 259 | _UpgradeReport_Files/ 260 | Backup*/ 261 | UpgradeLog*.XML 262 | UpgradeLog*.htm 263 | ServiceFabricBackup/ 264 | *.rptproj.bak 265 | 266 | # SQL Server files 267 | *.mdf 268 | *.ldf 269 | *.ndf 270 | 271 | # Business Intelligence projects 272 | *.rdl.data 273 | *.bim.layout 274 | *.bim_*.settings 275 | *.rptproj.rsuser 276 | *- [Bb]ackup.rdl 277 | *- [Bb]ackup ([0-9]).rdl 278 | *- [Bb]ackup ([0-9][0-9]).rdl 279 | 280 | # Microsoft Fakes 281 | FakesAssemblies/ 282 | 283 | # GhostDoc plugin setting file 284 | *.GhostDoc.xml 285 | 286 | # Node.js Tools for Visual Studio 287 | .ntvs_analysis.dat 288 | node_modules/ 289 | 290 | # Visual Studio 6 build log 291 | *.plg 292 | 293 | # Visual Studio 6 workspace options file 294 | *.opt 295 | 296 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 297 | *.vbw 298 | 299 | # Visual Studio LightSwitch build output 300 | **/*.HTMLClient/GeneratedArtifacts 301 | **/*.DesktopClient/GeneratedArtifacts 302 | **/*.DesktopClient/ModelManifest.xml 303 | **/*.Server/GeneratedArtifacts 304 | **/*.Server/ModelManifest.xml 305 | _Pvt_Extensions 306 | 307 | # Paket dependency manager 308 | .paket/paket.exe 309 | paket-files/ 310 | 311 | # FAKE - F# Make 312 | .fake/ 313 | 314 | # CodeRush personal settings 315 | .cr/personal 316 | 317 | # Python Tools for Visual Studio (PTVS) 318 | __pycache__/ 319 | *.pyc 320 | 321 | # Cake - Uncomment if you are using it 322 | # tools/** 323 | # !tools/packages.config 324 | 325 | # Tabs Studio 326 | *.tss 327 | 328 | # Telerik's JustMock configuration file 329 | *.jmconfig 330 | 331 | # BizTalk build output 332 | *.btp.cs 333 | *.btm.cs 334 | *.odx.cs 335 | *.xsd.cs 336 | 337 | # OpenCover UI analysis results 338 | OpenCover/ 339 | 340 | # Azure Stream Analytics local run output 341 | ASALocalRun/ 342 | 343 | # MSBuild Binary and Structured Log 344 | *.binlog 345 | 346 | # NVidia Nsight GPU debugger configuration file 347 | *.nvuser 348 | 349 | # MFractors (Xamarin productivity tool) working folder 350 | .mfractor/ 351 | 352 | # Local History for Visual Studio 353 | .localhistory/ 354 | 355 | # BeatPulse healthcheck temp database 356 | healthchecksdb 357 | 358 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 359 | MigrationBackup/ 360 | 361 | # Ionide (cross platform F# VS Code tools) working folder 362 | .ionide/ 363 | 364 | # Fody - auto-generated XML schema 365 | FodyWeavers.xsd 366 | 367 | ## 368 | ## Visual studio for Mac 369 | ## 370 | 371 | 372 | # globs 373 | Makefile.in 374 | *.userprefs 375 | *.usertasks 376 | config.make 377 | config.status 378 | aclocal.m4 379 | install-sh 380 | autom4te.cache/ 381 | *.tar.gz 382 | tarballs/ 383 | test-results/ 384 | 385 | # Mac bundle stuff 386 | *.dmg 387 | *.app 388 | 389 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 390 | # General 391 | .DS_Store 392 | .AppleDouble 393 | .LSOverride 394 | 395 | # Icon must end with two \r 396 | Icon 397 | 398 | 399 | # Thumbnails 400 | ._* 401 | 402 | # Files that might appear in the root of a volume 403 | .DocumentRevisions-V100 404 | .fseventsd 405 | .Spotlight-V100 406 | .TemporaryItems 407 | .Trashes 408 | .VolumeIcon.icns 409 | .com.apple.timemachine.donotpresent 410 | 411 | # Directories potentially created on remote AFP share 412 | .AppleDB 413 | .AppleDesktop 414 | Network Trash Folder 415 | Temporary Items 416 | .apdisk 417 | 418 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 419 | # Windows thumbnail cache files 420 | Thumbs.db 421 | ehthumbs.db 422 | ehthumbs_vista.db 423 | 424 | # Dump file 425 | *.stackdump 426 | 427 | # Folder config file 428 | [Dd]esktop.ini 429 | 430 | # Recycle Bin used on file shares 431 | $RECYCLE.BIN/ 432 | 433 | # Windows Installer files 434 | *.cab 435 | *.msi 436 | *.msix 437 | *.msm 438 | *.msp 439 | 440 | # Windows shortcuts 441 | *.lnk 442 | 443 | # JetBrains Rider 444 | .idea/ 445 | *.sln.iml 446 | 447 | ## 448 | ## Visual Studio Code 449 | ## 450 | .vscode/* 451 | !.vscode/settings.json 452 | !.vscode/tasks.json 453 | !.vscode/launch.json 454 | !.vscode/extensions.json 455 | 456 | *.live_chat.json* 457 | Properties/launchSettings.json 458 | *.info.json 459 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "overrides": [ 3 | { 4 | "files": ["*.md"], 5 | "options": { 6 | "tabWidth": 2, 7 | "useTabs": false 8 | } 9 | } 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "cooldown", 4 | "youtubelivechattodiscord" 5 | ] 6 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | ### Debug image 2 | ### Setup the same as base image but used dotnet/runtime 3 | FROM mcr.microsoft.com/dotnet/runtime:8.0-alpine AS debug 4 | 5 | WORKDIR /app 6 | RUN apk add --no-cache tzdata python3 && \ 7 | apk add --no-cache --virtual build-deps musl-dev gcc g++ python3-dev py3-pip && \ 8 | python3 -m venv /venv && \ 9 | source /venv/bin/activate && \ 10 | pip install --no-cache-dir yt-dlp && \ 11 | pip uninstall -y setuptools pip && \ 12 | apk del build-deps 13 | 14 | ENV PATH="/venv/bin:$PATH" 15 | ENV TZ=Asia/Taipei 16 | 17 | # Disable file locking on Unix 18 | # https://github.com/dotnet/runtime/issues/34126#issuecomment-1104981659 19 | ENV DOTNET_SYSTEM_IO_DISABLEFILELOCKING=true 20 | 21 | ### Base image for yt-dlp 22 | FROM mcr.microsoft.com/dotnet/runtime-deps:8.0-alpine AS base 23 | WORKDIR /app 24 | RUN apk add --no-cache tzdata python3 && \ 25 | apk add --no-cache --virtual build-deps musl-dev gcc g++ python3-dev py3-pip && \ 26 | python3 -m venv /venv && \ 27 | source /venv/bin/activate && \ 28 | pip install --no-cache-dir yt-dlp && \ 29 | pip uninstall -y setuptools pip && \ 30 | apk del build-deps 31 | 32 | ENV PATH="/venv/bin:$PATH" 33 | ENV TZ=Asia/Taipei 34 | 35 | # Disable file locking on Unix 36 | # https://github.com/dotnet/runtime/issues/34126#issuecomment-1104981659 37 | ENV DOTNET_SYSTEM_IO_DISABLEFILELOCKING=true 38 | 39 | ### Build .NET 40 | FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build 41 | ARG BUILD_CONFIGURATION=Release 42 | ARG TARGETARCH 43 | WORKDIR /src 44 | 45 | COPY ["YoutubeLiveChatToDiscord.csproj", "."] 46 | RUN dotnet restore -a $TARGETARCH "YoutubeLiveChatToDiscord.csproj" 47 | 48 | FROM build AS publish 49 | COPY . . 50 | ARG BUILD_CONFIGURATION=Release 51 | ARG TARGETARCH 52 | RUN dotnet publish "YoutubeLiveChatToDiscord.csproj" -a $TARGETARCH -c $BUILD_CONFIGURATION -o /app/publish --self-contained true 53 | 54 | 55 | ### Final image 56 | FROM base AS final 57 | 58 | ENV PATH="/app:$PATH" 59 | 60 | RUN mkdir -p /app && chown -R $APP_UID:$APP_UID /app && chmod u+rwx /app 61 | COPY --from=publish --chown=$APP_UID:$APP_UID /app/publish/YoutubeLiveChatToDiscord /app/YoutubeLiveChatToDiscord 62 | COPY --from=publish --chown=$APP_UID:$APP_UID /app/publish/appsettings.json /app/appsettings.json 63 | 64 | USER $APP_UID 65 | ENTRYPOINT ["/app/YoutubeLiveChatToDiscord"] -------------------------------------------------------------------------------- /Dockerfile.ubi: -------------------------------------------------------------------------------- 1 | # syntax=docker/dockerfile:1 2 | 3 | ### Python 4 | FROM registry.access.redhat.com/ubi9/ubi-minimal AS python 5 | 6 | ENV PYTHON_VERSION=3.11 7 | ENV PYTHONUNBUFFERED=1 8 | ENV PYTHONIOENCODING=UTF-8 9 | ARG PIP_DISABLE_PIP_VERSION_CHECK=1 10 | ARG PIP_NO_CACHE_DIR=1 11 | 12 | RUN microdnf -y install python3.11 python3.11-pip && \ 13 | microdnf -y clean all 14 | 15 | RUN python3.11 -m venv /venv && \ 16 | source /venv/bin/activate && \ 17 | pip3.11 install --no-cache-dir yt-dlp && \ 18 | pip3.11 uninstall -y setuptools pip && \ 19 | microdnf -y remove python3.11-pip && \ 20 | microdnf -y clean all 21 | 22 | ENV PATH="/venv/bin:$PATH" 23 | 24 | ### Base image 25 | FROM python AS base 26 | 27 | WORKDIR /app 28 | 29 | RUN microdnf -y install libicu tzdata && \ 30 | microdnf -y clean all 31 | 32 | ENV TZ=Asia/Taipei 33 | 34 | # Disable file locking on Unix 35 | # https://github.com/dotnet/runtime/issues/34126#issuecomment-1104981659 36 | ENV DOTNET_SYSTEM_IO_DISABLEFILELOCKING=true 37 | 38 | ### Debug image 39 | FROM base AS debug 40 | 41 | # Install .NET 8 SDK 42 | RUN microdnf -y install dotnet-sdk-8.0 43 | 44 | ### Build .NET 45 | FROM --platform=$BUILDPLATFORM registry.access.redhat.com/ubi8/dotnet-80 AS build 46 | 47 | USER 0 48 | ARG BUILD_CONFIGURATION=Release 49 | ARG TARGETARCH 50 | WORKDIR /src 51 | 52 | COPY ["YoutubeLiveChatToDiscord.csproj", "."] 53 | RUN dotnet restore -a $TARGETARCH "YoutubeLiveChatToDiscord.csproj" 54 | 55 | FROM build AS publish 56 | COPY . . 57 | ARG BUILD_CONFIGURATION=Release 58 | ARG TARGETARCH 59 | RUN dotnet publish "YoutubeLiveChatToDiscord.csproj" -a $TARGETARCH -c $BUILD_CONFIGURATION -o /app/publish --self-contained true 60 | 61 | ### Final image 62 | FROM base AS final 63 | 64 | ENV PATH="/app:$PATH" 65 | 66 | RUN mkdir -p /app && chown -R 1001:1001 /app && chmod u+rwx /app 67 | COPY --from=publish --chown=1001:1001 /app/publish/YoutubeLiveChatToDiscord /app/YoutubeLiveChatToDiscord 68 | COPY --from=publish --chown=1001:1001 /app/publish/appsettings.json /app/appsettings.json 69 | 70 | USER 1001 71 | ENTRYPOINT ["/app/YoutubeLiveChatToDiscord"] -------------------------------------------------------------------------------- /GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 | // This file is used by Code Analysis to maintain SuppressMessage 2 | // attributes that are applied to this project. 3 | // Project-level suppressions either have no target or are given 4 | // a specific target and scoped to a namespace, type, member, etc. 5 | 6 | using System.Diagnostics.CodeAnalysis; 7 | 8 | [assembly: SuppressMessage("Style", "IDE0046:轉換至條件運算式", Justification = "<暫止>", Scope = "member", Target = "~M:YoutubeLiveChatToDiscord.Helper.GetOriginalImage(System.String)~System.String")] 9 | -------------------------------------------------------------------------------- /Helper.cs: -------------------------------------------------------------------------------- 1 | using System.Text.RegularExpressions; 2 | 3 | namespace YoutubeLiveChatToDiscord; 4 | 5 | public static class Helper 6 | { 7 | /// 8 | /// Shared logger 9 | /// 10 | internal static class ApplicationLogging 11 | { 12 | internal static ILoggerFactory LoggerFactory { get; set; } = new LoggerFactory(); 13 | internal static ILogger CreateLogger() => LoggerFactory.CreateLogger(); 14 | internal static ILogger CreateLogger(string categoryName) => LoggerFactory.CreateLogger(categoryName); 15 | } 16 | 17 | private static readonly ILogger _logger = ApplicationLogging.CreateLogger("Helper"); 18 | 19 | /// 20 | /// 尋找yt-dlp程式路徑 21 | /// 22 | /// Full path of yt-dlp 23 | public static string WhereIsYt_dlp() 24 | { 25 | // https://stackoverflow.com/a/63021455 26 | string file = "yt-dlp"; 27 | string[] paths = Environment.GetEnvironmentVariable("PATH")?.Split(';') ?? []; 28 | string[] extensions = Environment.GetEnvironmentVariable("PATHEXT")?.Split(';') ?? []; 29 | string YtdlPath = (from p in new[] { Environment.CurrentDirectory }.Concat(paths) 30 | from e in extensions 31 | let path = Path.Combine(p.Trim(), file + e.ToLower()) 32 | where File.Exists(path) 33 | select path)?.FirstOrDefault() ?? "/venv/bin/yt-dlp"; 34 | _logger.LogDebug("Found yt-dlp at {path}", YtdlPath); 35 | return YtdlPath; 36 | } 37 | 38 | /// 39 | /// 處理Youtube的圖片url,取得原始尺寸圖片 40 | /// 41 | /// 42 | /// original big picture url 43 | public static string GetOriginalImage(string? url) 44 | { 45 | if (string.IsNullOrEmpty(url)) 46 | { 47 | return ""; 48 | } 49 | 50 | string pattern1 = @"^(https?:\/\/lh\d+\.googleusercontent\.com\/.+\/)([^\/]+)(\/[^\/]+(\.(jpg|jpeg|gif|png|bmp|webp))?)(?:\?.+)?$"; 51 | if (Regex.IsMatch(url, pattern1)) 52 | { 53 | GroupCollection matches = Regex.Matches(url, pattern1)[0].Groups; 54 | 55 | return $"{matches[1]}s0{matches[3]}"; 56 | } 57 | 58 | string pattern2 = @"^(https?:\/\/lh\d+\.googleusercontent\.com\/.+=)(.+)(?:\?.+)?$"; 59 | if (Regex.IsMatch(url, pattern2)) 60 | { 61 | return $"{Regex.Matches(url, pattern2)[0].Groups[1]}s0"; 62 | } 63 | 64 | string pattern3 = @"^(https?:\/\/\w+\.ggpht\.com\/.+\/)([^\/]+)(\/[^\/]+(\.(jpg|jpeg|gif|png|bmp|webp))?)(?:\?.+)?$"; 65 | if (Regex.IsMatch(url, pattern3)) 66 | { 67 | return $"{Regex.Matches(url, pattern3)[0].Groups[1]}s0"; 68 | } 69 | 70 | string pattern4 = @"^(https?:\/\/\w+\.ggpht\.com\/.+)=(?:[s|w|h])(\d+)(.+)?$"; 71 | if (Regex.IsMatch(url, pattern4)) 72 | { 73 | return $"{Regex.Matches(url, pattern4)[0].Groups[1]}=s0"; 74 | } 75 | 76 | return url; 77 | } 78 | 79 | public static string YoutubeColorConverter(long color) 80 | { 81 | color &= 16777215; 82 | long[] temp = [(color & 16711680) >> 16, (color & 65280) >> 8, color & 255]; 83 | int r = (int)temp[0]; 84 | int g = (int)temp[1]; 85 | int b = (int)temp[2]; 86 | 87 | if (r != (r & 255) || g != (g & 255) || b != (b & 255)) 88 | throw new Exception($"\"({r},{g},{b})\" is not a valid RGB color"); 89 | 90 | int hex = r << 16 | g << 8 | b; 91 | return r < 16 ? "#" + (16777216 | hex).ToString("X")[1..] : "#" + hex.ToString("X"); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /Json/SourceGenerationContext.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using System.Text.Json.Serialization; 3 | using YoutubeLiveChatToDiscord.Models; 4 | 5 | // Must read: 6 | // https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation?pivots=dotnet-8-0 7 | [JsonSourceGenerationOptions(WriteIndented = true, AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip)] 8 | [JsonSerializable(typeof(Info.info))] 9 | [JsonSerializable(typeof(Chat.chat))] 10 | [JsonSerializable(typeof(Info.Thumbnail), TypeInfoPropertyName = "InfoThumbnail")] 11 | [JsonSerializable(typeof(Chat.Thumbnail), TypeInfoPropertyName = "ChatThumbnail")] 12 | [JsonSerializable(typeof(List), TypeInfoPropertyName = "ChatThumbnailList")] 13 | [JsonSerializable(typeof(List), TypeInfoPropertyName = "InfoThumbnailList")] 14 | internal partial class SourceGenerationContext : JsonSerializerContext { } 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /LiveChatMonitorWorker.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | using System.Text.Json; 3 | using YoutubeLiveChatToDiscord.Services; 4 | using Chat = YoutubeLiveChatToDiscord.Models.Chat.chat; 5 | using Info = YoutubeLiveChatToDiscord.Models.Info.info; 6 | 7 | namespace YoutubeLiveChatToDiscord; 8 | 9 | public class LiveChatMonitorWorker : BackgroundService 10 | { 11 | private readonly ILogger _logger; 12 | private readonly string _id; 13 | private readonly FileInfo _liveChatFileInfo; 14 | private long _position = 0; 15 | private readonly LiveChatDownloadService _liveChatDownloadService; 16 | private readonly DiscordService _discordService; 17 | 18 | public LiveChatMonitorWorker( 19 | ILogger logger, 20 | LiveChatDownloadService liveChatDownloadService, 21 | DiscordService discordService 22 | ) 23 | { 24 | (_logger, _liveChatDownloadService, _discordService) = (logger, liveChatDownloadService, discordService); 25 | 26 | _id = Environment.GetEnvironmentVariable("VIDEO_ID") ?? ""; 27 | if (string.IsNullOrEmpty(_id)) throw new ArgumentException(nameof(_id)); 28 | 29 | _liveChatFileInfo = new($"{_id}.live_chat.json"); 30 | } 31 | 32 | protected override async Task ExecuteAsync(CancellationToken stoppingToken) 33 | { 34 | try 35 | { 36 | while (!stoppingToken.IsCancellationRequested) 37 | { 38 | if (_liveChatDownloadService.downloadProcess.IsCompleted) 39 | { 40 | _ = _liveChatDownloadService.ExecuteAsync(stoppingToken) 41 | .ContinueWith((_) => _logger.LogInformation("yt-dlp is stopped."), stoppingToken); 42 | } 43 | 44 | _logger.LogInformation("Wait 10 seconds."); 45 | await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); 46 | _liveChatFileInfo.Refresh(); 47 | 48 | try 49 | { 50 | if (!_liveChatFileInfo.Exists) 51 | { 52 | throw new FileNotFoundException(null, _liveChatFileInfo.FullName); 53 | } 54 | 55 | await Monitoring(stoppingToken); 56 | } 57 | catch (FileNotFoundException e) 58 | { 59 | _logger.LogWarning("Json file not found. {FileName}", e.FileName); 60 | } 61 | } 62 | } 63 | catch (TaskCanceledException) { } 64 | finally 65 | { 66 | _logger.LogError("Wait 10 seconds before closing the program. This is to prevent a restart loop from hanging the machine."); 67 | #pragma warning disable CA2016 // 將 'CancellationToken' 參數轉送給方法 68 | await Task.Delay(TimeSpan.FromSeconds(10)); 69 | #pragma warning restore CA2016 // 將 'CancellationToken' 參數轉送給方法 70 | } 71 | } 72 | 73 | /// 74 | /// Monitoring 75 | /// 76 | /// 77 | /// 78 | /// 79 | private async Task Monitoring(CancellationToken stoppingToken) 80 | { 81 | await GetVideoInfo(stoppingToken); 82 | 83 | #if !DEBUG 84 | if (null == Environment.GetEnvironmentVariable("SKIP_STARTUP_WAITING")) 85 | { 86 | _logger.LogInformation("Wait 1 miunute to skip old chats"); 87 | await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); 88 | _liveChatFileInfo.Refresh(); 89 | } 90 | #endif 91 | 92 | _position = _liveChatFileInfo.Length; 93 | _logger.LogInformation("Start at position: {position}", _position); 94 | _logger.LogInformation("Start Monitoring!"); 95 | 96 | while (!stoppingToken.IsCancellationRequested) 97 | { 98 | _liveChatFileInfo.Refresh(); 99 | if (_liveChatFileInfo.Length > _position) 100 | { 101 | await ProcessChats(stoppingToken); 102 | } 103 | else if (_liveChatDownloadService.downloadProcess.IsCompleted) 104 | { 105 | _logger.LogInformation("Download process is stopped. Restart monitoring."); 106 | return; 107 | } 108 | else 109 | { 110 | _position = _liveChatFileInfo.Length; 111 | _logger.LogTrace("No new chat. Wait 10 seconds."); 112 | // 每10秒檢查一次json檔 113 | await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); 114 | } 115 | } 116 | } 117 | 118 | /// 119 | /// GetVideoInfo 120 | /// 121 | /// 122 | /// 123 | /// 124 | [UnconditionalSuppressMessage( 125 | "Trimming", 126 | "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", 127 | Justification = $"{nameof(SourceGenerationContext)} is used.")] 128 | private async Task GetVideoInfo(CancellationToken stoppingToken) 129 | { 130 | FileInfo videoInfo = new($"{_id}.info.json"); 131 | if (!videoInfo.Exists) 132 | { 133 | // Chat json file 在 VideoInfo json file之後被產生,理論上這段不會進來 134 | throw new FileNotFoundException(null, videoInfo.FullName); 135 | } 136 | 137 | Info? info = JsonSerializer.Deserialize(json: await new StreamReader(videoInfo.OpenRead()).ReadToEndAsync(stoppingToken), 138 | jsonTypeInfo: SourceGenerationContext.Default.info); 139 | string? Title = info?.title; 140 | string? ChannelId = info?.channel_id; 141 | string? thumb = info?.thumbnail; 142 | 143 | Environment.SetEnvironmentVariable("TITLE", Title); 144 | Environment.SetEnvironmentVariable("CHANNEL_ID", ChannelId); 145 | Environment.SetEnvironmentVariable("VIDEO_THUMB", thumb); 146 | } 147 | 148 | [UnconditionalSuppressMessage( 149 | "Trimming", 150 | "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", 151 | Justification = $"{nameof(SourceGenerationContext)} is used.")] 152 | private async Task ProcessChats(CancellationToken stoppingToken) 153 | { 154 | // Notice: yt-dlp在Linux會使用lock鎖定此檔案,在Windows不鎖定。 155 | // 實作: https://github.com/yt-dlp/yt-dlp/commit/897376719871279eef89426b1452abb89051f0dc 156 | // Issue: https://github.com/yt-dlp/yt-dlp/issues/3124 157 | // 不像Windows是獨占鎖,Linux上是諮詢鎖,程式可以自行決定是否遵守鎖定。 158 | // FileStream「會」遵守鎖定,所以此處會在開啟檔案時報錯。 159 | // 詳細說明請參考這個issue,其中的討論過程非常清楚: https://github.com/dotnet/runtime/issues/34126 160 | // 這是.NET Core在Linux、Windows上關於鎖定設計的描述: https://github.com/dotnet/runtime/pull/55256 161 | // 如果要繞過這個問題,從.NET 6開始,可以加上環境變數「DOTNET_SYSTEM_IO_DISABLEFILELOCKING」讓FileStream「不」遵守鎖定。 162 | // (本專案已在Dockerfile加上此環境變數) 163 | using FileStream fs = new(_liveChatFileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 164 | using StreamReader sr = new(fs); 165 | 166 | sr.BaseStream.Seek(_position, SeekOrigin.Begin); 167 | while (_position < sr.BaseStream.Length) 168 | { 169 | string? str = ""; 170 | try 171 | { 172 | str = await sr.ReadLineAsync(stoppingToken); 173 | _position = sr.BaseStream.Position; 174 | if (string.IsNullOrEmpty(str)) continue; 175 | 176 | Chat? chat = JsonSerializer.Deserialize(json: str, 177 | jsonTypeInfo: SourceGenerationContext.Default.chat); 178 | if (null == chat) continue; 179 | 180 | await _discordService.BuildRequestAndSendToDiscord(chat, stoppingToken); 181 | } 182 | catch (JsonException e) 183 | { 184 | _logger.LogError("{error}", e.Message); 185 | _logger.LogError("{originalString}", str); 186 | } 187 | catch (ArgumentException e) 188 | { 189 | _logger.LogError("{error}", e.Message); 190 | _logger.LogError("{originalString}", str); 191 | } 192 | catch (IOException e) 193 | { 194 | _logger.LogError("{error}", e.Message); 195 | break; 196 | } 197 | } 198 | } 199 | } -------------------------------------------------------------------------------- /Models/Chat.cs: -------------------------------------------------------------------------------- 1 | #pragma warning disable IDE1006 // 命名樣式 2 | #nullable disable 3 | 4 | namespace YoutubeLiveChatToDiscord.Models; 5 | 6 | public class Chat 7 | { 8 | public class ContextMenuButton 9 | { 10 | public ButtonRenderer buttonRenderer { get; set; } 11 | } 12 | 13 | public class Icon 14 | { 15 | public string iconType { get; set; } 16 | } 17 | 18 | public class LiveChatBannerHeaderRenderer 19 | { 20 | public Icon icon { get; set; } 21 | public Text text { get; set; } 22 | public ContextMenuButton contextMenuButton { get; set; } 23 | } 24 | 25 | public class Header 26 | { 27 | public LiveChatBannerHeaderRenderer liveChatBannerHeaderRenderer { get; set; } 28 | public LiveChatSponsorshipsHeaderRenderer liveChatSponsorshipsHeaderRenderer { get; set; } 29 | public PollHeaderRenderer pollHeaderRenderer { get; set; } 30 | } 31 | 32 | public class AccessibilityData 33 | { 34 | public string label { get; set; } 35 | public AccessibilityData accessibilityData { get; set; } 36 | } 37 | 38 | public class Accessibility 39 | { 40 | public string label { get; set; } 41 | public AccessibilityData accessibilityData { get; set; } 42 | } 43 | 44 | public class Image 45 | { 46 | public List thumbnails { get; set; } 47 | public Accessibility accessibility { get; set; } 48 | public List sources { get; set; } 49 | } 50 | 51 | public class Emoji 52 | { 53 | public string emojiId { get; set; } 54 | public List shortcuts { get; set; } 55 | public List searchTerms { get; set; } 56 | public Image image { get; set; } 57 | public bool isCustomEmoji { get; set; } 58 | public bool supportsSkinTone { get; set; } 59 | public List variantIds { get; set; } 60 | } 61 | 62 | public class Run 63 | { 64 | public Emoji emoji { get; set; } 65 | public string text { get; set; } 66 | public bool bold { get; set; } 67 | public bool italics { get; set; } 68 | } 69 | 70 | public class Message 71 | { 72 | public List runs { get; set; } 73 | } 74 | 75 | public class HeaderPrimaryText 76 | { 77 | public List runs { get; set; } 78 | } 79 | 80 | public class HeaderSubtext 81 | { 82 | public List runs { get; set; } 83 | } 84 | 85 | public class AuthorName 86 | { 87 | public string simpleText { get; set; } 88 | } 89 | 90 | public class AuthorPhoto 91 | { 92 | public List thumbnails { get; set; } 93 | public Accessibility accessibility { get; set; } 94 | } 95 | 96 | public class WebCommandMetadata 97 | { 98 | public bool ignoreNavigation { get; set; } 99 | public string url { get; set; } 100 | public string webPageType { get; set; } 101 | public int rootVe { get; set; } 102 | public string apiUrl { get; set; } 103 | public bool sendPost { get; set; } 104 | } 105 | 106 | public class CommandMetadata 107 | { 108 | public WebCommandMetadata webCommandMetadata { get; set; } 109 | } 110 | 111 | public class LiveChatItemContextMenuEndpoint 112 | { 113 | public string @params { get; set; } 114 | } 115 | 116 | public class ContextMenuEndpoint 117 | { 118 | public string clickTrackingParams { get; set; } 119 | public CommandMetadata commandMetadata { get; set; } 120 | public LiveChatItemContextMenuEndpoint liveChatItemContextMenuEndpoint { get; set; } 121 | } 122 | 123 | public class CustomThumbnail 124 | { 125 | public List thumbnails { get; set; } 126 | } 127 | 128 | public class LiveChatAuthorBadgeRenderer 129 | { 130 | public CustomThumbnail customThumbnail { get; set; } 131 | public string tooltip { get; set; } 132 | public Accessibility accessibility { get; set; } 133 | public Icon icon { get; set; } 134 | } 135 | 136 | public class AuthorBadge 137 | { 138 | public LiveChatAuthorBadgeRenderer liveChatAuthorBadgeRenderer { get; set; } 139 | } 140 | 141 | public class ContextMenuAccessibility 142 | { 143 | public AccessibilityData accessibilityData { get; set; } 144 | } 145 | 146 | public class LiveChatTextMessageRenderer 147 | { 148 | public Message message { get; set; } 149 | public AuthorName authorName { get; set; } 150 | public AuthorPhoto authorPhoto { get; set; } 151 | public ContextMenuEndpoint contextMenuEndpoint { get; set; } 152 | public string id { get; set; } 153 | public string timestampUsec { get; set; } 154 | public List authorBadges { get; set; } 155 | public string authorExternalChannelId { get; set; } 156 | public ContextMenuAccessibility contextMenuAccessibility { get; set; } 157 | } 158 | 159 | public class PurchaseAmountText 160 | { 161 | public string simpleText { get; set; } 162 | } 163 | 164 | public class LiveChatPaidMessageRenderer 165 | { 166 | public string id { get; set; } 167 | public string timestampUsec { get; set; } 168 | public AuthorName authorName { get; set; } 169 | public AuthorPhoto authorPhoto { get; set; } 170 | public PurchaseAmountText purchaseAmountText { get; set; } 171 | public Message message { get; set; } 172 | public long headerBackgroundColor { get; set; } 173 | public long headerTextColor { get; set; } 174 | public long bodyBackgroundColor { get; set; } 175 | public long bodyTextColor { get; set; } 176 | public string authorExternalChannelId { get; set; } 177 | public long authorNameTextColor { get; set; } 178 | public ContextMenuEndpoint contextMenuEndpoint { get; set; } 179 | public long timestampColor { get; set; } 180 | public ContextMenuAccessibility contextMenuAccessibility { get; set; } 181 | public string trackingParams { get; set; } 182 | public HeaderOverlayImage headerOverlayImage { get; set; } 183 | public int textInputBackgroundColor { get; set; } 184 | public LowerBumper lowerBumper { get; set; } 185 | public CreatorHeartButton creatorHeartButton { get; set; } 186 | public bool isV2Style { get; set; } 187 | public PdgPurchasedNoveltyLoggingDirectives pdgPurchasedNoveltyLoggingDirectives { get; set; } 188 | } 189 | 190 | public class Text 191 | { 192 | public string simpleText { get; set; } 193 | public List runs { get; set; } 194 | public string content { get; set; } 195 | public List styleRuns { get; set; } 196 | } 197 | 198 | public class UrlEndpoint 199 | { 200 | public string url { get; set; } 201 | public string target { get; set; } 202 | public bool nofollow { get; set; } 203 | } 204 | 205 | public class NavigationEndpoint 206 | { 207 | public string clickTrackingParams { get; set; } 208 | public CommandMetadata commandMetadata { get; set; } 209 | public UrlEndpoint urlEndpoint { get; set; } 210 | } 211 | 212 | public class Command 213 | { 214 | public string clickTrackingParams { get; set; } 215 | public CommandMetadata commandMetadata { get; set; } 216 | public LiveChatItemContextMenuEndpoint liveChatItemContextMenuEndpoint { get; set; } 217 | } 218 | 219 | public class ButtonRenderer 220 | { 221 | public string style { get; set; } 222 | public string size { get; set; } 223 | public bool isDisabled { get; set; } 224 | public Text text { get; set; } 225 | public NavigationEndpoint navigationEndpoint { get; set; } 226 | public string trackingParams { get; set; } 227 | public AccessibilityData accessibilityData { get; set; } 228 | public Icon icon { get; set; } 229 | public Command command { get; set; } 230 | public Accessibility accessibility { get; set; } 231 | public string targetId { get; set; } 232 | } 233 | 234 | public class ActionButton 235 | { 236 | public ButtonRenderer buttonRenderer { get; set; } 237 | } 238 | 239 | public class LiveChatViewerEngagementMessageRenderer 240 | { 241 | public string id { get; set; } 242 | public string timestampUsec { get; set; } 243 | public Icon icon { get; set; } 244 | public Message message { get; set; } 245 | public ActionButton actionButton { get; set; } 246 | } 247 | 248 | public class Sticker 249 | { 250 | public List thumbnails { get; set; } 251 | public Accessibility accessibility { get; set; } 252 | } 253 | 254 | public class LiveChatPaidStickerRenderer 255 | { 256 | public string id { get; set; } 257 | public ContextMenuEndpoint contextMenuEndpoint { get; set; } 258 | public ContextMenuAccessibility contextMenuAccessibility { get; set; } 259 | public string timestampUsec { get; set; } 260 | public AuthorPhoto authorPhoto { get; set; } 261 | public AuthorName authorName { get; set; } 262 | public string authorExternalChannelId { get; set; } 263 | public Sticker sticker { get; set; } 264 | public long moneyChipBackgroundColor { get; set; } 265 | public long moneyChipTextColor { get; set; } 266 | public PurchaseAmountText purchaseAmountText { get; set; } 267 | public int stickerDisplayWidth { get; set; } 268 | public int stickerDisplayHeight { get; set; } 269 | public long backgroundColor { get; set; } 270 | public long authorNameTextColor { get; set; } 271 | public string trackingParams { get; set; } 272 | // Actually I doesn't find the 1st purchase sticker. These properties are copied from the LiveChatPaidMessageRenderer 273 | public HeaderOverlayImage headerOverlayImage { get; set; } 274 | public int textInputBackgroundColor { get; set; } 275 | public LowerBumper lowerBumper { get; set; } 276 | public CreatorHeartButton creatorHeartButton { get; set; } 277 | public bool isV2Style { get; set; } 278 | public PdgPurchasedNoveltyLoggingDirectives pdgPurchasedNoveltyLoggingDirectives { get; set; } 279 | } 280 | 281 | public class LiveChatMembershipItemRenderer 282 | { 283 | public string id { get; set; } 284 | public string timestampUsec { get; set; } 285 | public string authorExternalChannelId { get; set; } 286 | public HeaderPrimaryText headerPrimaryText { get; set; } 287 | public HeaderSubtext headerSubtext { get; set; } 288 | public Message message { get; set; } 289 | public AuthorName authorName { get; set; } 290 | public AuthorPhoto authorPhoto { get; set; } 291 | public List authorBadges { get; set; } 292 | public ContextMenuEndpoint contextMenuEndpoint { get; set; } 293 | public ContextMenuAccessibility contextMenuAccessibility { get; set; } 294 | public string trackingParams { get; set; } 295 | } 296 | 297 | public class Item 298 | { 299 | public LiveChatTextMessageRenderer liveChatTextMessageRenderer { get; set; } 300 | public LiveChatPaidMessageRenderer liveChatPaidMessageRenderer { get; set; } 301 | public LiveChatViewerEngagementMessageRenderer liveChatViewerEngagementMessageRenderer { get; set; } 302 | public LiveChatPaidStickerRenderer liveChatPaidStickerRenderer { get; set; } 303 | public LiveChatTickerPaidMessageItemRenderer liveChatTickerPaidMessageItemRenderer { get; set; } 304 | public LiveChatMembershipItemRenderer liveChatMembershipItemRenderer { get; set; } 305 | public LiveChatModeChangeMessageRenderer liveChatModeChangeMessageRenderer { get; set; } 306 | public LiveChatSponsorshipsGiftPurchaseAnnouncementRenderer liveChatSponsorshipsGiftPurchaseAnnouncementRenderer { get; set; } 307 | public LiveChatSponsorshipsGiftRedemptionAnnouncementRenderer liveChatSponsorshipsGiftRedemptionAnnouncementRenderer { get; set; } 308 | public LiveChatPlaceholderItemRenderer liveChatPlaceholderItemRenderer { get; set; } 309 | } 310 | 311 | public class AddChatItemAction 312 | { 313 | public Item item { get; set; } 314 | public string clientId { get; set; } 315 | } 316 | 317 | public class DeletedStateMessage 318 | { 319 | public List runs { get; set; } 320 | } 321 | 322 | public class MarkChatItemAsDeletedAction 323 | { 324 | public DeletedStateMessage deletedStateMessage { get; set; } 325 | public string targetItemId { get; set; } 326 | } 327 | 328 | public class Amount 329 | { 330 | public string simpleText { get; set; } 331 | } 332 | 333 | public class Renderer 334 | { 335 | public LiveChatPaidMessageRenderer liveChatPaidMessageRenderer { get; set; } 336 | } 337 | 338 | public class ShowLiveChatItemEndpoint 339 | { 340 | public Renderer renderer { get; set; } 341 | public string trackingParams { get; set; } 342 | } 343 | 344 | public class ShowItemEndpoint 345 | { 346 | public string clickTrackingParams { get; set; } 347 | public CommandMetadata commandMetadata { get; set; } 348 | public ShowLiveChatItemEndpoint showLiveChatItemEndpoint { get; set; } 349 | } 350 | 351 | public class LiveChatTickerPaidMessageItemRenderer 352 | { 353 | public string id { get; set; } 354 | public Amount amount { get; set; } 355 | public long amountTextColor { get; set; } 356 | public long startBackgroundColor { get; set; } 357 | public long endBackgroundColor { get; set; } 358 | public AuthorPhoto authorPhoto { get; set; } 359 | public int durationSec { get; set; } 360 | public ShowItemEndpoint showItemEndpoint { get; set; } 361 | public string authorExternalChannelId { get; set; } 362 | public int fullDurationSec { get; set; } 363 | public string trackingParams { get; set; } 364 | } 365 | 366 | public class AddLiveChatTickerItemAction 367 | { 368 | public Item item { get; set; } 369 | public string durationSec { get; set; } 370 | } 371 | 372 | public class UiActions 373 | { 374 | public bool hideEnclosingContainer { get; set; } 375 | } 376 | 377 | public class FeedbackEndpoint 378 | { 379 | public string feedbackToken { get; set; } 380 | public UiActions uiActions { get; set; } 381 | } 382 | 383 | public class ImpressionEndpoint 384 | { 385 | public string clickTrackingParams { get; set; } 386 | public CommandMetadata commandMetadata { get; set; } 387 | public FeedbackEndpoint feedbackEndpoint { get; set; } 388 | } 389 | 390 | public class AcceptCommand 391 | { 392 | public string clickTrackingParams { get; set; } 393 | public CommandMetadata commandMetadata { get; set; } 394 | public FeedbackEndpoint feedbackEndpoint { get; set; } 395 | } 396 | 397 | public class DismissCommand 398 | { 399 | public string clickTrackingParams { get; set; } 400 | public CommandMetadata commandMetadata { get; set; } 401 | public FeedbackEndpoint feedbackEndpoint { get; set; } 402 | } 403 | 404 | public class PromoConfig 405 | { 406 | public string promoId { get; set; } 407 | public List impressionEndpoints { get; set; } 408 | public AcceptCommand acceptCommand { get; set; } 409 | public DismissCommand dismissCommand { get; set; } 410 | } 411 | 412 | public class DetailsText 413 | { 414 | public List runs { get; set; } 415 | } 416 | 417 | public class SuggestedPosition 418 | { 419 | public string type { get; set; } 420 | } 421 | 422 | public class DismissStrategy 423 | { 424 | public string type { get; set; } 425 | } 426 | 427 | public class TooltipRenderer 428 | { 429 | public PromoConfig promoConfig { get; set; } 430 | public string targetId { get; set; } 431 | public DetailsText detailsText { get; set; } 432 | public SuggestedPosition suggestedPosition { get; set; } 433 | public DismissStrategy dismissStrategy { get; set; } 434 | public string dwellTimeMs { get; set; } 435 | public string trackingParams { get; set; } 436 | } 437 | 438 | public class Tooltip 439 | { 440 | public TooltipRenderer tooltipRenderer { get; set; } 441 | } 442 | 443 | public class ShowLiveChatTooltipCommand 444 | { 445 | public Tooltip tooltip { get; set; } 446 | } 447 | 448 | public class Contents 449 | { 450 | public LiveChatTextMessageRenderer liveChatTextMessageRenderer { get; set; } 451 | public PollRenderer pollRenderer { get; set; } 452 | } 453 | 454 | public class LiveChatBannerRenderer 455 | { 456 | public Header header { get; set; } 457 | public Contents contents { get; set; } 458 | public string actionId { get; set; } 459 | public bool viewerIsCreator { get; set; } 460 | public string targetId { get; set; } 461 | public bool isStackable { get; set; } 462 | public string backgroundType { get; set; } 463 | } 464 | 465 | public class BannerRenderer 466 | { 467 | public LiveChatBannerRenderer liveChatBannerRenderer { get; set; } 468 | } 469 | 470 | public class AddBannerToLiveChatCommand 471 | { 472 | public BannerRenderer bannerRenderer { get; set; } 473 | } 474 | 475 | public class RemoveBannerForLiveChatCommand 476 | { 477 | public string targetActionId { get; set; } 478 | } 479 | 480 | public class UpdateLiveChatPollAction 481 | { 482 | public PollToUpdate pollToUpdate { get; set; } 483 | } 484 | 485 | public class CloseLiveChatActionPanelAction 486 | { 487 | public string targetPanelId { get; set; } 488 | public bool skipOnDismissCommand { get; set; } 489 | } 490 | 491 | public class Action 492 | { 493 | public string clickTrackingParams { get; set; } 494 | public AddChatItemAction addChatItemAction { get; set; } 495 | public MarkChatItemAsDeletedAction markChatItemAsDeletedAction { get; set; } 496 | public AddLiveChatTickerItemAction addLiveChatTickerItemAction { get; set; } 497 | public ShowLiveChatTooltipCommand showLiveChatTooltipCommand { get; set; } 498 | public AddBannerToLiveChatCommand addBannerToLiveChatCommand { get; set; } 499 | public ReplaceChatItemAction replaceChatItemAction { get; set; } 500 | public RemoveChatItemAction removeChatItemAction { get; set; } 501 | public RemoveBannerForLiveChatCommand removeBannerForLiveChatCommand { get; set; } 502 | public UpdateLiveChatPollAction updateLiveChatPollAction { get; set; } 503 | public CloseLiveChatActionPanelAction closeLiveChatActionPanelAction { get; set; } 504 | public ShowLiveChatActionPanelAction showLiveChatActionPanelAction { get; set; } 505 | } 506 | 507 | public class RemoveChatItemAction 508 | { 509 | public string targetItemId { get; set; } 510 | } 511 | 512 | public class ReplayChatItemAction 513 | { 514 | public List actions { get; set; } 515 | public string videoOffsetTimeMsec { get; set; } 516 | } 517 | 518 | #pragma warning disable CS8981 // 類型名稱只包含小寫的 ASCII 字元。此類名稱可能保留供此語言使用。 519 | public class chat 520 | #pragma warning restore CS8981 // 類型名稱只包含小寫的 ASCII 字元。此類名稱可能保留供此語言使用。 521 | { 522 | public ReplayChatItemAction replayChatItemAction { get; set; } 523 | public string clickTrackingParams { get; set; } 524 | public string videoOffsetTimeMsec { get; set; } 525 | public bool isLive { get; set; } 526 | } 527 | 528 | public class LiveChatModeChangeMessageRenderer 529 | { 530 | public string id { get; set; } 531 | public string timestampUsec { get; set; } 532 | public Icon icon { get; set; } 533 | public Text text { get; set; } 534 | public Subtext subtext { get; set; } 535 | } 536 | 537 | public class Subtext 538 | { 539 | public List runs { get; set; } 540 | } 541 | 542 | public class ReplaceChatItemAction 543 | { 544 | public string targetItemId { get; set; } 545 | public ReplacementItem replacementItem { get; set; } 546 | } 547 | 548 | public class ReplacementItem 549 | { 550 | public LiveChatTextMessageRenderer liveChatTextMessageRenderer { get; set; } 551 | } 552 | 553 | public class Choice 554 | { 555 | public Text text { get; set; } 556 | public bool selected { get; set; } 557 | public double voteRatio { get; set; } 558 | public VotePercentage votePercentage { get; set; } 559 | public SelectServiceEndpoint selectServiceEndpoint { get; set; } 560 | } 561 | 562 | public class MetadataText 563 | { 564 | public List runs { get; set; } 565 | } 566 | 567 | public class PollHeaderRenderer 568 | { 569 | public PollQuestion pollQuestion { get; set; } 570 | public Thumbnail thumbnail { get; set; } 571 | public MetadataText metadataText { get; set; } 572 | public string liveChatPollType { get; set; } 573 | public ContextMenuButton contextMenuButton { get; set; } 574 | } 575 | 576 | public class PollQuestion 577 | { 578 | public List runs { get; set; } 579 | } 580 | 581 | public class PollRenderer 582 | { 583 | public List choices { get; set; } 584 | public string liveChatPollId { get; set; } 585 | public Header header { get; set; } 586 | public string trackingParams { get; set; } 587 | } 588 | 589 | public class PollToUpdate 590 | { 591 | public PollRenderer pollRenderer { get; set; } 592 | } 593 | 594 | public class SelectServiceEndpoint 595 | { 596 | public string clickTrackingParams { get; set; } 597 | public CommandMetadata commandMetadata { get; set; } 598 | public SendLiveChatVoteEndpoint sendLiveChatVoteEndpoint { get; set; } 599 | } 600 | 601 | public class SendLiveChatVoteEndpoint 602 | { 603 | public string @params { get; set; } 604 | } 605 | 606 | public class VotePercentage 607 | { 608 | public string simpleText { get; set; } 609 | } 610 | 611 | public class LiveChatActionPanelRenderer 612 | { 613 | public Contents contents { get; set; } 614 | public string id { get; set; } 615 | public string targetId { get; set; } 616 | } 617 | 618 | public class PanelToShow 619 | { 620 | public LiveChatActionPanelRenderer liveChatActionPanelRenderer { get; set; } 621 | } 622 | 623 | public class ShowLiveChatActionPanelAction 624 | { 625 | public PanelToShow panelToShow { get; set; } 626 | } 627 | 628 | public class LiveChatSponsorshipsGiftPurchaseAnnouncementRenderer 629 | { 630 | public string id { get; set; } 631 | public string timestampUsec { get; set; } 632 | public string authorExternalChannelId { get; set; } 633 | public Header header { get; set; } 634 | } 635 | 636 | public class LiveChatSponsorshipsGiftRedemptionAnnouncementRenderer 637 | { 638 | public string id { get; set; } 639 | public string timestampUsec { get; set; } 640 | public string authorExternalChannelId { get; set; } 641 | public AuthorName authorName { get; set; } 642 | public AuthorPhoto authorPhoto { get; set; } 643 | public Message message { get; set; } 644 | public ContextMenuEndpoint contextMenuEndpoint { get; set; } 645 | public ContextMenuAccessibility contextMenuAccessibility { get; set; } 646 | public string trackingParams { get; set; } 647 | } 648 | 649 | public class LiveChatSponsorshipsHeaderRenderer 650 | { 651 | public AuthorName authorName { get; set; } 652 | public AuthorPhoto authorPhoto { get; set; } 653 | public PrimaryText primaryText { get; set; } 654 | public List authorBadges { get; set; } 655 | public ContextMenuEndpoint contextMenuEndpoint { get; set; } 656 | public ContextMenuAccessibility contextMenuAccessibility { get; set; } 657 | public Image image { get; set; } 658 | } 659 | 660 | public class PrimaryText 661 | { 662 | public List runs { get; set; } 663 | } 664 | 665 | public class LiveChatPlaceholderItemRenderer 666 | { 667 | public string id { get; set; } 668 | public string timestampUsec { get; set; } 669 | } 670 | 671 | public class Thumbnail 672 | { 673 | public string url { get; set; } 674 | public int preference { get; set; } 675 | public string id { get; set; } 676 | public int height { get; set; } 677 | public int width { get; set; } 678 | public string resolution { get; set; } 679 | } 680 | 681 | public class BorderImageProcessor 682 | { 683 | public ImageTint imageTint { get; set; } 684 | } 685 | 686 | public class BumperUserEduContentViewModel 687 | { 688 | public Text text { get; set; } 689 | public string trackingParams { get; set; } 690 | public Image image { get; set; } 691 | } 692 | 693 | public class ClientResource 694 | { 695 | public string imageName { get; set; } 696 | public long imageColor { get; set; } 697 | } 698 | 699 | public class Content 700 | { 701 | public BumperUserEduContentViewModel bumperUserEduContentViewModel { get; set; } 702 | } 703 | 704 | public class CreatorHeartButton 705 | { 706 | public CreatorHeartViewModel creatorHeartViewModel { get; set; } 707 | } 708 | 709 | public class CreatorHeartViewModel 710 | { 711 | public CreatorThumbnail creatorThumbnail { get; set; } 712 | public HeartedIcon heartedIcon { get; set; } 713 | public UnheartedIcon unheartedIcon { get; set; } 714 | public string heartedHoverText { get; set; } 715 | public string heartedAccessibilityLabel { get; set; } 716 | public string unheartedAccessibilityLabel { get; set; } 717 | public string engagementStateKey { get; set; } 718 | public Gradient gradient { get; set; } 719 | public LoggingDirectives loggingDirectives { get; set; } 720 | } 721 | 722 | public class CreatorThumbnail 723 | { 724 | public List sources { get; set; } 725 | } 726 | 727 | public class Gradient 728 | { 729 | public List sources { get; set; } 730 | public Processor processor { get; set; } 731 | } 732 | 733 | public class HeaderOverlayImage 734 | { 735 | public List thumbnails { get; set; } 736 | } 737 | 738 | public class HeartedIcon 739 | { 740 | public List sources { get; set; } 741 | } 742 | 743 | public class ImageTint 744 | { 745 | public long color { get; set; } 746 | } 747 | 748 | public class LiveChatItemBumperViewModel 749 | { 750 | public Content content { get; set; } 751 | public PdgPurchasedBumperLoggingDirectives pdgPurchasedBumperLoggingDirectives { get; set; } 752 | } 753 | 754 | public class LoggingDirectives 755 | { 756 | public string trackingParams { get; set; } 757 | public Visibility visibility { get; set; } 758 | public bool enableDisplayloggerExperiment { get; set; } 759 | } 760 | 761 | public class LowerBumper 762 | { 763 | public LiveChatItemBumperViewModel liveChatItemBumperViewModel { get; set; } 764 | } 765 | 766 | public class PdgPurchasedBumperLoggingDirectives 767 | { 768 | public LoggingDirectives loggingDirectives { get; set; } 769 | } 770 | 771 | public class PdgPurchasedNoveltyLoggingDirectives 772 | { 773 | public LoggingDirectives loggingDirectives { get; set; } 774 | } 775 | 776 | public class Processor 777 | { 778 | public BorderImageProcessor borderImageProcessor { get; set; } 779 | } 780 | 781 | public class Source 782 | { 783 | public ClientResource clientResource { get; set; } 784 | public string url { get; set; } 785 | } 786 | 787 | public class StyleRun 788 | { 789 | public int startIndex { get; set; } 790 | public int length { get; set; } 791 | } 792 | 793 | public class TimestampText 794 | { 795 | public string simpleText { get; set; } 796 | } 797 | 798 | public class UnheartedIcon 799 | { 800 | public List sources { get; set; } 801 | public Processor processor { get; set; } 802 | } 803 | 804 | public class Visibility 805 | { 806 | public string types { get; set; } 807 | } 808 | } 809 | -------------------------------------------------------------------------------- /Models/Info.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | #pragma warning disable IDE1006 // 命名樣式 3 | 4 | namespace YoutubeLiveChatToDiscord.Models; 5 | 6 | public class Info 7 | { 8 | public class HttpHeaders 9 | { 10 | [JsonPropertyName("User-Agent")] 11 | public string? UserAgent { get; set; } 12 | public string? Accept { get; set; } 13 | 14 | [JsonPropertyName("Accept-Encoding")] 15 | public string? AcceptEncoding { get; set; } 16 | 17 | [JsonPropertyName("Accept-Language")] 18 | public string? AcceptLanguage { get; set; } 19 | 20 | [JsonPropertyName("Sec-Fetch-Mode")] 21 | public string? SecFetchMode { get; set; } 22 | } 23 | 24 | public class Fragment 25 | { 26 | public string? path { get; set; } 27 | public double duration { get; set; } 28 | } 29 | 30 | public class DownloaderOptions 31 | { 32 | public int http_chunk_size { get; set; } 33 | } 34 | 35 | public class Format 36 | { 37 | public string? format_id { get; set; } 38 | public string? url { get; set; } 39 | public string? manifest_url { get; set; } 40 | public double tbr { get; set; } 41 | public string? ext { get; set; } 42 | public double fps { get; set; } 43 | public string? protocol { get; set; } 44 | public int quality { get; set; } 45 | public int width { get; set; } 46 | public int height { get; set; } 47 | public string? vcodec { get; set; } 48 | public string? acodec { get; set; } 49 | public string? dynamic_range { get; set; } 50 | public string? video_ext { get; set; } 51 | public string? audio_ext { get; set; } 52 | public double vbr { get; set; } 53 | public double abr { get; set; } 54 | public string? format { get; set; } 55 | public string? resolution { get; set; } 56 | public HttpHeaders? http_headers { get; set; } 57 | public string? format_note { get; set; } 58 | public List? fragments { get; set; } 59 | public int? asr { get; set; } 60 | public long? filesize { get; set; } 61 | public int? source_preference { get; set; } 62 | public string? language { get; set; } 63 | public int? language_preference { get; set; } 64 | public DownloaderOptions? downloader_options { get; set; } 65 | public string? container { get; set; } 66 | public double? filesize_approx { get; set; } 67 | } 68 | 69 | public class Thumbnail 70 | { 71 | public string? url { get; set; } 72 | public int preference { get; set; } 73 | public string? id { get; set; } 74 | public int? height { get; set; } 75 | public int? width { get; set; } 76 | public string? resolution { get; set; } 77 | } 78 | 79 | public class LiveChat 80 | { 81 | public string? url { get; set; } 82 | public string? video_id { get; set; } 83 | public string? ext { get; set; } 84 | public string? protocol { get; set; } 85 | } 86 | 87 | public class Subtitles 88 | { 89 | public List? live_chat { get; set; } 90 | } 91 | 92 | public class Af 93 | { 94 | public string? ext { get; set; } 95 | public string? url { get; set; } 96 | public string? name { get; set; } 97 | } 98 | 99 | public class Sq 100 | { 101 | public string? ext { get; set; } 102 | public string? url { get; set; } 103 | public string? name { get; set; } 104 | } 105 | 106 | public class Am 107 | { 108 | public string? ext { get; set; } 109 | public string? url { get; set; } 110 | public string? name { get; set; } 111 | } 112 | 113 | public class Ar 114 | { 115 | public string? ext { get; set; } 116 | public string? url { get; set; } 117 | public string? name { get; set; } 118 | } 119 | 120 | public class Hy 121 | { 122 | public string? ext { get; set; } 123 | public string? url { get; set; } 124 | public string? name { get; set; } 125 | } 126 | 127 | public class Az 128 | { 129 | public string? ext { get; set; } 130 | public string? url { get; set; } 131 | public string? name { get; set; } 132 | } 133 | 134 | public class Bn 135 | { 136 | public string? ext { get; set; } 137 | public string? url { get; set; } 138 | public string? name { get; set; } 139 | } 140 | 141 | public class Eu 142 | { 143 | public string? ext { get; set; } 144 | public string? url { get; set; } 145 | public string? name { get; set; } 146 | } 147 | 148 | public class Be 149 | { 150 | public string? ext { get; set; } 151 | public string? url { get; set; } 152 | public string? name { get; set; } 153 | } 154 | 155 | public class B 156 | { 157 | public string? ext { get; set; } 158 | public string? url { get; set; } 159 | public string? name { get; set; } 160 | } 161 | 162 | public class Bg 163 | { 164 | public string? ext { get; set; } 165 | public string? url { get; set; } 166 | public string? name { get; set; } 167 | } 168 | 169 | public class My 170 | { 171 | public string? ext { get; set; } 172 | public string? url { get; set; } 173 | public string? name { get; set; } 174 | } 175 | 176 | public class Ca 177 | { 178 | public string? ext { get; set; } 179 | public string? url { get; set; } 180 | public string? name { get; set; } 181 | } 182 | 183 | public class Ceb 184 | { 185 | public string? ext { get; set; } 186 | public string? url { get; set; } 187 | public string? name { get; set; } 188 | } 189 | 190 | public class ZhHan 191 | { 192 | public string? ext { get; set; } 193 | public string? url { get; set; } 194 | public string? name { get; set; } 195 | } 196 | 197 | public class ZhHant 198 | { 199 | public string? ext { get; set; } 200 | public string? url { get; set; } 201 | public string? name { get; set; } 202 | } 203 | 204 | public class Co 205 | { 206 | public string? ext { get; set; } 207 | public string? url { get; set; } 208 | public string? name { get; set; } 209 | } 210 | 211 | public class Hr 212 | { 213 | public string? ext { get; set; } 214 | public string? url { get; set; } 215 | public string? name { get; set; } 216 | } 217 | 218 | public class C 219 | { 220 | public string? ext { get; set; } 221 | public string? url { get; set; } 222 | public string? name { get; set; } 223 | } 224 | 225 | public class Da 226 | { 227 | public string? ext { get; set; } 228 | public string? url { get; set; } 229 | public string? name { get; set; } 230 | } 231 | 232 | public class Nl 233 | { 234 | public string? ext { get; set; } 235 | public string? url { get; set; } 236 | public string? name { get; set; } 237 | } 238 | 239 | public class En 240 | { 241 | public string? ext { get; set; } 242 | public string? url { get; set; } 243 | public string? name { get; set; } 244 | } 245 | 246 | public class Eo 247 | { 248 | public string? ext { get; set; } 249 | public string? url { get; set; } 250 | public string? name { get; set; } 251 | } 252 | 253 | public class Et 254 | { 255 | public string? ext { get; set; } 256 | public string? url { get; set; } 257 | public string? name { get; set; } 258 | } 259 | 260 | public class Fil 261 | { 262 | public string? ext { get; set; } 263 | public string? url { get; set; } 264 | public string? name { get; set; } 265 | } 266 | 267 | public class Fi 268 | { 269 | public string? ext { get; set; } 270 | public string? url { get; set; } 271 | public string? name { get; set; } 272 | } 273 | 274 | public class Fr 275 | { 276 | public string? ext { get; set; } 277 | public string? url { get; set; } 278 | public string? name { get; set; } 279 | } 280 | 281 | public class Gl 282 | { 283 | public string? ext { get; set; } 284 | public string? url { get; set; } 285 | public string? name { get; set; } 286 | } 287 | 288 | public class Ka 289 | { 290 | public string? ext { get; set; } 291 | public string? url { get; set; } 292 | public string? name { get; set; } 293 | } 294 | 295 | public class De 296 | { 297 | public string? ext { get; set; } 298 | public string? url { get; set; } 299 | public string? name { get; set; } 300 | } 301 | 302 | public class El 303 | { 304 | public string? ext { get; set; } 305 | public string? url { get; set; } 306 | public string? name { get; set; } 307 | } 308 | 309 | public class Gu 310 | { 311 | public string? ext { get; set; } 312 | public string? url { get; set; } 313 | public string? name { get; set; } 314 | } 315 | 316 | public class Ht 317 | { 318 | public string? ext { get; set; } 319 | public string? url { get; set; } 320 | public string? name { get; set; } 321 | } 322 | 323 | public class Ha 324 | { 325 | public string? ext { get; set; } 326 | public string? url { get; set; } 327 | public string? name { get; set; } 328 | } 329 | 330 | public class Haw 331 | { 332 | public string? ext { get; set; } 333 | public string? url { get; set; } 334 | public string? name { get; set; } 335 | } 336 | 337 | public class Iw 338 | { 339 | public string? ext { get; set; } 340 | public string? url { get; set; } 341 | public string? name { get; set; } 342 | } 343 | 344 | public class Hi 345 | { 346 | public string? ext { get; set; } 347 | public string? url { get; set; } 348 | public string? name { get; set; } 349 | } 350 | 351 | public class Hmn 352 | { 353 | public string? ext { get; set; } 354 | public string? url { get; set; } 355 | public string? name { get; set; } 356 | } 357 | 358 | public class Hu 359 | { 360 | public string? ext { get; set; } 361 | public string? url { get; set; } 362 | public string? name { get; set; } 363 | } 364 | 365 | public class Is 366 | { 367 | public string? ext { get; set; } 368 | public string? url { get; set; } 369 | public string? name { get; set; } 370 | } 371 | 372 | public class Ig 373 | { 374 | public string? ext { get; set; } 375 | public string? url { get; set; } 376 | public string? name { get; set; } 377 | } 378 | 379 | public class Id 380 | { 381 | public string? ext { get; set; } 382 | public string? url { get; set; } 383 | public string? name { get; set; } 384 | } 385 | 386 | public class Ga 387 | { 388 | public string? ext { get; set; } 389 | public string? url { get; set; } 390 | public string? name { get; set; } 391 | } 392 | 393 | public class It 394 | { 395 | public string? ext { get; set; } 396 | public string? url { get; set; } 397 | public string? name { get; set; } 398 | } 399 | 400 | public class Ja 401 | { 402 | public string? ext { get; set; } 403 | public string? url { get; set; } 404 | public string? name { get; set; } 405 | } 406 | 407 | public class Jv 408 | { 409 | public string? ext { get; set; } 410 | public string? url { get; set; } 411 | public string? name { get; set; } 412 | } 413 | 414 | public class Kn 415 | { 416 | public string? ext { get; set; } 417 | public string? url { get; set; } 418 | public string? name { get; set; } 419 | } 420 | 421 | public class Kk 422 | { 423 | public string? ext { get; set; } 424 | public string? url { get; set; } 425 | public string? name { get; set; } 426 | } 427 | 428 | public class Km 429 | { 430 | public string? ext { get; set; } 431 | public string? url { get; set; } 432 | public string? name { get; set; } 433 | } 434 | 435 | public class Rw 436 | { 437 | public string? ext { get; set; } 438 | public string? url { get; set; } 439 | public string? name { get; set; } 440 | } 441 | 442 | public class Ko 443 | { 444 | public string? ext { get; set; } 445 | public string? url { get; set; } 446 | public string? name { get; set; } 447 | } 448 | 449 | public class Ku 450 | { 451 | public string? ext { get; set; } 452 | public string? url { get; set; } 453 | public string? name { get; set; } 454 | } 455 | 456 | public class Ky 457 | { 458 | public string? ext { get; set; } 459 | public string? url { get; set; } 460 | public string? name { get; set; } 461 | } 462 | 463 | public class Lo 464 | { 465 | public string? ext { get; set; } 466 | public string? url { get; set; } 467 | public string? name { get; set; } 468 | } 469 | 470 | public class La 471 | { 472 | public string? ext { get; set; } 473 | public string? url { get; set; } 474 | public string? name { get; set; } 475 | } 476 | 477 | public class Lv 478 | { 479 | public string? ext { get; set; } 480 | public string? url { get; set; } 481 | public string? name { get; set; } 482 | } 483 | 484 | public class Lt 485 | { 486 | public string? ext { get; set; } 487 | public string? url { get; set; } 488 | public string? name { get; set; } 489 | } 490 | 491 | public class Lb 492 | { 493 | public string? ext { get; set; } 494 | public string? url { get; set; } 495 | public string? name { get; set; } 496 | } 497 | 498 | public class Mk 499 | { 500 | public string? ext { get; set; } 501 | public string? url { get; set; } 502 | public string? name { get; set; } 503 | } 504 | 505 | public class Mg 506 | { 507 | public string? ext { get; set; } 508 | public string? url { get; set; } 509 | public string? name { get; set; } 510 | } 511 | 512 | public class M 513 | { 514 | public string? ext { get; set; } 515 | public string? url { get; set; } 516 | public string? name { get; set; } 517 | } 518 | 519 | public class Ml 520 | { 521 | public string? ext { get; set; } 522 | public string? url { get; set; } 523 | public string? name { get; set; } 524 | } 525 | 526 | public class Mt 527 | { 528 | public string? ext { get; set; } 529 | public string? url { get; set; } 530 | public string? name { get; set; } 531 | } 532 | 533 | public class Mi 534 | { 535 | public string? ext { get; set; } 536 | public string? url { get; set; } 537 | public string? name { get; set; } 538 | } 539 | 540 | public class Mr 541 | { 542 | public string? ext { get; set; } 543 | public string? url { get; set; } 544 | public string? name { get; set; } 545 | } 546 | 547 | public class Mn 548 | { 549 | public string? ext { get; set; } 550 | public string? url { get; set; } 551 | public string? name { get; set; } 552 | } 553 | 554 | public class Ne 555 | { 556 | public string? ext { get; set; } 557 | public string? url { get; set; } 558 | public string? name { get; set; } 559 | } 560 | 561 | public class No 562 | { 563 | public string? ext { get; set; } 564 | public string? url { get; set; } 565 | public string? name { get; set; } 566 | } 567 | 568 | public class Ny 569 | { 570 | public string? ext { get; set; } 571 | public string? url { get; set; } 572 | public string? name { get; set; } 573 | } 574 | 575 | public class Or 576 | { 577 | public string? ext { get; set; } 578 | public string? url { get; set; } 579 | public string? name { get; set; } 580 | } 581 | 582 | public class P 583 | { 584 | public string? ext { get; set; } 585 | public string? url { get; set; } 586 | public string? name { get; set; } 587 | } 588 | 589 | public class Fa 590 | { 591 | public string? ext { get; set; } 592 | public string? url { get; set; } 593 | public string? name { get; set; } 594 | } 595 | 596 | public class Pl 597 | { 598 | public string? ext { get; set; } 599 | public string? url { get; set; } 600 | public string? name { get; set; } 601 | } 602 | 603 | public class Pt 604 | { 605 | public string? ext { get; set; } 606 | public string? url { get; set; } 607 | public string? name { get; set; } 608 | } 609 | 610 | public class Pa 611 | { 612 | public string? ext { get; set; } 613 | public string? url { get; set; } 614 | public string? name { get; set; } 615 | } 616 | 617 | public class Ro 618 | { 619 | public string? ext { get; set; } 620 | public string? url { get; set; } 621 | public string? name { get; set; } 622 | } 623 | 624 | public class Ru 625 | { 626 | public string? ext { get; set; } 627 | public string? url { get; set; } 628 | public string? name { get; set; } 629 | } 630 | 631 | public class Sm 632 | { 633 | public string? ext { get; set; } 634 | public string? url { get; set; } 635 | public string? name { get; set; } 636 | } 637 | 638 | public class Gd 639 | { 640 | public string? ext { get; set; } 641 | public string? url { get; set; } 642 | public string? name { get; set; } 643 | } 644 | 645 | public class Sr 646 | { 647 | public string? ext { get; set; } 648 | public string? url { get; set; } 649 | public string? name { get; set; } 650 | } 651 | 652 | public class Sn 653 | { 654 | public string? ext { get; set; } 655 | public string? url { get; set; } 656 | public string? name { get; set; } 657 | } 658 | 659 | public class Sd 660 | { 661 | public string? ext { get; set; } 662 | public string? url { get; set; } 663 | public string? name { get; set; } 664 | } 665 | 666 | public class Si 667 | { 668 | public string? ext { get; set; } 669 | public string? url { get; set; } 670 | public string? name { get; set; } 671 | } 672 | 673 | public class Sk 674 | { 675 | public string? ext { get; set; } 676 | public string? url { get; set; } 677 | public string? name { get; set; } 678 | } 679 | 680 | public class Sl 681 | { 682 | public string? ext { get; set; } 683 | public string? url { get; set; } 684 | public string? name { get; set; } 685 | } 686 | 687 | public class So 688 | { 689 | public string? ext { get; set; } 690 | public string? url { get; set; } 691 | public string? name { get; set; } 692 | } 693 | 694 | public class St 695 | { 696 | public string? ext { get; set; } 697 | public string? url { get; set; } 698 | public string? name { get; set; } 699 | } 700 | 701 | public class E 702 | { 703 | public string? ext { get; set; } 704 | public string? url { get; set; } 705 | public string? name { get; set; } 706 | } 707 | 708 | public class Su 709 | { 710 | public string? ext { get; set; } 711 | public string? url { get; set; } 712 | public string? name { get; set; } 713 | } 714 | 715 | public class Sw 716 | { 717 | public string? ext { get; set; } 718 | public string? url { get; set; } 719 | public string? name { get; set; } 720 | } 721 | 722 | public class Sv 723 | { 724 | public string? ext { get; set; } 725 | public string? url { get; set; } 726 | public string? name { get; set; } 727 | } 728 | 729 | public class Tg 730 | { 731 | public string? ext { get; set; } 732 | public string? url { get; set; } 733 | public string? name { get; set; } 734 | } 735 | 736 | public class Ta 737 | { 738 | public string? ext { get; set; } 739 | public string? url { get; set; } 740 | public string? name { get; set; } 741 | } 742 | 743 | public class Tt 744 | { 745 | public string? ext { get; set; } 746 | public string? url { get; set; } 747 | public string? name { get; set; } 748 | } 749 | 750 | public class Te 751 | { 752 | public string? ext { get; set; } 753 | public string? url { get; set; } 754 | public string? name { get; set; } 755 | } 756 | 757 | public class Th 758 | { 759 | public string? ext { get; set; } 760 | public string? url { get; set; } 761 | public string? name { get; set; } 762 | } 763 | 764 | public class Tr 765 | { 766 | public string? ext { get; set; } 767 | public string? url { get; set; } 768 | public string? name { get; set; } 769 | } 770 | 771 | public class Tk 772 | { 773 | public string? ext { get; set; } 774 | public string? url { get; set; } 775 | public string? name { get; set; } 776 | } 777 | 778 | public class Uk 779 | { 780 | public string? ext { get; set; } 781 | public string? url { get; set; } 782 | public string? name { get; set; } 783 | } 784 | 785 | public class Ur 786 | { 787 | public string? ext { get; set; } 788 | public string? url { get; set; } 789 | public string? name { get; set; } 790 | } 791 | 792 | public class Ug 793 | { 794 | public string? ext { get; set; } 795 | public string? url { get; set; } 796 | public string? name { get; set; } 797 | } 798 | 799 | public class Uz 800 | { 801 | public string? ext { get; set; } 802 | public string? url { get; set; } 803 | public string? name { get; set; } 804 | } 805 | 806 | public class Vi 807 | { 808 | public string? ext { get; set; } 809 | public string? url { get; set; } 810 | public string? name { get; set; } 811 | } 812 | 813 | public class Cy 814 | { 815 | public string? ext { get; set; } 816 | public string? url { get; set; } 817 | public string? name { get; set; } 818 | } 819 | 820 | public class Fy 821 | { 822 | public string? ext { get; set; } 823 | public string? url { get; set; } 824 | public string? name { get; set; } 825 | } 826 | 827 | public class Xh 828 | { 829 | public string? ext { get; set; } 830 | public string? url { get; set; } 831 | public string? name { get; set; } 832 | } 833 | 834 | public class Yi 835 | { 836 | public string? ext { get; set; } 837 | public string? url { get; set; } 838 | public string? name { get; set; } 839 | } 840 | 841 | public class Yo 842 | { 843 | public string? ext { get; set; } 844 | public string? url { get; set; } 845 | public string? name { get; set; } 846 | } 847 | 848 | public class Zu 849 | { 850 | public string? ext { get; set; } 851 | public string? url { get; set; } 852 | public string? name { get; set; } 853 | } 854 | 855 | public class AutomaticCaptions 856 | { 857 | public List? af { get; set; } 858 | public List? sq { get; set; } 859 | public List? am { get; set; } 860 | public List? ar { get; set; } 861 | public List? hy { get; set; } 862 | public List? az { get; set; } 863 | public List? bn { get; set; } 864 | public List? eu { get; set; } 865 | public List? be { get; set; } 866 | public List? bs { get; set; } 867 | public List? bg { get; set; } 868 | public List? my { get; set; } 869 | public List? ca { get; set; } 870 | public List? ceb { get; set; } 871 | 872 | [JsonPropertyName("zh-Hans")] 873 | public List? ZhHans { get; set; } 874 | 875 | [JsonPropertyName("zh-Hant")] 876 | public List? ZhHant { get; set; } 877 | public List? co { get; set; } 878 | public List
? hr { get; set; } 879 | public List? cs { get; set; } 880 | public List? da { get; set; } 881 | public List? nl { get; set; } 882 | public List? en { get; set; } 883 | public List? eo { get; set; } 884 | public List? et { get; set; } 885 | public List? fil { get; set; } 886 | public List? fi { get; set; } 887 | public List? fr { get; set; } 888 | public List? gl { get; set; } 889 | public List? ka { get; set; } 890 | public List? de { get; set; } 891 | public List? el { get; set; } 892 | public List? gu { get; set; } 893 | public List? ht { get; set; } 894 | public List? ha { get; set; } 895 | public List? haw { get; set; } 896 | public List? iw { get; set; } 897 | public List? hi { get; set; } 898 | public List? hmn { get; set; } 899 | public List? hu { get; set; } 900 | public List? @is { get; set; } 901 | public List? ig { get; set; } 902 | public List? id { get; set; } 903 | public List? ga { get; set; } 904 | public List? it { get; set; } 905 | public List? ja { get; set; } 906 | public List? jv { get; set; } 907 | public List? kn { get; set; } 908 | public List? kk { get; set; } 909 | public List? km { get; set; } 910 | public List? rw { get; set; } 911 | public List? ko { get; set; } 912 | public List? ku { get; set; } 913 | public List? ky { get; set; } 914 | public List? lo { get; set; } 915 | public List? la { get; set; } 916 | public List? lv { get; set; } 917 | public List? lt { get; set; } 918 | public List? lb { get; set; } 919 | public List? mk { get; set; } 920 | public List? mg { get; set; } 921 | public List? ms { get; set; } 922 | public List? ml { get; set; } 923 | public List? mt { get; set; } 924 | public List? mi { get; set; } 925 | public List? mr { get; set; } 926 | public List? mn { get; set; } 927 | public List? ne { get; set; } 928 | public List? no { get; set; } 929 | public List? ny { get; set; } 930 | public List? or { get; set; } 931 | public List

? ps { get; set; } 932 | public List? fa { get; set; } 933 | public List? pl { get; set; } 934 | public List? pt { get; set; } 935 | public List? pa { get; set; } 936 | public List? ro { get; set; } 937 | public List? ru { get; set; } 938 | public List? sm { get; set; } 939 | public List? gd { get; set; } 940 | public List? sr { get; set; } 941 | public List? sn { get; set; } 942 | public List? sd { get; set; } 943 | public List? si { get; set; } 944 | public List? sk { get; set; } 945 | public List? sl { get; set; } 946 | public List? so { get; set; } 947 | public List? st { get; set; } 948 | public List? es { get; set; } 949 | public List? su { get; set; } 950 | public List? sw { get; set; } 951 | public List? sv { get; set; } 952 | public List? tg { get; set; } 953 | public List? ta { get; set; } 954 | public List? tt { get; set; } 955 | public List? te { get; set; } 956 | public List? th { get; set; } 957 | public List? tr { get; set; } 958 | public List? tk { get; set; } 959 | public List? uk { get; set; } 960 | public List? ur { get; set; } 961 | public List? ug { get; set; } 962 | public List? uz { get; set; } 963 | public List? vi { get; set; } 964 | public List? cy { get; set; } 965 | public List? fy { get; set; } 966 | public List? xh { get; set; } 967 | public List? yi { get; set; } 968 | public List? yo { get; set; } 969 | public List? zu { get; set; } 970 | } 971 | 972 | #pragma warning disable CS8981 // 類型名稱只包含小寫的 ASCII 字元。此類名稱可能保留供此語言使用。 973 | public class info 974 | #pragma warning restore CS8981 // 類型名稱只包含小寫的 ASCII 字元。此類名稱可能保留供此語言使用。 975 | { 976 | public string? id { get; set; } 977 | public string? title { get; set; } 978 | public List? formats { get; set; } 979 | public List? thumbnails { get; set; } 980 | public string? thumbnail { get; set; } 981 | public string? description { get; set; } 982 | public string? upload_date { get; set; } 983 | public string? uploader { get; set; } 984 | public string? uploader_id { get; set; } 985 | public string? uploader_url { get; set; } 986 | public string? channel_id { get; set; } 987 | public string? channel_url { get; set; } 988 | public int view_count { get; set; } 989 | public int age_limit { get; set; } 990 | public string? webpage_url { get; set; } 991 | public List? categories { get; set; } 992 | public List? tags { get; set; } 993 | public bool playable_in_embed { get; set; } 994 | public bool is_live { get; set; } 995 | public bool was_live { get; set; } 996 | public string? live_status { get; set; } 997 | public int release_timestamp { get; set; } 998 | public Subtitles? subtitles { get; set; } 999 | public int like_count { get; set; } 1000 | public string? channel { get; set; } 1001 | public int channel_follower_count { get; set; } 1002 | public string? availability { get; set; } 1003 | public string? webpage_url_basename { get; set; } 1004 | public string? extractor { get; set; } 1005 | public string? extractor_key { get; set; } 1006 | public string? display_id { get; set; } 1007 | public string? release_date { get; set; } 1008 | public string? fulltitle { get; set; } 1009 | public int epoch { get; set; } 1010 | public string? format_id { get; set; } 1011 | public string? url { get; set; } 1012 | public string? manifest_url { get; set; } 1013 | public double? tbr { get; set; } 1014 | public string? ext { get; set; } 1015 | public double? fps { get; set; } 1016 | public string? protocol { get; set; } 1017 | public int? quality { get; set; } 1018 | public int? width { get; set; } 1019 | public int? height { get; set; } 1020 | public string? vcodec { get; set; } 1021 | public string? acodec { get; set; } 1022 | public string? dynamic_range { get; set; } 1023 | public string? video_ext { get; set; } 1024 | public string? audio_ext { get; set; } 1025 | public double? vbr { get; set; } 1026 | public double? abr { get; set; } 1027 | public string? format { get; set; } 1028 | public string? resolution { get; set; } 1029 | public HttpHeaders? http_headers { get; set; } 1030 | public int? duration { get; set; } 1031 | public AutomaticCaptions? automatic_captions { get; set; } 1032 | public string? duration_string { get; set; } 1033 | public string? format_note { get; set; } 1034 | public int? filesize_approx { get; set; } 1035 | public int? asr { get; set; } 1036 | } 1037 | } 1038 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using Discord.Webhook; 2 | using YoutubeLiveChatToDiscord; 3 | using YoutubeLiveChatToDiscord.Services; 4 | 5 | Environment.SetEnvironmentVariable("VIDEO_ID", Environment.GetCommandLineArgs()[1]); 6 | Environment.SetEnvironmentVariable("WEBHOOK", Environment.GetCommandLineArgs()[2]); 7 | 8 | IEnumerable oldFiles = Directory.GetFiles(Directory.GetCurrentDirectory()) 9 | .Where(p => p.Contains($"{Environment.GetEnvironmentVariable("VIDEO_ID")}.live_chat.json")); 10 | foreach (var file in oldFiles) 11 | { 12 | File.Delete(file); 13 | } 14 | 15 | IHost host = Host.CreateDefaultBuilder(args) 16 | .ConfigureServices(services => 17 | { 18 | services.AddHostedService() 19 | .AddSingleton() 20 | .AddSingleton() 21 | .AddSingleton((service) => new DiscordWebhookClient(Environment.GetEnvironmentVariable("WEBHOOK"))); 22 | }) 23 | .Build(); 24 | 25 | await host.RunAsync(); 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Youtube Live Chat To Discord 2 | 3 | [![CodeFactor](https://www.codefactor.io/repository/github/jim60105/youtubelivechattodiscord/badge/master)](https://www.codefactor.io/repository/github/jim60105/youtubelivechattodiscord/overview/master) [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fjim60105%2FYoutubeLiveChatToDiscord.svg?type=small)](https://app.fossa.com/projects/git%2Bgithub.com%2Fjim60105%2FYoutubeLiveChatToDiscord?ref=badge_small) 4 | 5 | > [!CAUTION] 6 | > Please take note of the **AGPLv3** license that we are using. 7 | > You _**MUST**_ share **the source code** with **anyone who can access the services** (service, which means the Discord messages published by this program). 8 | > Share the URL of this GitHub repository, or publish the modified source code if any changes were made. 9 | 10 | ## Stream Youtube chat to Discord Webhook 11 | 12 | | Youtube Live Chat | | Discord Webhook | 13 | | :-----------------------------------------------------------------------------------------------------------------: | :-: | :-----------------------------------------------------------------------------------------------------------------: | 14 | | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/a979ae6a-8b99-4887-92bb-e08773f9c064) | ➡️ | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/2e58c0b6-6a34-4664-afd9-c16ea378987a) | 15 | | ![image](https://user-images.githubusercontent.com/16995691/151545455-af26cbe6-0942-464a-b15e-76ca67dfa142.png) | ➡️ | ![image](https://user-images.githubusercontent.com/16995691/151438025-d0c4a2de-6845-4d64-93db-89afb2f98e45.png) | 16 | | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/4d8d6417-4dda-4c42-a179-da7557d6a608) | ➡️ | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/77b4aced-0f82-48be-a591-fa351e1e5246) | 17 | | ![image](https://user-images.githubusercontent.com/16995691/151663570-999a5c8c-a336-407e-906a-56399530417b.png) | ➡️ | ![image](https://user-images.githubusercontent.com/16995691/151663574-dc5abbc2-cb5d-4e40-a4ce-bfc39f2a7029.png) | 18 | | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/c62951ef-1268-462f-8955-a5f507b9be43) | ➡️ | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/7307d06e-5cc9-4fd4-a489-2dd21b29abc6) | 19 | | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/d6d3338f-846e-4ee8-8a74-85d0b4d0479b) | ➡️ | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/6b72474d-99c6-4006-a165-d25ca4cb7474) | 20 | 21 |

22 | English | 23 | 24 | 中文 25 | 26 |

27 | 28 | - The underlying implementation uses yt-dlp instead of the YouTube API, so there is no API quota limit. 29 | - When this tool is idle, it reads the JSON file generated by yt-dlp every 10 seconds. 30 | - Upon startup, it waits for 1 minute to skip old chats before starting monitoring. 31 | > If you want to skip this waiting and start immediately, please pass the environment variable `SKIP_STARTUP_WAITING`. 32 | - It can monitor membership-only live streams by automatically detect and import the `cookies.txt` file in the execution directory into yt-dlp. 33 | - It is not suitable for for scenarios with a high message speed. 34 | It sends a maximum of one Discord webhook every two seconds, which may cause delays if the new chat speed exceeds the forwarding speed. 35 | > Discord has a limitation that allows calling webhooks up to 30 times per minute in the same channel [ref](https://twitter.com/lolpython/status/967621046277820416). 36 | > If multiple instances of this tool are simultaneously running and pushed to the same channel, it's easy to trigger Discord cooldown. Please be aware of your usage environment. 37 | 38 | ## Membership-only (login required) videos 39 | 40 | If a file named `cookies.txt` exists in the program's execution directory, it will be used automatically. 41 | 42 | For Docker, please mount `cookies.txt` to `/app/cookies.txt`. 43 | 44 | ## Docker 45 | 46 | > Please refer to `docker-compose.yml`. 47 | 48 | Two parameters need to be passed in: 49 | 50 | - Video ID 51 | - Discord Webhook URL 52 | 53 | ```sh 54 | docker run --rm ghcr.io/jim60105/youtubelivechattodiscord [Video_Id] [Discord_Webhook_Url] 55 | ``` 56 | 57 | Also available at [quay.io](https://quay.io/jim60105/youtubelivechattodiscord) 58 | 59 | ## Kubernetes Helm Chart 60 | 61 | ```sh 62 | git clone https://github.com/jim60105/YoutubeLiveChatToDiscord.git 63 | cd YoutubeLiveChatToDiscord/helm-chart 64 | vim values.yaml 65 | helm install [Release_Name] . 66 | ``` 67 | 68 | ### Timezone 69 | 70 | Default timezone is `Asia/Taipei`. Please change it with `TZ` environment variable. 71 | 72 | ## LICENSE 73 | 74 | [![AGPL-3.0](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/8c588957-5e07-4f6d-a116-b3366c064342)](LICENSE) 75 | 76 | [GNU AFFERO GENERAL PUBLIC LICENSE Version 3](LICENSE) 77 | 78 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 79 | 80 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 81 | 82 | You should have received a copy of the GNU Affero General Public License along with this program. If not, see . 83 | 84 | > [!CAUTION] 85 | > Please take note of the **AGPLv3** license that we are using. 86 | > You _**MUST**_ share **the source code** with **anyone who can access the services** (the Discord messages published by this program). 87 | > Share the URL of this GitHub repository, or publish the modified source code if any changes were made. 88 | -------------------------------------------------------------------------------- /README.zh.md: -------------------------------------------------------------------------------- 1 | # Youtube Live Chat To Discord 2 | 3 | [![CodeFactor](https://www.codefactor.io/repository/github/jim60105/youtubelivechattodiscord/badge/master)](https://www.codefactor.io/repository/github/jim60105/youtubelivechattodiscord/overview/master) [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fjim60105%2FYoutubeLiveChatToDiscord.svg?type=small)](https://app.fossa.com/projects/git%2Bgithub.com%2Fjim60105%2FYoutubeLiveChatToDiscord?ref=badge_small) 4 | 5 | > [!CAUTION] 6 | > 請留意我所使用的 **AGPLv3** 授權條款。 7 | > 你 _**必須**_ 將 **原始碼** 公開給 **任何能存取到服務的人** (服務,也就是指此程式所發布的 Discord 訊息)。 8 | > 請分享此 GitHub 儲存庫的網址,或是公開修改過的原始碼。 9 | 10 | ## 將 Youtube 聊天室串流至 Discord Webhook 11 | 12 | | Youtube Live Chat | | Discord Webhook | 13 | | :-----------------------------------------------------------------------------------------------------------------: | :-: | :-----------------------------------------------------------------------------------------------------------------: | 14 | | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/a979ae6a-8b99-4887-92bb-e08773f9c064) | ➡️ | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/2e58c0b6-6a34-4664-afd9-c16ea378987a) | 15 | | ![image](https://user-images.githubusercontent.com/16995691/151545455-af26cbe6-0942-464a-b15e-76ca67dfa142.png) | ➡️ | ![image](https://user-images.githubusercontent.com/16995691/151438025-d0c4a2de-6845-4d64-93db-89afb2f98e45.png) | 16 | | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/4d8d6417-4dda-4c42-a179-da7557d6a608) | ➡️ | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/77b4aced-0f82-48be-a591-fa351e1e5246) | 17 | | ![image](https://user-images.githubusercontent.com/16995691/151663570-999a5c8c-a336-407e-906a-56399530417b.png) | ➡️ | ![image](https://user-images.githubusercontent.com/16995691/151663574-dc5abbc2-cb5d-4e40-a4ce-bfc39f2a7029.png) | 18 | | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/c62951ef-1268-462f-8955-a5f507b9be43) | ➡️ | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/7307d06e-5cc9-4fd4-a489-2dd21b29abc6) | 19 | | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/d6d3338f-846e-4ee8-8a74-85d0b4d0479b) | ➡️ | ![image](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/6b72474d-99c6-4006-a165-d25ca4cb7474) | 20 | 21 |

22 | 23 | English 24 | | 25 | 中文 26 |

27 | 28 | - 底層使用 yt-dlp 而不是 youtube api 實作,因此沒有 API 額度限制 29 | - 此工具在閒置時,會以 10 秒為間隔讀取 yt-dlp 產出的 json 檔案 30 | - 剛啟動時會等待 1 分鐘跳過舊留言,再由此開始監控 31 | > 如果要跳過此等待即時啟動,請傳入環境變數 `SKIP_STARTUP_WAITING` 32 | - 它可以監控會員限定直播,會自動檢測執行目錄下的 `cookies.txt` 並將其匯入 yt-dlp 33 | - 不適合用在有大量留言的狀況,此工具是設計來監控 FreeChat 34 | 它最高每兩秒打一次 discord webhook ,可能會造成轉送速度跟不上留言速度 35 | > Discord 方面的限制為,同一頻道中每分鐘可呼叫 Webhook 30 次 [ref](https://twitter.com/lolpython/status/967621046277820416) 36 | > 若同時啟動複數此工具並推送至同一個頻道,很容易觸發 Discord 冷卻,請留意你的使用環境 37 | 38 | ## 會員限定 (需登入) 的影片 39 | 40 | 在程式的執行目錄若存在名為 `cookies.txt` 的檔案,它會自動使用 41 | 42 | Docker 請將 `cookies.txt` mount 至 `/app/cookies.txt` 43 | 44 | ## Docker 45 | 46 | > 請參考 `docker-compose.yml` 47 | 48 | 需傳入兩個參數 49 | 50 | - 影片 ID 51 | - Discord Webhook 網址 52 | 53 | ```sh 54 | docker run --rm ghcr.io/jim60105/youtubelivechattodiscord [Video_Id] [Discord_Webhook_Url] 55 | ``` 56 | 57 | 也可在[quay.io](https://quay.io/jim60105/youtubelivechattodiscord)取得。 58 | 59 | ## Kubernetes Helm Chart 60 | 61 | ```sh 62 | git clone https://github.com/jim60105/YoutubeLiveChatToDiscord.git 63 | cd YoutubeLiveChatToDiscord/helm-chart 64 | vim values.yaml 65 | helm install [Release_Name] . 66 | ``` 67 | 68 | ### Timezone 69 | 70 | 預設時區為 `Asia/Taipei`。請使用 `TZ` 環境變數進行更改。 71 | 72 | ## LICENSE 73 | 74 | [![AGPL-3.0](https://github.com/jim60105/YoutubeLiveChatToDiscord/assets/16995691/8c588957-5e07-4f6d-a116-b3366c064342)](LICENSE) 75 | 76 | [GNU AFFERO GENERAL PUBLIC LICENSE Version 3](LICENSE) 77 | 78 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 79 | 80 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 81 | 82 | You should have received a copy of the GNU Affero General Public License along with this program. If not, see . 83 | 84 | > [!CAUTION] 85 | > 請留意我們使用的 **AGPLv3** 授權條款。 86 | > 你 _**必須**_ 將 **原始碼** 公開給 **任何能存取到服務的人** (也就是此程式所發布的 Discord 訊息)。 87 | > 請分享此 GitHub 儲存庫的網址,或是公開修改過的原始碼。 88 | -------------------------------------------------------------------------------- /Services/DiscordService.cs: -------------------------------------------------------------------------------- 1 | using Discord; 2 | using Discord.Webhook; 3 | using static YoutubeLiveChatToDiscord.Models.Chat; 4 | using Chat = YoutubeLiveChatToDiscord.Models.Chat.chat; 5 | 6 | namespace YoutubeLiveChatToDiscord.Services; 7 | 8 | public class DiscordService 9 | { 10 | private readonly ILogger _logger; 11 | private readonly string _id; 12 | private readonly DiscordWebhookClient _client; 13 | private static readonly Color _ownerColor = new(0xffd600); 14 | private static readonly Color _sponsorColor = new(0x0f9d58); 15 | private static readonly string _crownIcon = "https://raw.githubusercontent.com/jim60105/YoutubeLiveChatToDiscord/master/assets/crown.png"; 16 | private static readonly string _walletIcon = "https://raw.githubusercontent.com/jim60105/YoutubeLiveChatToDiscord/master/assets/wallet.png"; 17 | private static readonly string _giftIcon = "https://raw.githubusercontent.com/jim60105/YoutubeLiveChatToDiscord/master/assets/gift.png"; 18 | 19 | public DiscordService( 20 | ILogger logger, 21 | DiscordWebhookClient client) 22 | { 23 | _logger = logger; 24 | _client = client; 25 | _client.Log += DiscordWebhookClient_Log; 26 | _id = Environment.GetEnvironmentVariable("VIDEO_ID") ?? ""; 27 | if (string.IsNullOrEmpty(_id)) throw new ArgumentException(nameof(_id)); 28 | } 29 | 30 | /// 31 | /// 把.NET Core logger對應到Discord內建的logger上面 32 | /// 33 | /// 34 | /// 35 | private Task DiscordWebhookClient_Log(LogMessage arg) 36 | => Task.Run(() => 37 | { 38 | switch (arg.Severity) 39 | { 40 | case LogSeverity.Critical: 41 | _logger.LogCritical("{message}", arg); 42 | break; 43 | case LogSeverity.Error: 44 | _logger.LogError("{message}", arg); 45 | break; 46 | case LogSeverity.Warning: 47 | _logger.LogWarning("{message}", arg); 48 | break; 49 | case LogSeverity.Info: 50 | _logger.LogInformation("{message}", arg); 51 | break; 52 | case LogSeverity.Verbose: 53 | _logger.LogTrace("{message}", arg); 54 | break; 55 | case LogSeverity.Debug: 56 | default: 57 | _logger.LogDebug("{message}", arg); 58 | break; 59 | } 60 | }); 61 | 62 | /// 63 | /// 建立Discord embed並送出至Webhook 64 | /// 65 | /// 66 | /// 67 | /// 68 | /// 訊息格式未支援 69 | public async Task BuildRequestAndSendToDiscord(Chat chat, CancellationToken stoppingToken) 70 | { 71 | EmbedBuilder eb = new(); 72 | eb.WithTitle(Environment.GetEnvironmentVariable("TITLE") ?? "") 73 | .WithUrl($"https://youtu.be/{_id}") 74 | .WithThumbnailUrl(Helper.GetOriginalImage(Environment.GetEnvironmentVariable("VIDEO_THUMB"))); 75 | 76 | var liveChatTextMessage = chat.replayChatItemAction?.actions?.FirstOrDefault()?.addChatItemAction?.item?.liveChatTextMessageRenderer; 77 | var liveChatPaidMessage = chat.replayChatItemAction?.actions?.FirstOrDefault()?.addChatItemAction?.item?.liveChatPaidMessageRenderer; 78 | var liveChatPaidSticker = chat.replayChatItemAction?.actions?.FirstOrDefault()?.addChatItemAction?.item?.liveChatPaidStickerRenderer; 79 | var liveChatMembershipItemRenderer = chat.replayChatItemAction?.actions?.FirstOrDefault()?.addChatItemAction?.item?.liveChatMembershipItemRenderer; 80 | var liveChatPurchaseSponsorshipsGift = chat.replayChatItemAction?.actions?.FirstOrDefault()?.addChatItemAction?.item?.liveChatSponsorshipsGiftPurchaseAnnouncementRenderer; 81 | 82 | // ReplaceChat: Treat as a new message 83 | // This is rare and not easy to test. 84 | // If it behaves strangely, please open a new issue with more examples. 85 | var replaceChat = chat.replayChatItemAction?.actions?.FirstOrDefault()?.replaceChatItemAction?.replacementItem?.liveChatTextMessageRenderer; 86 | if (null != replaceChat) 87 | { 88 | liveChatTextMessage = replaceChat; 89 | } 90 | 91 | string author; 92 | if (null != liveChatTextMessage) 93 | { 94 | BuildNormalMessage(ref eb, liveChatTextMessage, out author); 95 | } 96 | else if (null != liveChatPaidMessage) 97 | // Super Chat 98 | { 99 | BuildSuperChatMessage(ref eb, liveChatPaidMessage, out author); 100 | } 101 | else if (null != liveChatPaidSticker) 102 | // Super Chat Sticker 103 | { 104 | BuildSuperChatStickerMessage(ref eb, liveChatPaidSticker, out author); 105 | } 106 | else if (null != liveChatMembershipItemRenderer) 107 | // Join Membership 108 | { 109 | BuildMemberShipMessage(ref eb, liveChatMembershipItemRenderer, out author); 110 | } 111 | else if (null != liveChatPurchaseSponsorshipsGift 112 | && null != liveChatPurchaseSponsorshipsGift.header.liveChatSponsorshipsHeaderRenderer) 113 | // Purchase Sponsorships Gift 114 | { 115 | BuildPurchaseSponsorshipsGiftMessage(ref eb, liveChatPurchaseSponsorshipsGift, out author); 116 | } 117 | // Discrad known garbage messages. 118 | else if (IsGarbageMessage(chat)) { return; } 119 | else 120 | { 121 | _logger.LogWarning("Message type not supported, skip sending to discord."); 122 | throw new ArgumentException("Message type not supported", nameof(chat)); 123 | } 124 | 125 | if (stoppingToken.IsCancellationRequested) return; 126 | 127 | await SendMessage(eb, author, stoppingToken); 128 | 129 | // The rate for Discord webhooks are 30 requests/minute per channel. 130 | // Be careful when you run multiple instances in the same channel! 131 | _logger.LogTrace("Wait 2 seconds for discord webhook rate limit"); 132 | await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken); 133 | } 134 | 135 | private static bool IsGarbageMessage(Chat chat) => 136 | // Banner Pinned message. 137 | null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.addBannerToLiveChatCommand 138 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.removeBannerForLiveChatCommand 139 | // Click to show less. 140 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.showLiveChatTooltipCommand 141 | // Welcome to live chat! Remember to guard your privacy and abide by our community guidelines. 142 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.addChatItemAction?.item?.liveChatViewerEngagementMessageRenderer 143 | // SC Ticker messages. 144 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.addLiveChatTickerItemAction 145 | // Delete messages. 146 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.markChatItemAsDeletedAction 147 | // Remove Chat Item. Not really sure what this is. 148 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.removeChatItemAction 149 | // Live chat mode change. 150 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.addChatItemAction?.item?.liveChatModeChangeMessageRenderer 151 | // Poll 152 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.updateLiveChatPollAction 153 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.closeLiveChatActionPanelAction 154 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.showLiveChatActionPanelAction 155 | // Sponsorships Gift redemption 156 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.addChatItemAction?.item?.liveChatSponsorshipsGiftRedemptionAnnouncementRenderer 157 | // Have no idea what this is 158 | || null != chat.replayChatItemAction?.actions?.FirstOrDefault()?.addChatItemAction?.item?.liveChatPlaceholderItemRenderer; 159 | 160 | private static EmbedBuilder BuildNormalMessage(ref EmbedBuilder eb, LiveChatTextMessageRenderer liveChatTextMessage, out string author) 161 | { 162 | List runs = liveChatTextMessage.message?.runs ?? new List(); 163 | author = liveChatTextMessage.authorName?.simpleText ?? ""; 164 | string authorPhoto = Helper.GetOriginalImage(liveChatTextMessage.authorPhoto?.thumbnails?.LastOrDefault()?.url); 165 | 166 | eb.WithDescription(string.Join("", runs.Select(p => p.text ?? (p.emoji?.searchTerms?.FirstOrDefault())))) 167 | .WithAuthor(new EmbedAuthorBuilder().WithName(author) 168 | .WithUrl($"https://www.youtube.com/channel/{liveChatTextMessage.authorExternalChannelId}") 169 | .WithIconUrl(authorPhoto)); 170 | 171 | // Timestamp 172 | long timeStamp = long.TryParse(liveChatTextMessage.timestampUsec, out long l) ? l / 1000 : 0; 173 | EmbedFooterBuilder ft = new(); 174 | string authorBadgeUrl = Helper.GetOriginalImage(liveChatTextMessage.authorBadges?.FirstOrDefault()?.liveChatAuthorBadgeRenderer?.customThumbnail?.thumbnails?.LastOrDefault()?.url); 175 | ft.WithText(DateTimeOffset.FromUnixTimeMilliseconds(timeStamp) 176 | .LocalDateTime 177 | .ToString("yyyy/MM/dd HH:mm:ss")) 178 | .WithIconUrl(authorBadgeUrl); 179 | 180 | // From Stream Owner 181 | if (liveChatTextMessage.authorExternalChannelId == Environment.GetEnvironmentVariable("CHANNEL_ID")) 182 | { 183 | eb.WithColor(_ownerColor); 184 | ft.WithIconUrl(_crownIcon); 185 | } 186 | 187 | eb.WithFooter(ft); 188 | return eb; 189 | } 190 | 191 | private static EmbedBuilder BuildSuperChatMessage(ref EmbedBuilder eb, LiveChatPaidMessageRenderer liveChatPaidMessage, out string author) 192 | { 193 | List runs = liveChatPaidMessage.message?.runs ?? new List(); 194 | 195 | author = liveChatPaidMessage.authorName?.simpleText ?? ""; 196 | string authorPhoto = Helper.GetOriginalImage(liveChatPaidMessage.authorPhoto?.thumbnails?.LastOrDefault()?.url); 197 | 198 | eb.WithDescription(string.Join("", runs.Select(p => p.text ?? (p.emoji?.searchTerms?.FirstOrDefault())))) 199 | .WithAuthor(new EmbedAuthorBuilder().WithName(author) 200 | .WithUrl($"https://www.youtube.com/channel/{liveChatPaidMessage.authorExternalChannelId}") 201 | .WithIconUrl(authorPhoto)); 202 | 203 | // Super Chat Amount 204 | eb.WithFields(new EmbedFieldBuilder[] { new EmbedFieldBuilder().WithName("Amount").WithValue(liveChatPaidMessage.purchaseAmountText?.simpleText) }); 205 | 206 | // Super Chat Background Color 207 | Color bgColor = (Color)System.Drawing.ColorTranslator.FromHtml(Helper.YoutubeColorConverter(liveChatPaidMessage.bodyBackgroundColor)); 208 | eb.WithColor(bgColor); 209 | 210 | // Lower Bumper 211 | eb = AppendLowerBumper(ref eb, liveChatPaidMessage.lowerBumper); 212 | 213 | // Timestamp 214 | long timeStamp = long.TryParse(liveChatPaidMessage.timestampUsec, out long l) ? l / 1000 : 0; 215 | EmbedFooterBuilder ft = new(); 216 | ft.WithText(DateTimeOffset.FromUnixTimeMilliseconds(timeStamp) 217 | .LocalDateTime 218 | .ToString("yyyy/MM/dd HH:mm:ss")) 219 | .WithIconUrl(_walletIcon); 220 | 221 | // From Stream Owner 222 | if (liveChatPaidMessage.authorExternalChannelId == Environment.GetEnvironmentVariable("CHANNEL_ID")) 223 | { 224 | //eb.WithColor(_ownerColor); 225 | ft.WithIconUrl(_crownIcon); 226 | } 227 | 228 | eb.WithFooter(ft); 229 | return eb; 230 | } 231 | 232 | private static EmbedBuilder BuildSuperChatStickerMessage(ref EmbedBuilder eb, LiveChatPaidStickerRenderer liveChatPaidSticker, out string author) 233 | { 234 | author = liveChatPaidSticker.authorName?.simpleText ?? ""; 235 | string authorPhoto = Helper.GetOriginalImage(liveChatPaidSticker.authorPhoto?.thumbnails?.LastOrDefault()?.url); 236 | 237 | eb.WithDescription("") 238 | .WithAuthor(new EmbedAuthorBuilder().WithName(author) 239 | .WithUrl($"https://www.youtube.com/channel/{liveChatPaidSticker.authorExternalChannelId}") 240 | .WithIconUrl(authorPhoto)); 241 | 242 | // Super Chat Amount 243 | eb.WithFields(new EmbedFieldBuilder[] { new EmbedFieldBuilder().WithName("Amount").WithValue(liveChatPaidSticker.purchaseAmountText?.simpleText) }); 244 | 245 | // Super Chat Background Color 246 | Color bgColor = (Color)System.Drawing.ColorTranslator.FromHtml(Helper.YoutubeColorConverter(liveChatPaidSticker.backgroundColor)); 247 | eb.WithColor(bgColor); 248 | 249 | // Super Chat Sticker Picture 250 | string stickerThumbUrl = Helper.GetOriginalImage("https:" + liveChatPaidSticker.sticker?.thumbnails?.LastOrDefault()?.url); 251 | eb.WithThumbnailUrl(stickerThumbUrl); 252 | 253 | // Lower Bumper 254 | eb = AppendLowerBumper(ref eb, liveChatPaidSticker.lowerBumper); 255 | 256 | // Timestamp 257 | long timeStamp = long.TryParse(liveChatPaidSticker.timestampUsec, out long l) ? l / 1000 : 0; 258 | EmbedFooterBuilder ft = new(); 259 | ft.WithText(DateTimeOffset.FromUnixTimeMilliseconds(timeStamp) 260 | .LocalDateTime 261 | .ToString("yyyy/MM/dd HH:mm:ss")) 262 | .WithIconUrl(_walletIcon); 263 | 264 | // From Stream Owner 265 | if (liveChatPaidSticker.authorExternalChannelId == Environment.GetEnvironmentVariable("CHANNEL_ID")) 266 | { 267 | //eb.WithColor(_ownerColor); 268 | ft.WithIconUrl(_crownIcon); 269 | } 270 | 271 | eb.WithFooter(ft); 272 | return eb; 273 | } 274 | 275 | private static EmbedBuilder BuildMemberShipMessage(ref EmbedBuilder eb, LiveChatMembershipItemRenderer liveChatMembershipItemRenderer, out string author) 276 | { 277 | List? header = liveChatMembershipItemRenderer.headerPrimaryText?.runs 278 | ?? liveChatMembershipItemRenderer.headerSubtext?.runs; 279 | List? message = liveChatMembershipItemRenderer.message?.runs; 280 | 281 | author = liveChatMembershipItemRenderer.authorName?.simpleText ?? ""; 282 | string authorPhoto = Helper.GetOriginalImage(liveChatMembershipItemRenderer.authorPhoto?.thumbnails?.LastOrDefault()?.url); 283 | 284 | if (null != message) 285 | { 286 | eb.WithDescription(string.Join("", (message ?? []).Select(p => p.text ?? (p.emoji?.searchTerms?.FirstOrDefault())))); 287 | if (null != header) 288 | { 289 | eb.WithFields(new EmbedFieldBuilder[] 290 | { 291 | new EmbedFieldBuilder().WithName("Header") 292 | .WithValue(string.Join("", header.Select(p => p.text ?? (p.emoji?.searchTerms?.FirstOrDefault())))) 293 | }); 294 | } 295 | } 296 | else if (null != header) 297 | { 298 | eb.WithDescription(string.Join("", (header ?? []).Select(p => p.text ?? (p.emoji?.searchTerms?.FirstOrDefault())))); 299 | } 300 | 301 | eb.WithAuthor(new EmbedAuthorBuilder().WithName(author) 302 | .WithUrl($"https://www.youtube.com/channel/{liveChatMembershipItemRenderer.authorExternalChannelId}") 303 | .WithIconUrl(authorPhoto)); 304 | 305 | // Membership Background Color 306 | eb.WithColor(_sponsorColor); 307 | 308 | // Timestamp 309 | long timeStamp = long.TryParse(liveChatMembershipItemRenderer.timestampUsec, out long l) ? l / 1000 : 0; 310 | EmbedFooterBuilder ft = new(); 311 | string authorBadgeUrl = Helper.GetOriginalImage(liveChatMembershipItemRenderer.authorBadges?.FirstOrDefault()?.liveChatAuthorBadgeRenderer?.customThumbnail?.thumbnails?.LastOrDefault()?.url); 312 | ft.WithText(DateTimeOffset.FromUnixTimeMilliseconds(timeStamp) 313 | .LocalDateTime 314 | .ToString("yyyy/MM/dd HH:mm:ss")) 315 | .WithIconUrl(authorBadgeUrl); 316 | 317 | eb.WithFooter(ft); 318 | return eb; 319 | } 320 | 321 | private static EmbedBuilder BuildPurchaseSponsorshipsGiftMessage(ref EmbedBuilder eb, LiveChatSponsorshipsGiftPurchaseAnnouncementRenderer liveChatPurchaseSponsorshipsGift, out string author) 322 | { 323 | LiveChatSponsorshipsHeaderRenderer header = liveChatPurchaseSponsorshipsGift.header.liveChatSponsorshipsHeaderRenderer; 324 | author = header.authorName?.simpleText ?? ""; 325 | string authorPhoto = Helper.GetOriginalImage(header.authorPhoto?.thumbnails?.LastOrDefault()?.url); 326 | 327 | eb.WithDescription("") 328 | .WithAuthor(new EmbedAuthorBuilder().WithName(author) 329 | .WithUrl($"https://www.youtube.com/channel/{liveChatPurchaseSponsorshipsGift?.authorExternalChannelId}") 330 | .WithIconUrl(authorPhoto)); 331 | 332 | // Gift Amount 333 | eb.WithFields(new EmbedFieldBuilder[] { new EmbedFieldBuilder().WithName("Amount").WithValue(header?.primaryText?.runs?[1].text) }); 334 | 335 | // Gift Background Color 336 | eb.WithColor(_sponsorColor); 337 | 338 | // Gift Picture 339 | string? giftThumbUrl = header?.image?.thumbnails?.LastOrDefault()?.url; 340 | if (null != giftThumbUrl) eb.WithThumbnailUrl(giftThumbUrl); 341 | 342 | // Timestamp 343 | long timeStamp = long.TryParse(liveChatPurchaseSponsorshipsGift?.timestampUsec, out long l) ? l / 1000 : 0; 344 | EmbedFooterBuilder ft = new(); 345 | ft.WithText(DateTimeOffset.FromUnixTimeMilliseconds(timeStamp) 346 | .LocalDateTime 347 | .ToString("yyyy/MM/dd HH:mm:ss")) 348 | .WithIconUrl(_giftIcon); 349 | 350 | // From Stream Owner 351 | if (liveChatPurchaseSponsorshipsGift?.authorExternalChannelId == Environment.GetEnvironmentVariable("CHANNEL_ID")) 352 | { 353 | //eb.WithColor(_ownerColor); 354 | ft.WithIconUrl(_crownIcon); 355 | } 356 | 357 | eb.WithFooter(ft); 358 | return eb; 359 | } 360 | 361 | private static EmbedBuilder AppendLowerBumper(ref EmbedBuilder eb, LowerBumper? lowerBumper) 362 | => null == lowerBumper || null == lowerBumper.liveChatItemBumperViewModel?.content?.bumperUserEduContentViewModel 363 | ? eb 364 | : eb.WithFields(new EmbedFieldBuilder[] 365 | { 366 | new EmbedFieldBuilder().WithName("LowerBumper") 367 | .WithValue(lowerBumper.liveChatItemBumperViewModel.content.bumperUserEduContentViewModel?.text?.content) 368 | }); 369 | 370 | private async Task SendMessage(EmbedBuilder eb, string author, CancellationToken cancellationToken) 371 | { 372 | _logger.LogDebug("Sending Request to Discord: {author}: {message}", author, eb.Description); 373 | 374 | try 375 | { 376 | await _send(); 377 | } 378 | catch (TimeoutException) { } 379 | // System.Net.Http.HttpRequestException: Resource temporarily unavailable (discord.com:443) 380 | catch (HttpRequestException) 381 | { 382 | // Retry once after 5 sec 383 | await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); 384 | await _send(); 385 | } 386 | 387 | Task _send() 388 | => _client.SendMessageAsync(embeds: new Embed[] { eb.Build() }) 389 | .ContinueWith(p => 390 | { 391 | #pragma warning disable AsyncFixer02 // Long-running or blocking operations inside an async method 392 | ulong messageId = p.Result; 393 | #pragma warning restore AsyncFixer02 // Long-running or blocking operations inside an async method 394 | _logger.LogDebug("Message sent to discord, message id: {messageId}", messageId); 395 | }, cancellationToken); 396 | } 397 | } 398 | -------------------------------------------------------------------------------- /Services/LiveChatDownloadService.cs: -------------------------------------------------------------------------------- 1 | using YoutubeDLSharp; 2 | using YoutubeDLSharp.Options; 3 | 4 | namespace YoutubeLiveChatToDiscord.Services; 5 | 6 | public class LiveChatDownloadService 7 | { 8 | private readonly ILogger _logger; 9 | private readonly string _id; 10 | public Task downloadProcess = Task.FromResult(0); 11 | 12 | public LiveChatDownloadService(ILogger logger) 13 | { 14 | _logger = logger; 15 | _id = Environment.GetEnvironmentVariable("VIDEO_ID") ?? ""; 16 | if (string.IsNullOrEmpty(_id)) throw new ArgumentException(nameof(_id)); 17 | } 18 | 19 | public Task ExecuteAsync(CancellationToken stoppingToken) 20 | { 21 | downloadProcess = ExecuteAsyncInternal(stoppingToken); 22 | return downloadProcess; 23 | } 24 | 25 | private Task ExecuteAsyncInternal(CancellationToken stoppingToken) 26 | { 27 | OptionSet live_chatOptionSet = new() 28 | { 29 | IgnoreConfig = true, 30 | WriteSubs = true, 31 | SubLangs = "live_chat", 32 | SkipDownload = true, 33 | NoPart = true, 34 | NoContinue = true, 35 | Output = "%(id)s", 36 | IgnoreNoFormatsError = true 37 | }; 38 | 39 | OptionSet info_jsonOptionSet = new() 40 | { 41 | IgnoreConfig = true, 42 | WriteInfoJson = true, 43 | SkipDownload = true, 44 | NoPart = true, 45 | Output = "%(id)s", 46 | IgnoreNoFormatsError = true 47 | }; 48 | 49 | FileInfo cookies = new("cookies.txt"); 50 | if (cookies.Exists) 51 | { 52 | _logger.LogInformation("Detected {cookies}, use it for yt-dlp", cookies.FullName); 53 | var bak = cookies.CopyTo("cookies.copy.txt", true); 54 | live_chatOptionSet.Cookies = bak.FullName; 55 | info_jsonOptionSet.Cookies = bak.FullName; 56 | } 57 | 58 | YoutubeDLProcess ytdlProc = new(Helper.WhereIsYt_dlp()); 59 | ytdlProc.OutputReceived += (o, e) => _logger.LogTrace("{message}", e.Data); 60 | ytdlProc.ErrorReceived += (o, e) => _logger.LogError("{error}", e.Data); 61 | 62 | string url = $"https://www.youtube.com/watch?v={_id}"; 63 | _logger.LogInformation("Start yt-dlp with url: {url}", url); 64 | return ytdlProc.RunAsync(new string[] { url }, 65 | info_jsonOptionSet, 66 | stoppingToken) 67 | .ContinueWith((e) => ytdlProc.RunAsync(new string[] { url }, 68 | live_chatOptionSet, 69 | stoppingToken)) 70 | .Unwrap(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /YoutubeLiveChatToDiscord.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | net8.0 4 | enable 5 | enable 6 | dotnet-LiveChatToDiscord-ACE24696-7DD5-4164-8805-CF76B90CBA6C 7 | false 8 | true 9 | true 10 | true 11 | true 12 | true 13 | Linux 14 | . 15 | debug 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /YoutubeLiveChatToDiscord.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.32112.339 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "YoutubeLiveChatToDiscord", "YoutubeLiveChatToDiscord.csproj", "{FEDF1496-1E51-49BA-8C3B-FDD9856AECAC}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {FEDF1496-1E51-49BA-8C3B-FDD9856AECAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {FEDF1496-1E51-49BA-8C3B-FDD9856AECAC}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {FEDF1496-1E51-49BA-8C3B-FDD9856AECAC}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {FEDF1496-1E51-49BA-8C3B-FDD9856AECAC}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {46B345FA-6C68-4791-BF20-8D003B274F61} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "Microsoft.Hosting.Lifetime": "Information" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.Hosting.Lifetime": "Information" 6 | }, 7 | "Console": { 8 | "DisableColors": true, 9 | "FormatterOptions": { 10 | "SingleLine": true 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /assets/crown.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jim60105/YoutubeLiveChatToDiscord/97e48c13d0ab37ca741819c0ca21eb0c0ba1824e/assets/crown.png -------------------------------------------------------------------------------- /assets/gift.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jim60105/YoutubeLiveChatToDiscord/97e48c13d0ab37ca741819c0ca21eb0c0ba1824e/assets/gift.png -------------------------------------------------------------------------------- /assets/wallet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jim60105/YoutubeLiveChatToDiscord/97e48c13d0ab37ca741819c0ca21eb0c0ba1824e/assets/wallet.png -------------------------------------------------------------------------------- /docker-compose.override.yml: -------------------------------------------------------------------------------- 1 | # Override logging settings to LogServer 2 | version: "3.7" 3 | 4 | x-logging: 5 | &default-logging 6 | driver: "gelf" 7 | options: 8 | gelf-address: "udp://127.0.0.1:12201" 9 | 10 | services: 11 | youtubelivechattodiscord: 12 | logging: *default-logging 13 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.7" 2 | 3 | x-labels: 4 | labels: &default-label 5 | youtubelivechattodiscord: 6 | services: 7 | youtubelivechattodiscord: 8 | image: ghcr.io/jim60105/youtubelivechattodiscord 9 | # build: . 10 | labels: *default-label 11 | restart: on-failure:3 # yt-dlp is easyily to get stuck in a restart-failed loop during long-term downloads 12 | # volumes: 13 | # - ./appsettings.json:/app/appsettings.json 14 | # - ./cookies.txt:/app/cookies.txt 15 | # Youtube videoId, discord webhook url 16 | command: ["", ""] 17 | 18 | # Restart main container every hour. 19 | jobber: 20 | image: blacklabelops/jobber:docker 21 | restart: always 22 | volumes: 23 | - /var/run/docker.sock:/var/run/docker.sock:ro 24 | environment: 25 | - JOB_NAME1=start 26 | - JOB_COMMAND1=docker start $$(docker ps -aqf "label=youtubelivechattodiscord") 27 | - JOB_TIME1=0 0 * * * * #Every hour 28 | - JOB_NOTIFY_ERR1=false 29 | - JOB_NOTIFY_FAIL1=false 30 | -------------------------------------------------------------------------------- /helm-chart/.helmignore: -------------------------------------------------------------------------------- 1 | # Patterns to ignore when building packages. 2 | # This supports shell glob matching, relative path matching, and 3 | # negation (prefixed with !). Only one pattern per line. 4 | .DS_Store 5 | # Common VCS dirs 6 | .git/ 7 | .gitignore 8 | .bzr/ 9 | .bzrignore 10 | .hg/ 11 | .hgignore 12 | .svn/ 13 | # Common backup files 14 | *.swp 15 | *.bak 16 | *.tmp 17 | *.orig 18 | *~ 19 | # Various IDEs 20 | .project 21 | .idea/ 22 | *.tmproj 23 | .vscode/ 24 | -------------------------------------------------------------------------------- /helm-chart/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v2 2 | name: youtube-live-chat-to-discord 3 | description: Stream Youtube Chat to Discord Webhook 4 | # A chart can be either an 'application' or a 'library' chart. 5 | # 6 | # Application charts are a collection of templates that can be packaged into versioned archives 7 | # to be deployed. 8 | # 9 | # Library charts provide useful utilities or functions for the chart developer. They're included as 10 | # a dependency of application charts to inject those utilities and functions into the rendering 11 | # pipeline. Library charts do not define any templates and therefore cannot be deployed. 12 | type: application 13 | # This is the chart version. This version number should be incremented each time you make changes 14 | # to the chart and its templates, including the app version. 15 | # Versions are expected to follow Semantic Versioning (https://semver.org/) 16 | version: 0.1.0 17 | # This is the version number of the application being deployed. This version number should be 18 | # incremented each time you make changes to the application. Versions are not expected to 19 | # follow Semantic Versioning. They should reflect the version the application is using. 20 | # It is recommended to use it with quotes. 21 | appVersion: '0.1.0' 22 | -------------------------------------------------------------------------------- /helm-chart/templates/_helpers.tpl: -------------------------------------------------------------------------------- 1 | {{/* 2 | Expand the name of the chart. 3 | */}} 4 | {{- define "youtube-live-chat-to-discord.name" -}} 5 | {{- default $.Chart.Name $.Values.nameOverride | trunc 63 | trimSuffix "-" }} 6 | {{- end }} 7 | 8 | {{/* 9 | Create a default fully qualified app name. 10 | We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). 11 | If release name contains chart name it will be used as a full name. 12 | */}} 13 | {{- define "youtube-live-chat-to-discord.fullname" -}} 14 | {{- if $.Values.fullnameOverride }} 15 | {{- $.Values.fullnameOverride | trunc 63 | trimSuffix "-" }} 16 | {{- else }} 17 | {{- $name := default $.Chart.Name $.Values.nameOverride }} 18 | {{- if contains $name $.Release.Name }} 19 | {{- $.Release.Name | trunc 63 | trimSuffix "-" }} 20 | {{- else }} 21 | {{- printf "%s-%s" $.Release.Name $name | trunc 63 | trimSuffix "-" }} 22 | {{- end }} 23 | {{- end }} 24 | {{- end }} 25 | 26 | {{/* 27 | Create chart name and version as used by the chart label. 28 | */}} 29 | {{- define "youtube-live-chat-to-discord$.Chart" -}} 30 | {{- printf "%s-%s" $.Chart.Name $.Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} 31 | {{- end }} 32 | 33 | {{/* 34 | Common labels 35 | */}} 36 | {{- define "youtube-live-chat-to-discord.labels" -}} 37 | helm.sh/chart: {{ include "youtube-live-chat-to-discord$.Chart" . }} 38 | {{ include "youtube-live-chat-to-discord.selectorLabels" . }} 39 | {{- if $.Chart.AppVersion }} 40 | app.kubernetes.io/version: {{ $.Chart.AppVersion | quote }} 41 | {{- end }} 42 | app.kubernetes.io/managed-by: {{ $.Release.Service }} 43 | {{- end }} 44 | 45 | {{/* 46 | Selector labels 47 | */}} 48 | {{- define "youtube-live-chat-to-discord.selectorLabels" -}} 49 | app.kubernetes.io/name: {{ include "youtube-live-chat-to-discord.name" . }} 50 | app.kubernetes.io/instance: {{ $.Release.Name }} 51 | {{- end }} 52 | 53 | {{/* 54 | Create the name of the service account to use 55 | */}} 56 | {{- define "youtube-live-chat-to-discord.serviceAccountName" -}} 57 | {{- if $.Values.serviceAccount.create }} 58 | {{- default (include "youtube-live-chat-to-discord.fullname" .) $.Values.serviceAccount.name }} 59 | {{- else }} 60 | {{- default "default" $.Values.serviceAccount.name }} 61 | {{- end }} 62 | {{- end }} 63 | -------------------------------------------------------------------------------- /helm-chart/templates/configMap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: {{ include "youtube-live-chat-to-discord.fullname" $ }}-cookies 5 | data: 6 | cookies.txt: {{- .Values.cookies | toYaml | indent 1 }} 7 | -------------------------------------------------------------------------------- /helm-chart/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | {{- range .Values.deployments }} 2 | --- 3 | apiVersion: apps/v1 4 | kind: Deployment 5 | metadata: 6 | name: {{ include "youtube-live-chat-to-discord.fullname" $ }}-{{ .name }} 7 | labels: 8 | {{- include "youtube-live-chat-to-discord.labels" $ | nindent 4 }} 9 | spec: 10 | replicas: 1 11 | selector: 12 | matchLabels: 13 | app: {{ .name }} 14 | {{- include "youtube-live-chat-to-discord.selectorLabels" $ | nindent 6 }} 15 | template: 16 | metadata: 17 | labels: 18 | app: {{ .name }} 19 | {{- include "youtube-live-chat-to-discord.selectorLabels" $ | nindent 8 }} 20 | spec: 21 | restartPolicy: Always 22 | securityContext: 23 | runAsNonRoot: true 24 | containers: 25 | - name: {{ .name }} 26 | args: 27 | - {{ quote .youtubeId }} 28 | - {{ quote .discordWebhook }} 29 | env: 30 | - name: KUBERNETES_CLUSTER_DOMAIN 31 | value: {{ quote $.Values.kubernetesClusterDomain }} 32 | - name: Logging__LogLevel__Default 33 | value: Debug 34 | image: ghcr.io/jim60105/youtubelivechattodiscord:latest 35 | resources: 36 | limits: 37 | memory: "512Mi" 38 | cpu: "100m" 39 | requests: 40 | memory: "256Mi" 41 | cpu: "50m" 42 | securityContext: 43 | allowPrivilegeEscalation: false 44 | capabilities: 45 | drop: ["ALL"] 46 | seccompProfile: 47 | type: "RuntimeDefault" 48 | runAsUser: 1654 49 | runAsGroup: 1654 50 | {{- if .useCookies }} 51 | volumeMounts: 52 | - mountPath: /app/cookies.txt 53 | name: cookies 54 | subPath: cookies.txt 55 | volumes: 56 | - name: cookies 57 | configMap: 58 | name: {{ include "youtube-live-chat-to-discord.fullname" $ }}-cookies 59 | {{- end }} 60 | {{- end }} -------------------------------------------------------------------------------- /helm-chart/values.yaml: -------------------------------------------------------------------------------- 1 | deployments: 2 | - name: demo1 3 | youtubeId: dHT1kFn96G0 4 | discordWebhook: https://discord.com/api/webhooks/9000000000000/OOXXOOXX 5 | useCookies: false 6 | 7 | cookies: | 8 | # Netscape HTTP Cookie File 9 | # http://curl.haxx.se/rfc/cookie_spec.html 10 | # This is a generated file! Do not edit. 11 | .youtube.com TRUE / FALSE 1703311569 HSID AAAABBBBCCCCSSSSS 12 | .youtube.com TRUE / TRUE 1703311569 SSID HHHHJJJJJKKKKLLLL 13 | 14 | kubernetesClusterDomain: cluster.local --------------------------------------------------------------------------------