Erik Klem
Erik Klem

Reputation: 25

Using optional formatting tokens in python

I have a discord.py bot that sends a message when someone joins a guild. It has a custom message that is set by an admin using a command. The admin needs to put {user} and {rules} to mention the user and rules channel in that message. I am trying to make it so they don't have to put rules, or user, or either.

# Sends welcome message
welcome = cluster.find_one({'id': 'settings'})
welcome_channel = client.get_channel(welcome['welcome_channel'])
welcome_message = welcome['join_message']
rules_channel = client.get_channel(welcome['rules_channel'])
await welcome_channel.send(welcome_message.format(user=member.mention, rules=rules_channel.mention))

Leave contains the message. I get an error anytime the admin sets the message to be something like

"hello {user}", where it doesn't have rules.

Is there any way I can make it so that the formats are optional?

Upvotes: 0

Views: 38

Answers (1)

nejcs
nejcs

Reputation: 1262

Not with format. Format expects all values to be consumed while formatting message.

If you are willing to change your welcome message format a bit you can use templated strings:

from string import Template

welcome_message = Template(welcome['join_message'])
await welcome_channel.send(welcome_message.safe_substitute(user=member.mention, rules=rules_channel.mention))

This requires Python 3.2 or higher and message variables should be $var or ${var}. So in your case message would be Welcome $user, here are the $rules or something similar.

Upvotes: 1

Related Questions