-
-
Save DavidBuchanan314/f92b3925c5480e35076773613cb87bdd to your computer and use it in GitHub Desktop.
insert MIT license here
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Self, Tuple, List | |
import io | |
class FacetBuilder(): | |
def __init__(self) -> None: | |
self.buffer = io.BytesIO() | |
self.facets = [] | |
def build(self) -> Tuple[str, List[dict]]: | |
return self.buffer.getvalue().decode(), self.facets | |
def text(self, text: str) -> Self: | |
self.buffer.write(text.encode()) | |
return self | |
def link(self, text: str, uri: str) -> Self: | |
start_index = self.buffer.tell() | |
self.buffer.write(text.encode()) | |
end_index = self.buffer.tell() | |
self.facets.append({ | |
'index': {'byteStart': start_index, 'byteEnd': end_index}, | |
'features': [{ | |
'$type': 'app.bsky.richtext.facet#link', | |
'uri': uri | |
}] | |
}) | |
return self | |
def mention(self, text: str, did: str) -> Self: | |
start_index = self.buffer.tell() | |
self.buffer.write(text.encode()) | |
end_index = self.buffer.tell() | |
self.facets.append({ | |
'index': {'byteStart': start_index, 'byteEnd': end_index}, | |
'features': [{ | |
'$type': 'app.bsky.richtext.facet#mention', | |
'did': did | |
}] | |
}) | |
return self | |
if __name__ == "__main__": | |
text, facets = FacetBuilder() \ | |
.text("hello, ").mention("@user", "did:plc:blah") \ | |
.text("! please visit my ").link("website.", "https://example.com/") \ | |
.build() | |
print(text) # -> hello, @user! please visit my website. | |
print(facets) # -> [{'index': {'byteStart': 7, 'byteEnd': 12}, 'features': [{'$type': 'app.bsky.richtext.facet#mention', 'did': 'did:plc:blah'}]}, {'index': {'byteStart': 30, 'byteEnd': 38}, 'features': [{'$type': 'app.bsky.richtext.facet#link', 'uri': 'https://example.com/'}]}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment