Compare commits
80 Commits
e831ede37c
...
renovate/r
| Author | SHA1 | Date | |
|---|---|---|---|
| ea83db7c56 | |||
| de4260dd84 | |||
| 335626312b | |||
| 07a4da73c1 | |||
| fa1d720d0f | |||
| 1ec358ec8f | |||
| 624e08f3aa | |||
| f4f6a486c9 | |||
| c354ec0562 | |||
| e0f1abcd9c | |||
| aa302e4bb5 | |||
| c461671bfb | |||
| 271ec4d323 | |||
| 1e807c121d | |||
| 4293775824 | |||
| fa8f5f5b04 | |||
| 4ecf9bf205 | |||
|
5b5ca52c04
|
|||
|
ebb66e21cc
|
|||
| f240b8f0f6 | |||
| 65c09c5e85 | |||
| c9837e456e | |||
| 9efc372f8f | |||
|
7ff991206b
|
|||
|
b1d6069d81
|
|||
| de3262c072 | |||
| 8e88cadbb8 | |||
|
c6e34cf000
|
|||
| 3b135894eb | |||
| 14cab9d833 | |||
|
f2f4396674
|
|||
|
b60cce35ca
|
|||
|
9f1ed63011
|
|||
| 6096e625a2 | |||
| 5c42fb9480 | |||
|
d1df70a888
|
|||
| c4bc5503a5 | |||
| 16f6c97eec | |||
| cd42401280 | |||
| cc0af054f8 | |||
| aff5e1dd8d | |||
| ed9956c5a5 | |||
|
456a51bc70
|
|||
|
b9b3709bb4
|
|||
|
27168c36cf
|
|||
|
88d9c1d841
|
|||
|
d3a4114347
|
|||
|
a3e9175ea8
|
|||
|
6601396a88
|
|||
|
687f110416
|
|||
|
9146ac06a6
|
|||
|
a25e8ef65f
|
|||
|
f0337050c1
|
|||
|
440201e153
|
|||
|
f7dca8ff65
|
|||
|
1e523502eb
|
|||
|
dfd0f9c8c8
|
|||
|
3242f23f84
|
|||
|
8985945659
|
|||
|
4a69e0f578
|
|||
|
cad6cf22fa
|
|||
|
9f0e934f92
|
|||
|
92be6c26a6
|
|||
|
c5d9c49452
|
|||
|
dbaf1a1374
|
|||
|
c0d9f6cad5
|
|||
|
1aa0efc4a6
|
|||
|
ab7f56fe05
|
|||
| feccbebd4d | |||
| d6a54dfc06 | |||
|
fa17ed75f6
|
|||
| b19f6e552c | |||
|
0bee437e53
|
|||
|
3781785a50
|
|||
| cabae9ea19 | |||
|
54c36688b7
|
|||
|
55fe212424
|
|||
| 2c91c744dc | |||
|
a0ac87959b
|
|||
| b4a1efb22a |
@@ -12,3 +12,6 @@ README.md
|
|||||||
# Cargo files
|
# Cargo files
|
||||||
**/*.rs.bk
|
**/*.rs.bk
|
||||||
/target/
|
/target/
|
||||||
|
|
||||||
|
# Database files
|
||||||
|
data
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ name: tests
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
pull_request:
|
|
||||||
|
paths-ignore:
|
||||||
|
- 'README.md'
|
||||||
|
|
||||||
env:
|
env:
|
||||||
CARGO_TERM_COLOR: always
|
CARGO_TERM_COLOR: always
|
||||||
@@ -11,42 +13,47 @@ jobs:
|
|||||||
fmt:
|
fmt:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
- run: sudo apt-get update
|
- run: sudo apt-get update
|
||||||
- run: sudo apt-get install -y cmake
|
- 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:
|
with:
|
||||||
components: rustfmt
|
components: rustfmt
|
||||||
- name: Rustfmt Check
|
- name: Rustfmt Check
|
||||||
uses: actions-rust-lang/rustfmt@v1
|
uses: actions-rust-lang/rustfmt@559aa3035a47390ba96088dffa783b5d26da9326 # v1
|
||||||
|
|
||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
- run: sudo apt-get update
|
- run: sudo apt-get update
|
||||||
- run: sudo apt-get install -y cmake
|
- 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
|
- name: Build
|
||||||
run: cargo build --verbose
|
run: cargo build --verbose
|
||||||
|
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
- run: sudo apt-get update
|
- run: sudo apt-get update
|
||||||
- run: sudo apt-get install -y cmake
|
- run: sudo apt-get install -y cmake
|
||||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
- uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5
|
||||||
|
with:
|
||||||
|
python-version: '3.13'
|
||||||
|
- name: Install yt-dlp
|
||||||
|
run: pip install yt-dlp
|
||||||
|
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: cargo test --verbose --all-features
|
run: cargo test --verbose --all-features
|
||||||
|
|
||||||
clippy:
|
clippy:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
- run: sudo apt-get update
|
- run: sudo apt-get update
|
||||||
- run: sudo apt-get install -y cmake
|
- 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:
|
with:
|
||||||
components: clippy
|
components: clippy
|
||||||
- name: Run clippy
|
- name: Run clippy
|
||||||
@@ -55,13 +62,13 @@ jobs:
|
|||||||
pre-commit:
|
pre-commit:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
- run: sudo apt-get update
|
- run: sudo apt-get update
|
||||||
- run: sudo apt-get install -y cmake
|
- run: sudo apt-get install -y cmake
|
||||||
- uses: actions/setup-python@v5
|
- uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5
|
||||||
with:
|
with:
|
||||||
python-version: '3.12'
|
python-version: '3.13'
|
||||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
|
||||||
with:
|
with:
|
||||||
components: rustfmt
|
components: rustfmt
|
||||||
- uses: pre-commit/action@v3.0.1
|
- uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
|
||||||
|
|||||||
@@ -5,27 +5,31 @@ on:
|
|||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
|
|
||||||
|
paths-ignore:
|
||||||
|
- 'README.md'
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
release-image:
|
release-image:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v3
|
uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3
|
||||||
|
|
||||||
- name: Set up Docker BuildX
|
- name: Set up Docker BuildX
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3
|
||||||
|
|
||||||
- name: Login to DockerHub
|
- name: Login to DockerHub
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3
|
||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|
||||||
- name: Build and push
|
- name: Build and push
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@471d1dc4e07e5cdedd4c2171150001c434f0b7a4 # v6
|
||||||
with:
|
with:
|
||||||
platforms: |
|
platforms: |
|
||||||
linux/amd64
|
linux/amd64
|
||||||
linux/arm64
|
|
||||||
push: true
|
push: true
|
||||||
tags: jheuel/ohrwurm:latest
|
tags: jheuel/ohrwurm:latest
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
|||||||
32
.gitea/workflows/renovate.yaml
Normal file
32
.gitea/workflows/renovate.yaml
Normal 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@c21017a4a2fc9f42953bcc907e375a5a544557ec # v41.0.18
|
||||||
|
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"
|
||||||
33
.github/workflows/ci.yml
vendored
33
.github/workflows/ci.yml
vendored
@@ -12,42 +12,47 @@ jobs:
|
|||||||
fmt:
|
fmt:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
- run: sudo apt-get update
|
- run: sudo apt-get update
|
||||||
- run: sudo apt-get install -y cmake
|
- 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:
|
with:
|
||||||
components: rustfmt
|
components: rustfmt
|
||||||
- name: Rustfmt Check
|
- name: Rustfmt Check
|
||||||
uses: actions-rust-lang/rustfmt@v1
|
uses: actions-rust-lang/rustfmt@559aa3035a47390ba96088dffa783b5d26da9326 # v1
|
||||||
|
|
||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
- run: sudo apt-get update
|
- run: sudo apt-get update
|
||||||
- run: sudo apt-get install -y cmake
|
- 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
|
- name: Build
|
||||||
run: cargo build --verbose
|
run: cargo build --verbose
|
||||||
|
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
- run: sudo apt-get update
|
- run: sudo apt-get update
|
||||||
- run: sudo apt-get install -y cmake
|
- run: sudo apt-get install -y cmake
|
||||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
- uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5
|
||||||
|
with:
|
||||||
|
python-version: '3.13'
|
||||||
|
- name: Install yt-dlp
|
||||||
|
run: pip install yt-dlp
|
||||||
|
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: cargo test --verbose --all-features
|
run: cargo test --verbose --all-features
|
||||||
|
|
||||||
clippy:
|
clippy:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
- run: sudo apt-get update
|
- run: sudo apt-get update
|
||||||
- run: sudo apt-get install -y cmake
|
- 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:
|
with:
|
||||||
components: clippy
|
components: clippy
|
||||||
- name: Run clippy
|
- name: Run clippy
|
||||||
@@ -56,13 +61,13 @@ jobs:
|
|||||||
pre-commit:
|
pre-commit:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||||
- run: sudo apt-get update
|
- run: sudo apt-get update
|
||||||
- run: sudo apt-get install -y cmake
|
- run: sudo apt-get install -y cmake
|
||||||
- uses: actions/setup-python@v5
|
- uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5
|
||||||
with:
|
with:
|
||||||
python-version: '3.12'
|
python-version: '3.13'
|
||||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
- uses: actions-rust-lang/setup-rust-toolchain@9399c7bb15d4c7d47b27263d024f0a4978346ba4 # v1
|
||||||
with:
|
with:
|
||||||
components: rustfmt
|
components: rustfmt
|
||||||
- uses: pre-commit/action@v3.0.1
|
- uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,3 +1,6 @@
|
|||||||
/target
|
/target
|
||||||
.env
|
.env
|
||||||
.vscode
|
.vscode
|
||||||
|
|
||||||
|
# Database files
|
||||||
|
data
|
||||||
|
|||||||
3301
Cargo.lock
generated
3301
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
29
Cargo.toml
29
Cargo.toml
@@ -6,20 +6,27 @@ edition = "2021"
|
|||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|
||||||
[dependencies]
|
[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"] }
|
songbird = { version = "0.5.0", features = ["driver", "gateway", "twilight", "rustls", "builtin-queue"] }
|
||||||
tokio = { features = ["macros", "rt-multi-thread", "signal", "sync"], version = "1" }
|
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"] }
|
regex = { version = "1", features = ["unicode-case"] }
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
reqwest = "0.11"
|
reqwest = "0.12"
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = "0.2"
|
tracing-subscriber = "0.3"
|
||||||
twilight-gateway = "0.15"
|
twilight-gateway = "0.16"
|
||||||
twilight-http = "0.15"
|
twilight-http = "0.16"
|
||||||
twilight-model = "0.15"
|
twilight-model = "0.16"
|
||||||
twilight-standby = "0.15"
|
twilight-standby = "0.16"
|
||||||
twilight-cache-inmemory = "0.15"
|
twilight-cache-inmemory = "0.16"
|
||||||
twilight-util = { version = "0.15", features=["builder"] }
|
twilight-util = { version = "0.16", features=["builder"] }
|
||||||
dotenv = "0.15.0"
|
dotenv = "0.15.0"
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
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"
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# Build image
|
# Build image
|
||||||
FROM rust:slim-bullseye as build
|
FROM rust:slim-bullseye@sha256:f635d98d781930be4ab1a5135fd8e2f7b2bdf43c741c99e420d794d0777ead4d as build
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y \
|
RUN apt-get update && apt-get install -y \
|
||||||
build-essential autoconf automake cmake libtool libssl-dev pkg-config
|
build-essential autoconf automake cmake libtool libssl-dev pkg-config
|
||||||
@@ -18,9 +18,9 @@ RUN touch src/main.rs
|
|||||||
RUN cargo build --release --locked
|
RUN cargo build --release --locked
|
||||||
|
|
||||||
# Release image
|
# Release image
|
||||||
FROM debian:bullseye-slim
|
FROM debian:bullseye-slim@sha256:e4b93db6aad977a95aa103917f3de8a2b16ead91cf255c3ccdb300c5d20f3015
|
||||||
|
|
||||||
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
|
RUN pip install -U yt-dlp
|
||||||
|
|
||||||
COPY --from=build /app/target/release/ohrwurm .
|
COPY --from=build /app/target/release/ohrwurm .
|
||||||
|
|||||||
@@ -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.
|
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
|
# 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
|
```bash
|
||||||
docker run -d \
|
docker run -d \
|
||||||
--name ohrwurm \
|
--name ohrwurm \
|
||||||
|
|||||||
3
build.rs
Normal file
3
build.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
fn main() {
|
||||||
|
println!("cargo:rerun-if-changed=migrations");
|
||||||
|
}
|
||||||
33
migrations/20240620151940_init.sql
Normal file
33
migrations/20240620151940_init.sql
Normal 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
25
renovate.json
Normal 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
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
20
src/colors.rs
Normal file
20
src/colors.rs
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const BLURPLE: u32 = 0x58_65_F2;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const YELLOW: u32 = 0xFE_E7_5C;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const WHITE: u32 = 0xFF_FF_FF;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const GREYPLE: u32 = 0x99_AA_B5;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const BLACK: u32 = 0x23_27_2A;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const DARK_BUT_NOT_BLACK: u32 = 0x2C_2F_33;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const NOT_QUITE_BLACK: u32 = 0x23_27_2A;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const GREEN: u32 = 0x57_F2_87;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const FUCHSIA: u32 = 0xEB_45_9E;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) const RED: u32 = 0xED_42_45;
|
||||||
@@ -9,14 +9,14 @@ pub(crate) async fn delete(
|
|||||||
state: State,
|
state: State,
|
||||||
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
let admin = env::var("ADMIN")?.parse::<u64>()?;
|
let admin = env::var("ADMIN")?.parse::<u64>()?;
|
||||||
if msg.author.id != Id::from(NonZeroU64::new(admin).unwrap()) {
|
if msg.author.id != Id::from(NonZeroU64::new(admin).expect("Could not get author id")) {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let n = msg
|
let n = msg
|
||||||
.content
|
.content
|
||||||
.split(' ')
|
.split(' ')
|
||||||
.last()
|
.last()
|
||||||
.unwrap()
|
.unwrap_or("1")
|
||||||
.parse::<u16>()
|
.parse::<u16>()
|
||||||
.unwrap_or(1);
|
.unwrap_or(1);
|
||||||
if n > 100 {
|
if n > 100 {
|
||||||
@@ -26,7 +26,7 @@ pub(crate) async fn delete(
|
|||||||
.http
|
.http
|
||||||
.channel_messages(msg.channel_id)
|
.channel_messages(msg.channel_id)
|
||||||
.before(msg.id)
|
.before(msg.id)
|
||||||
.limit(n)?
|
.limit(n)
|
||||||
.await?
|
.await?
|
||||||
.model()
|
.model()
|
||||||
.await?;
|
.await?;
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
use crate::state::State;
|
use crate::state::State;
|
||||||
|
use anyhow::Context;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use tracing::debug;
|
use tracing::debug;
|
||||||
use twilight_model::{
|
use twilight_model::{
|
||||||
application::interaction::Interaction,
|
|
||||||
channel::message::MessageFlags,
|
channel::message::MessageFlags,
|
||||||
|
gateway::payload::incoming::InteractionCreate,
|
||||||
http::interaction::{InteractionResponse, InteractionResponseType},
|
http::interaction::{InteractionResponse, InteractionResponseType},
|
||||||
id::{
|
id::{
|
||||||
marker::{GuildMarker, UserMarker},
|
marker::{GuildMarker, UserMarker},
|
||||||
@@ -22,7 +23,7 @@ pub(crate) async fn join_channel(
|
|||||||
let channel_id = state
|
let channel_id = state
|
||||||
.cache
|
.cache
|
||||||
.voice_state(user_id, guild_id)
|
.voice_state(user_id, guild_id)
|
||||||
.ok_or("Cannot get voice state for user")?
|
.context("Could not get voice state for user")?
|
||||||
.channel_id();
|
.channel_id();
|
||||||
|
|
||||||
// join the voice channel
|
// join the voice channel
|
||||||
@@ -30,19 +31,22 @@ pub(crate) async fn join_channel(
|
|||||||
.songbird
|
.songbird
|
||||||
.join(guild_id.cast(), channel_id)
|
.join(guild_id.cast(), channel_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("Could not join voice channel: {:?}", e))?;
|
.context("Could not join voice channel")?;
|
||||||
|
|
||||||
// signal that we are not listening
|
// signal that we are not listening
|
||||||
if let Some(call_lock) = state.songbird.get(guild_id.cast()) {
|
if let Some(call_lock) = state.songbird.get(guild_id.cast()) {
|
||||||
let mut call = call_lock.lock().await;
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn join(
|
pub(crate) async fn join(
|
||||||
interaction: Interaction,
|
interaction: Box<InteractionCreate>,
|
||||||
state: State,
|
state: State,
|
||||||
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
debug!(
|
debug!(
|
||||||
|
|||||||
@@ -1,9 +1,59 @@
|
|||||||
use crate::state::State;
|
use crate::state::{State, StateRef};
|
||||||
use std::error::Error;
|
use anyhow::Context;
|
||||||
use twilight_model::application::interaction::Interaction;
|
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(
|
pub(crate) async fn leave(
|
||||||
interaction: Interaction,
|
interaction: Box<InteractionCreate>,
|
||||||
state: State,
|
state: State,
|
||||||
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
tracing::debug!(
|
tracing::debug!(
|
||||||
@@ -16,6 +66,8 @@ pub(crate) async fn leave(
|
|||||||
let Some(guild_id) = interaction.guild_id else {
|
let Some(guild_id) = interaction.guild_id else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
state.songbird.leave(guild_id).await?;
|
|
||||||
|
leave_channel(guild_id, Arc::clone(&state)).await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
119
src/commands/loop_queue.rs
Normal file
119
src/commands/loop_queue.rs
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
use crate::metadata::Metadata;
|
||||||
|
use crate::state::{State, StateRef};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use songbird::tracks::Track;
|
||||||
|
use songbird::{Event, EventContext, EventHandler, TrackEvent};
|
||||||
|
use std::ops::Sub;
|
||||||
|
use std::time::Duration;
|
||||||
|
use std::{error::Error, sync::Arc};
|
||||||
|
use twilight_model::{
|
||||||
|
gateway::payload::incoming::InteractionCreate,
|
||||||
|
http::interaction::{InteractionResponse, InteractionResponseType},
|
||||||
|
id::{marker::GuildMarker, Id},
|
||||||
|
};
|
||||||
|
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||||
|
|
||||||
|
pub(crate) async fn loop_queue(
|
||||||
|
interaction: Box<InteractionCreate>,
|
||||||
|
state: State,
|
||||||
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
|
tracing::debug!(
|
||||||
|
"loop command in guild {:?} in channel {:?} by {:?}",
|
||||||
|
interaction.guild_id,
|
||||||
|
interaction.channel,
|
||||||
|
interaction.author(),
|
||||||
|
);
|
||||||
|
|
||||||
|
let guild_id: Id<GuildMarker> = if let Some(guild_id) = interaction.guild_id {
|
||||||
|
guild_id
|
||||||
|
} else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
state.guild_settings.entry(guild_id).and_modify(|settings| {
|
||||||
|
settings.loop_queue = !settings.loop_queue;
|
||||||
|
});
|
||||||
|
|
||||||
|
let looping = state
|
||||||
|
.guild_settings
|
||||||
|
.get(&guild_id)
|
||||||
|
.expect("Cannot get loop state")
|
||||||
|
.loop_queue;
|
||||||
|
|
||||||
|
if let Some(call_lock) = state.songbird.get(guild_id) {
|
||||||
|
let mut call = call_lock.lock().await;
|
||||||
|
call.add_global_event(
|
||||||
|
Event::Track(TrackEvent::End),
|
||||||
|
TrackEndNotifier {
|
||||||
|
guild_id,
|
||||||
|
state: Arc::clone(&state),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let message = if looping {
|
||||||
|
"I'm now looping the current queue!".to_string()
|
||||||
|
} else {
|
||||||
|
"I'm not looping anymore!".to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
let interaction_response_data = InteractionResponseDataBuilder::new()
|
||||||
|
.content(message)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
let response = InteractionResponse {
|
||||||
|
kind: InteractionResponseType::ChannelMessageWithSource,
|
||||||
|
data: Some(interaction_response_data),
|
||||||
|
};
|
||||||
|
|
||||||
|
state
|
||||||
|
.http
|
||||||
|
.interaction(interaction.application_id)
|
||||||
|
.create_response(interaction.id, &interaction.token, &response)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TrackEndNotifier {
|
||||||
|
guild_id: Id<GuildMarker>,
|
||||||
|
state: Arc<StateRef>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl EventHandler for TrackEndNotifier {
|
||||||
|
async fn act(&self, ctx: &EventContext<'_>) -> Option<Event> {
|
||||||
|
if !self
|
||||||
|
.state
|
||||||
|
.guild_settings
|
||||||
|
.get(&self.guild_id)
|
||||||
|
.unwrap()
|
||||||
|
.loop_queue
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let EventContext::Track(track_list) = ctx else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let (_, track_handle) = track_list.first()?;
|
||||||
|
if let Some(call_lock) = self.state.songbird.get(self.guild_id) {
|
||||||
|
let mut call = call_lock.lock().await;
|
||||||
|
|
||||||
|
// get metadata from finished track
|
||||||
|
let old_metadata = track_handle.data::<Metadata>();
|
||||||
|
// enqueue track
|
||||||
|
let track = Track::new_with_data(old_metadata.src.clone().into(), old_metadata.clone());
|
||||||
|
let _handle = call.enqueue_with_preload(
|
||||||
|
track,
|
||||||
|
old_metadata.duration.map(|duration| -> Duration {
|
||||||
|
if duration.as_secs() > 5 {
|
||||||
|
duration.sub(Duration::from_secs(5))
|
||||||
|
} else {
|
||||||
|
duration
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,14 +3,21 @@ pub(crate) use join::join;
|
|||||||
|
|
||||||
mod leave;
|
mod leave;
|
||||||
pub(crate) use leave::leave;
|
pub(crate) use leave::leave;
|
||||||
|
pub(crate) use leave::leave_if_alone;
|
||||||
|
|
||||||
mod pause;
|
mod pause;
|
||||||
pub(crate) use pause::pause;
|
pub(crate) use pause::pause;
|
||||||
|
|
||||||
|
mod skip;
|
||||||
|
pub(crate) use skip::skip;
|
||||||
|
|
||||||
|
mod loop_queue;
|
||||||
|
pub(crate) use loop_queue::loop_queue;
|
||||||
|
|
||||||
mod play;
|
mod play;
|
||||||
pub(crate) use play::play;
|
pub(crate) use play::play;
|
||||||
|
|
||||||
mod queue;
|
pub(crate) mod queue;
|
||||||
pub(crate) use queue::queue;
|
pub(crate) use queue::queue;
|
||||||
|
|
||||||
mod resume;
|
mod resume;
|
||||||
@@ -29,12 +36,14 @@ pub(crate) fn get_chat_commands() -> Vec<twilight_model::application::command::C
|
|||||||
vec![
|
vec![
|
||||||
CommandBuilder::new("join", "Join the channel", CommandType::ChatInput).build(),
|
CommandBuilder::new("join", "Join the channel", CommandType::ChatInput).build(),
|
||||||
CommandBuilder::new("leave", "Leave the channel", CommandType::ChatInput).build(),
|
CommandBuilder::new("leave", "Leave the channel", CommandType::ChatInput).build(),
|
||||||
|
CommandBuilder::new("loop", "Loop queue", CommandType::ChatInput).build(),
|
||||||
|
CommandBuilder::new("skip", "Skip track", CommandType::ChatInput).build(),
|
||||||
|
CommandBuilder::new("queue", "Print track queue", CommandType::ChatInput).build(),
|
||||||
|
CommandBuilder::new("stop", "Stop playing", CommandType::ChatInput).build(),
|
||||||
CommandBuilder::new("pause", "Pause playing", CommandType::ChatInput).build(),
|
CommandBuilder::new("pause", "Pause playing", CommandType::ChatInput).build(),
|
||||||
|
CommandBuilder::new("resume", "Resume playing", CommandType::ChatInput).build(),
|
||||||
CommandBuilder::new("play", "Add a song to the queue", CommandType::ChatInput)
|
CommandBuilder::new("play", "Add a song to the queue", CommandType::ChatInput)
|
||||||
.option(StringBuilder::new("query", "URL of a song").required(true))
|
.option(StringBuilder::new("query", "URL of a song").required(true))
|
||||||
.build(),
|
.build(),
|
||||||
CommandBuilder::new("queue", "Print track queue", CommandType::ChatInput).build(),
|
|
||||||
CommandBuilder::new("resume", "Resume playing", CommandType::ChatInput).build(),
|
|
||||||
CommandBuilder::new("stop", "Stop playing", CommandType::ChatInput).build(),
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
use crate::state::State;
|
use crate::state::State;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use twilight_model::{
|
use twilight_model::{
|
||||||
application::interaction::Interaction,
|
|
||||||
channel::message::MessageFlags,
|
channel::message::MessageFlags,
|
||||||
|
gateway::payload::incoming::InteractionCreate,
|
||||||
http::interaction::{InteractionResponse, InteractionResponseType},
|
http::interaction::{InteractionResponse, InteractionResponseType},
|
||||||
};
|
};
|
||||||
use twilight_util::builder::InteractionResponseDataBuilder;
|
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||||
|
|
||||||
pub(crate) async fn pause(
|
pub(crate) async fn pause(
|
||||||
interaction: Interaction,
|
interaction: Box<InteractionCreate>,
|
||||||
state: State,
|
state: State,
|
||||||
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
tracing::debug!(
|
tracing::debug!(
|
||||||
|
|||||||
@@ -1,38 +1,301 @@
|
|||||||
use crate::commands::join::join_channel;
|
use crate::commands::join::join_channel;
|
||||||
use crate::metadata::{Metadata, MetadataMap};
|
use crate::metadata::Metadata;
|
||||||
use crate::state::State;
|
use crate::state::State;
|
||||||
use serde_json::Value;
|
use crate::{colors, db};
|
||||||
|
|
||||||
|
use anyhow::Context;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
use songbird::input::{Compose, YoutubeDl};
|
use songbird::input::{Compose, YoutubeDl};
|
||||||
use std::io::{BufRead, BufReader};
|
use songbird::tracks::Track;
|
||||||
use std::{error::Error, ops::Sub, time::Duration};
|
use std::sync::Arc;
|
||||||
|
use std::{error::Error, time::Duration};
|
||||||
|
use std::{
|
||||||
|
io::{BufRead, BufReader},
|
||||||
|
ops::Sub,
|
||||||
|
};
|
||||||
use tokio::process::Command;
|
use tokio::process::Command;
|
||||||
use tracing::debug;
|
use tracing::debug;
|
||||||
use twilight_model::application::interaction::Interaction;
|
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_model::http::interaction::{InteractionResponse, InteractionResponseType};
|
||||||
use twilight_util::builder::embed::EmbedBuilder;
|
use twilight_util::builder::embed::EmbedBuilder;
|
||||||
use twilight_util::builder::InteractionResponseDataBuilder;
|
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||||
use url::Url;
|
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>,
|
||||||
|
original_url: Option<String>,
|
||||||
|
title: String,
|
||||||
|
channel: String,
|
||||||
|
playlist: Option<String>,
|
||||||
|
playlist_id: Option<String>,
|
||||||
|
duration_string: String,
|
||||||
|
thumbnail: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_playlist_url(playlist_id: &str) -> String {
|
||||||
|
format!("https://www.youtube.com/playlist?list={}", playlist_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_tracks(
|
||||||
|
url: String,
|
||||||
|
) -> Result<Vec<YouTubeTrack>, Box<dyn Error + Send + Sync + 'static>> {
|
||||||
|
let output = Command::new("yt-dlp")
|
||||||
|
.args(vec![&url, "--flat-playlist", "-j"])
|
||||||
|
.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) {
|
||||||
|
if stderr.contains("This video is only available to Music Premium members") {
|
||||||
|
return Err("This video is only available to Music Premium members".into());
|
||||||
|
}
|
||||||
|
if stderr.contains("YouTube said: The playlist does not exist.") {
|
||||||
|
return Err("YouTube said: The playlist does not exist.".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Err("No tracks found".into());
|
||||||
|
}
|
||||||
|
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(
|
pub(crate) async fn play(
|
||||||
interaction: Interaction,
|
interaction: Box<InteractionCreate>,
|
||||||
state: State,
|
state: State,
|
||||||
query: String,
|
query: String,
|
||||||
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
debug!(
|
tracing::info!(
|
||||||
"play command in channel {:?} by {:?}",
|
"play command in channel {:?} by {:?}",
|
||||||
interaction.channel,
|
interaction.channel,
|
||||||
interaction.author(),
|
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);
|
let content = format!("Adding track(s) to the queue: {}", query);
|
||||||
let yellow = 0xFE_E7_5C;
|
tracing::info!("content: {:?}", content);
|
||||||
let embeds = vec![EmbedBuilder::new()
|
let embeds = vec![EmbedBuilder::new()
|
||||||
.description(content)
|
.description(content)
|
||||||
.color(yellow)
|
.color(colors::YELLOW)
|
||||||
.build()];
|
.build()];
|
||||||
let interaction_response_data = InteractionResponseDataBuilder::new().embeds(embeds).build();
|
let interaction_response_data = InteractionResponseDataBuilder::new()
|
||||||
|
.flags(MessageFlags::LOADING)
|
||||||
|
.embeds(embeds)
|
||||||
|
.build();
|
||||||
let response = InteractionResponse {
|
let response = InteractionResponse {
|
||||||
kind: InteractionResponseType::ChannelMessageWithSource,
|
kind: InteractionResponseType::DeferredChannelMessageWithSource,
|
||||||
data: Some(interaction_response_data),
|
data: Some(interaction_response_data),
|
||||||
};
|
};
|
||||||
state
|
state
|
||||||
@@ -57,101 +320,181 @@ pub(crate) async fn play(
|
|||||||
query
|
query
|
||||||
};
|
};
|
||||||
|
|
||||||
debug!("query: {:?}", query);
|
tracing::info!("query: {:?}", query);
|
||||||
|
|
||||||
let urls = get_playlist_urls(query).await?;
|
let tracks = get_tracks(query).await?;
|
||||||
|
tracing::info!("got tracks: {:?}", tracks);
|
||||||
|
|
||||||
|
if tracks.len() > 1 {
|
||||||
|
let first_track = tracks.first().unwrap();
|
||||||
|
let content = format!(
|
||||||
|
"Adding playlist [{}]({})",
|
||||||
|
first_track
|
||||||
|
.playlist
|
||||||
|
.clone()
|
||||||
|
.unwrap_or("Unknown".to_string()),
|
||||||
|
build_playlist_url(
|
||||||
|
&first_track
|
||||||
|
.playlist_id
|
||||||
|
.clone()
|
||||||
|
.unwrap_or("Unknown".to_string())
|
||||||
|
)
|
||||||
|
);
|
||||||
|
let embeds = vec![EmbedBuilder::new()
|
||||||
|
.description(content)
|
||||||
|
.color(colors::BLURPLE)
|
||||||
|
.build()];
|
||||||
|
state
|
||||||
|
.http
|
||||||
|
.interaction(interaction.application_id)
|
||||||
|
.update_response(&interaction.token)
|
||||||
|
.embeds(Some(&embeds))
|
||||||
|
.await
|
||||||
|
.context("Could not send playlist loading message")?;
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(call_lock) = state.songbird.get(guild_id) {
|
if let Some(call_lock) = state.songbird.get(guild_id) {
|
||||||
let call = call_lock.lock().await;
|
let call = call_lock.lock().await;
|
||||||
call.queue().resume()?;
|
call.queue().resume().context("Could not resume playing")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut tracks_added = vec![];
|
let mut tracks_added = vec![];
|
||||||
for url in urls {
|
for yttrack in &tracks {
|
||||||
let mut src = YoutubeDl::new(reqwest::Client::new(), url.to_string());
|
tracing::debug!("track: {:?}", yttrack);
|
||||||
if let Ok(metadata) = src.aux_metadata().await {
|
let url = yttrack
|
||||||
debug!("metadata: {:?}", metadata);
|
.original_url
|
||||||
tracks_added.push((url.clone(), metadata.title.clone()));
|
.clone()
|
||||||
|
.or(yttrack.url.clone())
|
||||||
|
.context("Could not find url")?;
|
||||||
|
|
||||||
if let Some(call_lock) = state.songbird.get(guild_id) {
|
let mut src = YoutubeDl::new(state.client.clone(), url.clone());
|
||||||
let mut call = call_lock.lock().await;
|
|
||||||
let handle = call.enqueue_with_preload(
|
match src.aux_metadata().await {
|
||||||
src.into(),
|
Ok(metadata) => {
|
||||||
metadata.duration.map(|duration| -> Duration {
|
debug!("metadata: {:?}", metadata);
|
||||||
if duration.as_secs() > 5 {
|
|
||||||
duration.sub(Duration::from_secs(5))
|
let track: Track = Track::new_with_data(
|
||||||
} else {
|
src.clone().into(),
|
||||||
duration
|
Arc::new(Metadata {
|
||||||
}
|
title: metadata.title.clone(),
|
||||||
|
duration: metadata.duration,
|
||||||
|
url: url.clone(),
|
||||||
|
src,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
let mut x = handle.typemap().write().await;
|
|
||||||
x.insert::<MetadataMap>(Metadata {
|
persistence(interaction, yttrack, Arc::clone(&state))
|
||||||
title: metadata.title,
|
.await
|
||||||
duration: metadata.duration,
|
.unwrap_or_else(|e| {
|
||||||
url,
|
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,
|
||||||
|
metadata.duration.map(|duration| -> Duration {
|
||||||
|
if duration.as_secs() > 5 {
|
||||||
|
duration.sub(Duration::from_secs(5))
|
||||||
|
} else {
|
||||||
|
duration
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
None => tracing::error!("could not get call lock"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
Err(e) => {
|
||||||
}
|
tracing::error!("could not get metadata: {:?}", e);
|
||||||
let mut content = String::new();
|
if e.to_string()
|
||||||
let num_tracks_added = tracks_added.len();
|
.contains("Sign in to confirm you’re not a bot.")
|
||||||
match num_tracks_added {
|
{
|
||||||
0 => {}
|
let content =
|
||||||
1 => {
|
"I seem to have been flagged by YouTube as a bot. :-(".to_string();
|
||||||
let track = tracks_added.first().unwrap().clone();
|
let embeds = vec to the queue", title, url);
|
.build()];
|
||||||
}
|
state
|
||||||
_ => {
|
.http
|
||||||
content = format!("Added {} tracks to the queue:\n", num_tracks_added);
|
.interaction(interaction.application_id)
|
||||||
for track in tracks_added.into_iter().take(num_tracks_added.min(3)) {
|
.update_response(&interaction.token)
|
||||||
let title = track.1.unwrap();
|
.embeds(Some(&embeds))
|
||||||
let url = track.0;
|
.await?;
|
||||||
content.push_str(&format!(" \"[{}]({})\"\n", title, url));
|
return Ok(());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let blurple = 0x58_65_F2;
|
let embeds = build_embeds(&tracks, &tracks_added);
|
||||||
let embeds = vec![EmbedBuilder::new()
|
|
||||||
.description(content)
|
|
||||||
.color(blurple)
|
|
||||||
.build()];
|
|
||||||
state
|
state
|
||||||
.http
|
.http
|
||||||
.interaction(interaction.application_id)
|
.interaction(interaction.application_id)
|
||||||
.update_response(&interaction.token)
|
.update_response(&interaction.token)
|
||||||
.embeds(Some(&embeds))
|
.embeds(Some(&embeds))
|
||||||
.unwrap()
|
.await
|
||||||
.await?;
|
.context("Could not send final play message")?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_playlist_urls(
|
#[cfg(test)]
|
||||||
url: String,
|
mod tests {
|
||||||
) -> Result<Vec<String>, Box<dyn Error + Send + Sync + 'static>> {
|
use super::*;
|
||||||
let output = Command::new("yt-dlp")
|
|
||||||
.args(vec![&url, "--flat-playlist", "-j"])
|
|
||||||
.output()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let reader = BufReader::new(output.stdout.as_slice());
|
#[tokio::test]
|
||||||
let urls = reader
|
async fn test_get_tracks() {
|
||||||
.lines()
|
let urls = [
|
||||||
.map_while(Result::ok)
|
"https://www.youtube.com/playlist?list=PLFxxhcEeloYa1OlnWD6UgxlVQKJH5i_0p",
|
||||||
.map(|line| {
|
"https://music.youtube.com/watch?v=RO75ZzqUOJw",
|
||||||
let entry: Value = serde_json::from_str(&line).unwrap();
|
"https://www.youtube.com/watch?v=qVHyl0P_P-M",
|
||||||
entry
|
"https://www.youtube.com/watch?v=34CZjsEI1yU",
|
||||||
.get("webpage_url")
|
];
|
||||||
.unwrap()
|
for url in urls.iter() {
|
||||||
.as_str()
|
println!("url: {:?}", url);
|
||||||
|
let tracks = get_tracks(url.to_string()).await.unwrap();
|
||||||
|
assert!(!tracks.is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_premium_tracks() {
|
||||||
|
let urls = ["https://www.youtube.com/watch?v=QgMZRmxQ0Dc"];
|
||||||
|
for url in urls.iter() {
|
||||||
|
println!("url: {:?}", url);
|
||||||
|
let tracks = get_tracks(url.to_string()).await;
|
||||||
|
assert!(tracks.is_err());
|
||||||
|
assert!(tracks
|
||||||
|
.err()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.to_string()
|
.to_string()
|
||||||
})
|
.contains("This video is only available to Music Premium members"));
|
||||||
.collect();
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(urls)
|
#[tokio::test]
|
||||||
|
async fn test_playlist_does_not_exist_tracks() {
|
||||||
|
let urls = ["https://www.youtube.com/playlist?list=PLox0oG0uy8Lc1IaIfGyrvtuRItuEyJiyG"];
|
||||||
|
for url in urls.iter() {
|
||||||
|
println!("url: {:?}", url);
|
||||||
|
let tracks = get_tracks(url.to_string()).await;
|
||||||
|
assert!(tracks.is_err());
|
||||||
|
assert!(tracks
|
||||||
|
.err()
|
||||||
|
.unwrap()
|
||||||
|
.to_string()
|
||||||
|
.contains("YouTube said: The playlist does not exist."));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,114 @@
|
|||||||
|
use songbird::tracks::TrackHandle;
|
||||||
|
use twilight_model::channel::message::component::{ActionRow, Button, ButtonStyle};
|
||||||
|
use twilight_model::channel::message::{Component, Embed, EmojiReactionType, MessageFlags};
|
||||||
|
use twilight_model::gateway::payload::incoming::InteractionCreate;
|
||||||
|
use twilight_model::http::interaction::InteractionResponse;
|
||||||
use twilight_model::http::interaction::InteractionResponseType;
|
use twilight_model::http::interaction::InteractionResponseType;
|
||||||
use twilight_model::{
|
|
||||||
application::interaction::Interaction, channel::message::MessageFlags,
|
|
||||||
http::interaction::InteractionResponse,
|
|
||||||
};
|
|
||||||
use twilight_util::builder::embed::EmbedBuilder;
|
use twilight_util::builder::embed::EmbedBuilder;
|
||||||
use twilight_util::builder::InteractionResponseDataBuilder;
|
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||||
|
|
||||||
use crate::{metadata::MetadataMap, state::State};
|
use crate::colors;
|
||||||
|
use crate::metadata::Metadata;
|
||||||
|
use crate::state::State;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
|
||||||
|
pub(crate) const TRACKS_PER_PAGE: usize = 5;
|
||||||
|
|
||||||
|
fn format_duration(duration: std::time::Duration) -> String {
|
||||||
|
let res = duration.as_secs();
|
||||||
|
let hours = res / (60 * 60);
|
||||||
|
let res = res - hours * 60 * 60;
|
||||||
|
let minutes = res / 60;
|
||||||
|
let res = res - minutes * 60;
|
||||||
|
let seconds = res;
|
||||||
|
let mut s = String::new();
|
||||||
|
if hours > 0 {
|
||||||
|
s.push_str(format!("{:02}:", hours).as_str());
|
||||||
|
}
|
||||||
|
s.push_str(format!("{:02}:{:02}", minutes, seconds).as_str());
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn build_queue_embeds(queue: &[TrackHandle], page: usize) -> Vec<Embed> {
|
||||||
|
let mut message = String::new();
|
||||||
|
if queue.is_empty() {
|
||||||
|
message.push_str("There are no tracks in the queue.\n");
|
||||||
|
}
|
||||||
|
for track in queue
|
||||||
|
.iter()
|
||||||
|
.skip(TRACKS_PER_PAGE * page)
|
||||||
|
.take(TRACKS_PER_PAGE)
|
||||||
|
{
|
||||||
|
let metadata = track.data::<Metadata>();
|
||||||
|
message.push_str(
|
||||||
|
format!(
|
||||||
|
"* [{}]({})",
|
||||||
|
metadata.title.clone().unwrap_or("Unknown".to_string()),
|
||||||
|
metadata.url,
|
||||||
|
)
|
||||||
|
.as_str(),
|
||||||
|
);
|
||||||
|
if let Some(duration) = metadata.duration {
|
||||||
|
message.push_str(" (");
|
||||||
|
message.push_str(&format_duration(duration));
|
||||||
|
message.push(')');
|
||||||
|
}
|
||||||
|
message.push('\n');
|
||||||
|
}
|
||||||
|
message.push('\n');
|
||||||
|
|
||||||
|
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)
|
||||||
|
.color(colors::BLURPLE)
|
||||||
|
.build()]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn build_action_row(page: usize, n_pages: usize) -> Vec<Component> {
|
||||||
|
vec![Component::ActionRow(ActionRow {
|
||||||
|
components: vec![
|
||||||
|
Component::Button(Button {
|
||||||
|
custom_id: Some(format!("page:{}", page as i32 - 1)),
|
||||||
|
style: ButtonStyle::Primary,
|
||||||
|
label: Some("Previous page".to_string()),
|
||||||
|
emoji: Some(EmojiReactionType::Unicode {
|
||||||
|
name: "⬅️".to_string(),
|
||||||
|
}),
|
||||||
|
url: None,
|
||||||
|
disabled: page == 0,
|
||||||
|
sku_id: None,
|
||||||
|
}),
|
||||||
|
Component::Button(Button {
|
||||||
|
custom_id: Some(format!("page:{}", page)),
|
||||||
|
style: ButtonStyle::Primary,
|
||||||
|
label: Some("Refresh".to_string()),
|
||||||
|
emoji: Some(EmojiReactionType::Unicode {
|
||||||
|
name: "🔄".to_string(),
|
||||||
|
}),
|
||||||
|
url: None,
|
||||||
|
disabled: false,
|
||||||
|
sku_id: None,
|
||||||
|
}),
|
||||||
|
Component::Button(Button {
|
||||||
|
custom_id: Some(format!("page:{}", page + 1)),
|
||||||
|
style: ButtonStyle::Primary,
|
||||||
|
label: Some("Next page".to_string()),
|
||||||
|
emoji: Some(EmojiReactionType::Unicode {
|
||||||
|
name: "➡️".to_string(),
|
||||||
|
}),
|
||||||
|
url: None,
|
||||||
|
disabled: page >= n_pages - 1,
|
||||||
|
sku_id: None,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
})]
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) async fn queue(
|
pub(crate) async fn queue(
|
||||||
interaction: Interaction,
|
interaction: Box<InteractionCreate>,
|
||||||
state: State,
|
state: State,
|
||||||
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
tracing::debug!(
|
tracing::debug!(
|
||||||
@@ -22,59 +120,43 @@ pub(crate) async fn queue(
|
|||||||
let Some(guild_id) = interaction.guild_id else {
|
let Some(guild_id) = interaction.guild_id else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let content = "Fetching queue".to_string();
|
||||||
|
let embeds = vec![EmbedBuilder::new()
|
||||||
|
.description(content)
|
||||||
|
.color(colors::YELLOW)
|
||||||
|
.build()];
|
||||||
|
let interaction_response_data = InteractionResponseDataBuilder::new()
|
||||||
|
.embeds(embeds)
|
||||||
|
.flags(MessageFlags::LOADING)
|
||||||
|
.build();
|
||||||
|
let response = InteractionResponse {
|
||||||
|
kind: InteractionResponseType::DeferredChannelMessageWithSource,
|
||||||
|
data: Some(interaction_response_data),
|
||||||
|
};
|
||||||
|
state
|
||||||
|
.http
|
||||||
|
.interaction(interaction.application_id)
|
||||||
|
.create_response(interaction.id, &interaction.token, &response)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let mut queue = Vec::new();
|
||||||
if let Some(call_lock) = state.songbird.get(guild_id) {
|
if let Some(call_lock) = state.songbird.get(guild_id) {
|
||||||
let call = call_lock.lock().await;
|
let call = call_lock.lock().await;
|
||||||
let queue = call.queue().current_queue();
|
queue = call.queue().current_queue();
|
||||||
let mut message = String::new();
|
|
||||||
if queue.is_empty() {
|
|
||||||
message.push_str("There are no tracks in the queue.\n");
|
|
||||||
} else {
|
|
||||||
message.push_str("Next songs are:\n");
|
|
||||||
}
|
|
||||||
for track in queue.iter().take(5) {
|
|
||||||
let map = track.typemap().read().await;
|
|
||||||
let metadata = map.get::<MetadataMap>().unwrap();
|
|
||||||
message.push_str(
|
|
||||||
format!(
|
|
||||||
"* [{}]({})",
|
|
||||||
metadata.title.clone().unwrap_or("Unknown".to_string()),
|
|
||||||
metadata.url,
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
);
|
|
||||||
if let Some(duration) = metadata.duration {
|
|
||||||
let res = duration.as_secs();
|
|
||||||
let hours = res / (60 * 60);
|
|
||||||
let res = res - hours * 60 * 60;
|
|
||||||
let minutes = res / 60;
|
|
||||||
let res = res - minutes * 60;
|
|
||||||
let seconds = res;
|
|
||||||
message.push_str(" (");
|
|
||||||
if hours > 0 {
|
|
||||||
message.push_str(format!("{:02}:", hours).as_str());
|
|
||||||
}
|
|
||||||
message.push_str(format!("{:02}:{:02}", minutes, seconds).as_str());
|
|
||||||
message.push(')');
|
|
||||||
}
|
|
||||||
message.push('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
let embeds = vec![EmbedBuilder::new().description(&message).build()];
|
|
||||||
let interaction_response_data = InteractionResponseDataBuilder::new()
|
|
||||||
.flags(MessageFlags::EPHEMERAL)
|
|
||||||
.embeds(embeds)
|
|
||||||
.build();
|
|
||||||
|
|
||||||
let response = InteractionResponse {
|
|
||||||
kind: InteractionResponseType::ChannelMessageWithSource,
|
|
||||||
data: Some(interaction_response_data),
|
|
||||||
};
|
|
||||||
|
|
||||||
state
|
|
||||||
.http
|
|
||||||
.interaction(interaction.application_id)
|
|
||||||
.create_response(interaction.id, &interaction.token, &response)
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let embeds = build_queue_embeds(&queue, 0).await;
|
||||||
|
let n_pages = queue.len().div_ceil(TRACKS_PER_PAGE);
|
||||||
|
let action_row = build_action_row(0, n_pages);
|
||||||
|
|
||||||
|
state
|
||||||
|
.http
|
||||||
|
.interaction(interaction.application_id)
|
||||||
|
.update_response(&interaction.token)
|
||||||
|
.embeds(Some(&embeds))
|
||||||
|
.components(Some(&action_row))
|
||||||
|
.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
use crate::state::State;
|
use crate::state::State;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use twilight_model::{
|
use twilight_model::{
|
||||||
application::interaction::Interaction,
|
|
||||||
channel::message::MessageFlags,
|
channel::message::MessageFlags,
|
||||||
|
gateway::payload::incoming::InteractionCreate,
|
||||||
http::interaction::{InteractionResponse, InteractionResponseType},
|
http::interaction::{InteractionResponse, InteractionResponseType},
|
||||||
};
|
};
|
||||||
use twilight_util::builder::InteractionResponseDataBuilder;
|
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||||
|
|
||||||
pub(crate) async fn resume(
|
pub(crate) async fn resume(
|
||||||
interaction: Interaction,
|
interaction: Box<InteractionCreate>,
|
||||||
state: State,
|
state: State,
|
||||||
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
tracing::debug!(
|
tracing::debug!(
|
||||||
|
|||||||
45
src/commands/skip.rs
Normal file
45
src/commands/skip.rs
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
use crate::state::State;
|
||||||
|
use std::error::Error;
|
||||||
|
use twilight_model::{
|
||||||
|
gateway::payload::incoming::InteractionCreate,
|
||||||
|
http::interaction::{InteractionResponse, InteractionResponseType},
|
||||||
|
};
|
||||||
|
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||||
|
|
||||||
|
pub(crate) async fn skip(
|
||||||
|
interaction: Box<InteractionCreate>,
|
||||||
|
state: State,
|
||||||
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
|
tracing::debug!(
|
||||||
|
"skip command in guild {:?} in channel {:?} by {:?}",
|
||||||
|
interaction.guild_id,
|
||||||
|
interaction.channel,
|
||||||
|
interaction.author(),
|
||||||
|
);
|
||||||
|
|
||||||
|
let Some(guild_id) = interaction.guild_id else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(call_lock) = state.songbird.get(guild_id) {
|
||||||
|
let call = call_lock.lock().await;
|
||||||
|
call.queue().skip()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let interaction_response_data = InteractionResponseDataBuilder::new()
|
||||||
|
.content("Skipped a track")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
let response = InteractionResponse {
|
||||||
|
kind: InteractionResponseType::ChannelMessageWithSource,
|
||||||
|
data: Some(interaction_response_data),
|
||||||
|
};
|
||||||
|
|
||||||
|
state
|
||||||
|
.http
|
||||||
|
.interaction(interaction.application_id)
|
||||||
|
.create_response(interaction.id, &interaction.token, &response)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use twilight_model::{
|
use twilight_model::{
|
||||||
application::interaction::Interaction,
|
|
||||||
channel::message::MessageFlags,
|
channel::message::MessageFlags,
|
||||||
|
gateway::payload::incoming::InteractionCreate,
|
||||||
http::interaction::{InteractionResponse, InteractionResponseType},
|
http::interaction::{InteractionResponse, InteractionResponseType},
|
||||||
};
|
};
|
||||||
use twilight_util::builder::InteractionResponseDataBuilder;
|
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||||
@@ -9,7 +9,7 @@ use crate::state::State;
|
|||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
|
||||||
pub(crate) async fn stop(
|
pub(crate) async fn stop(
|
||||||
interaction: Interaction,
|
interaction: Box<InteractionCreate>,
|
||||||
state: State,
|
state: State,
|
||||||
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
||||||
tracing::debug!(
|
tracing::debug!(
|
||||||
@@ -23,6 +23,10 @@ pub(crate) async fn stop(
|
|||||||
return Ok(());
|
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) {
|
if let Some(call_lock) = state.songbird.get(guild_id) {
|
||||||
let call = call_lock.lock().await;
|
let call = call_lock.lock().await;
|
||||||
call.queue().stop();
|
call.queue().stop();
|
||||||
|
|||||||
1
src/db/mod.rs
Normal file
1
src/db/mod.rs
Normal file
@@ -0,0 +1 @@
|
|||||||
|
pub mod track;
|
||||||
167
src/db/track.rs
Normal file
167
src/db/track.rs
Normal 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(())
|
||||||
|
}
|
||||||
245
src/handler.rs
245
src/handler.rs
@@ -1,72 +1,20 @@
|
|||||||
use crate::commands::{delete, join, leave, pause, play, queue, resume, stop};
|
use crate::commands::queue::{build_action_row, build_queue_embeds, TRACKS_PER_PAGE};
|
||||||
|
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::state::State;
|
||||||
use futures::Future;
|
use crate::utils::spawn;
|
||||||
use std::error::Error;
|
use anyhow::Context;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tracing::debug;
|
|
||||||
use twilight_gateway::Event;
|
use twilight_gateway::Event;
|
||||||
use twilight_model::application::interaction::application_command::CommandOptionValue;
|
use twilight_model::application::interaction::message_component::MessageComponentInteractionData;
|
||||||
use twilight_model::application::interaction::{Interaction, InteractionData};
|
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};
|
||||||
#[derive(Debug)]
|
use twilight_util::builder::InteractionResponseDataBuilder;
|
||||||
enum InteractionCommand {
|
|
||||||
Play(Interaction, String),
|
|
||||||
Stop(Interaction),
|
|
||||||
Pause(Interaction),
|
|
||||||
Resume(Interaction),
|
|
||||||
Leave(Interaction),
|
|
||||||
Join(Interaction),
|
|
||||||
Queue(Interaction),
|
|
||||||
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(())
|
|
||||||
}
|
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
pub(crate) struct Handler {
|
pub(crate) struct Handler {
|
||||||
state: State,
|
state: State,
|
||||||
}
|
}
|
||||||
@@ -75,80 +23,117 @@ impl Handler {
|
|||||||
pub(crate) fn new(state: State) -> Self {
|
pub(crate) fn new(state: State) -> Self {
|
||||||
Self { state }
|
Self { state }
|
||||||
}
|
}
|
||||||
pub(crate) async fn act(&self, event: Event) {
|
pub(crate) async fn act(&self, event: Event) -> anyhow::Result<()> {
|
||||||
match &event {
|
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('!') => {
|
Event::MessageCreate(message) if message.content.starts_with('!') => {
|
||||||
if message.content.contains("!delete") {
|
if message.content.contains("!delete") {
|
||||||
spawn(delete(message.0.clone(), Arc::clone(&self.state)));
|
spawn(delete(message.0.clone(), Arc::clone(&self.state)));
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
Event::VoiceStateUpdate(update) => {
|
_ => Ok(()),
|
||||||
spawn(leave_if_alone(*update.clone(), Arc::clone(&self.state)))
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let interaction_command = match event {
|
async fn handle_voice_state_update(&self, event: &Event) -> anyhow::Result<()> {
|
||||||
Event::InteractionCreate(interaction) => {
|
match event {
|
||||||
debug!("interaction: {:?}", &interaction);
|
Event::VoiceStateUpdate(update) => {
|
||||||
match &interaction.data {
|
let guild_id = update.guild_id.context("Guild ID not found")?;
|
||||||
Some(InteractionData::ApplicationCommand(command)) => {
|
spawn(leave_if_alone(guild_id, Arc::clone(&self.state)));
|
||||||
debug!("command: {:?}", command);
|
Ok(())
|
||||||
match command.name.as_str() {
|
}
|
||||||
"play" => {
|
_ => Ok(()),
|
||||||
if let Some(query_option) =
|
}
|
||||||
command.options.iter().find(|opt| opt.name == "query")
|
}
|
||||||
{
|
|
||||||
if let CommandOptionValue::String(query) = &query_option.value {
|
async fn handle_interaction(&self, event: &Event) -> anyhow::Result<()> {
|
||||||
InteractionCommand::Play(
|
match event {
|
||||||
interaction.0.clone(),
|
Event::InteractionCreate(interaction) => match &interaction.data {
|
||||||
query.clone(),
|
Some(InteractionData::ApplicationCommand(command)) => {
|
||||||
)
|
self.handle_application_command(command.clone().into(), interaction.clone())
|
||||||
} else {
|
|
||||||
InteractionCommand::NotImplemented
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
InteractionCommand::NotImplemented
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"stop" => InteractionCommand::Stop(interaction.0.clone()),
|
|
||||||
"pause" => InteractionCommand::Pause(interaction.0.clone()),
|
|
||||||
"resume" => InteractionCommand::Resume(interaction.0.clone()),
|
|
||||||
"leave" => InteractionCommand::Leave(interaction.0.clone()),
|
|
||||||
"join" => InteractionCommand::Join(interaction.0.clone()),
|
|
||||||
"queue" => InteractionCommand::Queue(interaction.0.clone()),
|
|
||||||
_ => InteractionCommand::NotImplemented,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => InteractionCommand::NotImplemented,
|
|
||||||
}
|
}
|
||||||
|
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::NotImplemented,
|
Ok(())
|
||||||
};
|
}
|
||||||
debug!("{:?}", interaction_command);
|
}
|
||||||
match interaction_command {
|
|
||||||
InteractionCommand::Play(interaction, query) => {
|
async fn handle_message_component(
|
||||||
spawn(play(interaction, Arc::clone(&self.state), query))
|
&self,
|
||||||
|
data: &MessageComponentInteractionData,
|
||||||
|
interaction: Box<InteractionCreate>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
if !data.custom_id.starts_with("page:") {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let page = data
|
||||||
|
.custom_id
|
||||||
|
.trim_start_matches("page:")
|
||||||
|
.parse::<usize>()
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
if let Some(guild_id) = interaction.guild_id {
|
||||||
|
let mut queue = Vec::new();
|
||||||
|
if let Some(call_lock) = self.state.songbird.get(guild_id) {
|
||||||
|
let call = call_lock.lock().await;
|
||||||
|
queue = call.queue().current_queue();
|
||||||
}
|
}
|
||||||
InteractionCommand::Stop(interaction) => {
|
let n_pages = queue.len().div_ceil(TRACKS_PER_PAGE);
|
||||||
spawn(stop(interaction, Arc::clone(&self.state)))
|
let page = page.min(n_pages - 1).max(0);
|
||||||
}
|
let embeds = build_queue_embeds(&queue, page).await;
|
||||||
InteractionCommand::Pause(interaction) => {
|
let action_row = build_action_row(page, n_pages);
|
||||||
spawn(pause(interaction, Arc::clone(&self.state)))
|
|
||||||
}
|
let interaction_response_data = InteractionResponseDataBuilder::new()
|
||||||
InteractionCommand::Resume(interaction) => {
|
.embeds(embeds)
|
||||||
spawn(resume(interaction, Arc::clone(&self.state)))
|
.components(action_row)
|
||||||
}
|
.build();
|
||||||
InteractionCommand::Leave(interaction) => {
|
let response = InteractionResponse {
|
||||||
spawn(leave(interaction, Arc::clone(&self.state)))
|
kind: InteractionResponseType::UpdateMessage,
|
||||||
}
|
data: Some(interaction_response_data),
|
||||||
InteractionCommand::Join(interaction) => {
|
};
|
||||||
spawn(join(interaction, Arc::clone(&self.state)))
|
self.state
|
||||||
}
|
.http
|
||||||
InteractionCommand::Queue(interaction) => {
|
.interaction(interaction.application_id)
|
||||||
spawn(queue(interaction, Arc::clone(&self.state)))
|
.create_response(interaction.id, &interaction.token, &response)
|
||||||
}
|
.await?;
|
||||||
_ => {}
|
Ok(())
|
||||||
};
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
44
src/interaction_commands.rs
Normal file
44
src/interaction_commands.rs
Normal 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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
125
src/main.rs
125
src/main.rs
@@ -1,23 +1,23 @@
|
|||||||
mod handler;
|
mod handler;
|
||||||
use handler::Handler;
|
use handler::Handler;
|
||||||
|
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
|
||||||
|
mod colors;
|
||||||
mod commands;
|
mod commands;
|
||||||
|
mod db;
|
||||||
|
mod interaction_commands;
|
||||||
mod metadata;
|
mod metadata;
|
||||||
mod signal;
|
mod signal;
|
||||||
mod state;
|
mod state;
|
||||||
|
mod utils;
|
||||||
|
|
||||||
use crate::commands::get_chat_commands;
|
use crate::commands::get_chat_commands;
|
||||||
use dotenv::dotenv;
|
use dotenv::dotenv;
|
||||||
use futures::StreamExt;
|
|
||||||
use signal::signal_handler;
|
|
||||||
use songbird::{shards::TwilightMap, Songbird};
|
use songbird::{shards::TwilightMap, Songbird};
|
||||||
use state::StateRef;
|
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 tracing::{debug, info};
|
||||||
use twilight_cache_inmemory::InMemoryCache;
|
use twilight_cache_inmemory::InMemoryCache;
|
||||||
use twilight_gateway::{
|
use twilight_gateway::{Event, EventTypeFlags, Intents, Shard, StreamExt as _};
|
||||||
stream::{self, ShardEventStream},
|
|
||||||
Intents, Shard,
|
|
||||||
};
|
|
||||||
use twilight_http::Client as HttpClient;
|
use twilight_http::Client as HttpClient;
|
||||||
use twilight_model::id::Id;
|
use twilight_model::id::Id;
|
||||||
use twilight_standby::Standby;
|
use twilight_standby::Standby;
|
||||||
@@ -28,12 +28,21 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
|||||||
|
|
||||||
println!("Starting up...");
|
println!("Starting up...");
|
||||||
|
|
||||||
// Initialize the tracing subscriber.
|
|
||||||
tracing_subscriber::fmt::init();
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
info!("Starting up...");
|
info!("Starting up...");
|
||||||
|
|
||||||
let (mut shards, state) = {
|
let (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 token = env::var("DISCORD_TOKEN").map_err(|_| "DISCORD_TOKEN is not set")?;
|
||||||
let app_id = env::var("DISCORD_APP_ID")
|
let app_id = env::var("DISCORD_APP_ID")
|
||||||
.map_err(|_| "DISCORD_APP_ID is not set")?
|
.map_err(|_| "DISCORD_APP_ID is not set")?
|
||||||
@@ -56,7 +65,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
|||||||
| Intents::MESSAGE_CONTENT;
|
| Intents::MESSAGE_CONTENT;
|
||||||
let config = twilight_gateway::Config::new(token.clone(), intents);
|
let config = twilight_gateway::Config::new(token.clone(), intents);
|
||||||
let shards: Vec<Shard> =
|
let shards: Vec<Shard> =
|
||||||
stream::create_recommended(&http, config, |_, builder| builder.build())
|
twilight_gateway::create_recommended(&http, config, |_, builder| builder.build())
|
||||||
.await?
|
.await?
|
||||||
.collect();
|
.collect();
|
||||||
let senders = TwilightMap::new(
|
let senders = TwilightMap::new(
|
||||||
@@ -67,6 +76,11 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
|||||||
);
|
);
|
||||||
let songbird = Songbird::twilight(Arc::new(senders), user_id);
|
let songbird = Songbird::twilight(Arc::new(senders), user_id);
|
||||||
let cache = InMemoryCache::new();
|
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,
|
shards,
|
||||||
@@ -75,6 +89,9 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
|||||||
cache,
|
cache,
|
||||||
songbird,
|
songbird,
|
||||||
standby: Standby::new(),
|
standby: Standby::new(),
|
||||||
|
guild_settings: Default::default(),
|
||||||
|
pool,
|
||||||
|
client,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
@@ -82,45 +99,55 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
|
|||||||
info!("Ready to receive events");
|
info!("Ready to receive events");
|
||||||
|
|
||||||
let handler = Handler::new(Arc::clone(&state));
|
let handler = Handler::new(Arc::clone(&state));
|
||||||
let mut stop_rx = signal_handler();
|
// let mut stop_rx = signal_handler();
|
||||||
let mut stream = ShardEventStream::new(shards.iter_mut());
|
let mut set = tokio::task::JoinSet::new();
|
||||||
loop {
|
|
||||||
select! {
|
|
||||||
biased;
|
|
||||||
_ = stop_rx.changed() => {
|
|
||||||
for guild in state.cache.iter().guilds() {
|
|
||||||
if let Some(user) = state.cache.current_user() {
|
|
||||||
if state.cache.voice_state(user.id, guild.id()).is_some() {
|
|
||||||
debug!("Leaving guild {:?}", guild.id());
|
|
||||||
state.songbird.leave(guild.id()).await?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// need to grab next event to properly leave voice channels
|
|
||||||
stream.next().await;
|
|
||||||
break;
|
|
||||||
},
|
|
||||||
next = stream.next() => {
|
|
||||||
let event = match next {
|
|
||||||
Some((_, Ok(event))) => event,
|
|
||||||
Some((_, Err(source))) => {
|
|
||||||
tracing::warn!(?source, "error receiving event");
|
|
||||||
if source.is_fatal() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
None => break,
|
|
||||||
};
|
|
||||||
debug!("Event: {:?}", &event);
|
|
||||||
|
|
||||||
state.cache.update(&event);
|
for shard in shards {
|
||||||
state.standby.process(&event);
|
set.spawn(tokio::spawn(runner(shard, handler.clone(), state.clone())));
|
||||||
state.songbird.process(&event).await;
|
|
||||||
|
|
||||||
handler.act(event).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
set.join_next().await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn runner(mut shard: Shard, handler: Handler, state: Arc<StateRef>) {
|
||||||
|
while let Some(item) = shard.next_event(EventTypeFlags::all()).await {
|
||||||
|
let event = match item {
|
||||||
|
Ok(event) => event,
|
||||||
|
Err(source) => {
|
||||||
|
tracing::warn!(?source, "error receiving event");
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
tokio::spawn({
|
||||||
|
let state = state.clone();
|
||||||
|
let handler = handler.clone();
|
||||||
|
async move {
|
||||||
|
handle_event(event, handler, state)
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|source| {
|
||||||
|
tracing::warn!(?source, "error handling event");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_event(
|
||||||
|
event: Event,
|
||||||
|
handler: Handler,
|
||||||
|
state: Arc<StateRef>,
|
||||||
|
) -> Result<(), Box<dyn Error>> {
|
||||||
|
state.standby.process(&event);
|
||||||
|
state.songbird.process(&event).await;
|
||||||
|
debug!("Event: {:?}", &event);
|
||||||
|
|
||||||
|
state.cache.update(&event);
|
||||||
|
state.standby.process(&event);
|
||||||
|
state.songbird.process(&event).await;
|
||||||
|
|
||||||
|
handler.act(event).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,10 @@
|
|||||||
use songbird::typemap::TypeMapKey;
|
use songbird::input::YoutubeDl;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
pub(crate) struct Metadata {
|
pub(crate) struct Metadata {
|
||||||
pub(crate) title: Option<String>,
|
pub(crate) title: Option<String>,
|
||||||
pub(crate) duration: Option<Duration>,
|
pub(crate) duration: Option<Duration>,
|
||||||
pub(crate) url: String,
|
pub(crate) url: String,
|
||||||
}
|
pub(crate) src: YoutubeDl<'static>,
|
||||||
|
|
||||||
pub(crate) struct MetadataMap;
|
|
||||||
impl TypeMapKey for MetadataMap {
|
|
||||||
type Value = Metadata;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
use tokio::{
|
// use tokio::{
|
||||||
select,
|
// select,
|
||||||
signal::unix::{signal, SignalKind},
|
// signal::unix::{signal, SignalKind},
|
||||||
sync::watch,
|
// sync::watch,
|
||||||
};
|
// };
|
||||||
|
|
||||||
pub(crate) fn signal_handler() -> watch::Receiver<()> {
|
// pub(crate) fn signal_handler() -> watch::Receiver<()> {
|
||||||
let (stop_tx, stop_rx) = watch::channel(());
|
// let (stop_tx, stop_rx) = watch::channel(());
|
||||||
tokio::spawn(async move {
|
// tokio::spawn(async move {
|
||||||
let mut sigterm = signal(SignalKind::terminate()).unwrap();
|
// let mut sigterm = signal(SignalKind::terminate()).unwrap();
|
||||||
let mut sigint = signal(SignalKind::interrupt()).unwrap();
|
// let mut sigint = signal(SignalKind::interrupt()).unwrap();
|
||||||
loop {
|
// loop {
|
||||||
select! {
|
// select! {
|
||||||
_ = sigterm.recv() => println!("Receive SIGTERM"),
|
// _ = sigterm.recv() => println!("Receive SIGTERM"),
|
||||||
_ = sigint.recv() => println!("Receive SIGTERM"),
|
// _ = sigint.recv() => println!("Receive SIGTERM"),
|
||||||
};
|
// };
|
||||||
stop_tx.send(()).unwrap();
|
// stop_tx.send(()).unwrap();
|
||||||
}
|
// }
|
||||||
});
|
// });
|
||||||
stop_rx
|
// stop_rx
|
||||||
}
|
// }
|
||||||
|
|||||||
22
src/state.rs
22
src/state.rs
@@ -1,15 +1,37 @@
|
|||||||
|
use dashmap::DashMap;
|
||||||
use songbird::Songbird;
|
use songbird::Songbird;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use twilight_cache_inmemory::InMemoryCache;
|
use twilight_cache_inmemory::InMemoryCache;
|
||||||
use twilight_http::Client as HttpClient;
|
use twilight_http::Client as HttpClient;
|
||||||
|
use twilight_model::id::{marker::GuildMarker, Id};
|
||||||
use twilight_standby::Standby;
|
use twilight_standby::Standby;
|
||||||
|
|
||||||
pub(crate) type State = Arc<StateRef>;
|
pub(crate) type State = Arc<StateRef>;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
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)]
|
#[derive(Debug)]
|
||||||
pub(crate) struct StateRef {
|
pub(crate) struct StateRef {
|
||||||
pub(crate) http: HttpClient,
|
pub(crate) http: HttpClient,
|
||||||
pub(crate) cache: InMemoryCache,
|
pub(crate) cache: InMemoryCache,
|
||||||
pub(crate) songbird: Songbird,
|
pub(crate) songbird: Songbird,
|
||||||
pub(crate) standby: Standby,
|
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
12
src/utils.rs
Normal 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);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user