Skip to content

Commit

Permalink
ffi: fix python examples
Browse files Browse the repository at this point in the history
Signed-off-by: Yuki Kishimoto <yukikishimoto@protonmail.com>
  • Loading branch information
yukibtc committed Nov 5, 2024
1 parent a5d6bb2 commit 5f3c24a
Show file tree
Hide file tree
Showing 14 changed files with 55 additions and 71 deletions.
2 changes: 1 addition & 1 deletion bindings/nostr-sdk-ffi/python/examples/blacklist.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async def main():
# Get events
f = Filter().authors([muted_public_key, other_public_key]).kind(Kind(0))
events = await client.fetch_events([f], timedelta(seconds=10))
print(f"Received {events.__len__()} events")
print(f"Received {events.len()} events")


if __name__ == '__main__':
Expand Down
19 changes: 5 additions & 14 deletions bindings/nostr-sdk-ffi/python/examples/bot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import asyncio
from nostr_sdk import Client, NostrSigner, Keys, Event, UnsignedEvent, Filter, \
HandleNotification, Timestamp, nip04_decrypt, UnwrappedGift, init_logger, LogLevel, Kind, KindEnum
from nostr_sdk import Client, Keys, Event, UnsignedEvent, Filter, \
HandleNotification, Timestamp, UnwrappedGift, init_logger, LogLevel, Kind, KindEnum


async def main():
Expand All @@ -15,8 +15,7 @@ async def main():
pk = keys.public_key()
print(f"Bot public key: {pk.to_bech32()}")

signer = NostrSigner.keys(keys)
client = Client(signer)
client = Client(keys)

await client.add_relay("wss://relay.damus.io")
await client.add_relay("wss://nostr.mom")
Expand All @@ -32,19 +31,11 @@ async def main():
class NotificationHandler(HandleNotification):
async def handle(self, relay_url, subscription_id, event: Event):
print(f"Received new event from {relay_url}: {event.as_json()}")
if event.kind().as_enum() == KindEnum.ENCRYPTED_DIRECT_MESSAGE():
print("Decrypting NIP04 event")
try:
msg = nip04_decrypt(sk, event.author(), event.content())
print(f"Received new msg: {msg}")
await client.send_direct_msg(event.author(), f"Echo: {msg}", event.id())
except Exception as e:
print(f"Error during content NIP04 decryption: {e}")
elif event.kind().as_enum() == KindEnum.GIFT_WRAP():
if event.kind().as_enum() == KindEnum.GIFT_WRAP():
print("Decrypting NIP59 event")
try:
# Extract rumor
unwrapped_gift = UnwrappedGift.from_gift_wrap(keys, event)
unwrapped_gift = await UnwrappedGift.from_gift_wrap(keys, event)
sender = unwrapped_gift.sender()
rumor: UnsignedEvent = unwrapped_gift.rumor()

Expand Down
13 changes: 6 additions & 7 deletions bindings/nostr-sdk-ffi/python/examples/client-with-opts.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,21 @@
async def main():
init_logger(LogLevel.INFO)

keys = Keys.generate()
print(keys.public_key().to_bech32())

# Configure client to use proxy for `.onion` relays
proxy = Connection().proxy("127.0.0.1:9050").target(ConnectionTarget.ONION)
connection = Connection().addr("127.0.0.1:9050").target(ConnectionTarget.ONION)
opts = (Options()
.connection_timeout(timedelta(seconds=60))
.send_timeout(timedelta(seconds=10))
.proxy(proxy))
.connection(connection))
client = Client.with_opts(None, opts)

await client.add_relay("wss://relay.damus.io")
await client.add_relay("ws://oxtrdevav64z64yb7x6rjg4ntzqjhedm5b5zjqulugknhzr46ny2qbad.onion")
await client.connect()

event = EventBuilder.text_note("Hello from Rust Nostr Python bindings!", []).to_event(keys)
keys = Keys.generate()
print(keys.public_key().to_bech32())

