Configuration API¶
This page assumes you’ve completed Creating a Simple Hello World Module. If not, check the previous pages.
You made your bot, everybody loves it, but people always ask “How can I change the
message?”. Let’s make sure they can change it easily using the
Configuration
API.
Configuration Files¶
The configuration files use the HOCON syntax, and generally live under the
DATA_PATH
’s conf
subdirectory
(/data/conf/<server id>.conf
by default). Instead of having multiple configuration
files per module, we instead have a single file for each server, and modules can put
their options under their own namespace.
The HOCON/Configuration
system is
also internally used in both Permissions
and Translation
.
Creating Keys¶
The first step towards using the configuration is creating the defaults other people will
modify. For that, we use
set_if_not_exist
like so:
async def on_ready(self):
for server in self.client.servers:
# self.client.get_configuration(server.id) is used to receive the
# configuration object for server
self.client.get_configuration(server.id).set_if_not_exist(
"helloworld.text", "Hello, {name}!"
)
self.client.get_configuration(server.id).save()
This will create the key helloworld.text
for any servers the bot finds on startup
Note
You might want to use something like
on_server_join
if you’re going to make a bot
that might join and leave servers overtime.
Getting Values¶
To get values from the config, we use the
get
method:
async def run(self, message: discord.Message, **kwargs):
name = kwargs.get("name", "World")
text = self.client.get_configuration(message.server.id).get("helloworld.text")
await self.client.send_message(message.channel, text.format(name=name))
This module (with some comments) can be found on our examples repository
Setting Values¶
To set values from the config, we use the
set
method:
async def run(self, message: discord.Message, **kwargs):
text = kwargs.get("text")
# Add auto_save=True to save after setting. Otherwise you'll have to use
# Configuration.save() manually
self.client.get_configuration(message.server.id).set("helloworld.text", text)