-
Notifications
You must be signed in to change notification settings - Fork 2
/
botnostr.py
2408 lines (2330 loc) · 111 KB
/
botnostr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from collections import OrderedDict
from datetime import datetime, timedelta
from nostr.key import PrivateKey, PublicKey
from nostr.event import Event, EventKind, EncryptedDirectMessage, AuthMessage
from nostr.filter import Filter, Filters
from nostr.message_type import ClientMessageType
from nostr.relay_manager import RelayManager
import bech32
import json
import random
import re
import ssl
import time
import botfiles as files
import botutils as utils
import botledger as ledger
import botlnd as lnd
import botlnurl as lnurl
import botreports as reports
logger = None
config = None
handledMessages = {}
botRelayManager = None
handledEvents = {}
_relayPublishTime = 2.50
_relayConnectTime = 1.25
_nostrRelayConnectsMade = 0
_singleRelayManager = False # controls whether a separate relay manager for reply/reactions
_relayReconnectExisting = False # when true, locks up in r.check_reconnect
_relayeventcounter = {}
_replyDebugMessages = False # controls whether debug messages send text as user reply
_replyDebugReactions = True # controls whether debug messags send caution reaction
_inboxoutbox = True
pubkeyrelays = {} # tracks relay list metadata for arbitrary pubkeys
def connectToRelays():
logger.debug("Connecting to relays")
global botRelayManager
global _nostrRelayConnectsMade
botRelayManager = RelayManager()
relays = getNostrRelaysFromConfig(config).copy()
random.shuffle(relays)
relaysLeftToAdd = 50
for nostrRelay in relays:
if relaysLeftToAdd <= 0: break
relaysLeftToAdd -= 1
if type(nostrRelay) is dict:
botRelayManager.add_relay(url=nostrRelay["url"],read=nostrRelay["read"],write=nostrRelay["write"])
if type(nostrRelay) is str:
botRelayManager.add_relay(url=nostrRelay)
botRelayManager.open_connections({"cert_reqs": ssl.CERT_NONE})
time.sleep(_relayConnectTime)
_nostrRelayConnectsMade += 1
def disconnectRelays():
logger.debug("Disconnecting from relays")
global botRelayManager
botRelayManager.close_connections()
def reconnectRelays():
if _relayReconnectExisting:
for r in botRelayManager.relays.values():
logger.debug(f"Reconnecting relay {r.url}")
r.check_reconnect() # seems to cause a lockup
logger.debug(f"- relay reconnection complete")
else:
disconnectRelays()
connectToRelays()
def getNpubConfigFilename(npub):
return f"{files.userConfigFolder}{npub}.json"
def getNpubConfigFile(npub):
filename = getNpubConfigFilename(npub)
npubConfig = files.loadJsonFile(filename)
if npubConfig is None: return {}
return npubConfig
def getBotPrivateKey():
if "botnsec" not in config:
logger.warning("Server config missing 'botnsec' in nostr section.")
quit()
botNsec = config["botnsec"]
if botNsec is None or len(botNsec) == 0:
logger.warning("Server config missing 'botnsec' in nostr section.")
quit()
botPrivkey = PrivateKey().from_nsec(botNsec)
return botPrivkey
def getBotPubkey():
if "botnpub" not in config:
botPrivkey = getBotPrivateKey()
if botPrivkey is None: return None
config["botnpub"] = botPrivkey.public_key.hex()
return utils.normalizeToHex(config["botnpub"])
def getOperatorNpub():
if "operatornpub" not in config:
logger.warning("Server config missing 'operatornpub' in nostr section.")
return None
operatornpub = config["operatornpub"]
return operatornpub
def sendDirectMessage(npub, message):
if npub is None:
logger.warning("Unable to send direct message to recipient npub (value is None).")
logger.warning(f" - message: {message}")
return
botPubkey = getBotPubkey()
if botPubkey is None:
logger.warning("Unable to send direct message to npub.")
logger.warning(f" - npub: {npub}")
logger.warning(f" - message: {message}")
return
recipient_pubkey = PublicKey().from_npub(npub).hex()
if "excludeFromDirectMessages" in config:
excludes = config["excludeFromDirectMessages"]
for exclude in excludes:
if "npub" not in exclude: continue
if exclude["npub"] == npub:
logger.debug("Not sending direct message to excluded npub: {npub}")
return
if exclude["npub"] == recipient_pubkey:
logger.debug("Not sending direct message to excluded pubkey: {recipient_pubkey}")
return
dm = EncryptedDirectMessage(
recipient_pubkey=recipient_pubkey,
cleartext_content=message
)
getBotPrivateKey().sign_event(dm)
botRelayManager.publish_event(dm)
time.sleep(_relayPublishTime)
# write to recipient read relays
if _inboxoutbox:
pubkeyRelay = getInboxRelayManagerForPubkey(recipient_pubkey)
if pubkeyRelay is not None:
pubkeyRelay.publish_event(dm)
time.sleep(_relayPublishTime)
pubkeyRelay.close_connections()
def removeSubscription(relaymanager, subid):
request = [ClientMessageType.CLOSE, subid]
message = json.dumps(request)
relaymanager.publish_message(message)
time.sleep(_relayPublishTime)
relaymanager.close_subscription(subid)
def checkDirectMessages():
global handledMessages # tracked in this file, and only this function
logger.debug("Checking messages")
newMessages = []
events = getDirectMessages()
for event in events:
# only add those not already in the handledMessages list
if event.id not in handledMessages:
newMessages.append(event)
handledMessages[event.id] = event.created_at
return newMessages
def isValidSignature(event):
sig = event.signature
id = event.id
publisherPubkey = event.public_key
pubkey = PublicKey(raw_bytes=bytes.fromhex(publisherPubkey))
return pubkey.verify_signed_message_hash(hash=id, sig=sig)
def processDirectMessages(messages):
logger.debug("Processing direct messages")
botPK = getBotPrivateKey()
for event in messages:
if not isValidSignature(event): continue
if event.kind != EventKind.ENCRYPTED_DIRECT_MESSAGE: continue
publisherHex = str(event.public_key).strip()
npub = PublicKey(raw_bytes=bytes.fromhex(publisherHex)).bech32()
content = str(event.content).strip()
content = botPK.decrypt_message(content, publisherHex)
logger.debug(f"{npub} command via DM: {content}")
if "forwardDirectMessagesToOperator" in config:
forwards = config["forwardDirectMessagesToOperator"]
operatornpub = getOperatorNpub()
if operatornpub is not None:
for forward in forwards:
if "npub" not in forward: continue
if forward["npub"] == npub:
message = f"Forwarded message from {npub}: {content}"
sendDirectMessage(operatornpub, message)
if "excludeFromDirectMessages" in config:
excludes = config["excludeFromDirectMessages"]
excluded = False
for exclude in excludes:
if "npub" not in exclude: continue
if exclude["npub"] == npub: excluded = True
if exclude["npub"] == publisherHex: excluded = True
if excluded:
logger.debug("Not processing direct messages from npub on exclusion list: {npub}")
continue
firstWord = content.split()[0].upper()
if firstWord == "HELP":
handleHelp(npub, content)
elif firstWord == "FEES":
handleFees(npub, content)
elif firstWord == "RELAYS" and not _singleRelayManager:
handleRelays(npub, content)
elif firstWord == "CONDITIONS":
handleConditions(npub, content)
elif firstWord == "EXCLUDES":
handleExcludes(npub, content)
elif firstWord == "PROFILE":
handleProfile(npub, content)
elif firstWord == "ZAPMESSAGE":
handleZapMessage(npub, content)
elif firstWord == "EVENT":
handleEvent(npub, content)
elif firstWord == "EVENTBUDGET":
handleEventBudget(npub, content)
elif firstWord == "EVENTAUTOCHANGE":
handleEventAutoChange(npub, content)
elif firstWord == "BALANCE":
handleBalance(npub, content)
elif firstWord == "CREDITS":
handleCredits(npub, content)
elif firstWord == "REPORTS":
handleReports(npub, content)
elif firstWord == "STATUS":
handleStatus(npub, content)
elif firstWord == "STATS":
handleStats(npub, content)
elif firstWord == "ENABLE":
handleEnable(npub, True)
elif firstWord == "DISABLE":
handleEnable(npub, False)
elif firstWord == "SUPPORT":
handleSupport(npub, content)
else:
handleHelp(npub, content)
def handleHelp(npub, content):
words = content.split()
handled = False
message = ""
if len(words) > 1:
secondWord = str(words[1]).upper()
if secondWord == "FEES":
message = "Return the fee rates for the service"
handled = True
elif secondWord == "RELAYS" and not _singleRelayManager:
message = "Relays commands:"
message = f"{message}\nRELAYS LIST"
message = f"{message}\nRELAYS ADD <relayUrl> [--canRead] [--canWrite]"
message = f"{message}\nRELAYS DELETE <index>"
message = f"{message}\nRELAYS CLEAR"
handled = True
elif secondWord == "CONDITIONS":
message = "Conditions commands:\nCONDITIONS LIST"
message = f"{message}\nCONDITIONS ADD [--amount <zap amount if matched>] [--randomWinnerLimit <number of random winners of this amount for the event>] [--requiredLength <length required to match>] [--requiredPhrase <phrase required to match>] [--requiredRegex <regular expression to match>] [--replyMessage <message to reply with if matched>]"
message = f"{message}\nCONDITIONS UP <index>"
message = f"{message}\nCONDITIONS DELETE <index>"
message = f"{message}\nCONDITIONS CLEAR"
handled = True
elif secondWord == "EXCLUDES":
message = "Excludes commands:"
message = f"{message}\nEXCLUDES LIST"
message = f"{message}\nEXCLUDES ADD <exclude phrase or npub>"
message = f"{message}\nEXCLUDES DELETE <index>"
message = f"{message}\nEXCLUDES CLEAR"
handled = True
elif secondWord == "PROFILE":
message = "Profile commands:"
message = f"{message}\nPROFILE [--name <name>] [--picture <url for profile picture>] [--banner <url for profile banner>] [--about <description of account>] [--nip05 <nip05 to assign>] [--lud16 <lightning address>]"
message = f"{message}\nSpecifying PROFILE without arguments will output the current profile"
handled = True
elif secondWord == "ZAPMESSAGE":
message = "Zap Message commands:"
message = f"{message}\nZAPMESSAGE <message to send with zap>"
handled = True
elif secondWord == "EVENT":
message = "Event commands:"
message = f"{message}\nEVENT <event identifier>"
handled = True
elif secondWord == "EVENTBUDGET":
message = "Set a limit to be spent on the current event"
message = f"{message}\nEVENTBUDGET 21000"
handled = True
elif secondWord == "EVENTAUTOCHANGE":
message = "Set a phrase that should trigger changing the event being monitored"
message = f"{message}\nEVENTAUTOCHANGE <phrase>"
handled = True
elif secondWord == "BALANCE":
message = "Get the balance of credits for your bot."
handled = True
elif secondWord == "CREDITS":
message = "Credits commands:"
message = f"{message}\nCREDITS ADD <amount>"
handled = True
elif secondWord == "ENABLE":
message = "Enable your bot to process events if configuration is valid."
message = f"{message}\nTo disable, use the DISABLE command."
handled = True
elif secondWord == "DISABLE":
message = "Disable your bot from processing events."
handled = True
elif secondWord == "REPORTS":
message = "Retrieve link to reports for the events monitored and zaps by the bot."
handled = True
elif secondWord == "STATUS":
message = "Reports the current summary status for your bot account."
handled = True
elif secondWord == "STATS":
message = "Reports stats of number of zaps, replies and costs since last ledger rotation"
handled = True
elif secondWord == "SUPPORT":
message = "Attempts to forward a message to the operator of the service."
message = f"{message}\nSUPPORT <message to send to support>"
handled = True
if not handled:
message = "This bot zaps responses to events based on rules you define. For detailed help, reply HELP followed by the command (e.g. HELP RELAYS)."
message = f"{message}\nCommands: "
message = f"{message} FEES, "
if not _singleRelayManager:
message = f"{message} RELAYS, "
message = f"{message} CONDITIONS, "
message = f"{message} PROFILE, "
message = f"{message} ZAPMESSAGE, "
message = f"{message} EVENT, "
message = f"{message} EVENTBUDGET, "
message = f"{message} EVENTAUTOCHANGE, "
message = f"{message} BALANCE, "
message = f"{message} CREDITS, "
message = f"{message} ENABLE, "
message = f"{message} DISABLE, "
message = f"{message} STATUS, "
message = f"{message} STATS, "
message = f"{message} SUPPORT"
message = f"{message}\n\nTo get started setting up a bot, define one or more CONDITIONS, provide a ZAPMESSAGE, and indicate the EVENT to monitor."
sendDirectMessage(npub, message)
def getNostrFieldForNpub(npub, fieldname):
npubConfig = getNpubConfigFile(npub)
if fieldname in npubConfig: return npubConfig[fieldname]
return ""
def setNostrFieldForNpub(npub, fieldname, fieldvalue):
npubConfig = getNpubConfigFile(npub)
changed = False
if fieldvalue is not None:
if fieldname in npubConfig:
if npubConfig[fieldname] != fieldvalue:
npubConfig[fieldname] = fieldvalue
changed = True
else:
npubConfig[fieldname] = fieldvalue
changed = True
elif fieldname in npubConfig:
del npubConfig[fieldname]
changed = True
if changed:
filename = getNpubConfigFilename(npub)
files.saveJsonFile(filename, npubConfig)
def addToNpubIndex(npub, eventId):
basePath = f"{files.userEventsFolder}{npub}/"
utils.makeFolderIfNotExists(basePath)
filename = f"{basePath}index.json"
npubIndex = files.loadJsonFile(filename, [])
_, diso = utils.getTimes()
newEntry = {"date_iso": diso, "eventId": eventId}
npubIndex.append(newEntry)
files.saveJsonFile(filename, npubIndex)
def incrementNostrFieldForNpub(npub, fieldname, amount):
npubConfig = getNpubConfigFile(npub)
newValue = amount if fieldname not in npubConfig else npubConfig[fieldname] + amount
npubConfig[fieldname] = newValue
filename = getNpubConfigFilename(npub)
files.saveJsonFile(filename, npubConfig)
return newValue
# pubkey is a user
def getRelayListMetadataForPubkey(pubkey):
global _monitoredRelayListMetadata
logger.debug(f"Getting relay list metadata for {pubkey}")
filters = Filters([Filter(kinds=[10002],authors=[pubkey])])
botPrivateKey = getBotPrivateKey()
t, _ = utils.getTimes()
subscription_id = f"pubkey_rlm_{t}"
request = [ClientMessageType.REQUEST, subscription_id]
request.extend(filters.to_json_array())
message = json.dumps(request)
botRelayManager.add_subscription(subscription_id, filters)
botRelayManager.publish_message(message)
time.sleep(_relayPublishTime)
# Check if needed to authenticate and publish again if need be
if authenticateRelays(botRelayManager, botPrivateKey):
botRelayManager.publish_message(message)
time.sleep(_relayPublishTime)
# Sift through messages
siftMessagePool()
# Remove this subscription
removeSubscription(botRelayManager, subscription_id)
# Find the relay list metadata
rlmToUse = None
created_at = 0
_tmp = []
for rlm in _monitoredRelayListMetadata:
if rlm.public_key != pubkey:
_tmp.append(rlm)
continue
if rlm.created_at < created_at: continue
if not isValidSignature(rlm): continue
if rlm.created_at > created_at:
created_at = rlm.created_at
rlmToUse = rlm
if rlmToUse is not None: _tmp.append(rlmToUse)
_monitoredRelayListMetadata = _tmp
return rlmToUse
# pubkey is a recipient (not one of our buts) that may be talking via DM, or we are replying to as kind 1
# this will either return a relay manager that has the relays the target pubkey reads from (their inbox)
# or will return as None if no information was found. simple caching by way of pubkeyrelays
def getInboxRelayManagerForPubkey(pubkey):
return getInboxOrOutboxRelayManagerForPubkey(pubkey, "read")
# pubkey is an entity (not one of our bots) that will have posted an event for which other users are
# replying to. This will either return a relay manager that has the relays the target pubkey wrote to
# (their outbox) or will return as None if no information was found. simple caching byway of pubkeyrelays
def getOutboxRelayManagerForPubkey(pubkey):
return getInboxOrOutboxRelayManagerForPubkey(pubkey, "write")
def getInboxOrOutboxRelayManagerForPubkey(pubkey, acl):
global pubkeyrelays
if pubkey not in pubkeyrelays:
relayEvent = getRelayListMetadataForPubkey(pubkey)
pubkeyrelays[pubkey] = relayEvent
if pubkey not in pubkeyrelays:
return None
relayEvent = pubkeyrelays[pubkey]
if relayEvent is None:
return None
newRelayManager = None
relayCount = 0
for tag in relayEvent.tags:
if len(tag) < 2: continue
if tag[0] != "r": continue
if len(tag) > 2 and tag[2] != acl: continue
relayUrl = tag[1]
relayCount = relayCount + 1
if relayCount == 1:
newRelayManager = RelayManager()
newRelayManager.add_relay(url=relayUrl)
if relayCount > 0:
newRelayManager.open_connections({"cert_reqs": ssl.CERT_NONE}) # NOTE: This disables ssl certificate verification
time.sleep(_relayConnectTime)
return newRelayManager
# npub is a bot
def getNostrRelaysForNpub(npub, npubConfig = None):
if npubConfig is None: npubConfig = getNpubConfigFile(npub)
relays = getNostrRelaysFromConfig(npubConfig)
if len(relays) == 0:
relaysFromConfig = getNostrRelaysFromConfig(config)
relays = []
for relay in relaysFromConfig:
if "url" not in relay: continue
url = relay["url"]
# exclusion of special relays when reading from main config
if "filter.nostr.wine" in url: continue
relays.append(relay)
return relays
# config of bot
def getNostrRelaysFromConfig(aConfig):
relays = []
relayUrls = []
if "relays" in aConfig:
for relay in aConfig["relays"]:
relayUrl = ""
canRead = True
canWrite = True
if type(relay) is str:
relayUrl = relay
if type(relay) is dict:
if "url" not in relay: continue
relayUrl = relay["url"]
canRead = relay["read"] if "read" in relay else canRead
canWrite = relay["write"] if "write" in relay else canWrite
relayUrl = relayUrl if str(relayUrl).startswith("wss://") else f"wss://{relayUrl}"
if relayUrl not in relayUrls:
relayUrls.append(relayUrl)
relays.append({"url":relayUrl,"read":canRead,"write":canWrite})
return relays
def handleFees(npub, content):
botConfig = getNpubConfigFile(npub)
feesZapEvent = feesReplyMessage = 50
feesTime864 = 1000
fees = config["fees"] if "fees" in config else None
fees = botConfig["fees"] if "fees" in botConfig else fees
if fees is not None:
if "replyMessage" in fees: feesReplyMessage = fees["replyMessage"]
if "zapEvent" in fees: feesZapEvent = fees["zapEvent"]
if "time864" in fees: feesTime864 = fees["time864"]
message = "Current Fee Rates:"
message = f"{message}\n- each event zapped: {feesZapEvent} millicredits"
message = f"{message}\n- each reply message: {feesReplyMessage} millicredits"
message = f"{message}\n- time units: {feesTime864} millicredits"
message = f"{message}\n (a time unit is 1/100th of the day, or 864 seconds of the bot monitoring events)"
sendDirectMessage(npub, message)
def handleRelays(npub, content):
singular = "Relay"
plural = "Relays"
pluralLower = str(plural).lower()
pluralupper = str(plural).upper()
relaysReset = False
words = content.split()
if len(words) > 1:
secondWord = str(words[1]).upper()
if secondWord == "DELETE":
handleGenericList(npub, content, singular, plural)
return
npubConfig = getNpubConfigFile(npub)
theList = npubConfig[pluralLower] if pluralLower in npubConfig else []
if secondWord in ("CLEAR", "RESET"):
relaysReset = True
theList = config["relays"]
setNostrFieldForNpub(npub, pluralLower, theList)
if secondWord in ("ADD"):
url = None
canRead = True if len(words) < 3 else False
canWrite = True if len(words) < 3 else False
for word in words[2:]:
if str(word).startswith("--"):
flagWord = str(word[2:]).lower()
if flagWord == "canread": canRead = True
if flagWord == "canwrite": canWrite = True
else:
url = word if url is None else url
if url is None:
message = "Please provide url of relay to add in wss://relay.domain format"
sendDirectMessage(npub, message)
return
url = url if str(url).startswith("wss://") else f"wss://{url}"
# transform list if it has strings
hasStrings = False
newList = []
for item in theList:
if type(item) is str:
hasStrings = True
newItem = {"url":item, "read": True, "write": True}
newList.append(newItem)
if type(item) is dict:
newList.append(item)
if hasStrings: theList = newList
# look for existing relay url in list
found = False
for item in theList:
if type(item) is dict:
if "url" in item and item["url"] == url:
# existing found, update it
found = True
item["read"] = canRead
item["write"] = canWrite
# not found, add it
if not found:
item = {"url": url, "read": canRead, "write": canWrite}
theList.append(item)
# save changes
setNostrFieldForNpub(npub, pluralLower, theList)
else:
npubConfig = getNpubConfigFile(npub)
theList = npubConfig[pluralLower] if pluralLower in npubConfig else []
# List
idx = 0
message = f"{plural}:"
if len(theList) > 0:
for item in theList:
idx += 1
desc = ""
perm = ""
if type(item) is str: desc = f"{item} [rw]"
if type(item) is dict:
if "url" in item: desc = item["url"]
if "read" in item and item["read"]: perm = f"{perm}r"
if "write" in item and item["write"]: perm = f"{perm}w"
if len(perm) > 0: desc = f"{desc} [{perm}]"
message = f"{message}\n{idx}) {desc}"
if relaysReset:
message = f"{message}\n\nRelay list was reset to defaults"
else:
message = f"{message}\n\n{singular} list is empty"
sendDirectMessage(npub, message)
def handleExcludes(npub, content):
handleGenericList(npub, content, "Exclude", "Excludes")
def handleGenericList(npub, content, singular, plural):
npubConfig = getNpubConfigFile(npub)
pluralLower = str(plural).lower()
pluralupper = str(plural).upper()
theList = npubConfig[pluralLower] if pluralLower in npubConfig else []
words = content.split()
if len(words) > 1:
secondWord = str(words[1]).upper()
if secondWord == "CLEAR":
theList = []
setNostrFieldForNpub(npub, pluralLower, theList)
if secondWord == "ADD":
if len(words) > 2:
itemValue = words[2]
if itemValue not in theList:
theList.append(itemValue)
setNostrFieldForNpub(npub, pluralLower, theList)
else:
sendDirectMessage(npub, f"Please provide the value to add to the {singular} list\n{pluralupper} ADD value-here")
return
if secondWord == "DELETE":
if len(words) <= 2:
sendDirectMessage(npub, f"Please provide the index of the item to remove from the {singular} list\n{pluralupper} DELETE 2")
return
value2Delete = words[2]
if str(value2Delete).isdigit():
idxNum = int(value2Delete)
if idxNum <= 0:
sendDirectMessage(npub, f"Please provide the index of the {singular} item to be deleted\n{pluralupper} DELETE 3")
return
if idxNum > len(theList):
sendDirectMessage(npub, f"Index not found in {singular} list")
else:
idxNum -= 1 # 0 based
del theList[idxNum]
setNostrFieldForNpub(npub, pluralLower, theList)
else:
if value2Delete in theList:
theList.remove(value2Delete)
setNostrFieldForNpub(npub, pluralLower, theList)
else:
sendDirectMessage(npub, f"Item not found in {singular} list")
# If still here, send the list
idx = 0
message = f"{plural}:"
if len(theList) > 0:
for item in theList:
idx += 1
message = f"{message}\n{idx}) {item}"
else:
message = f"{message}\n\n{singular} list is empty"
sendDirectMessage(npub, message)
def getNostrConditionsForNpub(npub):
npubConfig = getNpubConfigFile(npub)
if "conditions" in npubConfig:
return npubConfig["conditions"]
else:
return []
def handleConditions(npub, content):
conditions = getNostrConditionsForNpub(npub)
words = content.split()
supportedArguments = {
"amount": "amount",
"requiredlength": "requiredLength",
"requiredphrase": "requiredPhrase",
"requiredregex": "requiredRegex",
"randomwinnerlimit": "randomWinnerLimit",
"replymessage": "replyMessage"
}
if len(words) > 1:
secondWord = str(words[1]).upper()
if secondWord == "CLEAR":
conditions = []
setNostrFieldForNpub(npub, "conditions", conditions)
if secondWord == "ADD":
if len(words) > 2:
commandWord = None
newCondition = {
"amount":0,
"requiredlength":0,
"requiredphrase":None
}
for word in words[2:]:
# check if starting a new argument
if len(word) > 2 and str(word).startswith("--"):
argWord = str(word[2:]).lower()
if argWord in supportedArguments.keys():
# if ended an argument, need to assign value
if commandWord is not None:
# numbers
if commandWord in ["amount","requiredlength","randomwinnerlimit"]:
if str(combinedWords).isdigit():
newCondition[supportedArguments[commandWord]] = int(combinedWords)
# all others are strings
else:
newCondition[supportedArguments[commandWord]] = combinedWords
commandWord = argWord
combinedWords = ""
else:
# not starting an argument, build composite value
combinedWords = f"{combinedWords} {word}" if len(combinedWords) > 0 else word
# check if have a composite value needing assigned
if commandWord is not None:
# numbers
if commandWord in ["amount","requiredlength","randomwinnerlimit"]:
if str(combinedWords).isdigit():
newCondition[supportedArguments[commandWord]] = int(combinedWords)
# all others are strings
else:
newCondition[supportedArguments[commandWord]] = combinedWords
combinedWords = ""
# validate before adding
if newCondition["amount"] < 0:
sendDirectMessage(npub, "Amount for new condition must be greater than or equal to 0")
return
conditions.append(newCondition)
setNostrFieldForNpub(npub, "conditions", conditions)
else:
message = "Please provide the condition to be added using the command format:\nCONDITIONS ADD [--amount <zap amount if matched>][--requiredLength <length required to match>] [--requiredPhrase <phrase required to match>]"
message = f"{message}\n\nExample:\nCONDITIONS ADD --amount 20 --requiredPhrase Nodeyez"
sendDirectMessage(npub, message)
return
if secondWord == "UP":
if len(words) <= 2:
sendDirectMessage(npub, "Please provide the index of the condition to move up\nCONDITIONS UP 3")
return
value2Move = words[2]
if str(value2Move).isdigit():
idxNum = int(value2Move)
if idxNum <= 0:
sendDirectMessage(npub, "Please provide the index of the condition to be moved up\nCONDITIONS UP 3")
return
if idxNum > len(conditions):
sendDirectMessage(npub, "Index not found in condition list")
elif idxNum > 1:
swapCondition = conditions[idxNum-2]
conditions[idxNum-2] = conditions[idxNum-1]
conditions[idxNum-1] = swapCondition
setNostrFieldForNpub(npub, "conditions", conditions)
else:
sendDirectMessage(npub, "Please provide the index of the condition to be move up as a number\nCONDITIONS UP 3")
return
if secondWord == "DELETE":
if len(words) <= 2:
sendDirectMessage(npub, "Please provide the index of the condition to be deleted\nCONDITION DELETE 3")
return
value2Delete = words[2]
if str(value2Delete).isdigit():
idxNum = int(value2Delete)
if idxNum <= 0:
sendDirectMessage(npub, "Please provide the index of the condition to be deleted\nCONDITIONS DELETE 3")
return
if idxNum > len(conditions):
sendDirectMessage(npub, "Index not found in conditions list")
else:
idxNum -= 1 # 0 based
del conditions[idxNum]
setNostrFieldForNpub(npub, "conditions", conditions)
else:
sendDirectMessage(npub, "Please provide the index of the condition to be deleted as a number\nCONDITIONS DELETE 3")
return
# If still here, send the condition list
idx = 0
message = "Conditions/Rules based on response message content:"
if len(conditions) > 0:
for condition in conditions:
idx += 1
conditionAmount = condition["amount"]
message = f"{message}\n{idx}) zap {conditionAmount} sats"
rCount = 0
if "requiredLength" in condition:
conditionRequiredLength = condition["requiredLength"]
if conditionRequiredLength is not None and conditionRequiredLength > 0:
message = f"{message} if" if rCount == 0 else f"{message} and"
message = f"{message} length >= {conditionRequiredLength}"
rCount += 1
if "requiredPhrase" in condition:
conditionRequiredPhrase = condition["requiredPhrase"]
if conditionRequiredPhrase is not None and len(conditionRequiredPhrase) > 0:
message = f"{message} if" if rCount == 0 else f"{message} and"
message = f"{message} contains {conditionRequiredPhrase}"
rCount += 1
if "requiredRegex" in condition:
conditionRequiredRegex = condition["requiredRegex"]
if conditionRequiredRegex is not None and len(conditionRequiredRegex) > 0:
message = f"{message} if" if rCount == 0 else f"{message} and"
message = f"{message} matches regular expression {conditionRequiredRegex}"
rCount += 1
if "randomWinnerLimit" in condition:
randomWinnerLimit = condition["randomWinnerLimit"]
if randomWinnerLimit is not None and randomWinnerLimit > 0:
message = f"{message} if" if rCount == 0 else f"{message} and"
message = f"{message} one of {randomWinnerLimit} randomly selected winners"
if "replyMessage" in condition:
replyMessage = condition["replyMessage"]
if replyMessage is not None and len(replyMessage) > 0:
message = f"{message}, send reply message: {replyMessage}."
else:
message = f"{message}\n\nCondition list is empty"
sendDirectMessage(npub, message)
def getNostrProfileForNpub(npub):
# this is the bot profile from config, not from kind0
npubConfig = getNpubConfigFile(npub)
if "profile" in npubConfig:
return npubConfig["profile"], False
else:
newPrivateKey = PrivateKey()
newProfile = dict(config["defaultProfile"])
newProfile["nsec"] = newPrivateKey.bech32()
newProfile["npub"] = newPrivateKey.public_key.bech32()
setNostrFieldForNpub(npub, "profile", newProfile)
return newProfile, True
def handleProfile(npub, content):
profile, hasChanges = getNostrProfileForNpub(npub)
words = content.split()
if len(words) > 1:
commandWord = None
for word in words[1:]:
if str(word).startswith("--"):
if commandWord is None:
commandWord = word[2:]
combinedWords = ""
else:
if commandWord in ("name","about","nip05","lud16","picture","banner"):
if profile[commandWord] != combinedWords:
hasChanges = True
profile[commandWord] = combinedWords
commandWord = word
else:
combinedWords = f"{combinedWords} {word}" if len(combinedWords) > 0 else word
if commandWord is not None:
if profile[commandWord] != combinedWords:
hasChanges = True
profile[commandWord] = combinedWords
if hasChanges:
setNostrFieldForNpub(npub, "profile", profile)
publishSubBotProfile(npub, profile)
# Report fields in profile (except nsec)
message = "Profile information:\n"
for k, v in profile.items():
if k not in ("nsec"):
v1 = "not defined" if v is None or len(v) == 0 else v
message = f"{message}\n{k}: {v1}"
sendDirectMessage(npub, message)
def makeRelayManager(npub):
relays = getNostrRelaysForNpub(npub)
newRelayManager = RelayManager()
for nostrRelay in relays:
if type(nostrRelay) is dict:
newRelayManager.add_relay(url=nostrRelay["url"],read=nostrRelay["read"],write=nostrRelay["write"])
if type(nostrRelay) is str:
newRelayManager.add_relay(url=nostrRelay)
newRelayManager.open_connections({"cert_reqs": ssl.CERT_NONE}) # NOTE: This disables ssl certificate verification
time.sleep(_relayConnectTime)
return newRelayManager
def getProfile(pubkeyHex):
global _monitoredProfiles
logger.debug(f"Getting profile information for {pubkeyHex}")
filters = Filters([Filter(kinds=[EventKind.SET_METADATA],authors=[pubkeyHex])])
botPrivateKey = getBotPrivateKey()
t, _ = utils.getTimes()
subscription_id = f"my_profiles_{t}"
request = [ClientMessageType.REQUEST, subscription_id]
request.extend(filters.to_json_array())
message = json.dumps(request)
botRelayManager.add_subscription(subscription_id, filters)
botRelayManager.publish_message(message)
time.sleep(_relayPublishTime)
# Check if needed to authenticate and publish again if need be
if authenticateRelays(botRelayManager, botPrivateKey):
botRelayManager.publish_message(message)
time.sleep(_relayPublishTime)
# Sift through messages
siftMessagePool()
# Remove this subscription
removeSubscription(botRelayManager, subscription_id)
# Find the profile
profileToUse = None
profileToReturn = None
created_at = 0
_monitoredProfilesTmp = []
for profile in _monitoredProfiles:
if profile.public_key != pubkeyHex:
_monitoredProfilesTmp.append(profile)
continue
if profile.created_at < created_at: continue
if not isValidSignature(profile): continue
try:
ec = json.loads(profile.content)
created_at = profile.created_at
profileToUse = profile
profileToReturn = dict(ec)
except Exception as err:
logger.warning(f"Error while getting profile for {pubkeyHex}")
logger.eception(err)
continue
if profileToUse is not None: _monitoredProfilesTmp.append(profileToUse)
_monitoredProfiles = _monitoredProfilesTmp
return profileToReturn, created_at
def checkMainBotProfile():
botPubkey = getBotPubkey()
profileOnRelays, _ = getProfile(botPubkey) # getProfileForNpubFromRelays(None, botPubkey)
needsUpdated = (profileOnRelays is None)
if not needsUpdated:
configProfile = config["botProfile"]
kset = ("name","about","nip05","lud16","picture","banner")
for k in kset:
if k in configProfile:
if k not in profileOnRelays:
if len(configProfile[k]) > 0:
needsUpdated
break
elif configProfile[k] != profileOnRelays[k]:
needsUpdated
break
elif k in profileOnRelays:
needsUpdated = True
break
if needsUpdated: publishMainBotProfile()
def makeProfileFromDict(profile, pubkey):
j = {}
kset = ("name","about","description","nip05","lud16","picture","banner")
for k in kset:
if k in profile and len(profile[k]) > 0: j[k] = profile[k]
if "description" in j and "about" not in j:
j["about"] = j["description"]
del j["description"]
content = json.dumps(j)
kind0 = Event(
content=content,
public_key=pubkey,
kind=EventKind.SET_METADATA,
)
return kind0
def publishMainBotProfile():
profile = config["botProfile"]
profilePK = getBotPrivateKey()
pubkey = profilePK.public_key.hex()
kind0 = makeProfileFromDict(profile, pubkey)
profilePK.sign_event(kind0)
botRelayManager.publish_event(kind0)
time.sleep(_relayPublishTime)
def publishSubBotProfile(npub, profile):
profileNsec = profile["nsec"]
profilePK = PrivateKey().from_nsec(profileNsec)
pubkey = profilePK.public_key.hex()
kind0 = makeProfileFromDict(profile, pubkey)
profilePK.sign_event(kind0)
npubRelayManager = botRelayManager if _singleRelayManager else makeRelayManager(npub)
npubRelayManager.publish_event(kind0)
time.sleep(_relayPublishTime)
if not _singleRelayManager: npubRelayManager.close_connections()
def handleZapMessage(npub, content):
zapMessage = getNostrFieldForNpub(npub, "zapMessage")
words = content.split()
if len(words) > 1:
zapMessage = " ".join(words[1:])
setNostrFieldForNpub(npub, "zapMessage", zapMessage)
if len(zapMessage) > 0:
message = f"The zap message is set to: {zapMessage}"
else:
message = f"The zap message has not yet been set. Specify the message as follows\n\nZAPMESSAGE Comment to send with zaps"
sendDirectMessage(npub, message)
def handleEventAutoChange(npub, content):
words = str(content).strip().split()
newAutoChange = " ".join(words[1:]) if len(words) > 1 else None
setNostrFieldForNpub(npub, "eventAutoChange", newAutoChange)
if newAutoChange is None:
message = "No longer automatically changing event to monitor based on your posts"
else:
message = f"Whenever you create a new post with the phrase '{newAutoChange}', the bot will change to monitoring that post"
sendDirectMessage(npub, message)
def handleEventBudget(npub, content):
eventId = getNostrFieldForNpub(npub, "eventId")
budgetWord = getNostrFieldForNpub(npub, "eventBudget")
budget = 0
if budgetWord is not None and str(budgetWord).isdigit(): budget = int(budgetWord)
words = content.split()
if len(words) > 1:
budgetWord = words[1]
if not str(budgetWord).isdigit():
message = f"Please specify the budget amount as a whole number"
sendDirectMessage(npub, message); return
else:
newbudget = int(budgetWord)
if newbudget > budget:
setNostrFieldForNpub(npub, "eventBudgetWarningSent", None)
budget = newbudget
if budget <= 0:
setNostrFieldForNpub(npub, "eventBudget", None)
else: