38 Commits

Author SHA1 Message Date
897d4f2860 Update Rust crate sqlx to 0.8
Some checks failed
tests / fmt (push) Successful in 52s
tests / build (push) Successful in 1m33s
tests / test (push) Failing after 1m34s
tests / clippy (push) Successful in 1m21s
tests / pre-commit (push) Successful in 1m21s
2025-03-04 10:45:20 +00:00
b60cce35ca Merge branch 'main' of gitea:jheuel/ohrwurm
All checks were successful
tests / fmt (push) Successful in 1m9s
tests / build (push) Successful in 1m35s
tests / clippy (push) Successful in 1m26s
tests / pre-commit (push) Successful in 1m34s
deploy / release-image (push) Successful in 4m0s
tests / test (push) Successful in 1m19s
renovate / renovate (push) Successful in 54s
2025-03-04 11:44:05 +01:00
9f1ed63011 enable renovate automerge 2025-03-04 11:44:00 +01:00
6096e625a2 Merge pull request 'Update Rust crate tokio to v1.43.0' (#21) from renovate/tokio-1.x-lockfile into main
Some checks are pending
tests / fmt (push) Waiting to run
tests / build (push) Waiting to run
tests / test (push) Waiting to run
tests / clippy (push) Waiting to run
tests / pre-commit (push) Waiting to run
deploy / release-image (push) Waiting to run
renovate / renovate (push) Successful in 31s
Reviewed-on: #21
2025-03-04 11:39:12 +01:00
5c42fb9480 Update Rust crate tokio to v1.43.0
All checks were successful
tests / fmt (push) Successful in 1m18s
tests / clippy (push) Successful in 1m25s
tests / build (push) Successful in 1m43s
tests / test (push) Successful in 1m48s
tests / pre-commit (push) Successful in 1m4s
2025-03-04 10:27:46 +00:00
d1df70a888 disable automerge
Some checks failed
renovate / renovate (push) Successful in 31s
tests / fmt (push) Successful in 1m18s
tests / build (push) Successful in 1m17s
tests / clippy (push) Successful in 46s
tests / test (push) Successful in 1m10s
tests / pre-commit (push) Has been cancelled
deploy / release-image (push) Has been cancelled
2025-03-04 11:27:16 +01:00
c4bc5503a5 Update jheuel/ohrwurm:latest Docker digest to b5e0fbc
Some checks are pending
tests / fmt (push) Waiting to run
tests / build (push) Waiting to run
tests / test (push) Waiting to run
tests / clippy (push) Waiting to run
tests / pre-commit (push) Waiting to run
deploy / release-image (push) Waiting to run
renovate / renovate (push) Waiting to run
2025-03-04 10:02:01 +00:00
16f6c97eec Update Rust crate async-trait to v0.1.87
Some checks failed
renovate / renovate (push) Successful in 33s
tests / fmt (push) Successful in 1m11s
tests / build (push) Successful in 1m3s
tests / pre-commit (push) Failing after 1m52s
tests / clippy (push) Successful in 2m7s
tests / test (push) Successful in 2m36s
deploy / release-image (push) Successful in 3m59s
2025-03-04 07:25:52 +00:00
cd42401280 Update rust:slim-bullseye Docker digest to e94e2d2
All checks were successful
renovate / renovate (push) Successful in 33s
tests / fmt (push) Successful in 54s
tests / build (push) Successful in 50s
tests / test (push) Successful in 1m32s
tests / pre-commit (push) Successful in 1m50s
tests / clippy (push) Successful in 2m9s
deploy / release-image (push) Successful in 3m57s
2025-03-04 06:47:43 +00:00
cc0af054f8 Update Rust crate anyhow to v1.0.97
Some checks failed
renovate / renovate (push) Successful in 1m36s
tests / fmt (push) Successful in 1m12s
tests / build (push) Successful in 1m12s
tests / test (push) Successful in 52s
deploy / release-image (push) Failing after 11m45s
tests / pre-commit (push) Failing after 11m47s
tests / clippy (push) Failing after 11m56s
2025-03-03 13:38:02 +00:00
aff5e1dd8d Merge pull request 'Pin dependencies' (#9) from renovate/pin-dependencies into main
All checks were successful
tests / fmt (push) Successful in 35s
tests / clippy (push) Successful in 56s
tests / build (push) Successful in 1m6s
tests / test (push) Successful in 1m11s
tests / pre-commit (push) Successful in 42s
deploy / release-image (push) Successful in 4m13s
renovate / renovate (push) Successful in 1m55s
Reviewed-on: #9
2025-03-03 14:37:03 +01:00
ed9956c5a5 Pin dependencies
All checks were successful
tests / fmt (push) Successful in 2m51s
tests / build (push) Successful in 2m18s
tests / test (push) Successful in 1m54s
tests / clippy (push) Successful in 1m6s
tests / pre-commit (push) Successful in 1m7s
2025-03-03 13:32:53 +00:00
456a51bc70 add renovate
Some checks failed
renovate / renovate (push) Successful in 1m30s
tests / fmt (push) Successful in 2m5s
tests / clippy (push) Successful in 2m30s
tests / build (push) Successful in 2m36s
tests / test (push) Successful in 3m12s
tests / pre-commit (push) Successful in 1m34s
deploy / release-image (push) Has been cancelled
2025-03-03 14:31:29 +01:00
b9b3709bb4 disable arm64 platform
All checks were successful
tests / fmt (push) Successful in 2m2s
tests / pre-commit (push) Successful in 2m8s
tests / clippy (push) Successful in 2m14s
tests / test (push) Successful in 2m32s
tests / build (push) Successful in 2m58s
deploy / release-image (push) Successful in 4m3s
2024-11-28 20:14:37 +01:00
27168c36cf fix clippy warnings
Some checks failed
tests / clippy (push) Successful in 2m35s
tests / pre-commit (push) Successful in 2m43s
tests / fmt (push) Successful in 2m54s
tests / test (push) Successful in 2m54s
tests / build (push) Successful in 3m27s
deploy / release-image (push) Has been cancelled
2024-11-28 19:26:42 +01:00
88d9c1d841 Merge branch 'main' of gitea:jheuel/ohrwurm
Some checks failed
tests / fmt (push) Successful in 1m56s
tests / build (push) Successful in 3m38s
tests / clippy (push) Failing after 3m51s
tests / pre-commit (push) Successful in 3m52s
tests / test (push) Successful in 4m5s
deploy / release-image (push) Has been cancelled
2024-11-28 19:17:29 +01:00
d3a4114347 add arm64 platform 2024-11-28 19:16:14 +01:00
a3e9175ea8 remove ffmpeg
Some checks failed
tests / test (push) Failing after 1m55s
tests / pre-commit (push) Failing after 3m33s
tests / fmt (push) Successful in 7m33s
tests / build (push) Successful in 8m15s
tests / clippy (push) Successful in 8m19s
deploy / release-image (push) Successful in 11m24s
2024-11-27 13:30:29 +01:00
6601396a88 Merge branch 'main' of gitea:jheuel/ohrwurm 2024-11-27 12:35:34 +01:00
687f110416 add query logging 2024-11-27 12:35:24 +01:00
9146ac06a6 add docker-compose.yml
All checks were successful
tests / fmt (push) Successful in 45s
tests / build (push) Successful in 1m11s
tests / clippy (push) Successful in 2m22s
tests / pre-commit (push) Successful in 2m30s
tests / test (push) Successful in 2m43s
deploy / release-image (push) Successful in 5m16s
2024-11-26 21:52:22 +01:00
a25e8ef65f update dependencies
All checks were successful
tests / fmt (push) Successful in 1m3s
tests / build (push) Successful in 3m17s
tests / clippy (push) Successful in 3m54s
tests / test (push) Successful in 4m16s
tests / pre-commit (push) Successful in 5m39s
deploy / release-image (push) Successful in 7m57s
2024-11-26 19:55:49 +01:00
f0337050c1 add error context
All checks were successful
tests / fmt (push) Successful in 36s
tests / build (push) Successful in 2m3s
tests / test (push) Successful in 57s
tests / clippy (push) Successful in 39s
tests / pre-commit (push) Successful in 44s
deploy / release-image (push) Successful in 4m46s
2024-08-09 14:02:42 +02:00
440201e153 fix warning while persisting tracks
All checks were successful
tests / fmt (push) Successful in 36s
tests / build (push) Successful in 2m3s
tests / test (push) Successful in 55s
tests / clippy (push) Successful in 41s
tests / pre-commit (push) Successful in 2m40s
deploy / release-image (push) Successful in 7m2s
2024-08-09 11:18:38 +02:00
f7dca8ff65 improve error handling on play command
All checks were successful
tests / fmt (push) Successful in 1m56s
tests / test (push) Successful in 2m51s
tests / clippy (push) Successful in 2m39s
tests / build (push) Successful in 3m25s
tests / pre-commit (push) Successful in 3m55s
deploy / release-image (push) Successful in 8m5s
2024-08-08 18:04:36 +02:00
1e523502eb add timeouts to http requests
All checks were successful
tests / fmt (push) Successful in 2m5s
tests / clippy (push) Successful in 2m29s
tests / pre-commit (push) Successful in 2m33s
tests / test (push) Successful in 2m44s
tests / build (push) Successful in 2m54s
deploy / release-image (push) Successful in 9m8s
2024-07-04 21:31:40 +02:00
dfd0f9c8c8 cleanup
All checks were successful
tests / build (push) Successful in 1m15s
tests / fmt (push) Successful in 1m44s
tests / clippy (push) Successful in 1m57s
tests / pre-commit (push) Successful in 2m8s
tests / test (push) Successful in 2m19s
deploy / release-image (push) Successful in 5m6s
2024-06-30 11:16:12 +02:00
3242f23f84 play around with input types
All checks were successful
tests / fmt (push) Successful in 1m11s
tests / clippy (push) Successful in 2m24s
tests / pre-commit (push) Successful in 2m23s
tests / build (push) Successful in 2m36s
tests / test (push) Successful in 2m40s
2024-06-27 19:59:15 +02:00
8985945659 add database
All checks were successful
tests / fmt (push) Successful in 1m46s
tests / clippy (push) Successful in 1m48s
tests / test (push) Successful in 1m50s
tests / pre-commit (push) Successful in 2m5s
tests / build (push) Successful in 2m31s
deploy / release-image (push) Successful in 5m44s
2024-06-20 20:16:19 +02:00
4a69e0f578 cleanup
All checks were successful
tests / build (push) Successful in 1m4s
tests / fmt (push) Successful in 2m17s
tests / clippy (push) Successful in 2m14s
tests / pre-commit (push) Successful in 2m12s
tests / test (push) Successful in 2m27s
deploy / release-image (push) Successful in 6m11s
2024-06-19 19:14:44 +02:00
cad6cf22fa fix empty pages
All checks were successful
tests / fmt (push) Successful in 1m16s
tests / build (push) Successful in 1m54s
tests / clippy (push) Successful in 1m50s
tests / pre-commit (push) Successful in 1m50s
tests / test (push) Successful in 2m13s
deploy / release-image (push) Successful in 5m34s
2024-06-19 00:24:32 +02:00
9f0e934f92 use original_url returned by yt-dlp
All checks were successful
tests / build (push) Successful in 56s
tests / test (push) Successful in 3m4s
tests / fmt (push) Successful in 3m28s
tests / clippy (push) Successful in 3m55s
tests / pre-commit (push) Successful in 3m58s
deploy / release-image (push) Successful in 6m0s
2024-06-18 23:38:37 +02:00
92be6c26a6 fix pagination + add refresh button
All checks were successful
tests / fmt (push) Successful in 1m57s
tests / test (push) Successful in 2m7s
tests / clippy (push) Successful in 2m5s
tests / build (push) Successful in 2m11s
tests / pre-commit (push) Successful in 2m5s
deploy / release-image (push) Successful in 5m3s
2024-06-18 23:27:47 +02:00
c5d9c49452 improve message format
All checks were successful
tests / fmt (push) Successful in 1m50s
tests / test (push) Successful in 2m1s
tests / clippy (push) Successful in 1m59s
tests / pre-commit (push) Successful in 1m58s
tests / build (push) Successful in 2m7s
deploy / release-image (push) Successful in 5m22s
2024-06-18 17:06:33 +02:00
dbaf1a1374 reset loop state on leave/stop 2024-06-18 15:49:58 +02:00
c0d9f6cad5 update README.md
All checks were successful
tests / fmt (push) Successful in 36s
tests / build (push) Successful in 46s
tests / test (push) Successful in 54s
tests / clippy (push) Successful in 1m45s
tests / pre-commit (push) Successful in 1m52s
deploy / release-image (push) Successful in 6m23s
2024-06-18 11:51:28 +02:00
1aa0efc4a6 collect all youtube errors
All checks were successful
tests / fmt (push) Successful in 33s
tests / build (push) Successful in 45s
tests / test (push) Successful in 2m20s
tests / clippy (push) Successful in 51s
tests / pre-commit (push) Successful in 53s
deploy / release-image (push) Successful in 4m48s
2024-06-18 11:26:52 +02:00
ab7f56fe05 disable arm target (#8)
All checks were successful
tests / test (push) Successful in 1m27s
tests / clippy (push) Successful in 1m32s
tests / pre-commit (push) Successful in 1m33s
tests / fmt (push) Successful in 1m43s
tests / build (push) Successful in 1m42s
deploy / release-image (push) Successful in 4m34s
Reviewed-on: #8
2024-06-18 11:19:44 +02:00
28 changed files with 2213 additions and 646 deletions

View File

@@ -12,3 +12,6 @@ README.md
# Cargo files
**/*.rs.bk
/target/
# Database files
data

View File

@@ -13,47 +13,47 @@ jobs:
fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions-rust-lang/setup-rust-toolchain@v1
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
with:
components: rustfmt
- name: Rustfmt Check
uses: actions-rust-lang/rustfmt@v1
uses: actions-rust-lang/rustfmt@559aa3035a47390ba96088dffa783b5d26da9326 # v1
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions-rust-lang/setup-rust-toolchain@v1
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
- name: Build
run: cargo build --verbose
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions/setup-python@v5
- uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5
with:
python-version: '3.12'
- name: Install yt-dlp
run: pip install yt-dlp
- uses: actions-rust-lang/setup-rust-toolchain@v1
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
- name: Run tests
run: cargo test --verbose --all-features
clippy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions-rust-lang/setup-rust-toolchain@v1
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
with:
components: clippy
- name: Run clippy
@@ -62,13 +62,13 @@ jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions/setup-python@v5
- uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5
with:
python-version: '3.12'
- uses: actions-rust-lang/setup-rust-toolchain@v1
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
with:
components: rustfmt
- uses: pre-commit/action@v3.0.1
- uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1

View File

@@ -5,27 +5,29 @@ on:
branches:
- main
paths-ignore:
- 'README.md'
jobs:
release-image:
runs-on: ubuntu-latest
steps:
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3
- name: Set up Docker BuildX
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3
- name: Login to DockerHub
uses: docker/login-action@v3
uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 # v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push
uses: docker/build-push-action@v5
uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5
with:
platforms: |
linux/amd64
# linux/arm64
push: true
tags: jheuel/ohrwurm:latest

View File

@@ -0,0 +1,32 @@
---
# yamllint disable rule:line-length
name: renovate
on: # yamllint disable-line rule:truthy
schedule:
- cron: "@daily"
push:
branches:
- main
jobs:
renovate:
runs-on: [nas]
steps:
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Self-hosted Renovate
uses: renovatebot/github-action@02f4fdeb479bbb229caa7ad82cb5e691c07e80b3 # v41.0.14
with:
token: ${{ secrets.RENOVATE_TOKEN }}
env-regex: "^(?:RENOVATE_\\w+|LOG_LEVEL|GITHUB_COM_TOKEN)$"
env:
LOG_LEVEL: "info"
GITHUB_COM_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
RENOVATE_PLATFORM: "gitea"
RENOVATE_GIT_AUTHOR: "Renovate Bot <renovate@boosted.science>"
RENOVATE_GIT_EMAIL: "renovate@boosted.science"
RENOVATE_ENDPOINT: "https://gitea.jheuel.boosted.science/api/v1/"
RENOVATE_AUTODISCOVER: "true"
RENOVATE_OPTIMIZE_FOR_DISABLED: "true"

View File

@@ -12,47 +12,47 @@ jobs:
fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions-rust-lang/setup-rust-toolchain@v1
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
with:
components: rustfmt
- name: Rustfmt Check
uses: actions-rust-lang/rustfmt@v1
uses: actions-rust-lang/rustfmt@559aa3035a47390ba96088dffa783b5d26da9326 # v1
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions-rust-lang/setup-rust-toolchain@v1
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
- name: Build
run: cargo build --verbose
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions/setup-python@v5
- uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5
with:
python-version: '3.12'
- name: Install yt-dlp
run: pip install yt-dlp
- uses: actions-rust-lang/setup-rust-toolchain@v1
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
- name: Run tests
run: cargo test --verbose --all-features
clippy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions-rust-lang/setup-rust-toolchain@v1
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
with:
components: clippy
- name: Run clippy
@@ -61,13 +61,13 @@ jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- run: sudo apt-get update
- run: sudo apt-get install -y cmake
- uses: actions/setup-python@v5
- uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5
with:
python-version: '3.12'
- uses: actions-rust-lang/setup-rust-toolchain@v1
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
with:
components: rustfmt
- uses: pre-commit/action@v3.0.1
- uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1

3
.gitignore vendored
View File

@@ -1,3 +1,6 @@
/target
.env
.vscode
# Database files
data

1626
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,9 +6,10 @@ edition = "2021"
license = "MIT"
[dependencies]
symphonia = { version = "0.5.2", features=["all"] }
symphonia = { version = "0.5.2", features=["all", "opt-simd"] }
songbird = { version = "0.4.0", features = ["driver", "gateway", "twilight", "rustls", "builtin-queue"] }
tokio = { features = ["macros", "rt-multi-thread", "signal", "sync"], version = "1" }
sqlx = { version = "0.8", features = [ "runtime-tokio", "sqlite", "chrono", "migrate"] }
regex = { version = "1", features = ["unicode-case"] }
futures = "0.3"
reqwest = "0.11"
@@ -23,8 +24,9 @@ twilight-util = { version = "0.15", features=["builder"] }
dotenv = "0.15.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
url = "2.5.0"
url = "2.5.1"
anyhow = "1.0.86"
dashmap = "5.5.3"
async-trait = "0.1.80"
uuid = "1.8.0"
chrono = "0.4.38"

View File

@@ -1,5 +1,5 @@
# Build image
FROM rust:slim-bullseye as build
FROM rust:slim-bullseye@sha256:e94e2d2e0a9df48fdfcacb47d8b60d036abe60b7c6fa3ac3de1dd16a3d18f19a as build
RUN apt-get update && apt-get install -y \
build-essential autoconf automake cmake libtool libssl-dev pkg-config
@@ -18,9 +18,9 @@ RUN touch src/main.rs
RUN cargo build --release --locked
# Release image
FROM debian:bullseye-slim
FROM debian:bullseye-slim@sha256:33b7c2e071c29e618182ec872c471f39d2dde3d8904d95f5b7a61acf3a592e7b
RUN apt-get update && apt-get install -y python3-pip ffmpeg
RUN apt-get update && apt-get install -y python3-pip
RUN pip install -U yt-dlp
COPY --from=build /app/target/release/ohrwurm .

View File

@@ -8,7 +8,7 @@
Ohrwurm is a user-friendly bot designed to play music in Discord voice chats. Once added to your server, you can request a song using the command `/play {query}`, where query can be a URL to a YouTube video or playlist, or a simple search term. The bot will fetch the song and start playing it. You can pause the music with `/pause`, resume playback with `/resume`, and stop and clear the queue with `/stop`. If the bot is alone in a voice chat, it will automatically leave, but you can also manually make it leave with the `/leave` command.
# Deployment
To deploy Ohrwurm with Docker, you can use the [provided Docker](https://hub.docker.com/r/jheuel/ohrwurm) image:
To deploy Ohrwurm with Docker, you can use the [provided Docker image](https://hub.docker.com/r/jheuel/ohrwurm):
```bash
docker run -d \
--name ohrwurm \

3
build.rs Normal file
View File

@@ -0,0 +1,3 @@
fn main() {
println!("cargo:rerun-if-changed=migrations");
}

10
docker-compose.yml Normal file
View File

@@ -0,0 +1,10 @@
services:
ohrwurm:
container_name: ohrwurm
image: jheuel/ohrwurm:latest@sha256:b5e0fbc40ed86820eba8673bb5a97ad6ce53f27a1c557e46515cabce35199296
# build: .
restart: unless-stopped
volumes:
- ./data:/data
env_file:
- .env

View File

@@ -0,0 +1,33 @@
CREATE TABLE IF NOT EXISTS tracks
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
channel TEXT NOT NULL,
duration TEXT NOT NULL,
thumbnail TEXT NOT NULL,
updated DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS queries
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
guild_id TEXT NOT NULL,
track_id NUMBER NOT NULL,
updated DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS users
(
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
global_name TEXT,
updated DATETIME NOT NULL
);
CREATE TABLE IF NOT EXISTS guilds
(
id TEXT PRIMARY KEY,
updated DATETIME NOT NULL
);

25
renovate.json Normal file
View File

@@ -0,0 +1,25 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"timezone": "Europe/Berlin",
"extends": [
"config:recommended",
"helpers:pinGitHubActionDigests",
":configMigration",
":pinDevDependencies",
":dependencyDashboard",
"docker:pinDigests",
"preview:dockerCompose",
"preview:dockerVersions"
],
"packageRules": [
{
"matchUpdateTypes": [
"minor",
"patch",
"pin",
"digest"
],
"automerge": true
}
]
}

View File

@@ -1,4 +1,5 @@
use crate::state::State;
use anyhow::Context;
use std::error::Error;
use tracing::debug;
use twilight_model::{
@@ -22,7 +23,7 @@ pub(crate) async fn join_channel(
let channel_id = state
.cache
.voice_state(user_id, guild_id)
.ok_or("Cannot get voice state for user")?
.context("Could not get voice state for user")?
.channel_id();
// join the voice channel
@@ -30,14 +31,17 @@ pub(crate) async fn join_channel(
.songbird
.join(guild_id.cast(), channel_id)
.await
.map_err(|e| format!("Could not join voice channel: {:?}", e))?;
.context("Could not join voice channel")?;
// signal that we are not listening
if let Some(call_lock) = state.songbird.get(guild_id.cast()) {
let mut call = call_lock.lock().await;
call.deafen(true).await?;
call.deafen(true).await.context("Could not deafen")?;
}
// create guild config
state.guild_settings.entry(guild_id).or_default();
Ok(())
}

View File

@@ -1,6 +1,56 @@
use crate::state::State;
use std::error::Error;
use twilight_model::gateway::payload::incoming::InteractionCreate;
use crate::state::{State, StateRef};
use anyhow::Context;
use std::{error::Error, sync::Arc};
use twilight_model::{
gateway::payload::incoming::InteractionCreate,
id::{marker::GuildMarker, Id},
};
pub(crate) async fn leave_if_alone(
guild_id: Id<GuildMarker>,
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let user = state
.cache
.current_user()
.context("Cannot get current user")?;
let user_voice_state = state
.cache
.voice_state(user.id, guild_id)
.context("Cannot get voice state")?;
let channel = state
.cache
.channel(user_voice_state.channel_id())
.context("Cannot get channel")?;
let channel_voice_states = state
.cache
.voice_channel_states(channel.id)
.context("Cannot get voice channel")?;
let count = channel_voice_states.count();
// count is 1 if the bot is the only one in the channel
if count == 1 {
leave_channel(guild_id, Arc::clone(&state)).await?;
}
Ok(())
}
pub(crate) async fn leave_channel(
guild_id: Id<GuildMarker>,
state: Arc<StateRef>,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
// stop playing
if let Some(call_lock) = state.songbird.get(guild_id) {
let call = call_lock.lock().await;
call.queue().stop();
}
// leave the voice channel
state.songbird.leave(guild_id).await?;
// reset guild settings
state.guild_settings.remove(&guild_id);
Ok(())
}
pub(crate) async fn leave(
interaction: Box<InteractionCreate>,
@@ -16,6 +66,8 @@ pub(crate) async fn leave(
let Some(guild_id) = interaction.guild_id else {
return Ok(());
};
state.songbird.leave(guild_id).await?;
leave_channel(guild_id, Arc::clone(&state)).await?;
Ok(())
}

View File

@@ -1,5 +1,5 @@
use crate::metadata::MetadataMap;
use crate::state::{Settings, State, StateRef};
use crate::state::{State, StateRef};
use async_trait::async_trait;
use songbird::{Event, EventContext, EventHandler, TrackEvent};
use std::ops::Sub;
@@ -29,14 +29,8 @@ pub(crate) async fn loop_queue(
return Ok(());
};
state
.guild_settings
.entry(guild_id)
.or_insert_with(|| Settings { loop_queue: false });
state.guild_settings.entry(guild_id).and_modify(|settings| {
settings.loop_queue = !settings.loop_queue;
println!("loop_queue: {}", settings.loop_queue);
});
let looping = state

View File

@@ -3,6 +3,7 @@ pub(crate) use join::join;
mod leave;
pub(crate) use leave::leave;
pub(crate) use leave::leave_if_alone;
mod pause;
pub(crate) use pause::pause;

View File

@@ -1,23 +1,39 @@
use crate::colors;
use crate::commands::join::join_channel;
use crate::metadata::{Metadata, MetadataMap};
use crate::state::State;
use crate::{colors, db};
use anyhow::Context;
use serde::{Deserialize, Serialize};
use songbird::input::{Compose, YoutubeDl};
use songbird::tracks::Track;
use std::io::{BufRead, BufReader};
use std::ops::Sub;
use std::sync::Arc;
use std::{error::Error, time::Duration};
use std::{
io::{BufRead, BufReader},
ops::Sub,
};
use tokio::process::Command;
use tracing::debug;
use twilight_model::channel::message::MessageFlags;
use twilight_model::channel::message::embed::{
EmbedAuthor, EmbedField, EmbedFooter, EmbedThumbnail,
};
use twilight_model::channel::message::{Embed, MessageFlags};
use twilight_model::gateway::payload::incoming::InteractionCreate;
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
use twilight_util::builder::embed::EmbedBuilder;
use twilight_util::builder::InteractionResponseDataBuilder;
use url::Url;
#[derive(Debug)]
struct TrackType {
url: String,
title: Option<String>,
duration_string: String,
channel: String,
thumbnail: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
struct YouTubeTrack {
url: Option<String>,
@@ -27,6 +43,7 @@ struct YouTubeTrack {
playlist: Option<String>,
playlist_id: Option<String>,
duration_string: String,
thumbnail: Option<String>,
}
fn build_playlist_url(playlist_id: &str) -> String {
@@ -41,12 +58,18 @@ async fn get_tracks(
.output()
.await?;
tracing::info!(
"yt-dlp output: {:?}",
String::from_utf8_lossy(&output.stdout)
);
let reader = BufReader::new(output.stdout.as_slice());
let tracks: Vec<YouTubeTrack> = reader
.lines()
.map_while(Result::ok)
.flat_map(|line| serde_json::from_str(&line))
.collect();
tracing::info!("yt-dlp tracks: {:?}", tracks);
if tracks.is_empty() {
if let Ok(stderr) = String::from_utf8(output.stderr) {
@@ -59,22 +82,210 @@ async fn get_tracks(
}
return Err("No tracks found".into());
}
tracing::debug!("tracks: {:?}", tracks);
tracing::info!("tracks: {:?}", tracks);
Ok(tracks)
}
async fn persistence(
interaction: &InteractionCreate,
track: &YouTubeTrack,
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let Some(guild_id) = interaction.guild_id else {
return Ok(());
};
let Some(user_id) = interaction.author_id() else {
return Ok(());
};
let url = track
.original_url
.clone()
.or(track.url.clone())
.ok_or("Could not find url")?;
let (author_name, author_global_name) = if let Some(author) = interaction.author() {
(author.name.clone(), author.global_name.clone())
} else {
("".to_string(), None)
};
db::track::insert_guild(&state.pool, db::track::Guild::new(guild_id.to_string()))
.await
.context("failed to insert guild")?;
db::track::insert_user(
&state.pool,
db::track::User::new(user_id.to_string(), author_name, author_global_name),
)
.await
.context("failed to insert user")?;
let track_id = db::track::insert_track(
&state.pool,
db::track::Track::new(
url.clone(),
track.title.clone(),
track.channel.clone(),
track.duration_string.clone(),
track.thumbnail.clone().unwrap_or_default(),
),
)
.await
.context("failed to insert track")?;
db::track::insert_query(
&state.pool,
db::track::Query::new(user_id.to_string(), guild_id.to_string(), track_id),
)
.await
.context("failed to insert query")?;
Ok(())
}
fn build_single_track_added_embeds(tracks_added: &[TrackType]) -> Vec<Embed> {
let track = tracks_added.first().unwrap();
let host = if let Ok(host) = Url::parse(&track.url) {
Some(
host.host_str()
.unwrap_or_default()
.trim_start_matches("www.")
.to_string(),
)
} else {
None
};
let footer = match host {
Some(host) => EmbedFooter {
text: format!("Streaming from {}", host),
icon_url: Some(format!(
"https://www.google.com/s2/favicons?domain={}",
host
)),
proxy_icon_url: None,
},
None => EmbedFooter {
text: String::new(),
icon_url: None,
proxy_icon_url: None,
},
};
let mut embed = EmbedBuilder::new()
.author(EmbedAuthor {
name: "🔊 Added to queue".to_string(),
icon_url: None,
proxy_icon_url: None,
url: None,
})
.title(track.title.clone().unwrap_or("Unknown".to_string()))
.url(track.url.clone())
.color(colors::BLURPLE)
.footer(footer)
.field(EmbedField {
inline: true,
name: "Duration".to_string(),
value: track.duration_string.clone(),
})
.field(EmbedField {
inline: true,
name: "Channel".to_string(),
value: track.channel.clone(),
})
.build();
if let Some(thumbnail) = &track.thumbnail {
embed.thumbnail = Some(EmbedThumbnail {
height: None,
proxy_url: None,
url: thumbnail.to_string(),
width: None,
});
}
vec![embed]
}
fn build_playlist_added_embeds(tracks: &[YouTubeTrack], num_tracks_added: usize) -> Vec<Embed> {
let mut content = String::new();
let first_track = tracks.first().unwrap();
content.push_str(&format!(
"Adding playlist: [{}]({})\n",
&first_track
.playlist
.clone()
.unwrap_or("Unknown".to_string()),
build_playlist_url(
&first_track
.playlist_id
.clone()
.unwrap_or("Unknown".to_string())
)
));
content.push_str(&format!(
"Added {} tracks to the queue.\n",
num_tracks_added
));
let embed = EmbedBuilder::new()
.description(content)
.color(colors::BLURPLE)
.build();
vec![embed]
}
fn build_embeds(tracks: &[YouTubeTrack], tracks_added: &[TrackType]) -> Vec<Embed> {
let num_tracks_added = tracks_added.len();
match num_tracks_added {
0 => vec![],
1 => build_single_track_added_embeds(tracks_added),
_ => build_playlist_added_embeds(tracks, num_tracks_added),
}
}
pub(crate) async fn play(
interaction: Box<InteractionCreate>,
state: State,
query: String,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
debug!(
tracing::info!(
"play command in channel {:?} by {:?}",
interaction.channel,
interaction.author(),
);
match play_inner(&interaction, Arc::clone(&state), query).await {
Ok(_) => Ok(()),
Err(e) => {
tracing::debug!("Search did not result in any tracks: {}", e);
let content = "Search did not result in any tracks.".to_string();
let embeds = vec![EmbedBuilder::new()
.description(content)
.color(colors::RED)
.build()];
state
.http
.interaction(interaction.application_id)
.update_response(&interaction.token)
.embeds(Some(&embeds))?
.await?;
Ok(())
}
}
}
pub(crate) async fn play_inner(
interaction: &InteractionCreate,
state: State,
query: String,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing::info!(
"play_inner in channel {:?} by {:?}",
interaction.channel,
interaction.author(),
);
let content = format!("Adding track(s) to the queue: {}", query);
tracing::info!("content: {:?}", content);
let embeds = vec![EmbedBuilder::new()
.description(content)
.color(colors::YELLOW)
@@ -109,25 +320,10 @@ pub(crate) async fn play(
query
};
debug!("query: {:?}", query);
tracing::info!("query: {:?}", query);
let tracks = match get_tracks(query).await {
Err(e) => {
let content = format!("{}", e);
let embeds = vec![EmbedBuilder::new()
.description(content)
.color(colors::RED)
.build()];
state
.http
.interaction(interaction.application_id)
.update_response(&interaction.token)
.embeds(Some(&embeds))?
.await?;
return Ok(());
}
Ok(tracks) => tracks,
};
let tracks = get_tracks(query).await?;
tracing::info!("got tracks: {:?}", tracks);
if tracks.len() > 1 {
let first_track = tracks.first().unwrap();
@@ -153,27 +349,47 @@ pub(crate) async fn play(
.interaction(interaction.application_id)
.update_response(&interaction.token)
.embeds(Some(&embeds))?
.await?;
.await
.context("Could not send playlist loading message")?;
}
if let Some(call_lock) = state.songbird.get(guild_id) {
let call = call_lock.lock().await;
call.queue().resume()?;
call.queue().resume().context("Could not resume playing")?;
}
let mut tracks_added = vec![];
for track in &tracks {
tracing::debug!("track: {:?}", track);
let url = track.url.clone().or(track.original_url.clone()).ok_or("")?;
let mut src = YoutubeDl::new(reqwest::Client::new(), url.clone());
let src_copy = src.clone();
let track: Track = src_copy.into();
for yttrack in &tracks {
tracing::debug!("track: {:?}", yttrack);
let url = yttrack
.original_url
.clone()
.or(yttrack.url.clone())
.context("Could not find url")?;
if let Ok(metadata) = src.aux_metadata().await {
let mut src = YoutubeDl::new(state.client.clone(), url.clone());
let track: Track = src.clone().into();
match src.aux_metadata().await {
Ok(metadata) => {
debug!("metadata: {:?}", metadata);
tracks_added.push((url.clone(), metadata.title.clone()));
if let Some(call_lock) = state.songbird.get(guild_id) {
persistence(interaction, yttrack, Arc::clone(&state))
.await
.unwrap_or_else(|e| {
tracing::error!("could not persist track: {:?}", e);
});
tracks_added.push(TrackType {
url: url.clone(),
title: metadata.title.clone(),
duration_string: yttrack.duration_string.clone(),
channel: yttrack.channel.clone(),
thumbnail: metadata.thumbnail.clone(),
});
match state.songbird.get(guild_id) {
Some(call_lock) => {
let mut call = call_lock.lock().await;
let handle = call.enqueue_with_preload(
track,
@@ -193,46 +409,19 @@ pub(crate) async fn play(
src,
});
}
None => tracing::error!("could not get call lock"),
}
}
let mut content = String::new();
let num_tracks_added = tracks_added.len();
match num_tracks_added {
0 => {}
1 => {
let (title, url) = if let Some(track) = tracks_added.first() {
let track = track.clone();
(track.1.unwrap_or("Unknown".to_string()), track.0)
} else {
("Unknown".to_string(), "".to_string())
};
content = format!("Added [{}]({}) to the queue", title, url);
}
_ => {
let first_track = tracks.first().unwrap();
content.push_str(&format!(
"Adding playlist: [{}]({})\n",
&first_track
.playlist
.clone()
.unwrap_or("Unknown".to_string()),
build_playlist_url(
&first_track
.playlist_id
.clone()
.unwrap_or("Unknown".to_string())
)
));
content.push_str(&format!(
"Added {} tracks to the queue:\n",
num_tracks_added
));
}
}
Err(e) => {
tracing::error!("could not get metadata: {:?}", e);
if e.to_string()
.contains("Sign in to confirm youre not a bot.")
{
let content =
"I seem to have been flagged by YouTube as a bot. :-(".to_string();
let embeds = vec![EmbedBuilder::new()
.description(content)
.color(colors::BLURPLE)
.color(colors::RED)
.build()];
state
.http
@@ -240,6 +429,20 @@ pub(crate) async fn play(
.update_response(&interaction.token)
.embeds(Some(&embeds))?
.await?;
return Ok(());
}
}
}
}
let embeds = build_embeds(&tracks, &tracks_added);
state
.http
.interaction(interaction.application_id)
.update_response(&interaction.token)
.embeds(Some(&embeds))?
.await
.context("Could not send final play message")?;
Ok(())
}

View File

@@ -59,9 +59,9 @@ pub(crate) async fn build_queue_embeds(queue: &[TrackHandle], page: usize) -> Ve
}
message.push('\n');
let max_pages = queue.len() / TRACKS_PER_PAGE;
if max_pages > 0 {
message.push_str(&format!("page {}/{}", 1 + page, 1 + max_pages));
let n_pages = queue.len().div_ceil(TRACKS_PER_PAGE);
if n_pages > 1 {
message.push_str(&format!("page {}/{}", 1 + page, n_pages));
}
vec![EmbedBuilder::new()
.description(&message)
@@ -69,10 +69,7 @@ pub(crate) async fn build_queue_embeds(queue: &[TrackHandle], page: usize) -> Ve
.build()]
}
pub(crate) fn build_action_row(page: usize, max_pages: usize) -> Vec<Component> {
if max_pages == 0 {
return Vec::new();
}
pub(crate) fn build_action_row(page: usize, n_pages: usize) -> Vec<Component> {
vec![Component::ActionRow(ActionRow {
components: vec![
Component::Button(Button {
@@ -85,6 +82,16 @@ pub(crate) fn build_action_row(page: usize, max_pages: usize) -> Vec<Component>
url: None,
disabled: page == 0,
}),
Component::Button(Button {
custom_id: Some(format!("page:{}", page)),
style: ButtonStyle::Primary,
label: Some("Refresh".to_string()),
emoji: Some(ReactionType::Unicode {
name: "🔄".to_string(),
}),
url: None,
disabled: false,
}),
Component::Button(Button {
custom_id: Some(format!("page:{}", page + 1)),
style: ButtonStyle::Primary,
@@ -93,7 +100,7 @@ pub(crate) fn build_action_row(page: usize, max_pages: usize) -> Vec<Component>
name: "➡️".to_string(),
}),
url: None,
disabled: page >= max_pages,
disabled: page >= n_pages - 1,
}),
],
})]
@@ -139,7 +146,8 @@ pub(crate) async fn queue(
}
let embeds = build_queue_embeds(&queue, 0).await;
let action_row = build_action_row(0, queue.len() / TRACKS_PER_PAGE);
let n_pages = queue.len().div_ceil(TRACKS_PER_PAGE);
let action_row = build_action_row(0, n_pages);
state
.http

View File

@@ -23,6 +23,10 @@ pub(crate) async fn stop(
return Ok(());
};
state.guild_settings.entry(guild_id).and_modify(|settings| {
settings.loop_queue = false;
});
if let Some(call_lock) = state.songbird.get(guild_id) {
let call = call_lock.lock().await;
call.queue().stop();

1
src/db/mod.rs Normal file
View File

@@ -0,0 +1 @@
pub mod track;

167
src/db/track.rs Normal file
View File

@@ -0,0 +1,167 @@
use chrono::{DateTime, Utc};
use sqlx::FromRow;
#[derive(Debug, FromRow)]
pub(crate) struct Track {
#[allow(dead_code)]
pub(crate) id: i64,
pub(crate) url: String,
pub(crate) title: String,
pub(crate) channel: String,
pub(crate) duration: String,
pub(crate) thumbnail: String,
pub(crate) updated: DateTime<Utc>,
}
impl Track {
pub(crate) fn new(
url: String,
title: String,
channel: String,
duration: String,
thumbnail: String,
) -> Self {
Self {
id: 0,
url,
title,
channel,
duration,
thumbnail,
updated: chrono::offset::Utc::now(),
}
}
}
pub(crate) async fn insert_track(
pool: &sqlx::SqlitePool,
track: Track,
) -> Result<i64, sqlx::Error> {
let query = r#"
INSERT INTO tracks (url, title, channel, duration, thumbnail, updated)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (url) DO UPDATE SET
title = EXCLUDED.title,
channel = EXCLUDED.channel,
duration = EXCLUDED.duration,
thumbnail = EXCLUDED.thumbnail,
updated = EXCLUDED.updated
RETURNING id
"#;
let id = sqlx::query_scalar(query)
.bind(&track.url)
.bind(track.title)
.bind(track.channel)
.bind(track.duration)
.bind(track.thumbnail)
.bind(track.updated)
.fetch_one(pool)
.await?;
Ok(id)
}
#[derive(Debug, FromRow)]
pub(crate) struct User {
pub(crate) id: String,
pub(crate) name: String,
pub(crate) global_name: Option<String>,
pub(crate) updated: DateTime<Utc>,
}
impl User {
pub(crate) fn new(id: String, name: String, global_name: Option<String>) -> Self {
Self {
id,
name,
global_name,
updated: chrono::offset::Utc::now(),
}
}
}
pub(crate) async fn insert_user(pool: &sqlx::SqlitePool, user: User) -> Result<(), sqlx::Error> {
let query = r#"
INSERT INTO users (id, name, global_name, updated)
VALUES (?, ?, ?, ?)
ON CONFLICT (id) DO UPDATE SET
name = EXCLUDED.name,
global_name = EXCLUDED.global_name,
updated = EXCLUDED.updated
"#;
sqlx::query(query)
.bind(user.id)
.bind(user.name)
.bind(user.global_name)
.bind(user.updated)
.execute(pool)
.await?;
Ok(())
}
#[derive(Debug, FromRow)]
pub(crate) struct Query {
#[allow(dead_code)]
pub(crate) id: i64,
pub(crate) user_id: String,
pub(crate) guild_id: String,
pub(crate) track_id: i64,
pub(crate) updated: DateTime<Utc>,
}
impl Query {
pub(crate) fn new(user_id: String, guild_id: String, track_id: i64) -> Self {
Self {
id: 0,
user_id,
guild_id,
track_id,
updated: chrono::offset::Utc::now(),
}
}
}
pub(crate) async fn insert_query(pool: &sqlx::SqlitePool, q: Query) -> Result<i64, sqlx::Error> {
let query = r#"
INSERT INTO queries (user_id, guild_id, track_id, updated)
VALUES (?, ?, ?, ?)
"#;
let res = sqlx::query(query)
.bind(q.user_id)
.bind(q.guild_id)
.bind(q.track_id)
.bind(q.updated)
.execute(pool)
.await?;
Ok(res.last_insert_rowid())
}
#[derive(Debug, FromRow)]
pub(crate) struct Guild {
pub(crate) id: String,
pub(crate) updated: DateTime<Utc>,
}
impl Guild {
pub(crate) fn new(id: String) -> Self {
Self {
id,
updated: chrono::offset::Utc::now(),
}
}
}
pub(crate) async fn insert_guild(pool: &sqlx::SqlitePool, guild: Guild) -> Result<(), sqlx::Error> {
let query = r#"
INSERT INTO guilds (id, updated)
VALUES (?, ?)
ON CONFLICT (id) DO UPDATE SET
updated = EXCLUDED.updated
"#;
sqlx::query(query)
.bind(guild.id)
.bind(guild.updated)
.execute(pool)
.await?;
Ok(())
}

View File

@@ -1,79 +1,19 @@
use crate::commands::queue::{build_action_row, build_queue_embeds, TRACKS_PER_PAGE};
use crate::commands::{delete, join, leave, loop_queue, pause, play, queue, resume, skip, stop};
use crate::state::State;
use futures::Future;
use std::error::Error;
use std::sync::Arc;
use tracing::debug;
use twilight_gateway::Event;
use twilight_model::application::interaction::application_command::{
CommandData, CommandOptionValue,
use crate::commands::{
delete, join, leave, leave_if_alone, loop_queue, pause, play, queue, resume, skip, stop,
};
use crate::interaction_commands::InteractionCommand;
use crate::state::State;
use crate::utils::spawn;
use anyhow::Context;
use std::sync::Arc;
use twilight_gateway::Event;
use twilight_model::application::interaction::message_component::MessageComponentInteractionData;
use twilight_model::application::interaction::InteractionData;
use twilight_model::gateway::payload::incoming::VoiceStateUpdate;
use twilight_model::gateway::payload::incoming::InteractionCreate;
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
use twilight_util::builder::InteractionResponseDataBuilder;
#[derive(Debug)]
enum InteractionCommand {
Play(String),
Stop,
Pause,
Skip,
Loop,
Resume,
Leave,
Join,
Queue,
NotImplemented,
}
fn spawn(
fut: impl Future<Output = Result<(), Box<dyn Error + Send + Sync + 'static>>> + Send + 'static,
) {
tokio::spawn(async move {
if let Err(why) = fut.await {
tracing::debug!("handler error: {:?}", why);
}
});
}
pub(crate) async fn leave_if_alone(
update: VoiceStateUpdate,
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let guild_id = update.guild_id.ok_or("Guild ID not found")?;
let user = state
.cache
.current_user()
.ok_or("Cannot get current user")?;
let user_voice_state = state
.cache
.voice_state(user.id, guild_id)
.ok_or("Cannot get voice state")?;
let channel = state
.cache
.channel(user_voice_state.channel_id())
.ok_or("Cannot get channel")?;
let channel_voice_states = state
.cache
.voice_channel_states(channel.id)
.ok_or("Cannot get voice channel")?;
let count = channel_voice_states.count();
// count is 1 if the bot is the only one in the channel
if count == 1 {
// stop playing
if let Some(call_lock) = state.songbird.get(guild_id) {
let call = call_lock.lock().await;
call.queue().stop();
}
// leave the voice channel
state.songbird.leave(guild_id).await?;
}
Ok(())
}
pub(crate) struct Handler {
state: State,
}
@@ -83,6 +23,13 @@ impl Handler {
Self { state }
}
pub(crate) async fn act(&self, event: Event) -> anyhow::Result<()> {
self.handle_messages(&event).await?;
self.handle_voice_state_update(&event).await?;
self.handle_interaction(&event).await?;
Ok(())
}
async fn handle_messages(&self, event: &Event) -> anyhow::Result<()> {
match event {
Event::MessageCreate(message) if message.content.starts_with('!') => {
if message.content.contains("!delete") {
@@ -90,51 +37,66 @@ impl Handler {
}
Ok(())
}
_ => Ok(()),
}
}
async fn handle_voice_state_update(&self, event: &Event) -> anyhow::Result<()> {
match event {
Event::VoiceStateUpdate(update) => {
spawn(leave_if_alone(*update.clone(), Arc::clone(&self.state)));
let guild_id = update.guild_id.context("Guild ID not found")?;
spawn(leave_if_alone(guild_id, Arc::clone(&self.state)));
Ok(())
}
Event::InteractionCreate(interaction) => {
tracing::info!("interaction: {:?}", &interaction);
match &interaction.data {
_ => Ok(()),
}
}
async fn handle_interaction(&self, event: &Event) -> anyhow::Result<()> {
match event {
Event::InteractionCreate(interaction) => match &interaction.data {
Some(InteractionData::ApplicationCommand(command)) => {
let interaction_command = parse_interaction_command(command);
debug!("{:?}", interaction_command);
match interaction_command {
self.handle_application_command(command.clone().into(), interaction.clone())
}
Some(InteractionData::MessageComponent(data)) => {
self.handle_message_component(data, interaction.clone())
.await
}
_ => Ok(()),
},
_ => Ok(()),
}
}
fn handle_application_command(
&self,
command: InteractionCommand,
interaction: Box<InteractionCreate>,
) -> anyhow::Result<()> {
{
match command {
InteractionCommand::Play(query) => {
spawn(play(interaction, Arc::clone(&self.state), query))
}
InteractionCommand::Stop => {
spawn(stop(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Pause => {
spawn(pause(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Skip => {
spawn(skip(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Loop => {
spawn(loop_queue(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Resume => {
spawn(resume(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Leave => {
spawn(leave(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Join => {
spawn(join(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Queue => {
spawn(queue(interaction, Arc::clone(&self.state)))
}
InteractionCommand::Stop => spawn(stop(interaction, Arc::clone(&self.state))),
InteractionCommand::Pause => spawn(pause(interaction, Arc::clone(&self.state))),
InteractionCommand::Skip => spawn(skip(interaction, Arc::clone(&self.state))),
InteractionCommand::Loop => spawn(loop_queue(interaction, Arc::clone(&self.state))),
InteractionCommand::Resume => spawn(resume(interaction, Arc::clone(&self.state))),
InteractionCommand::Leave => spawn(leave(interaction, Arc::clone(&self.state))),
InteractionCommand::Join => spawn(join(interaction, Arc::clone(&self.state))),
InteractionCommand::Queue => spawn(queue(interaction, Arc::clone(&self.state))),
_ => {}
}
Ok(())
}
Some(InteractionData::MessageComponent(data)) => {
tracing::info!("message component: {:?}", data);
}
async fn handle_message_component(
&self,
data: &MessageComponentInteractionData,
interaction: Box<InteractionCreate>,
) -> anyhow::Result<()> {
if !data.custom_id.starts_with("page:") {
return Ok(());
}
@@ -143,7 +105,6 @@ impl Handler {
.trim_start_matches("page:")
.parse::<usize>()
.unwrap_or(0);
tracing::info!("page: {:?}", page);
if let Some(guild_id) = interaction.guild_id {
let mut queue = Vec::new();
@@ -151,8 +112,10 @@ impl Handler {
let call = call_lock.lock().await;
queue = call.queue().current_queue();
}
let n_pages = queue.len().div_ceil(TRACKS_PER_PAGE);
let page = page.min(n_pages - 1).max(0);
let embeds = build_queue_embeds(&queue, page).await;
let action_row = build_action_row(page, queue.len() / TRACKS_PER_PAGE);
let action_row = build_action_row(page, n_pages);
let interaction_response_data = InteractionResponseDataBuilder::new()
.embeds(embeds)
@@ -172,39 +135,4 @@ impl Handler {
Ok(())
}
}
_ => Ok(()),
}
}
event => {
tracing::info!("unhandled event: {:?}", event);
Ok(())
}
}
}
}
fn parse_interaction_command(command: &CommandData) -> InteractionCommand {
debug!("command: {:?}", command);
match command.name.as_str() {
"play" => {
if let Some(query_option) = command.options.iter().find(|opt| opt.name == "query") {
if let CommandOptionValue::String(query) = &query_option.value {
InteractionCommand::Play(query.clone())
} else {
InteractionCommand::NotImplemented
}
} else {
InteractionCommand::NotImplemented
}
}
"stop" => InteractionCommand::Stop,
"pause" => InteractionCommand::Pause,
"skip" => InteractionCommand::Skip,
"loop" => InteractionCommand::Loop,
"resume" => InteractionCommand::Resume,
"leave" => InteractionCommand::Leave,
"join" => InteractionCommand::Join,
"queue" => InteractionCommand::Queue,
_ => InteractionCommand::NotImplemented,
}
}

View File

@@ -0,0 +1,44 @@
use twilight_model::application::interaction::application_command::{
CommandData, CommandOptionValue,
};
#[derive(Debug)]
pub(crate) enum InteractionCommand {
Play(String),
Stop,
Pause,
Skip,
Loop,
Resume,
Leave,
Join,
Queue,
NotImplemented,
}
impl From<Box<CommandData>> for InteractionCommand {
fn from(command: Box<CommandData>) -> InteractionCommand {
match command.name.as_str() {
"play" => {
if let Some(query_option) = command.options.iter().find(|opt| opt.name == "query") {
if let CommandOptionValue::String(query) = &query_option.value {
InteractionCommand::Play(query.clone())
} else {
InteractionCommand::NotImplemented
}
} else {
InteractionCommand::NotImplemented
}
}
"stop" => InteractionCommand::Stop,
"pause" => InteractionCommand::Pause,
"skip" => InteractionCommand::Skip,
"loop" => InteractionCommand::Loop,
"resume" => InteractionCommand::Resume,
"leave" => InteractionCommand::Leave,
"join" => InteractionCommand::Join,
"queue" => InteractionCommand::Queue,
_ => InteractionCommand::NotImplemented,
}
}
}

View File

@@ -1,10 +1,14 @@
mod handler;
use handler::Handler;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
mod colors;
mod commands;
mod db;
mod interaction_commands;
mod metadata;
mod signal;
mod state;
mod utils;
use crate::commands::get_chat_commands;
use dotenv::dotenv;
@@ -12,7 +16,7 @@ use futures::StreamExt;
use signal::signal_handler;
use songbird::{shards::TwilightMap, Songbird};
use state::StateRef;
use std::{env, error::Error, sync::Arc};
use std::{env, error::Error, str::FromStr, sync::Arc, time::Duration};
use tokio::select;
use tracing::{debug, info};
use twilight_cache_inmemory::InMemoryCache;
@@ -30,12 +34,21 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
println!("Starting up...");
// Initialize the tracing subscriber.
tracing_subscriber::fmt::init();
info!("Starting up...");
let (mut shards, state) = {
let db = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let options = SqliteConnectOptions::from_str(&db)
.expect("could not create options")
.create_if_missing(true);
let pool = SqlitePoolOptions::new()
.max_connections(5)
.connect_with(options)
.await?;
sqlx::migrate!().run(&pool).await?;
let token = env::var("DISCORD_TOKEN").map_err(|_| "DISCORD_TOKEN is not set")?;
let app_id = env::var("DISCORD_APP_ID")
.map_err(|_| "DISCORD_APP_ID is not set")?
@@ -69,6 +82,11 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
);
let songbird = Songbird::twilight(Arc::new(senders), user_id);
let cache = InMemoryCache::new();
let client = reqwest::ClientBuilder::new()
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(3600))
.build()
.expect("could not build http client");
(
shards,
@@ -78,6 +96,8 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
songbird,
standby: Standby::new(),
guild_settings: Default::default(),
pool,
client,
}),
)
};

View File

@@ -13,6 +13,18 @@ pub(crate) struct Settings {
pub(crate) loop_queue: bool,
}
impl Settings {
pub(crate) fn new() -> Self {
Self { loop_queue: false }
}
}
impl Default for Settings {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub(crate) struct StateRef {
pub(crate) http: HttpClient,
@@ -20,4 +32,6 @@ pub(crate) struct StateRef {
pub(crate) songbird: Songbird,
pub(crate) standby: Standby,
pub(crate) guild_settings: DashMap<Id<GuildMarker>, Settings>,
pub(crate) pool: sqlx::SqlitePool,
pub(crate) client: reqwest::Client,
}

12
src/utils.rs Normal file
View File

@@ -0,0 +1,12 @@
use futures::Future;
use std::error::Error;
pub(crate) fn spawn(
fut: impl Future<Output = Result<(), Box<dyn Error + Send + Sync + 'static>>> + Send + 'static,
) {
tokio::spawn(async move {
if let Err(why) = fut.await {
tracing::debug!("handler error: {:?}", why);
}
});
}