event = EventBuilder.text_note("Hello from rust-nostr Python bindings!", []).sign_with_keys(keys)
event_id = await client.send_event(event)
print("Event sent:")
print(f" hex: {event_id.to_hex()}")
Expand Down
16 changes: 7 additions & 9 deletions bindings/nostr-sdk-ffi/python/examples/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,12 @@ async def main():
# client = Client()

# Or, initialize with Keys signer
keys = Keys.generate()
signer = NostrSigner.keys(keys)
signer = Keys.generate()

# Or, initialize with NIP46 signer
# app_keys = Keys.parse("..")
# uri = NostrConnectUri.parse("bunker://.. or nostrconnect://..")
# nip46 = NostrConnect(uri, app_keys, timedelta(seconds=60), None)
# signer = NostrSigner.nip46(nip46)
# signer = NostrConnect(uri, app_keys, timedelta(seconds=60), None)

client = Client(signer)

Expand All @@ -35,21 +33,21 @@ async def main():
# Mine a POW event and sign it with custom keys
custom_keys = Keys.generate()
print("Mining a POW text note...")
event = EventBuilder.text_note("Hello from rust-nostr Python bindings!", []).to_pow_event(custom_keys, 20)
event = EventBuilder.text_note("Hello from rust-nostr Python bindings!", []).pow(20).sign_with_keys(custom_keys)
output = await client.send_event(event)
print("Event sent:")
print(f" hex: {output.id.to_hex()}")
print(f" bech32: {output.id.to_bech32()}")
print(f" Successfully sent to: {output.success}")
print(f" Failed to send to: {output.failed}")
print(f" Successfully sent to: {output.output.success}")
print(f" Failed to send to: {output.output.failed}")

await asyncio.sleep(2.0)

# Get events from relays
print("Getting events from relays...")
f = Filter().authors([keys.public_key(), custom_keys.public_key()])
f = Filter().authors([signer.public_key(), custom_keys.public_key()])
events = await client.fetch_events([f], timedelta(seconds=10))
for event in events:
for event in events.to_vec():
print(event.as_json())


Expand Down
23 changes: 13 additions & 10 deletions bindings/nostr-sdk-ffi/python/examples/custom-database.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import asyncio
from nostr_sdk import Keys, Filter, ClientBuilder, CustomNostrDatabase, NostrDatabase, NegentropyOptions, Event, \
init_logger, LogLevel, uniffi_set_event_loop
from nostr_sdk import *
from nostr_sdk import uniffi_set_event_loop
from typing import List, Optional, Set

init_logger(LogLevel.INFO)


async def main():
init_logger(LogLevel.INFO)

uniffi_set_event_loop(asyncio.get_running_loop())

# Example of custom in-memory database
Expand All @@ -22,15 +22,18 @@ async def save_event(self, e: Event) -> bool:
self.events[e.id()] = e
return True

async def check_id(self, event_id: "EventId") -> DatabaseEventStatus:
if event_id in self.events:
return DatabaseEventStatus.SAVED
else:
return DatabaseEventStatus.NOT_EXISTENT

async def has_event_already_been_saved(self, event_id) -> bool:
return event_id in self.events

async def has_event_already_been_seen(self, event_id) -> bool:
return event_id in self.seen_event_ids

async def has_event_id_been_deleted(self, event_id) -> bool:
return False

async def has_coordinate_been_deleted(self, coordinate, timestamp) -> bool:
return False

Expand All @@ -44,7 +47,7 @@ async def event_id_seen(self, event_id, relay_url: str):
async def event_seen_on_relays(self, event_id) -> Optional[Set[str]]:
return self.seen_event_ids.get(event_id)

async def event_by_id(self, event_id) -> Event:
async def event_by_id(self, event_id) -> Event | None:
return self.events.get(event_id, None)

