This commit is contained in:
Felipe M 2025-05-13 11:52:37 +02:00
commit 1a4986f294
Signed by: fmartingr
GPG key ID: CCFBC5637D4000A8
18 changed files with 3181 additions and 0 deletions

22
.env.example Normal file
View file

@ -0,0 +1,22 @@
# Discord Jukebox Bot - Environment Variables Example
# Rename this file to .env and fill in your values
# Discord configuration (required)
JUKEBOX_DISCORD_TOKEN=your_discord_bot_token_here
# Discord Guild ID: NUMBERS ONLY, do not include variable name or equals sign
JUKEBOX_DISCORD_GUILD_ID=1234567890123456789
# Optional Discord settings
# JUKEBOX_DISCORD_CHANNEL_ID=specific_voice_channel_id
# Subsonic server configuration (required)
JUKEBOX_SUBSONIC_SERVER=https://your-subsonic-server.com
JUKEBOX_SUBSONIC_USERNAME=your_subsonic_username
JUKEBOX_SUBSONIC_PASSWORD=your_subsonic_password
# Optional Subsonic settings
# JUKEBOX_SUBSONIC_VERSION=1.16.1
# Jukebox settings
# JUKEBOX_AUDIO_VOLUME=0.5
# JUKEBOX_TIMEOUT_SEC=30

38
.gitignore vendored Normal file
View file

@ -0,0 +1,38 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
jukebox-bot
jukebox-bot_*
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
# IDE specific files
.idea/
.vscode/
*.swp
*.swo
# Environment variables file
.env
# OS specific files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

133
ARCHITECTURE.md Normal file
View file

@ -0,0 +1,133 @@
# Discord Jukebox Bot - Architecture
This document describes the architecture and design principles of the Discord Jukebox Bot application.
## Overview
Discord Jukebox Bot is a Go application that connects to a Discord server and a Subsonic-compatible music server to provide a jukebox experience in Discord voice channels. The bot fetches random tracks from the configured Subsonic server and streams them to a Discord voice channel.
## Project Structure
The project follows a clean, modular structure:
```
discord-jukebox-bot/
├── cmd/ # Command-line applications
│ └── bot/ # Main bot application
│ └── main.go # Entry point
├── pkg/ # Library packages
│ ├── config/ # Configuration management
│ ├── commands/ # Command registration and processing
│ ├── discord/ # Discord integration
│ └── subsonic/ # Subsonic API client
├── README.md # Project documentation
└── ARCHITECTURE.md # This architecture document
```
## Component Design
### Configuration (pkg/config)
The configuration package handles loading and validating environment variables. It uses the `JUKEBOX_` prefix for all environment variables to avoid conflicts with other applications.
Key responsibilities:
- Loading configuration from environment variables and .env files
- Providing default values for optional settings
- Validating required configuration
- Cleaning and normalizing input values (like Guild IDs)
### Subsonic Client (pkg/subsonic)
The Subsonic client package provides a client for interacting with Subsonic-compatible music servers.
Key responsibilities:
- Authenticating with the Subsonic server
- Fetching random songs with detailed metadata
- Generating streaming URLs for audio content
- Handling various API response formats (JSON/XML)
### Discord Bot (pkg/discord)
The Discord bot package manages the connection to Discord and provides voice channel functionality.
Key responsibilities:
- Connecting to Discord
- Managing voice channel connections
- Registering and handling slash commands
- Real-time audio encoding and streaming to voice channels
- Processing audio data from Subsonic to Discord-compatible Opus format
### Commands (pkg/commands)
The commands package sets up and registers all the bot commands, providing a clean interface for adding new commands.
Key responsibilities:
- Registering command handlers
- Providing a centralized setup function for all components
## Data Flow
1. The application starts in `cmd/bot/main.go`, which:
- Loads configuration
- Sets up the Discord bot and command handlers
- Starts the bot and waits for termination signals
2. When a user invokes the `/jukebox play` command:
- The bot joins the user's voice channel
- Fetches random songs from the Subsonic server
- Retrieves audio streams from Subsonic
- Transcodes the audio to Opus format in real-time
- Streams the encoded audio to the Discord voice channel
3. The jukebox player manages the playlist and playback:
- Maintains a queue of songs
- Fetches more songs when the queue is low
- Handles play, stop, and skip commands
- Manages audio encoding and streaming processes
- Controls volume and timing of audio playback
## Extension Points
The application is designed for easy extension:
1. **Adding New Commands**:
- Define new command handlers in `pkg/commands/setup.go`
- Register them with the `RegisterCustomCommand` function
2. **Supporting More Subsonic Features**:
- Extend the Subsonic client in `pkg/subsonic/client.go`
- Add new API methods as needed
3. **Adding New Jukebox Features**:
- Extend the `JukeboxPlayer` in `pkg/discord/jukebox.go`
- Add new command handlers for the features
## Concurrency Model
The application uses Go's concurrency primitives to handle multiple tasks:
- Mutexes protect shared state (playlist, playing status)
- Channels coordinate between the main goroutine and audio playback goroutines
- Dedicated goroutines handle audio encoding and streaming
- Precise timing controls for audio frame delivery
- The main goroutine handles signals for graceful shutdown
## Error Handling
Error handling follows Go's idiomatic approach:
- Functions return errors rather than using exceptions
- Errors are propagated up the call stack
- Critical errors are logged and cause application termination
- Non-critical errors (like playback issues) are logged and the application continues
## Future Improvements
Potential areas for future enhancement:
1. **Enhanced Audio Processing**: Add support for more audio formats and quality settings
2. **Extended Commands**: Add playlist management, search functionality, and more playback controls
3. **Persistent State**: Save state between restarts (current playlist, volume settings)
4. **Multiple Guild Support**: Support running in multiple Discord servers simultaneously
5. **Metrics and Monitoring**: Add telemetry for monitoring bot health and usage
6. **Voice Effects**: Add audio effects like equalizer, normalization, and bass boost
7. **Advanced Subsonic Features**: Support album art, playlists, and other Subsonic-specific features

231
LICENSE Normal file
View file

@ -0,0 +1,231 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
Copyright (C) 2024 fmartingr
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
Copyright (C) 2024 fmartingr
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.

66
Makefile Normal file
View file

@ -0,0 +1,66 @@
# Makefile for Discord Jukebox Bot
# Go parameters
GOCMD = go
GOBUILD = $(GOCMD) build
GORUN = $(GOCMD) run
GOCLEAN = $(GOCMD) clean
GOTEST = $(GOCMD) test
GOGET = $(GOCMD) get
GOMOD = $(GOCMD) mod
BINARY_NAME = jukebox-bot
MAIN_PATH = ./cmd/bot
.PHONY: all build clean run test deps tidy debug
all: deps build
build:
$(GOBUILD) -o $(BINARY_NAME) $(MAIN_PATH)
clean:
$(GOCLEAN)
rm -f $(BINARY_NAME)
run: build
./$(BINARY_NAME)
run-debug: build
./$(BINARY_NAME) -debug
dev:
$(GORUN) $(MAIN_PATH)
dev-debug:
$(GORUN) $(MAIN_PATH) -debug
test:
$(GOTEST) -v ./...
deps:
$(GOMOD) download
tidy:
$(GOMOD) tidy
debug:
@echo "=== Discord Jukebox Bot - Debug Information ==="
@echo "Go version:"
@go version
@echo
@echo "Environment variables (only showing JUKEBOX_ prefix):"
@env | grep JUKEBOX_ || echo "No JUKEBOX_ variables found"
@echo
@echo "Checking .env file:"
@if [ -f .env ]; then echo "✅ .env file exists"; else echo "❌ .env file NOT found"; fi
@echo
@echo "Project structure:"
@find . -type f -name "*.go" | sort
@echo
@echo "To run with debug logging, use: make run-debug"
release:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 $(GOBUILD) -o $(BINARY_NAME)_linux_amd64 $(MAIN_PATH)
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 $(GOBUILD) -o $(BINARY_NAME)_darwin_amd64 $(MAIN_PATH)
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 $(GOBUILD) -o $(BINARY_NAME)_darwin_arm64 $(MAIN_PATH)
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 $(GOBUILD) -o $(BINARY_NAME)_windows_amd64.exe $(MAIN_PATH)

166
README.md Normal file
View file

