Last active
February 18, 2023 04:34
-
-
Save vishalxl/e16c066408f45d39e92b647e9766efa1 to your computer and use it in GitHub Desktop.
Get Nostr Events from a Relay
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'dart:convert'; | |
String serverUrl = 'wss://nostr-pub.wellorder.net'; | |
var userPublickey = "3235036bd0957dfb27ccda02d452d7c763be40c91a1ac082ba6983b25238388c"; | |
var userSubReq = '["REQ","latest",{ "authors": ["$userPublickey"], "limit": 5 } ]'; | |
class EventData { | |
String id; | |
String pubkey; | |
String content; | |
EventData(this.id, this.pubkey, this.content); | |
factory EventData.fromJson(dynamic json) { | |
return EventData(json['id'] as String, json['pubkey'] as String, json['content'] as String); | |
} | |
@override | |
String toString() { | |
return 'id : $id\nAuthor : $pubkey\nMessage: $content\n'; | |
} | |
} | |
class Event { | |
String event; | |
String id; | |
EventData eventData; | |
Event(this.event, this.id, this.eventData); | |
factory Event.fromJson(dynamic json) { | |
if( json.length < 3) { | |
String e = ""; | |
if(json.length > 1) e = json[0]; | |
else e = ""; | |
return Event(e,"",EventData("empty","","")); | |
} | |
else | |
return Event(json[0] as String, json[1] as String, EventData.fromJson(json[2]) ); | |
} | |
@override | |
String toString() { | |
return '$eventData'; | |
} | |
} | |
void main() { | |
Future<WebSocket> fws = WebSocket.connect(serverUrl); | |
List<String> events = []; | |
fws.then((WebSocket ws) { | |
ws.listen( | |
(d) { events.add( d); }, | |
onError: (e) { print("error"); print(e); }, | |
onDone: () { print('in onDone'); ws.close() ; exit(0);} | |
); | |
ws.add(userSubReq); | |
}); | |
Future.delayed(const Duration(milliseconds: 2000), () { | |
for( int i = 0; i < events.length; i++) { | |
//print('Event number $i: ${events[i]}'); | |
Event e = Event.fromJson(jsonDecode(events[i])); | |
print('-------+\n$e'); | |
} | |
exit(0); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works: