Struct nostr_sdk::client::Client

source ·
pub struct Client { /* private fields */ }
Expand description

Nostr client

Implementations§

source§

impl Client

source

pub async fn req_signer_public_key( &self, timeout: Option<Duration> ) -> Result<(), Error>

Request the XOnlyPublicKey of the signer (sent with Connect request)

Call not required if you already added in Client::with_remote_signer.

Example
use std::time::Duration;

use nostr_sdk::prelude::*;

#[tokio::main]
async fn main() {
    let keys = Keys::generate();
    let relay_url = Url::parse("wss://relay.example.com").unwrap();
    let signer = RemoteSigner::new(relay_url, None);
    let client = Client::with_remote_signer(&keys, signer);

    // Signer public key MUST be requested in this case
    client
        .req_signer_public_key(Some(Duration::from_secs(180)))
        .await
        .unwrap();
}
Example
use std::str::FromStr;

use nostr_sdk::prelude::*;

#[tokio::main]
async fn main() {
    let keys = Keys::generate();
    let relay_url = Url::parse("wss://relay.example.com").unwrap();
    let signer_public_key = XOnlyPublicKey::from_str(
        "b2d670de53b27691c0c3400225b65c35a26d06093bcc41f48ffc71e0907f9d4a",
    )
    .unwrap();
    let signer = RemoteSigner::new(relay_url, Some(signer_public_key));

    // Signer public key request isn't needed since we already added in client constructor
    let _client = Client::with_remote_signer(&keys, signer);
}
source

pub async fn send_req_to_signer( &self, req: Request, timeout: Option<Duration> ) -> Result<Response, Error>

Send NIP46 Request to signer

source§

impl Client

source

pub fn new(keys: &Keys) -> Self

Create a new Client

Example
use nostr_sdk::prelude::*;

let my_keys = Keys::generate();
let client = Client::new(&my_keys);
source

pub fn with_opts(keys: &Keys, opts: Options) -> Self

Create a new Client with Options

Example
use nostr_sdk::prelude::*;

let my_keys = Keys::generate();
let opts = Options::new().wait_for_send(true);
let client = Client::with_opts(&my_keys, opts);
source

pub fn with_remote_signer(app_keys: &Keys, remote_signer: RemoteSigner) -> Self

Create a new NIP46 Client

source

pub fn with_remote_signer_and_opts( app_keys: &Keys, remote_signer: RemoteSigner, opts: Options ) -> Self

Create a new NIP46 Client with custom Options

source

pub fn update_difficulty(&self, difficulty: u8)

Update default difficulty for new Event

source

pub fn keys(&self) -> Keys

Get current Keys

source

pub fn pool(&self) -> RelayPool

source

pub fn nostr_connect_uri( &self, metadata: NostrConnectMetadata ) -> Result<NostrConnectURI, Error>

Get NIP46 uri

source

pub fn remote_signer(&self) -> Result<RemoteSigner, Error>

Get remote signer

source

pub async fn start(&self)

Start a previously stopped client

source

pub async fn stop(&self) -> Result<(), Error>

Stop the client

source

pub fn is_running(&self) -> bool

Check if RelayPool is running

source

pub async fn shutdown(self) -> Result<(), Error>

Completely shutdown Client

source

pub async fn clear_already_seen_events(&self)

Clear already seen events

source

pub fn notifications(&self) -> Receiver<RelayPoolNotification>

Get new notification listener

source

pub async fn relays(&self) -> HashMap<Url, Relay>

Get relays

source

pub async fn relay<U>(&self, url: U) -> Result<Relay, Error>where U: TryIntoUrl, Error: From<<U as TryIntoUrl>::Err>,

Get Relay

source

pub async fn add_relay<U>( &self, url: U, proxy: Option<SocketAddr> ) -> Result<(), Error>where U: TryIntoUrl, Error: From<<U as TryIntoUrl>::Err>,

Add new relay

Example
use nostr_sdk::prelude::*;

client
    .add_relay("wss://relay.nostr.info", None)
    .await
    .unwrap();
