Templates & filters¶
A recipe's text is a template: {name} is a variable, and | passes it through a filter.
- reply: '{nick} hugs {arg|default:everyone}'
- reply: 'games: {store.games|sorted|join:, }'
{{ and }} are a literal brace.
Filters¶
| Filter | Gives | Example |
|---|---|---|
join |
a list's items, joined with ,, or the text after : |
{members|join: and } |
sorted |
a list, sorted without regard to case | {store.games|sorted} |
count |
how many items | {members|count} here |
first, last |
the first or last item | {rolled|first} |
random |
one item at random | {members|random} |
upper, lower |
the text in upper or lower case | {nick|upper} |
default |
the text after : when the value is empty |
{arg|default:everyone} |
Filters run left to right: {store.games|sorted|first} is the first game alphabetically.
Read saved values¶
{store.games} reads the key games from the recipes' store. {saved.key} reads a key from a dict a step saved. A missing key is empty.
Add a filter from a plugin¶
A plugin adds filters for every recipe to use:
from pinhook import recipes
@recipes.template_filter('shout')
def shout(value, arg):
return str(value).upper() + '!'
value is the variable, and arg is the text after :, or None.
Add a step from a plugin¶
A plugin adds step types the same way. Each declares its fields, so recipe files using it are checked when they load:
from pinhook import recipes
@recipes.step('weather', {'weather': 'template', 'save': 'name'}, saves='save')
async def weather(run, fields):
forecast = await fetch_forecast(run.render(fields['weather']))
run.save(fields.get('save'), forecast)
A field's kind is one of template, text, name, path, steps, flag or any. check looks a step's fields over when its recipe loads, and returns what's wrong, or None, so a mistake in a field of kind any is caught before the recipe ever runs:
def known_units(fields):
if fields.get('units') not in (None, 'metric', 'imperial'):
return 'units should be metric or imperial'
return None
@recipes.step('weather', {'weather': 'template', 'units': 'text'}, check=known_units)
Mark text to show only¶
A step that saves text people should see but nothing should act on, like text a model wrote, marks it:
@recipes.step('guess', {'guess': 'template', 'save': 'name'}, saves='save')
async def guess(run, fields):
run.save(fields['save'], {'kind': 'bug', 'summary': await summarise(run)})
run.mark(fields['save'] + '.summary', '[guess] ')
A reply that uses {g.summary} starts every line with [guess]. A command, store or when that uses it stops the recipe, and a for_each over a marked list marks each {item}. Saving over a variable clears its marks. run.marked(template.paths) tells a step of its own whether a template uses marked text.