async def count(self, filters) -> int:
Expand All @@ -54,7 +57,7 @@ async def query(self, filters) -> List[Event]:
# Fake algorithm
return list(self.events.values())[:10]

async def delete(self, f: Filter):
async def delete(self, filter):
return

async def wipe(self):
Expand All @@ -74,7 +77,7 @@ async def wipe(self):

# Negentropy reconciliation
f = Filter().author(keys.public_key())
opts = NegentropyOptions()
opts = SyncOptions()
await client.sync(f, opts)

# Query events from database
Expand Down
6 changes: 3 additions & 3 deletions bindings/nostr-sdk-ffi/python/examples/database.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import asyncio
from nostr_sdk import Keys, Filter, ClientBuilder, NostrDatabase, SyncOptions, init_logger, LogLevel

init_logger(LogLevel.INFO)
from nostr_sdk import *


async def main():
init_logger(LogLevel.INFO)

keys = Keys.parse("nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85")
print(keys.public_key().to_bech32())

Expand Down
2 changes: 1 addition & 1 deletion bindings/nostr-sdk-ffi/python/examples/event_builder.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import asyncio
from nostr_sdk import Keys, EventBuilder, Kind
from nostr_sdk import *


async def main():
Expand Down
7 changes: 3 additions & 4 deletions bindings/nostr-sdk-ffi/python/examples/metadata.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import asyncio
from nostr_sdk import Metadata, Client, NostrSigner, Keys, Filter, PublicKey, Kind
from nostr_sdk import Metadata, Client, Keys, Filter, PublicKey, Kind
from datetime import timedelta


async def main():
keys = Keys.generate()

signer = NostrSigner.keys(keys)
client = Client(signer)
client = Client(keys)

await client.add_relay("wss://relay.damus.io")
await client.connect()
Expand All @@ -31,7 +30,7 @@ async def main():
print(f"\nGetting profile metadata for {pk.to_bech32()}...")
f = Filter().kind(Kind(0)).author(pk).limit(1)
events = await client.fetch_events([f], timedelta(seconds=10))
for event in events:
for event in events.to_vec():
metadata = Metadata.from_json(event.content())
print(f"Name: {metadata.get_name()}")
print(f"NIP05: {metadata.get_nip05()}")
Expand Down
2 changes: 1 addition & 1 deletion bindings/nostr-sdk-ffi/python/examples/nip57.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
msg = "Zap!"
data = ZapRequestData(public_key, relays).message(msg)

public_zap = EventBuilder.public_zap_request(data).to_event(keys)
public_zap = EventBuilder.public_zap_request(data).sign_with_keys(keys)
print(f"Public zap request: {public_zap.as_json()}\n")

anon_zap = nip57_anonymous_zap_request(data)
Expand Down
11 changes: 5 additions & 6 deletions bindings/nostr-sdk-ffi/python/examples/nip94.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import asyncio
from nostr_sdk import Keys, Client, NostrSigner, FileMetadata, RelayOptions
from nostr_sdk import Keys, Client, FileMetadata


async def main():
keys = Keys.generate()
print(keys.public_key().to_bech32())

signer = NostrSigner.keys(keys)
client = Client(signer)
client = Client(keys)

await client.add_relay("wss://relay.damus.io")
await client.connect()
Expand All @@ -18,10 +17,10 @@ async def main():
"application/zip",
"3951c152d38317e9ef2c095ddb280613e22b14b166f5fa5950d18773ac0a1d00"
)
event_id = await client.file_metadata("Coinstr Alpha Release v0.3.0", metadata)
output = await client.file_metadata("Coinstr Alpha Release v0.3.0", metadata)
print("Event sent:")
print(f" hex: {event_id.to_hex()}")
print(f" bech32: {event_id.to_bech32()}")
print(f" hex: {output.id.to_hex()}")
print(f" bech32: {output.id.to_bech32()}")
except Exception as e:
print(f"{e}")