client
    .add_relay("wss://relay.damus.io", None)
    .await
    .unwrap();
source

pub async fn add_relay_with_opts<U>( &self, url: U, proxy: Option<SocketAddr>, opts: RelayOptions ) -> Result<(), Error>where U: TryIntoUrl, Error: From<<U as TryIntoUrl>::Err>,

Add new relay with Options

Example
use nostr_sdk::prelude::*;

let read = true;
let write = false;
let opts = RelayOptions::new(read, write);
client
    .add_relay_with_opts("wss://relay.nostr.info", None, opts)
    .await
    .unwrap();
source

pub async fn remove_relay<U>(&self, url: U) -> Result<(), Error>where U: TryIntoUrl, Error: From<<U as TryIntoUrl>::Err>,

Disconnect and remove relay

Example
use nostr_sdk::prelude::*;

client.remove_relay("wss://relay.nostr.info").await.unwrap();
source

pub async fn add_relays<U>( &self, relays: Vec<(U, Option<SocketAddr>)> ) -> Result<(), Error>where U: TryIntoUrl, Error: From<<U as TryIntoUrl>::Err>,

Add multiple relays

source

pub async fn connect_relay<U>(&self, url: U) -> Result<(), Error>where U: TryIntoUrl, Error: From<<U as TryIntoUrl>::Err>,

Connect relay

Example
use nostr_sdk::prelude::*;

client
    .connect_relay("wss://relay.nostr.info")
    .await
    .unwrap();
source

pub async fn disconnect_relay<U>(&self, url: U) -> Result<(), Error>where U: TryIntoUrl, Error: From<<U as TryIntoUrl>::Err>,

Disconnect relay

Example
use nostr_sdk::prelude::*;

client
    .disconnect_relay("wss://relay.nostr.info")
    .await
    .unwrap();
source

pub async fn connect(&self)

Connect to all added relays

Example
use nostr_sdk::prelude::*;

client.connect().await;
source

pub async fn disconnect(&self) -> Result<(), Error>

Disconnect from all relays

Example
use nostr_sdk::prelude::*;

client.disconnect().await.unwrap();
source

pub async fn subscribe(&self, filters: Vec<Filter>)

Subscribe to filters

Example
use nostr_sdk::prelude::*;

let subscription = Filter::new()
    .pubkeys(vec![my_keys.public_key()])
    .since(Timestamp::now());

client.subscribe(vec![subscription]).await;
source

pub async fn subscribe_with_custom_wait( &self, filters: Vec<Filter>, wait: Option<Duration> )

Subscribe to filters with custom wait

source

pub async fn unsubscribe(&self)

Unsubscribe

source

pub async fn unsubscribe_with_custom_wait(&self, wait: Option<Duration>)

Unsubscribe with custom wait

source

pub async fn get_events_of( &self, filters: Vec<Filter>, timeout: Option<Duration> ) -> Result<Vec<Event>, Error>

Get events of filters

If timeout is set to None, the default from Options will be used.

Example
use std::time::Duration;

use nostr_sdk::prelude::*;

let subscription = Filter::new()
    .pubkeys(vec![my_keys.public_key()])
    .since(Timestamp::now());

let timeout = Duration::from_secs(10);
let _events = client
    .get_events_of(vec![subscription], Some(timeout))
    .await
    .unwrap();
source

pub async fn get_events_of_with_opts( &self, filters: Vec<Filter>, timeout: Option<Duration>, opts: FilterOptions ) -> Result<Vec<Event>, Error>

Get events of filters with FilterOptions

If timeout is set to None, the default from Options will be used.

source

pub async fn req_events_of( &self, filters: Vec<Filter>, timeout: Option<Duration> )

Request events of filters All events will be received on notification listener (client.notifications()) until the EOSE “end of stored events” message is received from the relay.

If timeout is set to None, the default from Options will be used.

source

pub async fn req_events_of_with_opts( &self, filters: Vec<Filter>, timeout: Option<Duration>, opts: FilterOptions )

Request events of filters with FilterOptions

If timeout is set to None, the default from Options will be used.

source

pub async fn send_msg(&self, msg: ClientMessage) -> Result<(), Error>

Send client message

source

pub async fn batch_msg( &self, msgs: Vec<ClientMessage>, wait: Option<Duration> ) -> Result<(), Error>

Send client message

source

pub async fn send_msg_to<U>( &self, url: U, msg: ClientMessage ) -> Result<(), Error>where U: TryIntoUrl, Error: From<<U as TryIntoUrl>::Err>,

Send client message to a specific relay

source

pub async fn send_event(&self, event: Event) -> Result<EventId, Error>

Send event

This method will wait for the OK message from the relay. If you not want to wait for the OK message, use send_msg method instead.

source

pub async fn batch_event( &self, events: Vec<Event>, opts: RelaySendOptions ) -> Result<(), Error>

Send multiple Event at once

source

pub async fn send_event_to<U>( &self, url: U, event: Event ) -> Result<EventId, Error>where U: TryIntoUrl, Error: From<<U as TryIntoUrl>::Err>,

Send event to specific relay

This method will wait for the OK message from the relay. If you not want to wait for the OK message, use send_msg method instead.

source

pub async fn set_metadata(&self, metadata: Metadata) -> Result<EventId, Error>

Update metadata

https://github.com/nostr-protocol/nips/blob/master/01.md

Example
use nostr_sdk::prelude::*;

let metadata = Metadata::new()
    .name("username")
    .display_name("My Username")
    .about("Description")
    .picture(Url::parse("https://example.com/avatar.png").unwrap())
    .nip05("username@example.com");

client.set_metadata(metadata).await.unwrap();
source

pub async fn publish_text_note<S>( &self, content: S, tags: &[Tag] ) -> Result<EventId, Error>where S: Into<String>,

Publish text note

https://github.com/nostr-protocol/nips/blob/master/01.md

Example
use nostr_sdk::prelude::*;

client
    .publish_text_note("My first text note from Nostr SDK!", &[])
    .await
    .unwrap();

Add recommended relay

https://github.com/nostr-protocol/nips/blob/master/01.md

Example
use nostr_sdk::prelude::*;

client
    .add_recommended_relay("wss://relay.damus.io")
    .await
    .unwrap();
source

pub async fn set_contact_list( &self, list: Vec<Contact> ) -> Result<EventId, Error>

source

pub async fn get_contact_list( &self, timeout: Option<Duration> ) -> Result<Vec<Contact>, Error>

Get contact list

https://github.com/nostr-protocol/nips/blob/master/02.md

Example
use std::time::Duration;

use nostr_sdk::prelude::*;

let timeout = Duration::from_secs(10);
let _list = client.get_contact_list(Some(timeout)).await.unwrap();
source

pub async fn get_contact_list_public_keys( &self, timeout: Option<Duration> ) -> Result<Vec<XOnlyPublicKey>, Error>

source

pub async fn get_contact_list_metadata( &self, timeout: Option<Duration> ) -> Result<HashMap<XOnlyPublicKey, Metadata>, Error>

Get contact list Metadata

source

pub async fn send_direct_msg<S>( &self, receiver: XOnlyPublicKey, msg: S, reply_to: Option<EventId> ) -> Result<EventId, Error>where S: Into<String>,

Send encrypted direct message

https://github.com/nostr-protocol/nips/blob/master/04.md

Example
use nostr_sdk::prelude::*;

let alice_pubkey = XOnlyPublicKey::from_bech32(
    "npub14f8usejl26twx0dhuxjh9cas7keav9vr0v8nvtwtrjqx3vycc76qqh9nsy",
)
.unwrap();

client
    .send_direct_msg(alice_pubkey, "My first DM fro Nostr SDK!", None)
    .await
    .unwrap();
source

pub async fn repost_event( &self, event_id: EventId, public_key: XOnlyPublicKey ) -> Result<EventId, Error>

Repost event

source

pub async fn delete_event<S>( &self, event_id: EventId, reason: Option<S> ) -> Result<EventId, Error>where S: Into<String>,

source

