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 new_with_opts(keys: &Keys, opts: Options) -> Self

👎Deprecated since 0.21.0: use with_opts instead
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 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 shutdown(self) -> Result<(), Error>

Completly shutdown Client

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 add_relay<S>( &self, url: S, proxy: Option<SocketAddr> ) -> Result<(), Error>where S: Into<String>,

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<S>( &self, url: S, proxy: Option<SocketAddr>, opts: RelayOptions ) -> Result<(), Error>where S: Into<String>,

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<S>(&self, url: S) -> Result<(), Error>where S: Into<String>,

Disconnect and remove relay

Example
use nostr_sdk::prelude::*;

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

pub async fn add_relays<S>( &self, relays: Vec<(S, Option<SocketAddr>)> ) -> Result<(), Error>where S: Into<String>,

Add multiple relays

source

pub async fn connect_relay<S>(&self, url: S) -> Result<(), Error>where S: Into<String>,

Connect relay

Example
use nostr_sdk::prelude::*;

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

pub async fn disconnect_relay<S>(&self, url: S) -> Result<(), Error>where S: Into<String>,

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 unsubscribe(&self)

Unsubscribe

source

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

Get events of filters

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 req_events_of( &self, filters: Vec<Filter>, timeout: Option<Duration> )

Request events of filters All events will be received on notification listener (client.notifications())

source

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

Send client message

source

pub async fn send_msg_to<S>( &self, url: S, msg: ClientMessage ) -> Result<(), Error>where S: Into<String>,

Send client message to a specific relay

source

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

Send event

source

pub async fn send_event_to<S>( &self, url: S, event: Event ) -> Result<EventId, Error>where S: Into<String>,

Send event to specific relay

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 ) -> 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!")
    .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 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<()>>,

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

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,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · 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>,

const: unstable · 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.
const: unstable · 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.
const: unstable · 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