Expand Down
4 changes: 2 additions & 2 deletions bindings/nostr-sdk-ffi/python/examples/relays.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ async def main():
for url, relay in relays.items():
stats = relay.stats()
print(f"Relay: {url}")
print(f"Connected: {await relay.is_connected()}")
print(f"Status: {await relay.status()}")
print(f"Connected: {relay.is_connected()}")
print(f"Status: {relay.status()}")
print("Stats:")
print(f" Attempts: {stats.attempts()}")
print(f" Success: {stats.success()}")
Expand Down
10 changes: 4 additions & 6 deletions bindings/nostr-sdk-ffi/python/examples/tags.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
from nostr_sdk import Keys, EventBuilder, PublicKey, Tag, TagEnum
from nostr_sdk import Keys, EventBuilder, PublicKey, Tag, TagStandard

keys = Keys.generate()

other_user_pk = PublicKey.from_bech32("npub14f8usejl26twx0dhuxjh9cas7keav9vr0v8nvtwtrjqx3vycc76qqh9nsy")

tag = Tag.parse(["p", other_user_pk.to_hex()])
# OR
tag = Tag.from_enum(TagEnum.PUBLIC_KEY_TAG(other_user_pk, None, None, False))
tag = Tag.from_standardized(TagStandard.PUBLIC_KEY_TAG(other_user_pk, None, None, False))
# OR
tag = Tag.public_key(other_user_pk)

event = EventBuilder.text_note("New note from Rust Nostr python bindings", [tag]).to_event(keys)
event = EventBuilder.text_note("New note from Rust Nostr python bindings", [tag]).sign_with_keys(keys)
print(event.as_json())

print("\nTags:")
for tag in event.tags():
for tag in event.tags().to_vec():
print(tag.as_vec())
# OR handle it as enum
# TODO
6 changes: 2 additions & 4 deletions bindings/nostr-sdk-ffi/python/examples/tor.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import asyncio
from nostr_sdk import NostrSigner, Keys, Client, Options, EventBuilder, Connection, ConnectionTarget, init_logger, LogLevel
from nostr_sdk import Keys, Client, Options, EventBuilder, Connection, ConnectionTarget, init_logger, LogLevel
from datetime import timedelta


Expand All @@ -9,12 +9,10 @@ async def main():
keys = Keys.generate()
print(keys.public_key().to_bech32())

signer = NostrSigner.keys(keys)

# Configure client to use embedded tor for `.onion` relays
connection = Connection().embedded_tor().target(ConnectionTarget.ONION)
opts = Options().connection(connection).connection_timeout(timedelta(seconds=60))
client = Client.with_opts(signer, opts)
client = Client.with_opts(keys, opts)

await client.add_relay("wss://relay.damus.io")
await client.add_relay("ws://oxtrdevav64z64yb7x6rjg4ntzqjhedm5b5zjqulugknhzr46ny2qbad.onion")
Expand Down
5 changes: 2 additions & 3 deletions bindings/nostr-sdk-ffi/python/examples/zapper.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import asyncio
from nostr_sdk import Keys, ClientBuilder, NostrSigner, NostrZapper, NostrWalletConnectUri, PublicKey, ZapEntity, \
from nostr_sdk import Keys, ClientBuilder, NostrZapper, NostrWalletConnectUri, PublicKey, ZapEntity, \
init_logger, LogLevel


Expand All @@ -12,9 +12,8 @@ async def main():

# Compose client
keys = Keys.generate()
signer = NostrSigner.keys(keys)
zapper = NostrZapper.nwc(uri)
client = ClientBuilder().signer(signer).zapper(zapper).build()
client = ClientBuilder().signer(keys).zapper(zapper).build()

await client.add_relay("wss://relay.damus.io")
await client.connect()
Expand Down

0 comments on commit 5f3c24a

Please sign in to comment.