LiaScript Course

LiaScript course material

Nostr-Konto erstellen - funktioniert

--{{0}}--

Der folgende Code fügt einen Button hinzu, der per Klick einen Nostr-Anmeldedialog öffnet. Alle Schritte sind im Code selbst ausführlich kommentiert.

{{1}}
--{{1}}--

Damit ist der gesamte Code sichtbar, führt einfach einen Doppel-Klick auf den Button aus.

Erläuterungen:

  • Parameter im Überblick:

    • baseUrl: Quelle für API und Assets.
    • an: App-Name für den Modal-Header.
    • aa: Farbakzent ( als Hex).
    • al: Sprache des Interfaces.
    • am: Licht- oder Dunkelmodus.
    • s: Empfohlene Nostr-Accounts
    • afb/asb: Bunker-Modi für erhöhten Datenschutz.
    • aan/aac: Steuerung der Rückgabe privater Schlüssel.
    • arr/awr: Primal Relay als Lese- und Schreib-Relay.
  • Callbacks:

    • onComplete: Schließt das Modal, zeigt eine Bestätigung und bietet die Weiterleitung zu Primal an.
    • onCancel: Schließt das Modal und protokolliert den Abbruch.

Alternativ

// 1. Modal konfigurieren und öffnen
const wizard = new NstartModal({
  // Basis-URL für die Nostr-API
  baseUrl: 'https://nstart.me',

  // an: Anwendungsname, erscheint im Modal-Header
  an: 'Meine Nostr-Anwendung',

  // aa: Accent Color – hier Foerbico-Farbe (Hex ohne '#')
  aa: '203a8f',  // ← Hier den Foerbico-Hex-Code eintragen

  // al: Sprache (ISO-Code), hier Deutsch
  al: 'de',

  // am: Anzeige-Modus ('light' oder 'dark')
  am: 'light',

  // ← hier MUST be an ARRAY:
  s: [
    'npub1f7jar3qnu269uyx5p0e4v24hqxjnxysxudvujza2ur5ehltvdeqsly2fx9',
    'npub1ak7mtjnyha96rjqjdaav7tkjjulcmx7vgmcd6map82vsags8dhtsmecgtd',
    'npub1cmvrxn8k50ljamtqlcd3eqznqlnz50zpyp2q45dh0p5gcvyg84ksxezqps',
    'npub14c3ffunyuzpl69y526dcknn785t35zvq6y63pvxvmfvghfj6dewqc0v55d',
    'npub1pg3axz6qtzwnfgppyysyu0n0ku0gpdhfjn9fpzjsr4c85qcgujzqp5ged9'
  ],

  // afb/asb: Bunker-Modi für Datenschutz
  afb: false,   // erzwingt erweiterten Bunker-Mode
  asb: true,   // erlaubt, den Bunker-Mode zu überspringen

  // aan/aac: Steuerung, ob private Schlüssel mitgeliefert werden
  aan: false,   // kein Nsec zurückgeben
  aac: false,   // kein Ncryptsec zurückgeben

  // arr/awr: WebSocket-Relays – hier Primal Relay als Bezugspunkt
  arr: ['wss://relay.primal.net'],
  awr: ['wss://relay.primal.net'],

  // Callback: Erfolgreiche Anmeldung
  onComplete: result => {
    console.log('Login-Token:', result.nostrLogin);
  },
  // Callback: Abbruch durch Nutzer
  onCancel: () => {
    console.warn('Anmeldung abgebrochen');
  }
});

// Modal anzeigen
wizard.open();

Weitere Beispiele

// 1. Generate a new private key (hex-encoded string)
const privKey = nostr.generatePrivateKey()
// 2. Derive the corresponding public key
const pubKey = nostr.getPublicKey(privKey)

console.log("Private Key: ", privKey)
console.log("Public Key: ", pubKey)

console.debug("📋 Store your private key somewhere safe!")

// A more robust Nostr posting example

const privateKey = nostr.generatePrivateKey()
const publicKey = nostr.getPublicKey(privateKey)

console.log('Using public key:', publicKey)

