Skip to content

Latest commit

 

History

History
85 lines (66 loc) · 2.8 KB

File metadata and controls

85 lines (66 loc) · 2.8 KB

Using nostr-java

Navigation: Docs index · Getting started · Streaming subscriptions · Custom events · API reference

This guide shows how to set up the library and publish a basic Nostr event.

Minimal setup

Add the client module to your project (with the BOM):

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>xyz.tcheeric</groupId>
      <artifactId>nostr-java-bom</artifactId>
      <version><!-- X.Y.Z --></version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>xyz.tcheeric</groupId>
    <artifactId>nostr-java-client</artifactId>
  </dependency>
</dependencies>

The nostr-java-client module transitively brings in all other modules (identity, event, core).

Check the releases page for the latest BOM version.

Create, sign, and publish an event

import nostr.base.Kinds;
import nostr.client.springwebsocket.NostrRelayClient;
import nostr.event.impl.GenericEvent;
import nostr.event.message.EventMessage;
import nostr.event.tag.GenericTag;
import nostr.id.Identity;

import java.util.List;

public class QuickStart {
    public static void main(String[] args) throws Exception {
        Identity identity = Identity.generateRandomIdentity();

        GenericEvent event = GenericEvent.builder()
            .pubKey(identity.getPublicKey())
            .kind(Kinds.TEXT_NOTE)
            .content("Hello Nostr!")
            .tags(List.of(GenericTag.of("t", "nostr-java")))
            .build();

        identity.sign(event);

        try (NostrRelayClient client = new NostrRelayClient("wss://relay.398ja.xyz")) {
            client.send(new EventMessage(event));
        }
    }
}

Async alternative (Virtual Threads)

NostrRelayClient.connectAsync("wss://relay.398ja.xyz")
    .thenCompose(client -> client.sendAsync(new EventMessage(event)))
    .thenAccept(responses -> System.out.println("Sent! Responses: " + responses))
    .join();

Reference

Next steps