Skip to content

Commit 5b02e62

Browse files
committed
docs(examples): improve string parser example
1 parent a3e434a commit 5b02e62

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

examples/string_parser.py

+25-5
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
11
import asyncio
2-
import logging
32
import re
3+
import typing
44

55
import velum
66

77
import sail
88

9-
logging.basicConfig()
10-
logging.getLogger().setLevel(logging.DEBUG)
11-
12-
139
# Occasionally, the default string parser gets in your way.
1410
# Say you want to do something with codeblocks, where you do not want the
1511
# quotes inside to be consumed by the default parser. In situations like these,
@@ -57,6 +53,30 @@ async def codeblock(ctx: sail.Context, codeblock: str) -> None:
5753
... # Actual code eval implementation...
5854

5955

56+
# However, we can make this a bit more powerful if we want.
57+
# If we do the regex parsing in the parser, we can actually provide separate
58+
# args/kwargs to the function:
59+
60+
61+
def improved_parser(
62+
user_input: str,
63+
) -> typing.Tuple[typing.Sequence[str], typing.Dict[str, typing.Sequence[str]]]:
64+
match = CODEBLOCK_RE.fullmatch(user_input)
65+
66+
if not match:
67+
# This can be handled externally...
68+
raise RuntimeError("Not a codeblock.")
69+
70+
return [match.group("lang"), match.group("body")], {}
71+
72+
73+
@manager.command(string_parser=improved_parser)
74+
async def cooler_codeblock(ctx: sail.Context, lang: str, body: str) -> None:
75+
await client.rest.send_message("Sail", f"Evaluating your `{lang}` code...")
76+
77+
... # Actual code eval implementation...
78+
79+
6080
# Finally, we can run the bot as per usual.
6181

6282
asyncio.run(client.start())

0 commit comments

Comments
 (0)