Custom Service
This example will explain how to create a custom Shuttle service using Poise and Axum.
In this simple example we will implement Service
for a custom service that serves a Discord bot alongside a web server created using Axum.
Prerequisites
To be able to create this example, we’ll need to grab an API token from the Discord developer portal.
- Click the New Application button, name your application and click Create.
- Navigate to the Bot tab in the lefthand menu, and add a new bot.
- On the bot page click the Reset Token button to reveal your token. Put this token in your
Secrets.toml
(explained below). It’s very important that you don’t reveal your token to anyone, as it can be abused. Create a.gitignore
file to omit yourSecrets.toml
from version control.
Your Secrets.toml
file needs to be in the root of your directory once the project has been initialised - the file will use a format similar to a .env
file, like so:
To add the bot to a server, we need to create an invite link:
- On your bot’s application page, open the OAuth2 page via the lefthand panel.
- Go to the URL Generator via the lefthand panel, and select the
bot
scope. - Copy the URL, open it in your browser and select a Discord server you wish to invite the bot to.
Initial Setup
Start by running the following command:
This will simply initialize a new cargo crate with a dependency on shuttle-runtime
.
We also want to add several dependencies for this - make sure your Cargo.toml looks like below:
Getting Started
To get started, we need to return a wrapper struct from our shuttle_runtime::main
.
Then we need to implement shuttle_service::Service
for our wrapper. If you need to bind to an address,
for example if you’re implementing service for an HTTP server, you can use the addr
argument from bind
.
You can only have one HTTP service bound to the addr
, but you can start other services that don’t rely on
binding to a socket, like so:
Commands/Routing
Before we can actually run the program, we will need to set up the commands and routing that it needs before we can add them to the struct implementation. Let’s do that now:
Struct Implementation
To finish up, we return the wrapper struct from our shuttle_runtime::main
function and add implementation
for setting up each of our services for the struct, like so:
Finishing Up
Try it out with the run
command:
Was this page helpful?