Skip to main content

Client

Struct Client 

Source
pub struct Client {
    pub relays: HashMap<String, Arc<Mutex<SimplifiedWS>>>,
    pub subscriptions: HashMap<String, Vec<Message>>,
}
Expand description

Nostr Client

Fields§

§relays: HashMap<String, Arc<Mutex<SimplifiedWS>>>§subscriptions: HashMap<String, Vec<Message>>

Implementations§

Source§

impl Client

Source

pub fn set_metadata( &mut self, identity: &Identity, name: Option<&str>, about: Option<&str>, picture: Option<&str>, nip05: Option<&str>, difficulty_target: u16, ) -> Result<Event, NIP1Error>

Set the metadata of the identity

§Example
§Example
use nostr_rust::{nostr_client::Client, Identity};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();

// Here we set the metadata of the identity but not the profile picture one
client.set_metadata(&identity, Some("Rust Nostr Client"), Some("Automated account for Rust Nostr Client tests :)"), None, None, 0).unwrap();
Source

pub fn publish_text_note( &mut self, identity: &Identity, content: &str, tags: &[Vec<String>], difficulty_target: u16, ) -> Result<Event, NIP1Error>

Publish a text note (text_note) event

§Example
use nostr_rust::{nostr_client::Client, Identity, utils::get_timestamp};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();
let message = format!("Hello Nostr! {}", get_timestamp());
client.publish_text_note(&identity, &message, &vec![], 0).unwrap();
Source

pub fn broadcast_event(&mut self, event: &Event) -> Result<(), NIP1Error>

Broadcast event

§Example
use nostr_rust::{nostr_client::Client, Identity, utils::get_timestamp};
use std::str::FromStr;
use serde_json::json;

let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();

let event = identity.make_event(1, "Hello Nostr!", &vec![], 0);
client.broadcast_event(&event).unwrap();

Add recommended relay server

§Example
use nostr_rust::{nostr_client::Client, Identity};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();

// Here we set the recommended relay server to the url set in env
client.add_recommended_relay(&identity, env!("RELAY_URL"), 0).unwrap();
Source§

impl Client

Source

pub fn publish_replaceable_event( &mut self, identity: &Identity, kind: u16, content: &str, tags: &[Vec<String>], difficulty_target: u16, ) -> Result<Event, NIP16Error>

Publish a replaceable event. kind argument should be less then 9999. publish_replaceable_event adds 10000 to kind to update event kind to be within the NIP16 replaceable event range 10000 <= kind < 20000

§Example
use nostr_rust::nostr_client::Client;
use nostr_rust::Identity;
use nostr_rust::nips::nip16::NIP16Error;
use std::str::FromStr;
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let event = client.publish_replaceable_event(
 &identity,
 20000,
 "hello world",
 &[],
 0).unwrap_err();
assert_eq!(format!("{:?}", event), "EventKindOutOfRange");

let event = client.publish_replaceable_event(
 &identity,
 10,
 "hello world",
 &[],
 0).unwrap();
assert_eq!(event.kind, 10010)
Source

pub fn publish_ephemeral_event( &mut self, identity: &Identity, kind: u16, content: &str, tags: &[Vec<String>], difficulty_target: u16, ) -> Result<Event, NIP16Error>

Publish an ephemeral event. kind argument should be less then 9999. publish_ephemeral_event adds 20000 to kind to update event kind to be within the NIP16 ephemeral event range of 20000 <= kind < 30000

§Example
use nostr_rust::nostr_client::Client;
use nostr_rust::Identity;
use nostr_rust::nips::nip16::NIP16Error;
use std::str::FromStr;
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let event = client.publish_ephemeral_event(
                        &identity,
                        10000,
                        "hello world",
                        &[],
                        0)
                        .unwrap_err();
assert_eq!(format!("{:?}",event), format!("{:?}",NIP16Error::EventKindOutOfRange));
let event = client.publish_ephemeral_event(&identity, 5, "hello world", &[],
0).unwrap();
assert_eq!(event.kind, 20005);
Source

pub fn publish_nip16_event(&mut self, event: &Event) -> Result<(), NIP16Error>

Source§

impl Client

Source

pub fn set_contact_list( &mut self, identity: &Identity, contact_list: Vec<ContactListTag>, difficulty_target: u16, ) -> Result<(), NIP2Error>

Set the contact list of the identity

§Example
use nostr_rust::{nostr_client::Client, Identity, nips::nip2::ContactListTag};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();

// Here we set the contact list of the identity
client.set_contact_list(&identity, vec![ContactListTag {
  key: "884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6".to_string(),
  main_relay: Some(env!("RELAY_URL").to_string()),
  surname: Some("Rust Nostr Client".to_string()),
}],
0).unwrap();
Source

pub fn get_contact_list( &mut self, pubkey: &str, ) -> Result<Vec<ContactListTag>, NIP2Error>

Get the contact list of a pub key

§Example
use nostr_rust::{nostr_client::Client, Identity, nips::nip2::ContactListTag};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let contact_list = client.get_contact_list("884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6").unwrap();
Source§

impl Client

Source

pub fn react_to( &mut self, identity: &Identity, event_id: &str, event_pub_key: &str, reaction: &str, difficulty_target: u16, ) -> Result<Event, NIP25Error>

React to an event

‘+’ = Like
‘-’ = Dislike
Emoji = React with an emoji

§Example
use nostr_rust::{nostr_client::Client, Identity};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();

// Here we react to an event
client.react_to(&identity, "342060554ca30a9792f6e6959675ae734aed02c23e35037d2a0f72ac6316e83d", "884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6", "+", 0).unwrap();
Source

pub fn like( &mut self, identity: &Identity, event_id: &str, event_pub_key: &str, difficulty_target: u16, ) -> Result<Event, NIP25Error>

Add a like to an event

§Example
use nostr_rust::{nostr_client::Client, Identity};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();
client.like(&identity, "342060554ca30a9792f6e6959675ae734aed0223e35037d2a0f72ac6316e83d", "884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6", 0).unwrap();
Source

pub fn dislike( &mut self, identity: &Identity, event_id: &str, event_pub_key: &str, difficulty_target: u16, ) -> Result<Event, NIP25Error>

Add a dislike to an event

§Example
use nostr_rust::{nostr_client::Client, Identity};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();
client.dislike(&identity, "342060554ca30a9792f6e6959675ae734aed02c23e35037d2a0f72ac6316e83d", "884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6", 0).unwrap();
Source§

impl Client

Source

pub fn send_private_message( &mut self, identity: &Identity, pubkey: &str, message: &str, difficulty_target: u16, ) -> Result<Event, Error>

Send private message to a public key

§Example
use nostr_rust::{nostr_client::Client, Identity};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();
let pubkey = "884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6";

client.send_private_message(&identity, pubkey, "Hello from Rust Nostr Client!", 0).unwrap();
Source

pub fn get_private_events_with( &mut self, identity: &Identity, pubkey: &str, limit: u64, ) -> Result<Vec<Event>, Error>

Get private events (messages) with a public key

§Example
use nostr_rust::{nostr_client::Client, Identity};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();
let pubkey = "884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6";
let messages = client.get_private_events_with(&identity, pubkey, 10).unwrap();
Source

pub fn get_private_messages_with( &mut self, identity: &Identity, pubkey: &str, limit: u64, ) -> Result<Vec<PrivateMessage>, Error>

Get private messages with a public key

§Example
use nostr_rust::{nostr_client::Client, Identity};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();
let pubkey = "884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6";
let messages = client.get_private_messages_with(&identity, pubkey, 10).unwrap();
Source§

impl Client

Source

pub fn delete_event( &mut self, identity: &Identity, event_id: &str, difficulty_target: u16, ) -> Result<Event, NIP9Error>

Delete an event

§Example
use nostr_rust::{nostr_client::Client, Identity};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();
// Create an event
let event = client.publish_text_note(&identity, "Hello Nostr! :)", &[], 0)
  .unwrap();

// Delete the event
client.delete_event(&identity, &event.id, 0).unwrap();
Source

pub fn delete_event_with_reason( &mut self, identity: &Identity, event_id: &str, reason: &str, difficulty_target: u16, ) -> Result<Event, NIP9Error>

Delete an event with a reason

§Example
use nostr_rust::{nostr_client::Client, Identity};
use std::str::FromStr;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let identity = Identity::from_str(env!("SECRET_KEY")).unwrap();
// Create an event
let event = client.publish_text_note(&identity, "Hello Nostr! :)", &[], 0)
 .unwrap();

// Delete the event with a reason
client.delete_event_with_reason(&identity, &event.id, "This is a reason", 0).unwrap();
Source§

impl Client

Source

pub fn new(default_relays: Vec<&str>) -> Result<Self, ClientError>

Create a new client with a list of default relays

§Example
use nostr_rust::nostr_client::Client;
let client = Client::new(vec![env!("RELAY_URL")]).unwrap();
Source§

impl Client

Source

pub fn add_relay(&mut self, relay: &str) -> Result<(), ClientError>