@ -0,0 +1,166 @@
# Discord Jukebox Bot
A Discord bot written in Go that plays random music from a Subsonic-compatible server. The bot acts as a jukebox, streaming randomly selected songs directly to a Discord voice channel using real-time audio encoding.
## Features
- Connect to any Subsonic-compatible server (Subsonic, Navidrome, Airsonic, etc.)
- Play random music in a Discord voice channel with real-time audio streaming
- Automatic audio format conversion for Discord compatibility
- Simple slash commands for controlling the jukebox
- Configurable through environment variables
## Requirements
- Go 1.24 or later
- A Discord bot token
- A Subsonic-compatible server
## Installation
### From Source
1. Clone the repository:
```
git clone https://github.com/yourusername/discord-jukebox-bot.git
cd discord-jukebox-bot
```
2. Build the application:
```
go build -o jukebox-bot ./cmd/bot
```
3. Set up environment variables (see Configuration section)
4. Create a `.env` file in the project root (or set environment variables)
5. Run the bot:
```
./jukebox-bot # Normal mode
./jukebox-bot -debug # Debug mode with verbose logging
```
## Discord Bot Setup
1. Go to the [Discord Developer Portal](https://discord.com/developers/applications)
2. Create a new application
3. Navigate to the "Bot" tab and click "Add Bot"
4. Under the "Privileged Gateway Intents" section, enable:
- Server Members Intent
- Message Content Intent
- Voice States
5. Copy the bot token (this will be used in your environment variables)
6. Go to the "OAuth2" -> "URL Generator" tab
7. Select the following scopes:
- `bot`
- `applications.commands`
8. Select the following bot permissions:
- Connect
- Speak
- Send Messages
- Use Slash Commands
9. Copy the generated URL and open it in your browser to add the bot to your server
## Configuration
Configure the bot using environment variables with the `JUKEBOX_` prefix. You can set them in two ways:
1. **Using a `.env` file** (recommended):
- Create a `.env` file in the project root directory (same location as the executable)
- Use the provided `.env.example` as a template
- The bot will automatically load variables from this file when it starts
2. **Setting system environment variables**:
- Set the variables in your shell or operating system
### Required Environment Variables
- `JUKEBOX_DISCORD_TOKEN`: Your Discord bot token
- `JUKEBOX_DISCORD_GUILD_ID`: The ID of your Discord server
- `JUKEBOX_SUBSONIC_SERVER`: URL of your Subsonic server (e.g., `https://demo.subsonic.org`)
- `JUKEBOX_SUBSONIC_USERNAME`: Your Subsonic username
- `JUKEBOX_SUBSONIC_PASSWORD`: Your Subsonic password
### Optional Environment Variables
- `JUKEBOX_DISCORD_CHANNEL_ID`: Specific voice channel ID (bot will join user's channel if not specified)
- `JUKEBOX_SUBSONIC_VERSION`: Subsonic API version (default: `1.16.1`)
- `JUKEBOX_AUDIO_VOLUME`: Volume level from 0.0 to 1.0 for audio playback (default: `0.5`)
- `JUKEBOX_TIMEOUT_SEC`: HTTP request timeout in seconds (default: `30`)
### Sample .env File
```
# Required settings
JUKEBOX_DISCORD_TOKEN=your_discord_bot_token_here
JUKEBOX_DISCORD_GUILD_ID=your_discord_guild_id_here
JUKEBOX_SUBSONIC_SERVER=https://your-subsonic-server.com
JUKEBOX_SUBSONIC_USERNAME=your_subsonic_username
JUKEBOX_SUBSONIC_PASSWORD=your_subsonic_password
# Optional settings
# JUKEBOX_DISCORD_CHANNEL_ID=specific_voice_channel_id
# JUKEBOX_SUBSONIC_VERSION=1.16.1
# JUKEBOX_AUDIO_VOLUME=0.5
# JUKEBOX_TIMEOUT_SEC=30
```
## Troubleshooting
If you encounter issues with the bot:
1. First, run the bot in debug mode to get more detailed logs:
```
./jukebox-bot -debug
```
2. Check the [TROUBLESHOOTING.md](TROUBLESHOOTING.md) guide for common problems and solutions.
3. If you're having audio issues, the detailed logs in debug mode will show:
- If songs are being fetched correctly from your Subsonic server
- The exact URL being used to stream audio
- Audio encoding and streaming progress
## Usage
### Debug Mode
If you're experiencing issues with the bot or want to see more detailed logs:
```
# Run with debug mode enabled
./jukebox-bot -debug
# Using make
make run-debug
```
Debug mode provides:
- Detailed logging of Subsonic API requests and responses
- Audio encoding and streaming progress information
- Configuration validation and detailed error messages
### Commands
The bot provides the following slash commands:
- `/jukebox play` - Starts playing random music from your Subsonic library
- `/jukebox stop` - Stops playing music and leaves the voice channel
- `/jukebox skip` - Skips the current song and plays the next one
## License
This project is licensed under the MIT License - see the LICENSE file for details.
## Developer Resources
- [ARCHITECTURE.md](ARCHITECTURE.md) - Documentation of the project architecture
- [TROUBLESHOOTING.md](TROUBLESHOOTING.md) - Solutions to common problems
## Acknowledgements
- [discordgo](https://github.com/bwmarrin/discordgo) - Go package for Discord API
- [The Subsonic API](http://www.subsonic.org/pages/api.jsp) - The API this bot uses to fetch music
- [jonas747/dca](https://github.com/jonas747/dca) - Audio encoding for Discord
- [layeh/gopus](https://github.com/layeh/gopus) - Opus codec binding for Go

225
TROUBLESHOOTING.md Normal file
View file

@ -0,0 +1,225 @@
# Discord Jukebox Bot - Troubleshooting Guide
This guide helps you resolve common issues with the Discord Jukebox Bot.
> **Note:** For more detailed diagnostics, run the bot in debug mode: `./jukebox-bot -debug` or `make run-debug`
> **Important:** The bot now streams real audio to Discord voice channels!
## Common Errors
### "Invalid Form Body" / "Value is not snowflake"
#### Error Message
```
Error starting bot: error creating command 'jukebox': HTTP 400 Bad Request,
{"message": "Invalid Form Body", "code": 50035, "errors": {"guild_id": {"_errors":
[{"code": "NUMBER_TYPE_COERCE", "message": "Value \"guild_id=1234567890123456\" is not snowflake."}]}}}
```
#### Cause
This happens when your Guild ID contains extra text or isn't in the correct format. Discord expects Guild IDs to be numeric snowflakes (just numbers).
#### Solution
1. Check your `.env` file for the `JUKEBOX_DISCORD_GUILD_ID` variable
2. Make sure it contains ONLY the numeric Guild ID, for example:
```
JUKEBOX_DISCORD_GUILD_ID=1234567890123456789
```
3. Remove any extra text, spaces, quotes, or the variable name itself from the value
4. If you copied the line with `JUKEBOX_DISCORD_GUILD_ID=`, make sure you didn't accidentally include the line twice
## Environment Variables Not Loading
### Symptoms
- Bot reports "configuration is required" or "X is required" at startup
- Commands don't work properly
- Bot cannot connect to Discord or your Subsonic server
### Solutions
1. **Check your .env file location**
- Make sure the .env file is in the same directory as the bot executable
- Run `make debug` to check if the .env file is detected
2. **Check .env file format**
- Ensure each variable is on its own line
- No spaces around the equal sign: `JUKEBOX_DISCORD_TOKEN=yourtoken` (correct)
- Not: `JUKEBOX_DISCORD_TOKEN = yourtoken` (incorrect)
- All variables must have the `JUKEBOX_` prefix
3. **Check variable names**
- Copy exact variable names from the `.env.example` file
- Common issues: typos, missing prefix, wrong capitalization
4. **Use direct environment variables**
- If .env isn't working, set variables directly in your shell:
```
export JUKEBOX_DISCORD_TOKEN=yourtoken
export JUKEBOX_SUBSONIC_SERVER=https://yourserver.com
# etc...
```
## Discord Connection Issues
### Symptoms
- "Error creating Discord session" message
- "Error opening connection" message
- Bot starts but doesn't appear online in Discord
### Solutions
1. **Check your Discord bot token**
- Verify the token in the Discord Developer Portal
- Generate a new token if necessary
- Make sure you're using the bot token, not the client secret
2. **Check bot permissions**
- The bot needs proper OAuth2 scopes and permissions
- Required scopes: `bot`, `applications.commands`
- Required permissions: Connect, Speak, Send Messages, Use Slash Commands
3. **Verify slash commands**
- Commands may take up to an hour to register globally
- Try using guild-specific commands for faster testing
- Check if you provided the correct Guild ID
## Subsonic Connection Issues
### Symptoms
- "subsonic server is required" error
- "Error getting random songs" message
- Bot connects to Discord but doesn't play music
### Solutions
1. **Check your Subsonic credentials**
- Verify the server URL, username, and password
- Try logging in through a web browser to confirm credentials
- Server URL should include `http://` or `https://` prefix
2. **Check Subsonic API compatibility**
- Ensure your server supports the Subsonic API
- Try setting an older API version (e.g., `JUKEBOX_SUBSONIC_VERSION=1.13.0`)
- Some Subsonic-compatible servers only implement part of the API
3. **Network connectivity**
- Ensure the server is reachable from where the bot is running
- Check firewall settings that might block connectivity
- Try accessing the server from the same machine using a browser
## Guild ID Issues
### Symptoms
- "Invalid Form Body" error when starting the bot
- "Value is not snowflake" error message
- Bot starts but commands don't register
### Solutions
1. **Correct Guild ID Format**
- Guild ID should be only numbers with no other characters
- Correct: `JUKEBOX_DISCORD_GUILD_ID=123456789012345678`
- Incorrect: `JUKEBOX_DISCORD_GUILD_ID=guild_id=123456789012345678`
- Incorrect: `JUKEBOX_DISCORD_GUILD_ID="123456789012345678"`
2. **Check for Duplicates**
- Make sure the Guild ID variable isn't defined twice in your `.env` file
- Sometimes copy-pasting causes duplicated variables
3. **Get a Fresh Guild ID**
- Enable Developer Mode in Discord (Settings > Advanced)
- Right-click your server and select "Copy ID"
- Use this exact ID in your configuration
## Voice Connection Issues
### Symptoms
- Bot responds to commands but doesn't join voice channel
- "Error joining voice channel" message
- Bot joins voice channel but doesn't play audio
### Solutions
1. **Check Discord permissions**
- Bot needs "Connect" and "Speak" permissions in the voice channel
- Try giving the bot Administrator permission temporarily to test
2. **User in voice channel**
- The user must be in a voice channel when using `/jukebox play`
- The bot will join the user's current channel
3. **Guild ID configuration**
- Make sure your `JUKEBOX_DISCORD_GUILD_ID` is correct
- You can get the Guild ID by enabling Developer Mode in Discord, then right-clicking the server and selecting "Copy ID"
## Audio Playback Issues
### Symptoms
- Bot joins voice channel successfully but no sound plays
- "Error creating encoding session" message in logs
- Songs appear to be playing (bot shows "Now playing") but no audio
### Solutions
1. **Check Subsonic streaming capabilities**
- Verify your Subsonic server allows streaming
- Test streaming directly in your browser by visiting the stream URL (visible in debug logs)
- Some Subsonic servers require additional authentication for streaming
2. **Check audio format compatibility**
- The bot now converts audio to Opus format required by Discord
- Some audio formats might not be compatible with the encoder
- If specific songs don't play, try different ones to rule out format issues
3. **Network issues**
- Ensure your Subsonic server is accessible from where the bot is running
- Check firewall settings that might be blocking the audio stream
- Audio streaming requires stable, low-latency connectivity
4. **Discord limitations**
- Discord has bandwidth limits that might affect audio quality
- Try a different voice region if audio is choppy or not playing
- The default bitrate (96kbps) should work on most Discord servers
## Debugging
For better debugging information:
1. **Run the bot in debug mode**
```
./jukebox-bot -debug
```
or
```
make run-debug
```
2. **Use the debug command for environment checks**
```
make debug
```
3. **Check log output**
- Look for error messages in the console
- The debug mode shows detailed API requests and responses
- Audio playback simulation will show progress updates
4. **Try running directly**
- Run the bot directly with Go:
```
cd discord-jukebox-bot
go run ./cmd/bot -debug
```
5. **Audio debugging**
- In debug mode, the bot will print the exact stream URL being used
- Copy this URL and try opening it in a browser to test if streaming works
- Look for "Audio streaming in progress" messages showing actual bytes sent
- If you see "error creating encoding session", the audio format may be incompatible
## Still Having Issues?
If you're still experiencing problems:
1. Open an issue on the GitHub repository with:
- The exact error message
- Your environment (OS, Go version)
- Steps to reproduce the issue
- Output from `make debug`
2. Make sure to remove any sensitive information (tokens, passwords) before sharing logs.

85
cmd/bot/main.go Normal file
View file

@ -0,0 +1,85 @@
package main
import (
"flag"
"os"
"os/exec"
"os/signal"
"syscall"
"discord-jukebox-bot/pkg/commands"
"discord-jukebox-bot/pkg/config"
"discord-jukebox-bot/pkg/logger"
)
func main() {
// Parse command-line flags
debugMode := flag.Bool("debug", false, "Enable debug mode with verbose logging")
flag.Parse()
// Initialize logger
logger.Init(*debugMode)
logger.Info("Discord Jukebox Bot - Starting up...")
if *debugMode {
logger.Debug("Debug mode enabled - verbose logging will be shown")
}
// Load configuration from environment variables and .env file
logger.Info("Loading configuration...")
cfg, err := config.Load()
if err != nil {
logger.Error("Error loading configuration", "error", err)
config.PrintDebugInfo()
os.Exit(1)
}
logger.Info("Configuration loaded successfully")
// Print config summary in debug mode
if logger.IsDebug() {
logger.Debug("Configuration Summary",
"discord_guild_id", cfg.DiscordGuildID,
"subsonic_server", cfg.SubsonicServer,
"subsonic_username", cfg.SubsonicUsername,
"subsonic_api_version", cfg.SubsonicVersion)
}
// Check if ffmpeg is available - important for audio transcoding
ffmpegPath, err := exec.LookPath("ffmpeg")
if err != nil {
logger.Warn("ffmpeg not found in system PATH. Audio streaming may be less reliable.",
"error", err.Error())
} else {
logger.Info("ffmpeg found and available for audio transcoding",
"path", ffmpegPath)
}
// Set up commands and the Discord bot
logger.Info("Setting up bot and commands...")
bot, err := commands.Setup(cfg)
if err != nil {
logger.Error("Error setting up bot", "error", err)
os.Exit(1)
}
// Start the bot
logger.Info("Starting Discord bot...")
if err := bot.Start(); err != nil {
logger.Error("Error starting bot", "error", err)
os.Exit(1)
}
logger.Info("Discord Jukebox Bot is now running.")
logger.Info("Use /jukebox play, /jukebox stop, or /jukebox skip in your Discord server.")
logger.Info("Press Ctrl+C to exit.")
// Wait for a termination signal
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-sc
// Clean up and exit
logger.Info("Shutting down Discord Jukebox Bot...")
if err := bot.Stop(); err != nil {
logger.Error("Error stopping bot", "error", err)
}
logger.Info("Bot stopped. Goodbye!")
}

17
go.mod Normal file
View file

@ -0,0 +1,17 @@
module discord-jukebox-bot
go 1.21
require (
github.com/bwmarrin/discordgo v0.27.1
github.com/joho/godotenv v1.5.1
github.com/lmittmann/tint v1.0.4
layeh.com/gopus v0.0.0-20210501142526-1ee02d434e32
)
require (
github.com/gorilla/websocket v1.5.1 // indirect
golang.org/x/crypto v0.17.0 // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/sys v0.15.0 // indirect
)

23
go.sum Normal file
View file

@ -0,0 +1,23 @@
github.com/bwmarrin/discordgo v0.27.1 h1:ib9AIc/dom1E/fSIulrBwnez0CToJE113ZGt4HoliGY=
github.com/bwmarrin/discordgo v0.27.1/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/lmittmann/tint v1.0.4 h1:LeYihpJ9hyGvE0w+K2okPTGUdVLfng1+nDNVR4vWISc=
github.com/lmittmann/tint v1.0.4/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
layeh.com/gopus v0.0.0-20210501142526-1ee02d434e32 h1:/S1gOotFo2sADAIdSGk1sDq1VxetoCWr6f5nxOG0dpY=
layeh.com/gopus v0.0.0-20210501142526-1ee02d434e32/go.mod h1:yDtyzWZDFCVnva8NGtg38eH2Ns4J0D/6hD+MMeUGdF0=

54
pkg/commands/setup.go Normal file
View file

@ -0,0 +1,54 @@
package commands
import (
"fmt"
"discord-jukebox-bot/pkg/config"
"discord-jukebox-bot/pkg/discord"
"discord-jukebox-bot/pkg/subsonic"
"github.com/bwmarrin/discordgo"
)
// Setup sets up all commands for the Discord bot
func Setup(cfg *config.Config) (*discord.Bot, error) {
// Create the Subsonic client
subsonicClient := subsonic.New(
cfg.SubsonicServer,
cfg.SubsonicUsername,
cfg.SubsonicPassword,
cfg.SubsonicVersion,
cfg.GetTimeout(),
)
// Create the Discord bot
bot, err := discord.New(cfg, subsonicClient)
if err != nil {
return nil, fmt.Errorf("error creating bot: %w", err)
}
// Initialize the jukebox player
jukebox := discord.NewJukeboxPlayer(bot)
if jukebox == nil {
return nil, fmt.Errorf("error creating jukebox player")
}
// Add any additional command initialization here
// This is where you can easily add new commands in the future
return bot, nil
}
// RegisterCustomCommand is a helper function to register a new command
// This makes it easy to add new commands in the future
func RegisterCustomCommand(
bot *discord.Bot,
name string,
description string,
options []*discordgo.ApplicationCommandOption,
handler func(s *discordgo.Session, i *discordgo.InteractionCreate),
) error {
// Register the command handler
bot.RegisterCommand(name, handler)
return nil
}

222
pkg/config/config.go Normal file
View file

@ -0,0 +1,222 @@
package config
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/joho/godotenv"
"log/slog"
)
const (
// Environment variable prefix for the application
envPrefix = "JUKEBOX_"
)
// Config holds all the configuration for the application
type Config struct {
// Discord configuration
DiscordToken string
DiscordGuildID string
DiscordChannelID string
// Subsonic configuration
SubsonicServer string
SubsonicUsername string
SubsonicPassword string
SubsonicVersion string
// Jukebox configuration
AudioVolume float64
TimeoutSec int
}
// Load loads the configuration from environment variables and .env file
func Load() (*Config, error) {
// Try to load .env file
if err := godotenv.Load(); err != nil {
slog.Info("No .env file found, using environment variables only")
} else {
slog.Info("Loaded environment variables from .env file")
}
// Load the raw values first
rawGuildID := getEnv(envPrefix+"DISCORD_GUILD_ID", "")
// Clean up Guild ID - ensure we have just the snowflake
cleanGuildID := cleanSnowflake(rawGuildID)
if cleanGuildID != rawGuildID && rawGuildID != "" {
slog.Warn("Cleaned Discord Guild ID", "original", rawGuildID, "cleaned", cleanGuildID)
}
config := &Config{
// Discord
DiscordToken: getEnv(envPrefix+"DISCORD_TOKEN", ""),
DiscordGuildID: cleanGuildID,
DiscordChannelID: getEnv(envPrefix+"DISCORD_CHANNEL_ID", ""),
// Subsonic
SubsonicServer: getEnv(envPrefix+"SUBSONIC_SERVER", ""),
SubsonicUsername: getEnv(envPrefix+"SUBSONIC_USERNAME", ""),
SubsonicPassword: getEnv(envPrefix+"SUBSONIC_PASSWORD", ""),
SubsonicVersion: getEnv(envPrefix+"SUBSONIC_VERSION", "1.16.1"),
// Jukebox
AudioVolume: getEnvFloat(envPrefix+"AUDIO_VOLUME", 0.5),
TimeoutSec: getEnvInt(envPrefix+"TIMEOUT_SEC", 30),
}
if err := config.validate(); err != nil {
// Print helpful debug information
PrintDebugInfo()
return nil, err
}
return config, nil
}
// validate checks if the required configuration values are set
func (c *Config) validate() error {
if c.DiscordToken == "" {
return errorMissingConfig("discord token")
}
if c.SubsonicServer == "" {
return errorMissingConfig("subsonic server")
}
if c.SubsonicUsername == "" {
return errorMissingConfig("subsonic username")
}
if c.SubsonicPassword == "" {
return errorMissingConfig("subsonic password")
}
return nil
}
// errorMissingConfig returns a formatted error for missing configuration
func errorMissingConfig(name string) error {
return fmt.Errorf("%s is required", name)
}
// GetTimeout returns the timeout duration
func (c *Config) GetTimeout() time.Duration {
return time.Duration(c.TimeoutSec) * time.Second
}
// getEnv gets an environment variable or returns a default value
func getEnv(key, defaultValue string) string {
if value, exists := os.LookupEnv(key); exists {
return value
}
return defaultValue
}
// getEnvInt gets an environment variable as an integer or returns a default value
func getEnvInt(key string, defaultValue int) int {
if value, exists := os.LookupEnv(key); exists {
if intValue, err := strconv.Atoi(value); err == nil {
return intValue
}
}
return defaultValue
}
// getEnvFloat gets an environment variable as a float or returns a default value
func getEnvFloat(key string, defaultValue float64) float64 {
if value, exists := os.LookupEnv(key); exists {
if floatValue, err := strconv.ParseFloat(value, 64); err == nil {
return floatValue
}
}
return defaultValue
}
// PrintDebugInfo prints helpful debugging information for environment variables
func PrintDebugInfo() {
slog.Info("=== Configuration Debug Information ===")
slog.Info("Required environment variables:")
checkEnvVar(envPrefix + "DISCORD_TOKEN")
checkEnvVar(envPrefix + "DISCORD_GUILD_ID")
checkEnvVar(envPrefix + "SUBSONIC_SERVER")
checkEnvVar(envPrefix + "SUBSONIC_USERNAME")
checkEnvVar(envPrefix + "SUBSONIC_PASSWORD")
slog.Info("Optional environment variables:")
checkEnvVar(envPrefix + "DISCORD_CHANNEL_ID")
checkEnvVar(envPrefix + "SUBSONIC_VERSION")
checkEnvVar(envPrefix + "AUDIO_VOLUME")
checkEnvVar(envPrefix + "TIMEOUT_SEC")
slog.Info("Troubleshooting tips:")
slog.Info("1. Your .env file is in the correct directory")
slog.Info("2. All variable names have the JUKEBOX_ prefix")
slog.Info("3. There are no spaces around the = sign in your .env file")
slog.Info(" Example: JUKEBOX_DISCORD_TOKEN=your_token_here")
slog.Info("4. Your .env file has been loaded (check for errors above)")
slog.Info("===================================")
}
// checkEnvVar checks if an environment variable is set and prints its status
func checkEnvVar(name string) {
if value, exists := os.LookupEnv(name); exists {
// Mask sensitive values
displayValue := value
if contains(name, "TOKEN", "PASSWORD") {
if len(displayValue) > 8 {
displayValue = displayValue[:4] + "..." + displayValue[len(displayValue)-4:]
} else {
displayValue = "****"
}
}
// Special handling for Guild ID to detect common issues
if strings.Contains(name, "GUILD_ID") && strings.Contains(value, "=") {
slog.Warn("Environment variable contains equals sign",
"name", name,
"raw_value", displayValue,
"cleaned_value", cleanSnowflake(value))
} else {
slog.Info("Environment variable check", "name", name, "value", displayValue, "status", "set")
}
} else {
slog.Warn("Environment variable not set", "name", name)
}
}
// contains checks if the string contains any of the substrings
func contains(str string, substrings ...string) bool {
for _, substring := range substrings {
if strings.Contains(str, substring) {
return true
}
}
return false
}
// cleanSnowflake cleans a Discord snowflake (ID) from potential contamination
// This handles cases where the ID might include the variable name or other text
func cleanSnowflake(input string) string {
// If the input contains an equals sign, it might be contaminated
if strings.Contains(input, "=") {
parts := strings.SplitN(input, "=", 2)
if len(parts) == 2 {
input = parts[1] // Take the part after the equals sign
}
}
// Extract only digits
var result strings.Builder
for _, char := range input {
if char >= '0' && char <= '9' {
result.WriteRune(char)
}
}
return result.String()
}

390
pkg/discord/bot.go Normal file
View file

@ -0,0 +1,390 @@
package discord
import (
"fmt"
"log/slog"
"sync"
"time"
"discord-jukebox-bot/pkg/config"
"discord-jukebox-bot/pkg/subsonic"
"github.com/bwmarrin/discordgo"
)
// Bot represents a Discord bot with voice capabilities
type Bot struct {
config *config.Config
session *discordgo.Session
subsonic *subsonic.Client
commandsMux sync.RWMutex
commands map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate)
voiceConn *discordgo.VoiceConnection
playing bool
stopChan chan struct{}
mu sync.Mutex
}
// New creates a new Discord bot
func New(cfg *config.Config, subsonic *subsonic.Client) (*Bot, error) {
session, err := discordgo.New("Bot " + cfg.DiscordToken)
if err != nil {
return nil, fmt.Errorf("error creating Discord session: %w", err)
}
bot := &Bot{
config: cfg,
session: session,
subsonic: subsonic,
commands: make(map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate)),
stopChan: make(chan struct{}),
}
// Set up event handlers
session.AddHandler(bot.onReady)
session.AddHandler(bot.onInteractionCreate)
// Add needed intents
session.Identify.Intents = discordgo.IntentsGuilds | discordgo.IntentsGuildVoiceStates
return bot, nil
}
// RegisterCommand registers a new slash command handler
func (b *Bot) RegisterCommand(name string, handler func(s *discordgo.Session, i *discordgo.InteractionCreate)) {
b.commandsMux.Lock()
defer b.commandsMux.Unlock()
b.commands[name] = handler
}
// Start starts the Discord bot
func (b *Bot) Start() error {
// Add voice state update handler
b.session.AddHandler(b.onVoiceStateUpdate)
if err := b.session.Open(); err != nil {
return fmt.Errorf("error opening connection: %w", err)
}
// Register slash commands
commands := []*discordgo.ApplicationCommand{
{
Name: "jukebox",
Description: "Control the jukebox",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "play",
Description: "Start playing random music",
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "stop",
Description: "Stop playing music",
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "skip",
Description: "Skip to the next song",
},
{
Type: discordgo.ApplicationCommandOptionSubCommand,
Name: "info",
Description: "Display information about the current song",
},
},
},
}
for _, cmd := range commands {
// Check if guild ID is provided, create global command if not
guildID := b.config.DiscordGuildID
if guildID == "" {
slog.Warn("No Guild ID provided, registering commands globally")
}
_, err := b.session.ApplicationCommandCreate(b.session.State.User.ID, guildID, cmd)
if err != nil {
return fmt.Errorf("error creating command '%s': %w", cmd.Name, err)
}
}
return nil
}
// Stop stops the Discord bot
func (b *Bot) Stop() error {
slog.Info("Shutting down Discord bot")
// Clear Discord status
if b.session != nil {
b.session.UpdateGameStatus(0, "")
}
// Stop any playing music
b.stopPlaying()
// Clean up voice connection if it exists
b.leaveVoiceChannel()
// Close the Discord session with timeout
disconnectDone := make(chan error)
go func() {
disconnectDone <- b.session.Close()
}()
select {
case err := <-disconnectDone:
if err != nil {
return fmt.Errorf("error closing connection: %w", err)
}
case <-time.After(10 * time.Second):
return fmt.Errorf("timeout closing Discord session")
}
slog.Info("Discord bot shutdown complete")
return nil
}
// JoinVoiceChannel joins a voice channel
func (b *Bot) JoinVoiceChannel(guildID, channelID string) error {
b.mu.Lock()
// Store current playing state if we're already connected
wasPlaying := b.playing && b.voiceConn != nil
// Check if we're already in the requested channel
alreadyInChannel := b.voiceConn != nil && b.voiceConn.ChannelID == channelID
b.mu.Unlock()
// If we're already in this channel, no need to reconnect
if alreadyInChannel {
slog.Info("Already in the requested voice channel", "channel_id", channelID)
return nil
}
// Leave the current voice channel if we're in one
b.leaveVoiceChannel()
// Join the new voice channel
slog.Info("Joining voice channel", "guild_id", guildID, "channel_id", channelID)
vc, err := b.session.ChannelVoiceJoin(guildID, channelID, false, true)
if err != nil {
return fmt.Errorf("error joining voice channel: %w", err)
}
// Wait for the connection to be established
timeout := time.After(10 * time.Second)
for !vc.Ready {
select {
case <-timeout:
b.leaveVoiceChannel()
return fmt.Errorf("timeout waiting for voice connection to be ready")
default:
slog.Debug("Waiting for voice connection to be ready...")
time.Sleep(100 * time.Millisecond)
}
}
slog.Info("Successfully connected to voice channel", "guild_id", guildID, "channel_id", channelID)
b.voiceConn = vc
// Restore playing state if we were playing before
if wasPlaying {
b.mu.Lock()
b.playing = true
b.mu.Unlock()
slog.Info("Restoring playback state after rejoining channel")
}
return nil
}
// leaveVoiceChannel leaves the current voice channel
func (b *Bot) leaveVoiceChannel() {
b.mu.Lock()
defer b.mu.Unlock()
if b.voiceConn != nil {
slog.Info("Leaving voice channel", "channel_id", b.voiceConn.ChannelID)
// Make sure we're not sending audio
b.voiceConn.Speaking(false)
// Disconnect with a timeout
disconnectErr := make(chan error, 1)
go func() {
disconnectErr <- b.voiceConn.Disconnect()
}()
// Wait for disconnect or timeout
select {
case err := <-disconnectErr:
if err != nil {
slog.Error("Error disconnecting from voice channel", "error", err)
}
case <-time.After(5 * time.Second):
slog.Warn("Timeout disconnecting from voice channel")
}
// Cleanup resources
b.voiceConn = nil
slog.Info("Voice channel disconnected")
// Note: We intentionally don't reset the playing state here
// so that if we rejoin, we can resume playing
}
}
// IsPlaying returns true if the bot is currently playing music
func (b *Bot) IsPlaying() bool {
b.mu.Lock()
defer b.mu.Unlock()
return b.playing
}
// stopPlaying stops playing music completely
func (b *Bot) stopPlaying() {
b.mu.Lock()
defer b.mu.Unlock()
if b.playing {
slog.Debug("Stopping playback")
// Signal all audio processors to stop
close(b.stopChan)
// Create a new channel for future use
b.stopChan = make(chan struct{})
// Mark as not playing anymore
b.playing = false
// Update Discord status
if b.session != nil {
err := b.session.UpdateGameStatus(0, "Ready to play music | /jukebox play")
if err != nil {
slog.Warn("Failed to update status after stopping", "error", err)
}
}
slog.Debug("Playback stopped completely")
}
}
// onReady is called when the Discord bot is ready
func (b *Bot) onReady(s *discordgo.Session, event *discordgo.Ready) {
slog.Info("Bot is now running",
"username", s.State.User.Username,
"discriminator", s.State.User.Discriminator,
"guilds", len(event.Guilds))
// Set initial status
err := s.UpdateGameStatus(0, "Ready to play music | /jukebox play")
if err != nil {
slog.Warn("Failed to set initial status", "error", err)
}
}
// onVoiceStateUpdate handles voice state changes
func (b *Bot) onVoiceStateUpdate(s *discordgo.Session, v *discordgo.VoiceStateUpdate) {
b.mu.Lock()
defer b.mu.Unlock()
// If we're not connected to voice, nothing to do
if b.voiceConn == nil {
return
}
// Check if this update is for our bot
if v.UserID == s.State.User.ID {
// If we got disconnected
if v.ChannelID == "" && b.voiceConn != nil && b.voiceConn.ChannelID != "" {
slog.Warn("Bot was disconnected from voice channel",
"previous_channel", b.voiceConn.ChannelID)
// Stop playing and clean up
b.stopPlaying()
b.voiceConn = nil
} else if v.ChannelID != "" && b.voiceConn != nil && v.ChannelID != b.voiceConn.ChannelID {
slog.Info("Bot was moved to different voice channel",
"previous_channel", b.voiceConn.ChannelID,
"new_channel", v.ChannelID)
// Update our voice connection to the new channel
oldChannelID := b.voiceConn.ChannelID
// Store the current playing state before reconnecting
wasPlaying := b.playing
// We need to create a new voice connection for the new channel
err := b.voiceConn.ChangeChannel(v.ChannelID, false, true)
if err != nil {
slog.Error("Failed to update voice channel", "error", err)
// Since changing channel failed, attempt a full reconnect
b.leaveVoiceChannel()
err = b.JoinVoiceChannel(v.GuildID, v.ChannelID)
if err != nil {
slog.Error("Failed to rejoin voice channel after move", "error", err)
return
}
}
slog.Info("Successfully moved to new voice channel",
"from", oldChannelID,
"to", v.ChannelID)
// If we were playing before, and we're not playing now, restore playing state
if wasPlaying && !b.playing {
b.playing = true
slog.Info("Restoring playback state after channel move")
}
}
}
// Check if we're in a voice channel but alone
if b.voiceConn != nil && b.playing {
// Count how many users are in our voice channel
usersInChannel := 0
guild, err := s.State.Guild(b.voiceConn.GuildID)
if err == nil {
for _, state := range guild.VoiceStates {
if state.ChannelID == b.voiceConn.ChannelID {
usersInChannel++
}
}
}
// If the bot is alone (just the bot itself), stop playing and disconnect
if usersInChannel <= 1 {
slog.Info("Bot is alone in voice channel, disconnecting")
b.stopPlaying()
b.leaveVoiceChannel()
}
}
}
// onInteractionCreate is called when a slash command is invoked
func (b *Bot) onInteractionCreate(s *discordgo.Session, i *discordgo.InteractionCreate) {
if i.Type != discordgo.InteractionApplicationCommand {
return
}
// Handle jukebox commands
if i.ApplicationCommandData().Name == "jukebox" {
options := i.ApplicationCommandData().Options
if len(options) > 0 {
subCommand := options[0].Name
b.commandsMux.RLock()
handler, exists := b.commands[subCommand]
b.commandsMux.RUnlock()
if exists {
handler(s, i)
return
}
}
}
// Unknown command
_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Unknown command",
},
})
}

