Skip to content

Instantly share code, notes, and snippets.

@DavidBuchanan314
Last active September 6, 2023 12:31
Show Gist options
  • Save DavidBuchanan314/f92b3925c5480e35076773613cb87bdd to your computer and use it in GitHub Desktop.
Save DavidBuchanan314/f92b3925c5480e35076773613cb87bdd to your computer and use it in GitHub Desktop.
insert MIT license here
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