try {
  if (nostr.SimplePool) {
    console.log('Using SimplePool approach')
    const pool = new nostr.SimplePool()
    
    // Add more relays for better reliability
    const relays = [
      'wss://relay.damus.io',
      'wss://nos.lol',
      'wss://relay.nostr.band'
    ]
    
    // Create a note event
    const event = {
      kind: 1,
      created_at: Math.floor(Date.now() / 1000),
      tags: [],
      content: 'Hello from Nostr using SimplePool! ' + new Date().toISOString(),
      pubkey: publicKey,
    }
    
    // Sign the event
    event.id = nostr.getEventHash(event)
    event.sig = nostr.signEvent(event, privateKey)
    
    console.log('Event created:', event)
    console.log('Publishing to relays:', relays)
    
    // Properly handle the Promise returned by publish
    try {
      // Publish returns an array of promises
      const pubPromises = pool.publish(relays, event)
      console.log('Publication requested to', relays.length, 'relays')
      
      // Track which relays succeeded
      const results = { success: [], failed: [] }
      
      // Handle the promises more explicitly
      Promise.allSettled(pubPromises).then(outcomes => {
        outcomes.forEach((outcome, i) => {
          if (outcome.status === 'fulfilled') {
            console.log(`✅ Published to ${relays[i]}`)
            results.success.push(relays[i])
          } else {
            console.log(`❌ Failed to publish to ${relays[i]}: ${outcome.reason}`)
            results.failed.push(relays[i])
          }
        })
        
        if (results.success.length > 0) {
          console.log(`Successfully published to ${results.success.length} relays`)
        } else {
          console.error('Failed to publish to any relays')
        }
      })
    } catch (pubError) {
      console.error('Publish error:', pubError)
      //out.textContent += '\n\nFailed to send message: ' + (pubError.message || pubError)
    }
  } else {
    console.error('SimplePool not available in this version of nostr-tools')
    //out.textContent += '\n\nFailed: SimplePool not available in this version'
  }
} catch (error) {
  console.error('Error:', error)
  //out.textContent += '\n\nError: ' + (error.message || error)
}

// Subscribing only to your own content

// Initialize connection
const privateKey = nostr.generatePrivateKey()
const publicKey = nostr.getPublicKey(privateKey)

console.log('Using public key for identification:', publicKey)

try {
  if (nostr.SimplePool) {
    console.log('Creating SimplePool for subscriptions...')
    const pool = new nostr.SimplePool()
    
    // Use multiple relays for better content discovery
    const relays = [
      'wss://relay.damus.io',
      'wss://nos.lol',
      'wss://relay.nostr.info',
      'wss://nostr.fmt.wiz.biz'
    ]
    
    console.log('Subscribing to only MY events from relays')
    
    // This filter will only show your own posts
    const filters = [
      {
        kinds: [1],
        authors: [publicKey], // Only your public key
        since: Math.floor(Date.now() / 1000) - 3600, // Last hour
        limit: 10
      }
    ]
    
    console.log('Creating subscription with filters:', filters)
    const sub = pool.sub(relays, filters)
    
    // Handle events as they come in
    sub.on('event', event => {
      console.log(`📬 Received my note:`)
      console.log(`  Content: ${event.content.slice(0, 100)}${event.content.length > 100 ? '...' : ''}`)
      console.log(`  Posted: ${new Date(event.created_at * 1000).toLocaleString()}`)
      console.log('-'.repeat(40))
    })
    
    // Handle when a relay is done sending events
    sub.on('eose', () => {
      console.log('End of stored events - now listening for new events in real-time')
    })
    
    // Publish a test note
    setTimeout(async () => {
      console.log('Publishing a test note...')
      
      const event = {
        kind: 1,
        created_at: Math.floor(Date.now() / 1000),
        tags: [],
        content: 'This is a test from my filtered subscription! ' + new Date().toISOString(),
        pubkey: publicKey,
      }
      
      event.id = nostr.getEventHash(event)
      event.sig = nostr.signEvent(event, privateKey)
      
      await pool.publish(relays, event)
      console.log('Published test note! It should appear in the subscription feed shortly.')
    }, 3000)
    
    // Cleanup after 30 seconds
    setTimeout(() => {
      console.log('Closing subscription...')
      sub.unsub()
      console.log('Subscription closed')
      send.lia("LIA: stop")
    }, 30000)
  }
} catch (error) {
  console.error('Error:', error)
}

Ping Pong

Theoretisch könnte man auch ein paar Demos mit Texteingaben bauen. Als Beispiel einfach beide Snippets ausführen …

``` js send.register("ping", function(e){ console.warn("ping", e) })

send.handle(“input”, input => { send.dispatch(“pong”, input) })

“LIA: terminal” // execute the code and

<script>@input</script>
</div>

<div class="flex-child" style="min-width: 250px">
``` js
send.register("pong", function(e){
  console.warn("pong", e)
})

send.handle("input", input => {
  send.dispatch("ping", input)
})

"LIA: terminal" // execute the code and

Write a comment
No comments yet.