774
pkg/discord/jukebox.go Normal file
View file

@ -0,0 +1,774 @@
package discord
import (
"bufio"
"context"
"encoding/binary"
"fmt"
"io"
"log/slog"
"os/exec"
"strings"
"sync"
"time"
"discord-jukebox-bot/pkg/subsonic"
"github.com/bwmarrin/discordgo"
"layeh.com/gopus"
)
// JukeboxPlayer handles the music playback functionality
type JukeboxPlayer struct {
bot *Bot
currentSong *subsonic.Song
playlist []subsonic.Song
playlistMutex sync.Mutex
playingMutex sync.Mutex
currentStreamCancel context.CancelFunc
}
// NewJukeboxPlayer creates a new jukebox player
func NewJukeboxPlayer(bot *Bot) *JukeboxPlayer {
jukebox := &JukeboxPlayer{
bot: bot,
playlist: make([]subsonic.Song, 0),
}
// Register command handlers
bot.RegisterCommand("play", jukebox.handlePlay)
bot.RegisterCommand("stop", jukebox.handleStop)
bot.RegisterCommand("skip", jukebox.handleSkip)
bot.RegisterCommand("info", jukebox.handleInfo)
return jukebox
}
// handlePlay handles the play command
func (j *JukeboxPlayer) handlePlay(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Acknowledge the interaction immediately
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
})
if err != nil {
slog.Error("Error responding to interaction", "error", err)
return
}
// Find the voice channel the user is in
var channelID string
if i.GuildID != "" {
// Find the voice state of the user
vs, err := s.State.VoiceState(i.GuildID, i.Member.User.ID)
if err == nil && vs != nil && vs.ChannelID != "" {
channelID = vs.ChannelID
}
}
// If we couldn't find the user's voice channel
if channelID == "" {
content := "You need to be in a voice channel to use this command."
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: &content,
})
if err != nil {
slog.Error("Error editing interaction response", "error", err)
}
return
}
// Join the voice channel
err = j.bot.JoinVoiceChannel(i.GuildID, channelID)
if err != nil {
content := "Failed to join voice channel: " + err.Error()
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: &content,
})
if err != nil {
slog.Error("Error editing interaction response", "error", err)
}
return
}
// Start playing music if not already playing
if !j.bot.IsPlaying() {
go j.startPlaying()
content := "🎵 Jukebox started! Random songs will be played from your Subsonic library."
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: &content,
})
} else {
content := "🎵 Jukebox is already playing!"
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: &content,
})
}
if err != nil {
slog.Error("Error editing interaction response", "error", err)
}
}
// handleStop handles the stop command
func (j *JukeboxPlayer) handleStop(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Acknowledge the interaction immediately
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Stopping jukebox...",
},
})
if err != nil {
slog.Error("Error responding to interaction", "error", err)
return
}
// First stop the music
j.bot.stopPlaying()
// Then leave the voice channel
j.bot.leaveVoiceChannel()
// Clear the Discord status when stopping
j.bot.session.UpdateGameStatus(0, "")
// Update the response
content := "🛑 Jukebox stopped."
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: &content,
})
if err != nil {
slog.Error("Error editing interaction response", "error", err)
}
}
// handleSkip handles the skip command
func (j *JukeboxPlayer) handleSkip(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Acknowledge the interaction immediately
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Skipping to next song...",
},
})
if err != nil {
slog.Error("Error responding to interaction", "error", err)
return
}
if !j.bot.IsPlaying() {
content := "Jukebox is not currently playing."
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: &content,
})
if err != nil {
slog.Error("Error editing interaction response", "error", err)
}
return
}
// Get the current song info for the response message
currentSong := j.GetCurrentSong()
songInfo := ""
if currentSong != nil {
songInfo = fmt.Sprintf(" (\"%s\" by %s)", currentSong.Title, currentSong.Artist)
}
// Skip the current song without stopping the playback
j.skipCurrentSong()
// Update the response
content := fmt.Sprintf("⏭️ Skipped current song%s. Loading next track...", songInfo)
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: &content,
})
if err != nil {
slog.Error("Error editing interaction response", "error", err)
}
}
// startPlaying starts the jukebox playback
func (j *JukeboxPlayer) startPlaying() {
j.bot.mu.Lock()
if j.bot.playing {
slog.Debug("Jukebox is already playing, ignoring play request")
j.bot.mu.Unlock()
return
}
j.bot.playing = true
stopChan := j.bot.stopChan
j.bot.mu.Unlock()
// Make sure the voice connection is speaking
if j.bot.voiceConn != nil && j.bot.voiceConn.Ready {
err := j.bot.voiceConn.Speaking(true)
if err != nil {
slog.Warn("Failed to set speaking state", "error", err)
// Try to reconnect voice
if j.bot.voiceConn != nil && j.bot.voiceConn.GuildID != "" && j.bot.voiceConn.ChannelID != "" {
err = j.bot.JoinVoiceChannel(j.bot.voiceConn.GuildID, j.bot.voiceConn.ChannelID)
if err != nil {
slog.Error("Failed to restore voice connection", "error", err)
// Continue anyway, we'll try again when playing song
}
}
}
}
slog.Info("Starting jukebox playback")
for {
// For each iteration, get the latest stop channel
j.bot.mu.Lock()
localStopChan := j.bot.stopChan
isPlaying := j.bot.playing
j.bot.mu.Unlock()
// If we're completely stopped, exit the playback loop
if !isPlaying {
slog.Info("Jukebox playback stopped")
// Clear current song when stopping
j.playingMutex.Lock()
j.currentSong = nil
j.playingMutex.Unlock()
return
}
stopChan = localStopChan
// Check if we should stop
select {
case <-stopChan:
// Check if we're still supposed to be playing (complete stop vs. skip)
j.bot.mu.Lock()
stillPlaying := j.bot.playing
j.bot.mu.Unlock()
if !stillPlaying {
return // Completely stop playback
}
slog.Info("Skipping to next song")
// Otherwise, continue to the next song (was a skip)
default:
// Continue playing
}
// Check if we need to load more songs
j.ensurePlaylist()
// Get the next song to play
song := j.getNextSong()
if song == nil {
// No songs available
time.Sleep(1 * time.Second)
continue
}
j.playingMutex.Lock()
j.currentSong = song
j.playingMutex.Unlock()
// Update Discord status with the current song information in format "Artist - Title (Album)"
var statusText string
if song.Album != "" {
statusText = fmt.Sprintf("%s - %s (%s)", song.Artist, song.Title, song.Album)
} else {
statusText = fmt.Sprintf("%s - %s", song.Artist, song.Title)
}
// Truncate if too long for Discord status (128 char limit)
if len(statusText) > 128 {
statusText = statusText[:125] + "..."
}
statusErr := j.bot.session.UpdateGameStatus(0, statusText)
if statusErr != nil {
slog.Warn("Failed to update Discord status", "error", statusErr)
} else {
slog.Debug("Updated Discord status", "status", statusText)
}
// Announce the song in the voice channel
if j.bot.voiceConn != nil && j.bot.voiceConn.Ready {
slog.Info("Now playing",
"artist", song.Artist,
"title", song.Title,
"album", song.Album,
"id", song.ID,
"duration", song.Duration,
"path", song.Path)
}
// Play the song
err := j.playSong(song)
if err != nil {
slog.Error("Error playing song", "error", err)
time.Sleep(1 * time.Second)
}
}
}
// ensurePlaylist ensures that the playlist has songs
func (j *JukeboxPlayer) ensurePlaylist() {
j.playlistMutex.Lock()
defer j.playlistMutex.Unlock()
// If we have songs in the playlist, we're good
if len(j.playlist) > 0 {
return
}
// Fetch random songs from Subsonic
songs, err := j.bot.subsonic.GetRandomSongs(10)
if err != nil {
slog.Error("Error getting random songs", "error", err)
return
}
j.playlist = songs
}
// getNextSong gets the next song from the playlist
func (j *JukeboxPlayer) getNextSong() *subsonic.Song {
j.playlistMutex.Lock()
defer j.playlistMutex.Unlock()
if len(j.playlist) == 0 {
return nil
}
// Get the first song
song := j.playlist[0]
// Remove it from the playlist
j.playlist = j.playlist[1:]
return &song
}
// playSong plays a song over the voice connection
func (j *JukeboxPlayer) playSong(song *subsonic.Song) error {
// Check if voice connection is ready, and attempt to reconnect if needed
if j.bot.voiceConn == nil || !j.bot.voiceConn.Ready {
slog.Warn("Voice connection not ready, attempting to restore it")
// If we have guild ID and channel ID available, try to reconnect
if j.bot.voiceConn != nil && j.bot.voiceConn.GuildID != "" && j.bot.voiceConn.ChannelID != "" {
err := j.bot.JoinVoiceChannel(j.bot.voiceConn.GuildID, j.bot.voiceConn.ChannelID)
if err != nil {
return fmt.Errorf("failed to restore voice connection: %w", err)
}
slog.Info("Successfully restored voice connection")
} else {
return fmt.Errorf("voice connection not ready and cannot be restored")
}
}
// Get the stream URL (raw format for better compatibility)
streamURL := j.bot.subsonic.GetRawStreamURL(song.ID)
slog.Debug("Attempting to play song with direct FFmpeg method", "url", streamURL)
// Check if ffmpeg is available
ffmpegPath, err := exec.LookPath("ffmpeg")
if err != nil || ffmpegPath == "" {
return fmt.Errorf("ffmpeg not found, required for audio streaming: %w", err)
}
// Create a context that can be cancelled when skipping songs
streamCtx, cancelStream := context.WithCancel(context.Background())
// We'll cancel this context when the song ends or is skipped
j.bot.mu.Lock()
j.currentStreamCancel = cancelStream
j.bot.mu.Unlock()
// Make sure we clean up our context if we exit
defer func() {
j.bot.mu.Lock()
// No need to check equality, just clean up if we have a cancellation function
if j.currentStreamCancel != nil {
j.currentStreamCancel = nil
}
j.bot.mu.Unlock()
cancelStream()
}()
// Create an opusEncoder and begin speaking
slog.Debug("Setting Discord voice status to Speaking")
err = j.bot.voiceConn.Speaking(true)
if err != nil {
slog.Warn("Failed to set speaking state", "error", err)
// Try to recover the voice connection
if j.bot.voiceConn != nil && j.bot.voiceConn.GuildID != "" && j.bot.voiceConn.ChannelID != "" {
err = j.bot.JoinVoiceChannel(j.bot.voiceConn.GuildID, j.bot.voiceConn.ChannelID)
if err != nil {
slog.Error("Failed to reconnect to voice channel", "error", err)
} else {
err = j.bot.voiceConn.Speaking(true)
if err != nil {
slog.Error("Still failed to set speaking state after reconnection", "error", err)
}
}
}
}
defer j.bot.voiceConn.Speaking(false)
// Create FFmpeg command with optimized parameters for Discord streaming
cmd := exec.CommandContext(streamCtx, ffmpegPath,
"-hide_banner", // Reduce console output
"-loglevel", "warning", // Only show warnings and errors
"-reconnect", "1", // Allow reconnection
"-reconnect_streamed", "1", // Reconnect to streamed resources
"-reconnect_delay_max", "5", // Maximum delay between reconnection attempts (seconds)
"-i", streamURL, // Input from Subsonic stream URL
"-acodec", "pcm_s16le",
"-f", "s16le",
"-ar", "48000",
"-ac", "2",
"-")
// Get the stdout and stderr pipes
stdout, err := cmd.StdoutPipe()
if err != nil {
return fmt.Errorf("error creating stdout pipe: %w", err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
return fmt.Errorf("error creating stderr pipe: %w", err)
}
// Start the FFmpeg process
if err := cmd.Start(); err != nil {
return fmt.Errorf("error starting FFmpeg: %w", err)
}
// Ensure we clean up the FFmpeg process
defer func() {
if cmd.Process != nil {
cmd.Process.Kill()
cmd.Wait()
}
}()
// Monitor stderr for debugging
go func() {
scanner := bufio.NewScanner(stderr)
for scanner.Scan() {
// Check if we've been cancelled
select {
case <-streamCtx.Done():
return
default:
line := scanner.Text()
if len(line) > 0 {
slog.Debug("FFmpeg output", "message", line)
}
}
}
}()
// Use this to signal that streaming has started
frameSent := make(chan struct{}, 1)
// For signaling errors or completion
done := make(chan error, 1)
// Create Opus encoder
opusEncoder, err := gopus.NewEncoder(48000, 2, gopus.Audio)
if err != nil {
return fmt.Errorf("failed to create opus encoder: %w", err)
}
// Set the bitrate
opusEncoder.SetBitrate(64000) // 64 kbps is sufficient for music over Discord
// Buffer for reading PCM data
pcmBuffer := make([]int16, 960*2) // 960 PCM samples * 2 channels
opusBuffer := make([]byte, 1000) // Buffer for opus data
go func() {
defer close(done)
slog.Debug("Starting direct PCM to Opus conversion")
framesSent := 0
firstFrameSent := false
// Read from stdout, encode to opus, send to Discord
for {
// Check if we should stop
select {
case <-j.bot.stopChan:
slog.Debug("Audio streaming interrupted by stop channel")
return
case <-streamCtx.Done():
slog.Debug("Audio streaming interrupted by context cancellation")
return
default:
// Continue streaming
}
// Read raw PCM data with a timeout
readDone := make(chan error, 1)
go func() {
err := binary.Read(stdout, binary.LittleEndian, pcmBuffer)
readDone <- err
}()
// Wait for read or cancellation
select {
case err := <-readDone:
if err == io.EOF {
if framesSent == 0 {
done <- fmt.Errorf("stream ended without producing any audio frames")
} else {
slog.Debug("End of audio stream reached", "total_frames", framesSent)
}
return
}
if err != nil {
// Check if context was cancelled or if this is a closed file error (which is normal during skips)
select {
case <-streamCtx.Done():
slog.Debug("PCM read interrupted by context cancellation")
return
case <-j.bot.stopChan:
slog.Debug("PCM read interrupted by stop channel")
return
default:
// Only log warnings for errors that aren't related to normal stream endings
errMsg := err.Error()
if !strings.Contains(errMsg, "file already closed") &&
!strings.Contains(errMsg, "unexpected EOF") {
slog.Warn("Error reading PCM data", "error", err)
}
time.Sleep(20 * time.Millisecond)
continue
}
}
case <-streamCtx.Done():
slog.Debug("PCM read interrupted by context cancellation while reading")
return
case <-j.bot.stopChan:
slog.Debug("PCM read interrupted by stop channel while reading")
return
}
// Encode the PCM data to Opus
opus, err := opusEncoder.Encode(pcmBuffer, 960, len(opusBuffer))
if err != nil {
slog.Warn("Failed to encode PCM to Opus", "error", err)
time.Sleep(20 * time.Millisecond)
continue
}
// Send the Opus data to Discord
select {
case j.bot.voiceConn.OpusSend <- opus:
framesSent++
// Signal that the first frame was sent
if !firstFrameSent {
firstFrameSent = true
select {
case frameSent <- struct{}{}:
default:
// Channel buffer full, no need to block
}
}
// Log progress
if framesSent%250 == 0 {
slog.Debug("Audio streaming progress", "frames_sent", framesSent)
}
case <-j.bot.stopChan:
return
case <-streamCtx.Done():
return
case <-time.After(50 * time.Millisecond):
// Timeout, try again with the next frame
continue
}
// Control the frame timing (20ms per frame)
time.Sleep(15 * time.Millisecond)
}
}()
// Wait for the first frame to be sent or a timeout
select {
case <-frameSent:
slog.Info("Audio streaming started successfully")
case err := <-done:
if err != nil {
return fmt.Errorf("failed to start audio streaming: %w", err)
}
case <-time.After(10 * time.Second):
return fmt.Errorf("timeout waiting for first audio frame to be sent")
}
// Wait for the song to finish or be interrupted
slog.Debug("Waiting for song to complete or be interrupted")
// Create a timeout for the entire song (based on song duration plus a margin)
songDurationSecs := song.Duration
if songDurationSecs <= 0 {
// If we don't have a proper duration, use a default max duration
songDurationSecs = 600 // 10 minutes maximum
}
// Add a 30-second margin for buffering and network delays
songTimeout := time.Duration(songDurationSecs+30) * time.Second
select {
case err := <-done:
if err != nil {
slog.Error("Song ended with error", "error", err)
} else {
slog.Debug("Song completed successfully")
}
return err
case <-j.bot.stopChan:
slog.Debug("Song playback interrupted")
return nil
case <-time.After(songTimeout):
slog.Warn("Song playback exceeded maximum duration",
"expected_duration_seconds", songDurationSecs,
"timeout_seconds", songTimeout/time.Second)
return fmt.Errorf("song playback timed out after %d seconds", songTimeout/time.Second)
}
}
// skipCurrentSong skips the current song without stopping the playback
func (j *JukeboxPlayer) skipCurrentSong() {
// Signal to stop the current song only but keep overall playback going
j.bot.mu.Lock()
if j.bot.playing {
// Cancel the current stream context if it exists
if j.currentStreamCancel != nil {
slog.Debug("Cancelling current stream context")
j.currentStreamCancel()
j.currentStreamCancel = nil
}
// Also close the stop channel for compatibility with other parts of the code
close(j.bot.stopChan)
j.bot.stopChan = make(chan struct{})
slog.Debug("Skip signal sent - current song will stop")
// Show "Skipping..." status while transitioning between songs
j.bot.session.UpdateGameStatus(0, "Skipping to next track...")
} else {
slog.Debug("Skip requested but jukebox is not playing")
}
j.bot.mu.Unlock()
}
// handleInfo handles the info command
func (j *JukeboxPlayer) handleInfo(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Acknowledge the interaction immediately
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
})
if err != nil {
slog.Error("Failed to acknowledge interaction", "error", err)
return
}
// Get the current song information
j.playingMutex.Lock()
currentSong := j.currentSong
j.playingMutex.Unlock()
// Check if the bot is playing and has a voice connection
isPlaying := j.bot.IsPlaying() && j.bot.voiceConn != nil && j.bot.voiceConn.Ready
if currentSong == nil || !isPlaying {
// No song is playing, inform the user
content := "No song is currently playing. Start the jukebox with `/jukebox play`!"
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: &content,
})
if err != nil {
slog.Error("Failed to send 'no song playing' message", "error", err)
}
return
}
// Create an embed with song information
embed := &discordgo.MessageEmbed{
Title: "Currently Playing",
Description: fmt.Sprintf("**%s**", currentSong.Title),
Color: 0x1DB954, // Spotify green color
Fields: []*discordgo.MessageEmbedField{
{
Name: "Artist",
Value: currentSong.Artist,
Inline: true,
},
{
Name: "Album",
Value: currentSong.Album,
Inline: true,
},
},
Timestamp: time.Now().Format(time.RFC3339),
Footer: &discordgo.MessageEmbedFooter{
Text: "Discord Jukebox Bot",
},
}
// Add duration field if available
if currentSong.Duration > 0 {
minutes := currentSong.Duration / 60
seconds := currentSong.Duration % 60
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "Duration",
Value: fmt.Sprintf("%d:%02d", minutes, seconds),
Inline: true,
})
}
// Add genre field if available
if currentSong.Genre != "" {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "Genre",
Value: currentSong.Genre,
Inline: true,
})
}
// Add year field if available
if currentSong.Year > 0 {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{
Name: "Year",
Value: fmt.Sprintf("%d", currentSong.Year),
Inline: true,
})
}
// Add cover art if available
if currentSong.CoverArt != "" {
coverArtURL := j.bot.subsonic.GetCoverArtURL(currentSong.CoverArt)
embed.Thumbnail = &discordgo.MessageEmbedThumbnail{
URL: strings.Replace(coverArtURL, ".fmartingr.dev", "", -1),
}
}
// Send the embed response
embeds := []*discordgo.MessageEmbed{embed}
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Embeds: &embeds,
})
if err != nil {
slog.Error("Failed to send song info message", "error", err)
}
}
// GetCurrentSong returns the current song
func (j *JukeboxPlayer) GetCurrentSong() *subsonic.Song {
j.playingMutex.Lock()
defer j.playingMutex.Unlock()
return j.currentSong
}

91
pkg/logger/logger.go Normal file
View file

@ -0,0 +1,91 @@
package logger
import (
"io"
"log/slog"
"os"
"time"
"github.com/lmittmann/tint"
)
var (
// Default logger is a tinted logger that writes to stdout
defaultLogger *slog.Logger
// Debug flag controls verbose logging
debugMode bool
)
// Init initializes the global logger with the specified debug level
func Init(debug bool) {
debugMode = debug
// Set the minimum log level based on debug mode
level := slog.LevelInfo
if debug {
level = slog.LevelDebug
}
// Create a tinted logger with time, level, and source
defaultLogger = slog.New(
tint.NewHandler(os.Stdout, &tint.Options{
Level: level,
TimeFormat: time.RFC3339,
AddSource: debug,
}),
)
// Set the default slog logger
slog.SetDefault(defaultLogger)
}
// InitWithWriter initializes the logger with a custom writer (useful for testing)
func InitWithWriter(w io.Writer, debug bool) {
debugMode = debug
level := slog.LevelInfo
if debug {
level = slog.LevelDebug
}
defaultLogger = slog.New(
tint.NewHandler(w, &tint.Options{
Level: level,
TimeFormat: time.RFC3339,
AddSource: debug,
}),
)
slog.SetDefault(defaultLogger)
}
// IsDebug returns true if debug mode is enabled
func IsDebug() bool {
return debugMode
}
// Debug logs a message at debug level
func Debug(msg string, args ...any) {
slog.Debug(msg, args...)
}
// Info logs a message at info level
func Info(msg string, args ...any) {
slog.Info(msg, args...)
}
// Warn logs a message at warn level
func Warn(msg string, args ...any) {
slog.Warn(msg, args...)
}
// Error logs a message at error level
func Error(msg string, args ...any) {
slog.Error(msg, args...)
}
// With returns a new logger with the given attributes
func With(args ...any) *slog.Logger {
return slog.With(args...)
}