Add a relay to the client

§Example
use nostr_rust::nostr_client::Client;
let mut client = Client::new(vec![]).unwrap();
client.add_relay(env!("RELAY_URL")).unwrap();
Source

pub fn remove_relay(&mut self, relay: &str) -> Result<(), ClientError>

Remove a relay from the client

§Example
use nostr_rust::nostr_client::Client;
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
client.remove_relay(env!("RELAY_URL")).unwrap();
Source

pub fn publish_event(&mut self, event: &Event) -> Result<(), ClientError>

Publish a Nostr event

Source

pub fn next_data(&mut self) -> Result<Vec<(String, Message)>, ClientError>

Get next data from the relays

§Example
use std::{
 sync::{Arc, Mutex},
 thread,
};
use tungstenite::Message;
use nostr_rust::{nostr_client::Client, req::ReqFilter};

fn handle_message(relay_url: &String, message: &Message) -> Result<(), String> {
  println!("Received message: {:?}", message);

  Ok(())
}

let mut client = Arc::new(Mutex::new(Client::new(vec![env!("RELAY_URL")]).unwrap()));

// Run a new thread to listen
let nostr_clone = client.clone();
let nostr_thread = thread::spawn(move || loop {
   let events = nostr_clone.lock().unwrap().next_data().unwrap();
    
  for (relay_url, message) in events.iter() {
    handle_message(relay_url, message).unwrap();
  }
});

// Subscribe to the most beautiful Nostr profile event
client
.lock()
.unwrap()
.subscribe(vec![ReqFilter {
    ids: None,
    authors: Some(vec![
        "884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6".to_string(),
    ]),
    kinds: None,
    e: None,
    p: None,
    since: None,
    until: None,
    limit: Some(1),
}])
.unwrap();

// Wait 3s for the thread to finish
std::thread::sleep(std::time::Duration::from_secs(3));
Source

pub fn subscribe( &mut self, filters: Vec<ReqFilter>, ) -> Result<String, ClientError>

Subscribe

§Example
use nostr_rust::{nostr_client::Client, req::ReqFilter};
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
client
.subscribe(vec![ReqFilter { // None means generate a random ID
    ids: None,
    authors: Some(vec![
        "884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6".to_string(),
    ]),
    kinds: None,
    e: None,
    p: None,
    since: None,
    until: None,
    limit: Some(1),
}])
.unwrap();
Source

pub fn subscribe_with_id( &mut self, subscription_id: &str, filters: Vec<ReqFilter>, ) -> Result<(), ClientError>

Subscribe with a specific ID

§Example
use nostr_rust::{nostr_client::Client, req::ReqFilter};
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
client
.subscribe_with_id("my_subscription_id", vec![ReqFilter {
   ids: None,
   authors: Some(vec![
     "884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6".to_string(),
   ]),
   kinds: None,
   e: None,
   p: None,
   since: None,
   until: None,
   limit: Some(1),
}])
.unwrap();
Source

pub fn unsubscribe(&mut self, subscription_id: &str) -> Result<(), ClientError>

Unsubscribe

§Example
use nostr_rust::{nostr_client::Client, req::ReqFilter};
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let subscription_id = client
.subscribe(vec![ReqFilter {
   ids: None,
  authors: Some(vec![
       "884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6".to_string(),
  ]),
 kinds: None,
 e: None,
 p: None,
 since: None,
 until: None,
 limit: Some(1),
}])
.unwrap();
client.unsubscribe(&subscription_id).unwrap();
Source

pub fn add_event(&mut self, subscription_id: &str, message: Message)

Add event to a subscription

Source

pub fn get_events(&mut self, subscription_id: &str) -> Option<Vec<Message>>

Get events and remove them from the subscription

Source

pub fn get_events_of( &mut self, filters: Vec<ReqFilter>, ) -> Result<Vec<Event>, ClientError>

Get events of a given filters

§Example
use nostr_rust::{nostr_client::Client, req::ReqFilter};
let mut client = Client::new(vec![env!("RELAY_URL")]).unwrap();
let events = client.get_events_of(vec![ReqFilter {
   ids: None,
   authors: Some(vec!["884704bd421721e292edbff42eb77547fe115c6ff9825b08fc366be4cd69e9f6".to_string()]),
   kinds: Some(vec![3]),
   e: None,
   p: None,
   since: None,
   until: None,
   limit: Some(1),
}]).unwrap();

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where 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 T
where 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 for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

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 T
where U: TryFrom<T>,

Source§

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.
Source§

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

Source§

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
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,