pub async fn like( &self, event_id: EventId, public_key: XOnlyPublicKey ) -> Result<EventId, Error>

Like event

https://github.com/nostr-protocol/nips/blob/master/25.md

Example
use std::str::FromStr;

use nostr_sdk::prelude::*;

let event_id =
    EventId::from_hex("3aded8d2194dc2fedb1d7b70480b43b6c4deb0a22dcdc9c471d1958485abcf21")
        .unwrap();
let public_key = XOnlyPublicKey::from_str(
    "a8e76c3ace7829f9ee44cf9293309e21a1824bf1e57631d00685a1ed0b0bd8a2",
)
.unwrap();

client.like(event_id, public_key).await.unwrap();
source

pub async fn dislike( &self, event_id: EventId, public_key: XOnlyPublicKey ) -> Result<EventId, Error>

Disike event

https://github.com/nostr-protocol/nips/blob/master/25.md

Example
use std::str::FromStr;

use nostr_sdk::prelude::*;

let event_id =
    EventId::from_hex("3aded8d2194dc2fedb1d7b70480b43b6c4deb0a22dcdc9c471d1958485abcf21")
        .unwrap();
let public_key = XOnlyPublicKey::from_str(
    "a8e76c3ace7829f9ee44cf9293309e21a1824bf1e57631d00685a1ed0b0bd8a2",
)
.unwrap();

client.dislike(event_id, public_key).await.unwrap();
source

pub async fn reaction<S>( &self, event_id: EventId, public_key: XOnlyPublicKey, content: S ) -> Result<EventId, Error>where S: Into<String>,

React to an Event

https://github.com/nostr-protocol/nips/blob/master/25.md

Example
use std::str::FromStr;

use nostr_sdk::prelude::*;

let event_id =
    EventId::from_hex("3aded8d2194dc2fedb1d7b70480b43b6c4deb0a22dcdc9c471d1958485abcf21")
        .unwrap();
let public_key = XOnlyPublicKey::from_str(
    "a8e76c3ace7829f9ee44cf9293309e21a1824bf1e57631d00685a1ed0b0bd8a2",
)
.unwrap();

client.reaction(event_id, public_key, "🐻").await.unwrap();
source

pub async fn new_channel(&self, metadata: Metadata) -> Result<EventId, Error>

source

pub async fn set_channel_metadata( &self, channel_id: ChannelId, relay_url: Option<Url>, metadata: Metadata ) -> Result<EventId, Error>

source

pub async fn send_channel_msg<S>( &self, channel_id: ChannelId, relay_url: Url, msg: S ) -> Result<EventId, Error>where S: Into<String>,

source

pub async fn hide_channel_msg<S>( &self, message_id: EventId, reason: Option<S> ) -> Result<EventId, Error>where S: Into<String>,

source

pub async fn mute_channel_user<S>( &self, pubkey: XOnlyPublicKey, reason: Option<S> ) -> Result<EventId, Error>where S: Into<String>,

source

pub async fn auth<S>(&self, challenge: S, relay: Url) -> Result<EventId, Error>where S: Into<String>,

source

pub async fn new_zap_receipt<S>( &self, bolt11: S, preimage: Option<S>, zap_request: Event ) -> Result<EventId, Error>where S: Into<String>,

source

pub async fn file_metadata<S>( &self, description: S, metadata: FileMetadata ) -> Result<EventId, Error>where S: Into<String>,

source

pub async fn get_channels( &self, timeout: Option<Duration> ) -> Result<Vec<Event>, Error>

Get a list of channels

source

pub async fn get_entity_of<S>( &self, entity: S, timeout: Option<Duration> ) -> Result<Entity, Error>where S: Into<String>,

Get entity of hex string

source

pub async fn handle_notifications<F, Fut>(&self, func: F) -> Result<(), Error>where F: Fn(RelayPoolNotification) -> Fut, Fut: Future<Output = Result<bool>>,

Handle notifications

Trait Implementations§

source§

impl Clone for Client

source§

fn clone(&self) -> Client

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Client

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for Client

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl From<Client> for Client

source§

fn from(client: Client) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more