352
pkg/subsonic/client.go Normal file
View file

@ -0,0 +1,352 @@
package subsonic
import (
"bytes"
"crypto/md5"
"encoding/hex"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"log/slog"
"math"
"math/rand"
"net/http"
"net/url"
"path"
"strconv"
"time"
)
// Client represents a Subsonic API client
type Client struct {
baseURL string
username string
password string
version string
httpClient *http.Client
}
// New creates a new Subsonic client
func New(server, username, password, version string, timeout time.Duration) *Client {
// Create a transport with reasonable defaults
transport := &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
DisableCompression: false, // Allow compression for efficiency
TLSHandshakeTimeout: 10 * time.Second,
DisableKeepAlives: false, // Enable keep-alives for connection reuse
ForceAttemptHTTP2: false, // Avoid HTTP/2 stream errors
ResponseHeaderTimeout: 15 * time.Second,
}
return &Client{
baseURL: server,
username: username,
password: password,
version: version,
httpClient: &http.Client{
Timeout: timeout,
Transport: transport,
},
}
}
// Response is the base response from the Subsonic API
type Response struct {
XMLName xml.Name `xml:"subsonic-response" json:"-"`
Status string `xml:"status,attr" json:"status"`
Version string `xml:"version,attr" json:"version"`
Type string `xml:"-" json:"type,omitempty"`
ServerVersion string `xml:"-" json:"serverVersion,omitempty"`
OpenSubsonic bool `xml:"-" json:"openSubsonic,omitempty"`
Error *APIError `xml:"error" json:"error,omitempty"`
RandomSong *MusicList `xml:"randomSongs" json:"randomSongs,omitempty"`
}
// APIError represents an error from the Subsonic API
type APIError struct {
Code int `xml:"code,attr" json:"code"`
Message string `xml:"message,attr" json:"message"`
}
// MusicList represents a list of songs
type MusicList struct {
Song []Song `xml:"song" json:"song"`
}
// Genre represents a music genre
type Genre struct {
Name string `xml:"name,attr" json:"name"`
}
// Artist represents an artist
type Artist struct {
ID string `xml:"id,attr" json:"id"`
Name string `xml:"name,attr" json:"name"`
}
// ReplayGain represents replay gain information
type ReplayGain struct {
TrackGain float64 `xml:"trackGain,attr" json:"trackGain"`
TrackPeak float64 `xml:"trackPeak,attr" json:"trackPeak"`
AlbumPeak float64 `xml:"albumPeak,attr" json:"albumPeak"`
}
// Contributor represents a contributor to a song
type Contributor struct {
Role string `xml:"role,attr" json:"role"`
Artist *Artist `xml:"artist" json:"artist"`
}
// Song represents a song in the Subsonic API
type Song struct {
ID string `xml:"id,attr" json:"id"`
ParentID string `xml:"parent,attr" json:"parent"`
IsDir bool `xml:"isDir,attr" json:"isDir"`
Title string `xml:"title,attr" json:"title"`
Album string `xml:"album,attr" json:"album"`
Artist string `xml:"artist,attr" json:"artist"`
Track int `xml:"track,attr" json:"track"`
Year int `xml:"year,attr" json:"year"`
Genre string `xml:"genre,attr" json:"genre"`
CoverArt string `xml:"coverArt,attr" json:"coverArt"`
Size int `xml:"size,attr" json:"size"`
ContentType string `xml:"contentType,attr" json:"contentType"`
Suffix string `xml:"suffix,attr" json:"suffix"`
Duration int `xml:"duration,attr" json:"duration"`
BitRate int `xml:"bitRate,attr" json:"bitRate"`
Path string `xml:"path,attr" json:"path"`
DiscNumber int `xml:"discNumber,attr" json:"discNumber"`
Created string `xml:"created,attr" json:"created"`
AlbumId string `xml:"albumId,attr" json:"albumId"`
ArtistId string `xml:"artistId,attr" json:"artistId"`
Type string `xml:"type,attr" json:"type"`
IsVideo bool `xml:"isVideo,attr" json:"isVideo"`
Bpm int `xml:"bpm,attr" json:"bpm"`
Comment string `xml:"comment,attr" json:"comment"`
SortName string `xml:"sortName,attr" json:"sortName"`
MediaType string `xml:"mediaType,attr" json:"mediaType"`
MusicBrainzId string `xml:"musicBrainzId,attr" json:"musicBrainzId"`
Genres []Genre `xml:"genres>genre" json:"genres"`
ReplayGain *ReplayGain `xml:"replayGain" json:"replayGain"`
ChannelCount int `xml:"channelCount,attr" json:"channelCount"`
SamplingRate int `xml:"samplingRate,attr" json:"samplingRate"`
BitDepth int `xml:"bitDepth,attr" json:"bitDepth"`
Moods []string `xml:"moods>mood" json:"moods"`
Artists []Artist `xml:"artists>artist" json:"artists"`
DisplayArtist string `xml:"displayArtist,attr" json:"displayArtist"`
AlbumArtists []Artist `xml:"albumArtists>artist" json:"albumArtists"`
DisplayAlbumArtist string `xml:"displayAlbumArtist,attr" json:"displayAlbumArtist"`
Contributors []Contributor `xml:"contributors>contributor" json:"contributors"`
DisplayComposer string `xml:"displayComposer,attr" json:"displayComposer"`
ExplicitStatus string `xml:"explicitStatus,attr" json:"explicitStatus"`
}
// GetRandomSongs retrieves random songs from the library
func (c *Client) GetRandomSongs(size int) ([]Song, error) {
params := url.Values{}
params.Set("size", strconv.Itoa(size))
slog.Debug("Requesting random songs from Subsonic server", "count", size)
resp := &Response{}
err := c.makeRequest("getRandomSongs", params, resp)
if err != nil {
slog.Error("Error getting random songs", "error", err)
return nil, err
}
if resp.Error != nil {
slog.Error("Subsonic API error", "code", resp.Error.Code, "message", resp.Error.Message)
return nil, fmt.Errorf("subsonic API error %d: %s", resp.Error.Code, resp.Error.Message)
}
if resp.RandomSong == nil || len(resp.RandomSong.Song) == 0 {
slog.Info("No random songs returned from Subsonic server")
return []Song{}, nil
}
slog.Debug("Successfully retrieved random songs", "count", len(resp.RandomSong.Song))
// Debug output to verify song data
for i, song := range resp.RandomSong.Song {
slog.Debug("Song details",
"index", i+1,
"id", song.ID,
"title", song.Title,
"artist", song.Artist,
"content_type", song.ContentType,
"suffix", song.Suffix,
"bit_rate", song.BitRate,
"duration", song.Duration)
}
return resp.RandomSong.Song, nil
}
// GetStreamURL returns the URL for streaming a song with processed format
func (c *Client) GetStreamURL(id string) string {
params := c.getBaseParams()
params.Set("id", id)
// Request specific format and bitrate to ensure compatibility with Discord
params.Set("format", "mp3") // Common format that most servers support
params.Set("estimateContentLength", "true") // Helps with proper buffering
params.Set("maxBitRate", "128") // Lower bitrate for better stability
params.Set("timeOffset", "0") // Start from the beginning
params.Set("size", "") // Don't resize
baseURL, _ := url.Parse(c.baseURL)
baseURL.Path = path.Join(baseURL.Path, "rest", "stream")
baseURL.RawQuery = params.Encode()
streamURL := baseURL.String()
slog.Debug("Generated stream URL", "song_id", id, "url", streamURL, "format", "mp3", "bitrate", "128")
return streamURL
}
// GetRawStreamURL returns the URL for streaming a song in its raw format
func (c *Client) GetRawStreamURL(id string) string {
params := c.getBaseParams()
params.Set("id", id)
// Don't specify format to get the raw file
params.Set("estimateContentLength", "true")
baseURL, _ := url.Parse(c.baseURL)
baseURL.Path = path.Join(baseURL.Path, "rest", "stream")
baseURL.RawQuery = params.Encode()
streamURL := baseURL.String()
slog.Debug("Generated raw stream URL", "song_id", id, "url", streamURL)
return streamURL
}
// GetCoverArtURL returns the URL for getting cover art
func (c *Client) GetCoverArtURL(id string) string {
params := c.getBaseParams()
params.Set("id", id)
baseURL, _ := url.Parse(c.baseURL)
baseURL.Path = path.Join(baseURL.Path, "rest", "getCoverArt")
baseURL.RawQuery = params.Encode()
return baseURL.String()
}
// makeRequest makes a request to the Subsonic API
func (c *Client) makeRequest(method string, additionalParams url.Values, result interface{}) error {
params := c.getBaseParams()
for k, v := range additionalParams {
params[k] = v
}
baseURL, err := url.Parse(c.baseURL)
if err != nil {
return err
}
baseURL.Path = path.Join(baseURL.Path, "rest", method)
baseURL.RawQuery = params.Encode()
fullURL := baseURL.String()
slog.Debug("Making Subsonic API request", "url", fullURL, "method", method)
// Create a request with additional headers
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
slog.Error("Error creating HTTP request", "error", err)
return err
}
// Add headers for better compatibility
req.Header.Set("User-Agent", "DiscordJukeboxBot/1.0")
req.Header.Set("Accept", "application/json, application/xml, */*")
// Execute the request
resp, err := c.httpClient.Do(req)
if err != nil {
slog.Error("HTTP request error", "error", err)
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
slog.Error("Unexpected HTTP status", "code", resp.StatusCode, "status", resp.Status)
return fmt.Errorf("unexpected status code: %d, status: %s", resp.StatusCode, resp.Status)
}
contentType := resp.Header.Get("Content-Type")
slog.Debug("Response content type", "type", contentType)
// For debugging, read the raw response
bodyBytes, _ := io.ReadAll(resp.Body)
if len(bodyBytes) < 1000 {
slog.Debug("Response body", "body", string(bodyBytes))
} else {
slog.Debug("Response body length", "length", len(bodyBytes),
"preview", string(bodyBytes[:int(math.Min(200, float64(len(bodyBytes))))]))
}
var decodeErr error
if contentType == "application/json" || contentType == "text/json" {
// For JSON, handle the "subsonic-response" wrapper
var respWrapper struct {
SubsonicResponse *Response `json:"subsonic-response"`
}
// Decode into the wrapper first
decodeErr = json.Unmarshal(bodyBytes, &respWrapper)
if decodeErr == nil && respWrapper.SubsonicResponse != nil {
// Copy the response fields to the result
resultAsResponse, ok := result.(*Response)
if ok {
*resultAsResponse = *respWrapper.SubsonicResponse
} else {
decodeErr = fmt.Errorf("expected result to be *Response, got %T", result)
}
}
} else {
// For XML, decode directly
decoder := xml.NewDecoder(bytes.NewReader(bodyBytes))
decodeErr = decoder.Decode(result)
}
if decodeErr != nil {
slog.Error("Error decoding response", "error", decodeErr,
"response_preview", string(bodyBytes[:int(math.Min(500, float64(len(bodyBytes))))]))
}
return decodeErr
}
// getBaseParams returns the base parameters for a Subsonic API request
func (c *Client) getBaseParams() url.Values {
params := url.Values{}
params.Set("u", c.username)
// Generate a random salt
salt := generateRandomString(10)
params.Set("s", salt)
// Use MD5 for password security
token := md5Hash(c.password + salt)
params.Set("t", token)
params.Set("v", c.version)
params.Set("c", "JukeboxBot")
params.Set("f", "json") // We prefer JSON, but handle XML too
return params
}
// generateRandomString generates a random string of the given length
func generateRandomString(length int) string {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
result := make([]byte, length)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := range result {
result[i] = chars[r.Intn(len(chars))]
}
return string(result)
}
// md5Hash computes the MD5 hash of a string
func md5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}

