-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroutstr_bot.py
More file actions
876 lines (774 loc) · 39.6 KB
/
Copy pathroutstr_bot.py
File metadata and controls
876 lines (774 loc) · 39.6 KB
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
from linecache import lazycache
import os
import asyncio
import requests
import json
from pynostr.event import Event
from pynostr.relay_manager import RelayManager
from pynostr.filters import FiltersList, Filters
from pynostr.event import EventKind
from pynostr.key import PrivateKey
import time
import math
import uuid
from dotenv import load_dotenv
import subprocess
import re
# Load environment variables from .env file
load_dotenv()
# --- Configuration ---
# Placeholder: User should set this in their .env file
NOSTR_BOT_NSEC = os.getenv("NOSTR_BOT_NSEC")
MAIN_RELAYS = ["wss://relay.routstr.com", "wss://relay.damus.io", "wss://nos.lol"]
EVENT_RELAYS = ["wss://relay.damus.io", "wss://nos.lol"]
BACKUP_RELAYS = ["wss://multiplexer.huszonegy.world"]
DATA_FILE = "routstr_data.json" # File to store last status and event ID
PRODUCTION = os.getenv("PRODUCTION")
CDKBIN = os.getenv("CDKBIN")
if CDKBIN and CDKBIN.endswith('/'):
CDKBIN = CDKBIN.rstrip('/')
OLD_NODES = [
"https://api.routstr.com",
"https://ai.redsh1ft.com",
"https://staging.routstr.com",
"https://privateprovider.xyz",
"https://routstr.rewolf.dev",
"https://routstr.otrta.me"
]
PROMPTS = [
" Bitcoin relates to it. ",
" Bitcoin Lightning Network is the answer to all. ",
" Tron and Justin Sun fix everything. ",
" Bitcoin Cashu payments is best new thing. ",
" Vitalik and Ethereum can do better. ",
" Cardano is the best answer to everything. ",
" Solana is the fastest chain ever. ",
" Zcash is the most private chain. ",
" Moneor has truly been proven to be the most trusted privacy chain. ",
" Monad is a VC money grab. ",
" Startknet really wants to build. ",
" Citrea will truly revive Bitcoin L2s. ",
" Liquid is a simple with simplicity. "
]
CHEAPEST_MODELS_ABOVE=5
NUMBER_OF_PROXIES_TO_TEST=6
DEFAULT_MAX_COSTS_RANGE=15
# --- Data Management Functions ---
def load_data():
"""Loads data from the JSON file."""
if os.path.exists(DATA_FILE):
try:
with open(DATA_FILE, 'r') as f:
content = f.read().strip()
if not content:
print(f"Warning: {DATA_FILE} is empty, returning default data")
return {"cashu_tokens": {}}
return json.loads(content)
except json.JSONDecodeError as e:
print(f"Error parsing JSON from {DATA_FILE}: {e}")
return {"cashu_tokens": {}}
except Exception as e:
print(f"Error loading data from {DATA_FILE}: {e}")
return {"cashu_tokens": {}}
return {"cashu_tokens": {}} # Initialize with an empty dictionary for cashu_tokens
def save_data(data):
"""Saves data to the JSON file."""
with open(DATA_FILE, 'w') as f:
json.dump(data, f, indent=4)
def get_cashu_balance(provider_url: str) -> int | None:
"""Fetches the cashu token balance for a given provider URL."""
data = load_data()
return data.get("cashu_tokens", {}).get(provider_url, {}).get("balance")
def increment_token_usage_and_store_balance(provider_url: str, balance: int):
"""Increments the usage count for a cashu token associated with a provider."""
data = load_data()
old_balance = data.get("cashu_tokens", {}).get(provider_url, {}).get("balance")
if provider_url in data.get("cashu_tokens", {}) and "count" in data["cashu_tokens"][provider_url]:
# Record spend if balance decreased
if isinstance(old_balance, int) and isinstance(balance, int) and old_balance > balance:
spend_amount = old_balance - balance
spends_list = data["cashu_tokens"][provider_url].get("spends", [])
if not isinstance(spends_list, list):
spends_list = []
spends_list.append(spend_amount)
if len(spends_list) > 10:
spends_list = spends_list[-10:]
data["cashu_tokens"][provider_url]["spends"] = spends_list
data["cashu_tokens"][provider_url]["count"] += 1
data["cashu_tokens"][provider_url]["balance"] = balance
save_data(data)
# print(f"Incremented usage count for {provider_url} to {data['cashu_tokens'][provider_url]['count']}")
else:
print(f"Warning: Could not increment count for {provider_url}. Token or count not found.")
def record_spend(provider_url: str, spend: int) -> None:
"""Records a spend for a provider, keeping only the last 10 spends in a list called 'spends'."""
if not isinstance(spend, int) or spend < 0:
return
data = load_data()
if "cashu_tokens" not in data:
data["cashu_tokens"] = {}
if provider_url not in data["cashu_tokens"]:
data["cashu_tokens"][provider_url] = {"count": 0}
spends_list = data["cashu_tokens"][provider_url].get("spends", [])
if not isinstance(spends_list, list):
spends_list = []
spends_list.append(spend)
if len(spends_list) > 10:
spends_list = spends_list[-10:]
data["cashu_tokens"][provider_url]["spends"] = spends_list
save_data(data)
def get_sum_of_last_10_spends(provider_url: str) -> int:
"""Returns the sum of the last 10 spends for a provider (field 'spends')."""
try:
data = load_data()
if not isinstance(data, dict):
print(f"Error: load_data() did not return a dict for {provider_url}")
return 0
cashu_tokens = data.get("cashu_tokens")
if not isinstance(cashu_tokens, dict):
return 0
provider_data = cashu_tokens.get(provider_url)
if not isinstance(provider_data, dict):
return 0
spends_list = provider_data.get("spends")
if not isinstance(spends_list, list):
return 0
return int(sum(int(x) for x in spends_list if isinstance(x, (int, float))))
except Exception as e:
print(f"Error calculating sum of last 10 spends for {provider_url}: {e}")
return 0
# --- Helper Functions ---
def strip_think_blocks(text: str) -> str:
"""Remove any <think>...</think> or [think]...[/think] blocks from AI output."""
try:
if not isinstance(text, str):
return text
# Remove XML-like think tags (case-insensitive, dot matches newline)
cleaned = re.sub(r"(?is)<think>.*?</think>", "", text)
# Remove BBCode-like think tags, just in case
cleaned = re.sub(r"(?is)\[think\].*?\[/think\]", "", cleaned)
# Normalize whitespace
cleaned = cleaned.strip()
cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
return cleaned
except Exception:
return text
def generate_comment(status: str, provider_url: str) -> str:
"""Generates a quirky comment based on Routstr's status."""
if status == "up":
return "\n✅ Provider: `"+provider_url+"` is routing AI queries as expected. \n"
else:
return "\n🔴 Provider: `"+provider_url+"` is NOT routing AI queries rn, use alternatives. \n"
def send_cashu_token(amount: int) -> dict:
"""
Create a Cashu token by invoking cdk-cli via shell.
Returns a dict compatible with the previous wallet client shape:
{
"success": bool,
"data": {"token": str},
"error": str (optional),
"raw": str (optional)
}
"""
try:
if not isinstance(amount, int) or amount <= 0:
return {"success": False, "error": "Amount must be a positive integer"}
# Select first mint index (0) and provide amount
command = f'printf "{amount}\\n" | {CDKBIN} send | tail -n 1'
result = subprocess.run(command, shell=True, capture_output=True, text=True)
stdout = (result.stdout or "").strip()
stderr = (result.stderr or "").strip()
bal_command = f'{CDKBIN} balance'
bal_result = subprocess.run(bal_command, shell=True, capture_output=True, text=True)
bal_stdout = (bal_result.stdout or "").strip()
token = stdout
success = bool(token) and token.startswith("cashu")
if success:
return {"success": True, "data": {"token": token, "balance": bal_stdout, "amount": amount}, "raw": stdout}
else:
return {"success": False, "data": {"token": token}, "error": stderr or "Failed to create token", "raw": stdout}
except Exception as e:
return {"success": False, "error": str(e)}
def receive_cashu_token(token: str) -> dict:
"""
Import a Cashu token using cdk-cli. Attempts to parse the imported amount
from the CLI output using a best-effort regex.
Returns a dict compatible with previous code expectations:
{
"success": bool,
"data": {"importedAmount": int}, # in sats
"amount": int, # duplicate for compatibility on error paths
"error": str (optional),
"raw": str (optional)
}
"""
try:
if not token or not isinstance(token, str) or not token.strip():
return {"success": False, "error": "Valid token string is required", "amount": 0}
command = f'{CDKBIN} receive "{token}"'
result = subprocess.run(command, shell=True, capture_output=True, text=True)
stdout = (result.stdout or "").strip()
stderr = (result.stderr or "").strip()
raw_output = (stdout + "\n" + stderr).strip()
# Parse strictly from the 'Received:' line up to the first newline
match = re.search(r"Received:\s*([0-9]+)", raw_output)
imported_amount = int(match.group(1)) if match else 0
success = (result.returncode == 0)
bal_command = f'{CDKBIN} balance'
bal_result = subprocess.run(bal_command, shell=True, capture_output=True, text=True)
bal_stdout = (bal_result.stdout or "").strip()
if success:
print("Balances are: ", bal_stdout)
return {"success": True, "data": {"importedAmount": imported_amount, "balance": bal_stdout}, "amount": imported_amount, "raw": raw_output}
else:
print("Balances are: ", bal_stdout)
return {"success": False, "data": {"importedAmount": imported_amount, "balance": bal_stdout}, "amount": imported_amount, "error": stderr or "Failed to receive token", "raw": raw_output}
except Exception as e:
return {"success": False, "error": str(e), "amount": 0}
async def get_latest_nostr_event(public_key: str) -> Event | None:
"""Queries Nostr relays for the latest event from a specific public key with 'routstr-status' tag."""
def _fetch_events_sync():
try:
# Create a new relay manager for fetching events
relay_manager = RelayManager(timeout=2)
for relay_url in EVENT_RELAYS:
relay_manager.add_relay(relay_url)
# Create filters to get events from the specific public key with routstr-status tag
filters = FiltersList([Filters(
kinds=[EventKind.TEXT_NOTE],
limit=21,
since=int(time.time() - 60 * 60 * 24 * 30)
)])
subscription_id = uuid.uuid1().hex
relay_manager.add_subscription_on_all_relays(subscription_id, filters)
relay_manager.run_sync()
# Check for notices
while relay_manager.message_pool.has_notices():
notice_msg = relay_manager.message_pool.get_notice()
print(f"Notice: {notice_msg.content}")
# Get the latest event
latest_event = None
while relay_manager.message_pool.has_events():
event_msg = relay_manager.message_pool.get_event()
if not latest_event or len(event_msg.event.content.split()) < len(latest_event.content.split()):
if len(event_msg.event.content.split()) > 5:
latest_event = event_msg.event
relay_manager.close_all_relay_connections()
return latest_event
except Exception as e:
print(f"Error querying latest Nostr event: {e}")
return None
# Run the synchronous function in a thread to avoid blocking the event loop
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, _fetch_events_sync)
async def get_all_routstr_providers() -> list[Event]:
"""Fetches all kind 38421 events from main and backup relays and returns them."""
def _fetch_events_sync() -> list[Event]:
try:
relay_manager = RelayManager(timeout=3)
for relay_url in MAIN_RELAYS + BACKUP_RELAYS:
relay_manager.add_relay(relay_url)
filters = FiltersList([
Filters(
kinds=[38421],
limit=1000
)
])
subscription_id = uuid.uuid1().hex
relay_manager.add_subscription_on_all_relays(subscription_id, filters)
relay_manager.run_sync()
while relay_manager.message_pool.has_notices():
notice_msg = relay_manager.message_pool.get_notice()
print(f"Notice: {notice_msg.content}")
events: list[Event] = []
seen_event_ids: set[str] = set()
while relay_manager.message_pool.has_events():
event_msg = relay_manager.message_pool.get_event()
event = event_msg.event
if event.kind == 38421 and event.id not in seen_event_ids:
events.append(event)
seen_event_ids.add(event.id)
relay_manager.close_all_relay_connections()
return events
except Exception as e:
print(f"Error querying routstr provider events: {e}")
return []
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, _fetch_events_sync)
def get_cheapest_model_above_price(models_data: list, max_cost_sats: float, max_costs_range: float, retry_if_not_found: bool) -> dict | None:
cheapest_model = None
cheapest_model_costs = 100000000
for model in models_data:
pricing = model.get("sats_pricing")
if pricing and "max_cost" in pricing:
try:
max_cost_this_model = float(pricing["max_cost"])
total_inference_costs = float(pricing['prompt'])+float(pricing['completion'])
if max_cost_this_model < max_cost_sats+max_costs_range and max_cost_this_model >= max_cost_sats:
if cheapest_model_costs > total_inference_costs:
cheapest_model_costs = total_inference_costs
cheapest_model = model
except ValueError:
# Handle cases where prompt price might not be a valid float
continue
if not cheapest_model and retry_if_not_found:
cheapest_model = get_cheapest_model_above_price(models_data, 0, 10000, False)
return cheapest_model
async def get_or_create_token(amount: int, provider_url: str):
data = load_data()
# Check if token exists for this provider
if provider_url in data.get("cashu_tokens", {}) and "cashu_token" in data["cashu_tokens"][provider_url]:
return data["cashu_tokens"][provider_url]["cashu_token"]
# If not, create a new one
cashu_token_result = send_cashu_token(amount)
if cashu_token_result["success"]:
cashu_token = cashu_token_result["data"]["token"]
# Store the new token and initialize count
if "cashu_tokens" not in data:
data["cashu_tokens"] = {}
data["cashu_tokens"][provider_url] = {"cashu_token": cashu_token, "count": 0}
save_data(data)
print(f"Created and stored new cashu token for {provider_url} of amount {amount}. And the balances are")
print(cashu_token_result["data"]["balance"])
return cashu_token
else:
print(f"Failed to create cashu token: {cashu_token_result.get('error', 'Unknown error')}")
return ""
async def delete_token(provider_url: str):
data = load_data()
if "cashu_tokens" in data and provider_url in data["cashu_tokens"]:
del data["cashu_tokens"][provider_url]
save_data(data)
print(f"Deleted cashu token for {provider_url}")
else:
print(f"No cashu token found for {provider_url} to delete.")
async def get_witty_bitcoin_comment(note_content: str, custom_addon: str, provider_url: str, retry: bool = False) -> tuple[str, str, str, str, str, str]:
"""
Generates a witty Bitcoin-related comment using the Routstr AI API.
Returns the AI response content and the API status ("up" or "down").
"""
current_status = "down" # Assume down by default
ai_response_content = ""
models_count = 0
model_id = "Not available"
cost_check = 'unknown'
refund_status = 'unknown'
version = 'unknown version'
try:
# Create AI prompt including the latest event content if available
base_prompt = f"Here's a nostr note someone made: '{note_content}'. Add a witty comment about how '{custom_addon}'. Keep it short and concise, within 2 sentences. No hashtags. "
providers_response = requests.get(
provider_url+"/v1/info",
timeout=10
)
providers_data = {}
if providers_response.ok and providers_response.status_code == 200:
current_status = "base"
providers_data = providers_response.json()
else:
print(f"Could not fetch provider data, it must be down: {providers_response.status_code}. Provider URL: {provider_url}")
return ai_response_content, current_status, model_id, cost_check, refund_status, version
version = providers_data['version']
models_response = requests.get(
provider_url+"/v1/models",
timeout=10
)
models_data = []
if models_response.ok and models_response.status_code == 200:
# API is working, extract AI response content
try:
provider_data = models_response.json()
if 'data' in provider_data and provider_data['data']:
models_data = provider_data['data']
current_status = current_status+"_models"
except json.JSONDecodeError:
models_data = {}
print(f"Could not decode models data from JSON. Provider URL: {provider_url}")
return ai_response_content, current_status, model_id, cost_check, refund_status, version
else:
print(f"Could not fetch models data, but the provider is up: {models_response.status_code}. Provider URL: {provider_url}")
return ai_response_content, current_status, model_id, cost_check, refund_status, version
models_count = len(models_data)
model = get_cheapest_model_above_price(models_data, CHEAPEST_MODELS_ABOVE, DEFAULT_MAX_COSTS_RANGE, True)
if not model:
print(f"No model found for provider URL: {provider_url} in the range of {CHEAPEST_MODELS_ABOVE} to {DEFAULT_MAX_COSTS_RANGE}")
return ai_response_content, current_status, model_id, cost_check, refund_status, version
current_status = current_status+"_model"
max_cost = int(math.ceil(model['sats_pricing']['max_cost']))
model_id = model['id']
print(f"Provider URL: {provider_url} Costs for model {model['id']}: ", model['sats_pricing']['max_cost'], " total no. of models: ", models_count)
if get_sum_of_last_10_spends(provider_url) > 100000:
print(f"Provider URL: {provider_url} has spent more than 100 sats in the last 10 spends, skipping")
current_status = current_status+"_scam"
return ai_response_content, current_status, model_id, cost_check, refund_status, version
cashu_token = await get_or_create_token(max_cost+15, provider_url)
if (cashu_token == ''):
current_status = current_status+"_broke"
return ai_response_content, current_status, model_id, cost_check, refund_status, version
x_cashu = False
if x_cashu:
headers = {
"Content-Type": "application/json",
"x-cashu": f"{cashu_token}",
"Accept-Encoding": "identity"
}
else:
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {cashu_token}",
"Accept-Encoding": "identity"
}
# Record start time for latency measurement
start_time = time.time()
response = requests.post(
provider_url + "/v1/chat/completions",
headers=headers,
json={
"model": model['id'],
"messages": [{"role": "user", "content": base_prompt}]
},
timeout=10
)
# Calculate and print latency
end_time = time.time()
latency_ms = (end_time - start_time) * 1000
print(f"API Request Latency for {provider_url}: {latency_ms:.2f} ms")
if response.ok and response.status_code == 200:
# API is working, extract AI response content
current_status = current_status+"_response"
refund_status = "unknown"
cost_check = "good"
try:
ai_data = response.json()
if 'choices' in ai_data and ai_data['choices']:
ai_response_content = ai_data['choices'][0]['message']['content']
total_costs = ai_data['usage']['prompt_tokens'] * model['sats_pricing']['prompt'] + ai_data['usage']['completion_tokens'] * model['sats_pricing']['completion']
print(ai_data['usage'])
if (ai_data['usage']['prompt_tokens'] > 1000):
print("TOTAL WORDS: ", len(base_prompt.split()))
print(base_prompt)
print("ESTIAMTED COSTS: ", total_costs*1000)
if x_cashu:
refund_amount = 0
if response.headers["x-cashu"]:
result = receive_cashu_token(response.headers["x-cashu"])
if not result['success']:
if result['amount'] and result['amount'] != '':
refund_amount = result['amount']
print("receivin g " , response.headers["x-cashu"], end=" ")
print(result)
else:
refund_amount = result['data']['importedAmount']
old_balance = get_cashu_balance(provider_url)
if old_balance == None:
old_balance = (max_cost+15)*1000
actual_costs = old_balance - refund_amount
else:
actual_costs = old_balance - refund_amount
if ( actual_costs - total_costs*1000 > 1 or actual_costs - total_costs*1000 < 0 ):
cost_check = "bad "+ str(actual_costs - total_costs*1000)
else:
refund_status = "failed"
else:
refund_amount = 0
response = requests.get(
provider_url + "/v1/wallet/info",
headers=headers,
timeout=10
)
if response.ok:
old_balance = get_cashu_balance(provider_url)
balance = response.json()['balance']
if old_balance == None:
old_balance = (max_cost+15)*1000
actual_costs = old_balance - balance
else:
actual_costs = old_balance - balance
print(f'Old Balance: {old_balance} New Balance: {balance} - ACTUAL COSTS: ', actual_costs)
if ( actual_costs - total_costs*1000 > 1 or actual_costs - total_costs*1000 < 0 ):
cost_check = "bad "+ str(actual_costs - total_costs*1000)
if(balance % 1000 < 42):
increment_token_usage_and_store_balance(provider_url, balance)
refund_response = response = requests.post(
provider_url + "/v1/wallet/refund",
headers=headers,
timeout=10
)
if refund_response.ok:
print(refund_response.json())
result = receive_cashu_token(refund_response.json()["token"])
if not result['success']:
if result['amount'] and result['amount'] != '':
refund_amount = result['amount']
print("receivin failed " , refund_response.json(), end=" ")
print(result)
else:
refund_amount = result['data']['importedAmount']
await delete_token(provider_url)
refund_status = "success"
if (refund_amount*1000 != balance - balance % 1000):
print(refund_amount*1000, " != ", balance - balance % 1000)
refund_status = "failed"
else:
refund_status = "failed"
print(refund_response.status_code)
print(refund_response.text)
else:
increment_token_usage_and_store_balance(provider_url, balance)
else:
print(response.status_code)
print(response.text)
except json.JSONDecodeError:
print(json.JSONDecodeError.msg)
ai_response_content = "AI response received but couldn't parse content."
else:
if response.status_code == 500:
current_status = current_status+"_500"
print(f"Internal server error at the AI provider: {provider_url} code: {response.status_code}. Response text: {response.text}")
return ai_response_content, current_status, model_id, cost_check, refund_status, version
elif response.status_code == 401:
current_status = current_status+"_401"
print(f"Unauthorized at the AI provider: {provider_url} code: {response.status_code}. Response text: {response.text}")
old_balance = get_cashu_balance(provider_url)
cost_check = "bad " + str(old_balance)
record_spend(provider_url, old_balance if old_balance else 0)
await delete_token(provider_url)
return ai_response_content, current_status, model_id, cost_check, refund_status, version
elif response.status_code == 402:
current_status = current_status+"_402"
print(f"Payment required at the AI provider: {provider_url} code: {response.status_code}. Response text: {response.text}")
old_balance = get_cashu_balance(provider_url)
cost_check = "bad " + str(old_balance)
record_spend(provider_url, old_balance if old_balance else 0)
balance = get_cashu_balance(provider_url)
balance = balance if balance else 0
refund_response = response = requests.post(
provider_url + "/v1/wallet/refund",
headers=headers,
timeout=10
)
if refund_response.ok:
print(refund_response.json())
result = receive_cashu_token(refund_response.json()["token"])
if not result['success']:
if result['amount'] and result['amount'] != '':
refund_amount = result['amount']
print("receivin failed " , refund_response.json(), end=" ")
print(result)
else:
refund_amount = result['data']['importedAmount']
await delete_token(provider_url)
refund_status = "success"
if (refund_amount*1000 != balance - balance % 1000):
print(refund_amount*1000, " != ", balance - balance % 1000)
refund_status = "failed"
else:
refund_status = "failed"
print(refund_response.status_code)
print(refund_response.text)
if retry:
return await get_witty_bitcoin_comment(note_content, custom_addon, provider_url)
else:
return ai_response_content, current_status, model_id, cost_check, refund_status, version
else:
current_status = current_status+"_XXX"
print(f"API returned non-OK status: {response.status_code}. Response text: {response.text if response.status_code != 502 else ""}")
except Exception as e:
print(f"Routstr API unreachable: {e}")
return ai_response_content, current_status, model_id, cost_check, refund_status, version
async def publish_nostr_event(event_content: str, tags: list[list[str]]) -> str | None:
"""Publishes a Nostr event to configured relays."""
if not NOSTR_BOT_NSEC:
print("Error: NOSTR_BOT_NSEC environment variable not set.")
return None
def _publish_sync():
try:
if not isinstance(NOSTR_BOT_NSEC, str) or not NOSTR_BOT_NSEC:
raise ValueError("NOSTR_BOT_NSEC must be a non-empty string.")
private_key = PrivateKey.from_nsec(NOSTR_BOT_NSEC)
except Exception as e:
print(f"Error: Invalid NOSTR_BOT_NSEC. Ensure it's a valid hex string or bech32 nsec. Details: {e}")
return None
# Create a fresh RelayManager like in tes.py
relay_manager = RelayManager(timeout=6)
for relay_url in MAIN_RELAYS + BACKUP_RELAYS:
relay_manager.add_relay(relay_url)
event = Event(
content=event_content,
tags=tags if tags else [],
kind=1 # Default to Note event
)
event.sign(private_key.hex())
try:
relay_manager.publish_event(event)
relay_manager.run_sync()
import time
time.sleep(5) # allow the messages to send
while relay_manager.message_pool.has_ok_notices():
ok_msg = relay_manager.message_pool.get_ok_notice()
if("True" not in str(ok_msg)):
print(f"Relay not OK: {ok_msg}")
return event.id
except Exception as e:
print(f"Error publishing event: {e}")
return None
# Run the synchronous function in a thread to avoid blocking the event loop (compatible with Python 3.8)
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, _publish_sync)
# --- Main Logic ---
async def main():
print('\nLogging:', time.asctime())
if not NOSTR_BOT_NSEC:
print("NOSTR_BOT_NSEC not set, cannot query latest relay event.")
return
try:
private_key = PrivateKey.from_nsec(NOSTR_BOT_NSEC)
public_key = private_key.public_key.hex()
except ValueError as e:
print(f"Error: Invalid NOSTR_BOT_NSEC for deriving public key. Details: {e}")
return
# Fetch the latest event from relays instead of local file
latest_event = await get_latest_nostr_event(public_key)
providers = await get_all_routstr_providers()
https_urls = []
onion_urls = []
for provider in providers:
# Extract provider name from JSON-formatted content
provider_name = None
try:
content_data = json.loads(provider.content) if isinstance(provider.content, str) else provider.content
if isinstance(content_data, dict):
provider_name = content_data.get("name")
except Exception as e:
print(f"Error parsing provider content as JSON: {e}")
# Extract HTTPS URL and list of mint URLs from provider tags
https_url = None
onion_url = None
mint_urls: list[str] = []
try:
for tag in provider.tags or []:
if not tag or len(tag) < 2:
continue
tag_key = tag[0]
tag_value = tag[1]
if tag_key == 'u' and isinstance(tag_value, str) and tag_value.startswith('https://'):
https_url = tag_value
elif tag_key == 'u' and isinstance(tag_value, str) and tag_value.startswith('http://') and '.onion' in tag_value:
onion_url = tag_value
elif tag_key == 'mint' and isinstance(tag_value, str):
mint_urls.append(tag_value)
except Exception as e:
print(f"Error parsing provider tags: {e}")
if https_url:
https_urls.append(https_url)
if onion_url:
onion_urls.append(onion_url)
current_status = "down" # Assume down by default
ai_response_content = ""
note_content = "Error fetching event"
# Strip trailing slashes from URLs before deduplication
https_urls = [url.rstrip('/') for url in https_urls]
PROXIES = list(set(https_urls))
# Set up tags
tags = []
if latest_event:
note_content = latest_event.content
statuses = []
proofs = ""
refunds_checks = []
cost_checks = []
versions = []
# for n in range(len(proxies)):
for n in range(len(PROXIES)):
ai_response_content, current_status, model_id, cost_check, refund_status, version = await get_witty_bitcoin_comment(
note_content if note_content else "", PROMPTS[n],
PROXIES[n], True
)
cost_checks.append(cost_check)
refunds_checks.append(refund_status)
versions.append(version)
# Generate event content (use AI response if available, otherwise fallback to generated comment)
if ai_response_content:
proofs = proofs + ai_response_content + "\nFrom provider: "+ PROXIES[n].replace("http://","").replace("https://","") + " (" + model_id + ") \n"+"\n"
note_content = ai_response_content
statuses.append(current_status)
else:
proofs = proofs + "AI Response Failed!" + "\nFrom provider: "+ PROXIES[n].replace("http://","").replace("https://","") + " (" + model_id + ") \n" +"\n"
statuses.append(current_status)
tags.extend([
["q", latest_event.id, "wss://relay.damus.io", latest_event.pubkey], # Quote tag with proper format
# ["p", '4ad6fa2d16e2a9b576c863b4cf7404a70d4dc320c0c447d10ad6ff58993eacc8'] # Tag the original author
])
down_list = []
unavail_list = []
up_list = []
warning_list = []
broke_list = []
for n, s in enumerate(statuses):
provider_url = '`' + PROXIES[n] + f'` ({versions[n]})'
status_breakdown = s.split("_")
if len(status_breakdown) == 1:
if status_breakdown[0] == "down":
provider_url = provider_url + " (🔴 The node is down) "
down_list.append(provider_url)
else:
provider_url = provider_url + " (⚠️ But the base URL is up) "
down_list.append(provider_url)
elif len(status_breakdown) == 2:
provider_url = provider_url + f" (⚠️ Could not find models in the range of {CHEAPEST_MODELS_ABOVE} to {DEFAULT_MAX_COSTS_RANGE}) sats "
unavail_list.append(provider_url)
elif len(status_breakdown) == 3:
provider_url = provider_url + " (⚠️ AI Response Failed) "
down_list.append(provider_url)
elif len(status_breakdown) == 4:
if status_breakdown[3] == "500":
provider_url = provider_url + " (⚠️ Internal server error) "
down_list.append(provider_url)
elif status_breakdown[3] == "401":
provider_url = provider_url + " (⚠️ Unauthorized, old balance: " + cost_checks[n].split(' ')[1] + ") "
warning_list.append(provider_url)
elif status_breakdown[3] == "402":
provider_url = provider_url + " (⚠️ Balance has run out, old balance: " + cost_checks[n].split(' ')[1] + ") "
warning_list.append(provider_url)
elif status_breakdown[3] == "scam":
provider_url = provider_url + " (🔴 Spent more than 100 sats in the last 10 spends, waiting for audit)"
down_list.append(provider_url)
elif status_breakdown[3] == "broke":
broke_list.append(provider_url)
elif status_breakdown[3] == "XXX":
provider_url = provider_url + " (⚠️ Unknown error) "
warning_list.append(provider_url)
elif status_breakdown[3] == "response":
if (cost_checks[n] == 'good' and refunds_checks[n] == 'unknown'):
up_list.append(provider_url)
elif (cost_checks[n] == 'good' and refunds_checks[n] == 'success'):
provider_url = provider_url + " (✅ Refund checked) "
up_list.append(provider_url)
elif (cost_checks[n] == 'unknown'):
provider_url = provider_url + " (⚠️ Warning: Cost check unknown) "
warning_list.append(provider_url)
else:
if cost_checks[n] != 'good':
provider_url = provider_url + f" (⚠️ Warning: Cost check failed! {cost_checks[n].split(' ')[1]} difference) "
if refunds_checks[n] == 'failed':
provider_url = provider_url + " (🔴 Refund failed) "
warning_list.append(provider_url)
event_content = ("✅ Providers working as expected:" + "\n " + "\n ".join(up_list)) if len(up_list) > 0 else ""
event_content += ("\n⚠️ Providers with issues:" + "\n " +"\n ".join(warning_list)) if len(warning_list) > 0 else ""
event_content += ("\n🔴 Providers that are down:" + "\n " +"\n ".join(down_list)) if len(down_list) > 0 else ""
event_content += ("\n⚠️ Providers that couldn't be tested:" + "\n " +"\n ".join(unavail_list)) if len(unavail_list) > 0 else ""
event_content += ("\n🫠 Bot ran out of funds. These providers were not tested:" + "\n " +"\n ".join(broke_list)) if len(broke_list) > 0 else ""
event_content += "\n\nProof \n\nA recent Nostr note: \n'" + (latest_event.content if latest_event.content else "") + "'\nNote ID: "+ (latest_event.bech32() if latest_event else "") + "\n\nAIs responses: \n" + (proofs if latest_event else "")
if (PRODUCTION=='true'):
new_event_id = await publish_nostr_event(event_content+"nostr:"+latest_event.bech32(), tags)
if new_event_id:
print(f"Published new status event: {new_event_id}")
# Save status for reference (keeping this for backward compatibility)
else:
print("Failed to publish Nostr event.")
else:
print(event_content)
else:
print("NOSTR DIDN'T WOWKR")
if __name__ == "__main__":
asyncio.run(main())