145
pkg/subsonic/client_test.go Normal file
View file

@ -0,0 +1,145 @@
package subsonic
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"testing"
)
func TestParseRandomSongsJSON(t *testing.T) {
// Open the test JSON file
file, err := os.Open("testdata/random_songs_response.json")
if err != nil {
t.Fatalf("Failed to open test file: %v", err)
}
defer file.Close()
// Read the file content
jsonData, err := io.ReadAll(file)
if err != nil {
t.Fatalf("Failed to read test file: %v", err)
}
// Parse JSON into Response struct
var respWrapper struct {
SubsonicResponse Response `json:"subsonic-response"`
}
err = json.Unmarshal(jsonData, &respWrapper)
if err != nil {
t.Fatalf("Failed to parse JSON: %v", err)
}
resp := respWrapper.SubsonicResponse
// Verify the Response fields
if resp.Status != "ok" {
t.Errorf("Expected status 'ok', got '%s'", resp.Status)
}
if resp.Version != "1.16.1" {
t.Errorf("Expected version '1.16.1', got '%s'", resp.Version)
}
if resp.Type != "navidrome" {
t.Errorf("Expected type 'navidrome', got '%s'", resp.Type)
}
if resp.ServerVersion != "0.55.2 (a057a680)" {
t.Errorf("Expected serverVersion '0.55.2 (a057a680)', got '%s'", resp.ServerVersion)
}
if !resp.OpenSubsonic {
t.Error("Expected openSubsonic to be true")
}
// Verify RandomSong data
if resp.RandomSong == nil {
t.Fatal("RandomSong is nil, expected data")
}
// We should have 2 songs in our test data
if len(resp.RandomSong.Song) != 2 {
t.Fatalf("Expected 2 songs, got %d", len(resp.RandomSong.Song))
}
// Check the first song
song1 := resp.RandomSong.Song[0]
if song1.ID != "WxADUtZQmq1rvWMKRteTvh" {
t.Errorf("Expected song ID 'WxADUtZQmq1rvWMKRteTvh', got '%s'", song1.ID)
}
if song1.Title != "The First Book (Extended)" {
t.Errorf("Expected song title 'The First Book (Extended)', got '%s'", song1.Title)
}
if song1.Artist != "桜庭統" {
t.Errorf("Expected artist '桜庭統', got '%s'", song1.Artist)
}
if song1.Album != "Golden Sun" {
t.Errorf("Expected album 'Golden Sun', got '%s'", song1.Album)
}
if song1.Duration != 377 {
t.Errorf("Expected duration 377, got %d", song1.Duration)
}
if song1.Path != "桜庭統/Golden Sun/01-02 - The First Book (Extended).mp3" {
t.Errorf("Expected path '桜庭統/Golden Sun/01-02 - The First Book (Extended).mp3', got '%s'", song1.Path)
}
// Check nested structures
if len(song1.Genres) != 1 {
t.Errorf("Expected 1 genre, got %d", len(song1.Genres))
} else if song1.Genres[0].Name != "Game Soundtrack" {
t.Errorf("Expected genre 'Game Soundtrack', got '%s'", song1.Genres[0].Name)
}
// Check second song
song2 := resp.RandomSong.Song[1]
if song2.ID != "1LuCYVkmVmNfmJgc8orwCi" {
t.Errorf("Expected song ID '1LuCYVkmVmNfmJgc8orwCi', got '%s'", song2.ID)
}
if song2.Title != "Divine Beast Vah Ruta Battle" {
t.Errorf("Expected song title 'Divine Beast Vah Ruta Battle', got '%s'", song2.Title)
}
if song2.Artist != "Yasuaki Iwata" {
t.Errorf("Expected artist 'Yasuaki Iwata', got '%s'", song2.Artist)
}
}
func TestMakeRequest(t *testing.T) {
// Create a test server that returns our test JSON
testFile, err := os.ReadFile("testdata/random_songs_response.json")
if err != nil {
t.Fatalf("Failed to read test file: %v", err)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(testFile)
}))
defer server.Close()
// Create a client using our test server URL
client := &Client{
baseURL: server.URL,
username: "testuser",
password: "testpass",
version: "1.16.1",
httpClient: &http.Client{},
}
// Test the GetRandomSongs method which uses makeRequest
songs, err := client.GetRandomSongs(10)
if err != nil {
t.Fatalf("GetRandomSongs failed: %v", err)
}
// Verify we got some songs back
if len(songs) != 2 {
t.Errorf("Expected 2 songs, got %d", len(songs))
}
// Check that the song data was parsed correctly
if songs[0].Title != "The First Book (Extended)" {
t.Errorf("Expected song title 'The First Book (Extended)', got '%s'", songs[0].Title)
}
if songs[1].Title != "Divine Beast Vah Ruta Battle" {
t.Errorf("Expected song title 'Divine Beast Vah Ruta Battle', got '%s'", songs[1].Title)
}
}

View file

@ -0,0 +1,147 @@
{
"subsonic-response": {
"status": "ok",
"version": "1.16.1",
"type": "navidrome",
"serverVersion": "0.55.2 (a057a680)",
"openSubsonic": true,
"randomSongs": {
"song": [
{
"id": "WxADUtZQmq1rvWMKRteTvh",
"parent": "0xRVI3OwZhprfTzN6vs6ti",
"isDir": false,
"title": "The First Book (Extended)",
"album": "Golden Sun",
"artist": "桜庭統",
"track": 2,
"year": 2007,
"genre": "Game Soundtrack",
"coverArt": "mf-WxADUtZQmq1rvWMKRteTvh_65045c88",
"size": 3910630,
"contentType": "audio/mpeg",
"suffix": "mp3",
"duration": 377,
"bitRate": 80,
"path": "桜庭統/Golden Sun/01-02 - The First Book (Extended).mp3",
"discNumber": 1,
"created": "2025-05-12T18:22:47.912430557Z",
"albumId": "0xRVI3OwZhprfTzN6vs6ti",
"artistId": "6I2Nnx3eA2xnsUGwQTtr3D",
"type": "music",
"isVideo": false,
"bpm": 0,
"comment": "www.sittingonclouds.net",
"sortName": "the first book (extended)",
"mediaType": "song",
"musicBrainzId": "46d99fd8-4b84-4202-aeeb-56ffd03bc4aa",
"genres": [
{
"name": "Game Soundtrack"
}
],
"replayGain": {
"trackPeak": 1,
"albumPeak": 1
},
"channelCount": 2,
"samplingRate": 32000,
"bitDepth": 0,
"moods": [],
"artists": [
{
"id": "6I2Nnx3eA2xnsUGwQTtr3D",
"name": "桜庭統"
}
],
"displayArtist": "桜庭統",
"albumArtists": [
{
"id": "6I2Nnx3eA2xnsUGwQTtr3D",
"name": "桜庭統"
}
],
"displayAlbumArtist": "桜庭統",
"contributors": [
{
"role": "composer",
"artist": {
"id": "7ALBQiGRFZDSjXkrHPK9xX",
"name": "Motoi Sakuraba"
}
}
],
"displayComposer": "Motoi Sakuraba",
"explicitStatus": ""
},
{
"id": "1LuCYVkmVmNfmJgc8orwCi",
"parent": "092dQuAiPh55hzAd7Y06lM",
"isDir": false,
"title": "Divine Beast Vah Ruta Battle",
"album": "The Legend of Zelda: Breath of the Wild Original Soundtrack",
"artist": "Yasuaki Iwata",
"track": 8,
"year": 2018,
"genre": "Game Soundtrack",
"coverArt": "mf-1LuCYVkmVmNfmJgc8orwCi_65045c9c",
"size": 12278801,
"contentType": "audio/flac",
"suffix": "flac",
"duration": 119,
"bitRate": 819,
"path": "Manaka Kataoka, Yasuaki Iwata & Hajime Wakai/The Legend of Zelda: Breath of the Wild Original Soundtrack/02-08 - Divine Beast Vah Ruta Battle.flac",
"discNumber": 2,
"created": "2025-05-12T18:22:47.166382716Z",
"albumId": "092dQuAiPh55hzAd7Y06lM",
"artistId": "7aGQqm0XpMOc4e4rEgj5iV",
"type": "music",
"isVideo": false,
"bpm": 0,
"comment": "sittingoncloudsost.com/ost",
"sortName": "divine beast vah ruta battle",
"mediaType": "song",
"musicBrainzId": "e2102713-f587-4eae-9538-2fc019e1c440",
"genres": [
{
"name": "Game Soundtrack"
}
],
"replayGain": {
"trackPeak": 1,
"albumPeak": 1
},
"channelCount": 2,
"samplingRate": 44100,
"bitDepth": 16,
"moods": [],
"artists": [
{
"id": "7aGQqm0XpMOc4e4rEgj5iV",
"name": "Yasuaki Iwata"
}
],
"displayArtist": "Yasuaki Iwata",
"albumArtists": [
{
"id": "600iKBbJhoZWOE782AHR14",
"name": "Manaka Kataoka, Yasuaki Iwata & Hajime Wakai"
}
],
"displayAlbumArtist": "Manaka Kataoka, Yasuaki Iwata & Hajime Wakai",
"contributors": [
{
"role": "composer",
"artist": {
"id": "7aGQqm0XpMOc4e4rEgj5iV",
"name": "Yasuaki Iwata"
}
}
],
"displayComposer": "Yasuaki Iwata",
"explicitStatus": ""
}
]
}
}
}