This repository was archived by the owner on Mar 10, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathasync_api.py
1692 lines (1503 loc) · 86.8 KB
/
async_api.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
from httpx import AsyncClient, ConnectError, ReadTimeout
import asyncio, queue, orjson, random, ssl, threading, websocket, string, secrets, os, hashlib, re, aiofiles
from typing import AsyncIterator
from loguru import logger
from requests_toolbelt import MultipartEncoder
# Allow multi-threading for asyncio
import nest_asyncio
nest_asyncio.apply()
from .utils import (
BASE_URL,
HEADERS,
SubscriptionsMutation,
BOTS_LIST,
REVERSE_BOTS_LIST,
bot_map,
generate_nonce,
generate_file
)
from .queries import generate_payload
from .bundles import PoeBundle
from .proxies import PROXY
if PROXY:
from .proxies import fetch_proxy
"""
This API is modified and maintained by @snowby666
Credit to @ading2210 for the GraphQL queries
"""
class AsyncPoeApi:
BASE_URL = BASE_URL
HEADERS = HEADERS
MAX_CONCURRENT_MESSAGES = 3
def __init__(self, tokens: dict={}, proxy: list=[], auto_proxy: bool=False):
self.client = None
if not {'p-b', 'p-lat'}.issubset(tokens):
raise ValueError("Please provide valid p-b and p-lat cookies")
self.proxy: list = proxy
self.auto_proxy: bool = auto_proxy
self.tokens: dict = tokens
self.formkey: str = ""
self.ws_connecting: bool = False
self.ws_connected: bool = False
self.ws_error: bool = False
self.active_messages: dict[int, str] = {}
self.message_queues: dict[int, queue.Queue] = {}
self.current_thread: dict[str, list] = {}
self.retry_attempts: int = 3
self.ws_refresh: int = 3
self.groups: dict = {}
self.proxies: dict = {}
self.bundle: PoeBundle = None
self.loop: asyncio.AbstractEventLoop = None
self.client = AsyncClient(headers=self.HEADERS, timeout=60, http2=True)
self.client.cookies.update({
'p-b': self.tokens['p-b'],
'p-lat': self.tokens['p-lat']
})
if { '__cf_bm', 'cf_clearance'}.issubset(tokens):
self.client.cookies.update({
'__cf_bm': tokens['__cf_bm'],
'cf_clearance': tokens['cf_clearance']
})
if 'formkey' in tokens:
self.formkey = tokens['formkey']
self.client.headers.update({
'Poe-Formkey': self.formkey,
})
async def create(self):
await self.load_bundle()
if self.proxy != [] or self.auto_proxy == True:
await self.select_proxy(self.proxy, auto_proxy=self.auto_proxy)
elif self.proxy == [] and self.auto_proxy == False:
await self.connect_ws()
else:
raise ValueError("Please provide a valid proxy list or set auto_proxy to False")
logger.info("Async instance created")
return self
def __del__(self):
if self.client:
asyncio.get_event_loop().run_until_complete(self.client.aclose())
async def load_bundle(self):
try:
webData = await self.client.get(self.BASE_URL)
self.bundle = PoeBundle(webData.text)
self.formkey = self.bundle.get_form_key()
self.client.headers.update({
'Poe-Formkey': self.formkey,
})
except Exception as e:
logger.error(f"Failed to load bundle. Reason: {e}")
logger.warning("Failed to get formkey from bundle. Please provide a valid formkey manually." if self.formkey == "" else "Continuing with provided formkey")
async def select_proxy(self, proxy: list, auto_proxy: bool=False):
if proxy == [] and auto_proxy == True:
if not PROXY:
raise ValueError("Please install ballyregan for auto proxy")
proxies = fetch_proxy()
elif proxy != [] and auto_proxy == False:
proxies = proxy
else:
raise ValueError("Please provide a valid proxy list or set auto_proxy to False")
for p in range(len(proxies)):
try:
self.proxies = proxies[p]
self.client.proxies = self.proxies
await self.connect_ws()
logger.info(f"Connection established with {proxies[p]}")
break
except:
logger.info(f"Connection failed with {proxies[p]}. Trying {p+1}/{len(proxies)} ...")
await asyncio.sleep(1)
async def send_request(self, path: str, query_name: str="", variables: dict={}, file_form: list=[], knowledge: bool=False, ratelimit: int = 0):
if ratelimit > 0:
logger.warning(f"Waiting queue {ratelimit}/2 to avoid rate limit")
asyncio.sleep(random.randint(2, 3))
status_code = 0
try:
payload = generate_payload(query_name, variables)
base_string = payload + self.formkey + "4LxgHM6KpFqokX0Ox"
if file_form == []:
headers = {'Content-Type': 'application/json'}
else:
fields = {'queryInfo': payload}
if not knowledge:
for i in range(len(file_form)):
fields[f'file{i}'] = file_form[i]
else:
fields['file'] = file_form[0]
payload = MultipartEncoder(
fields=fields
)
headers = {'Content-Type': payload.content_type}
payload = payload.to_string()
headers.update({
"poe-tag-id": hashlib.md5(base_string.encode()).hexdigest(),
})
response = await self.client.post(f'{self.BASE_URL}/api/{path}', data=payload, headers=headers, follow_redirects=True, timeout=30)
status_code = response.status_code
json_data = orjson.loads(response.text)
if (
"success" in json_data.keys()
and not json_data["success"]
or (json_data and json_data["data"] is None)
):
err_msg: str = json_data["errors"][0]["message"]
if err_msg == "Server Error":
raise RuntimeError(f"Server Error. Raw response data: {json_data}")
else:
logger.error(response.status_code)
logger.error(response.text)
raise Exception(response.text)
if status_code == 200:
for file in file_form:
try:
if hasattr(file[1], 'closed') and not file[1].closed:
file[1].close()
except IOError as e:
logger.warning(f"Failed to close file: {file[0]}. Reason: {e}")
return json_data
except Exception as e:
if isinstance(e, ReadTimeout):
if query_name == "sendMessageMutation":
logger.error(f"Failed to send message {variables['query']} due to ReadTimeout")
raise e
else:
logger.error(f"Automatic retrying request {query_name} due to ReadTimeout")
return await self.send_request(path, query_name, variables, file_form)
if (
isinstance(e, ConnectError) or 500 <= status_code < 600
) and ratelimit < 2:
return await self.send_request(path, query_name, variables, file_form, ratelimit=ratelimit + 1)
error_code = f"status_code:{status_code}, " if status_code else ""
raise Exception(
f"Sending request {query_name} failed. {error_code} Error log: {repr(e)}"
)
async def get_channel_settings(self):
response = await self.client.get(f'{self.BASE_URL}/api/settings', headers=self.HEADERS, follow_redirects=True, timeout=30)
response_json = orjson.loads(response.text)
self.ws_domain = f"tch{random.randint(1, int(1e6))}"[:11]
self.tchannel_data = response_json["tchannelData"]
self.client.headers["Poe-Tchannel"] = self.tchannel_data["channel"]
self.channel_url = f'ws://{self.ws_domain}.tch.{self.tchannel_data["baseHost"]}/up/{self.tchannel_data["boxName"]}/updates?min_seq={self.tchannel_data["minSeq"]}&channel={self.tchannel_data["channel"]}&hash={self.tchannel_data["channelHash"]}'
await self.subscribe()
async def subscribe(self):
response_json = await self.send_request('gql_POST', "SubscriptionsMutation", SubscriptionsMutation)
if response_json['data'] == None and response_json["errors"]:
raise RuntimeError(f'Failed to subscribe by sending SubscriptionsMutation. Raw response data: {response_json}')
def ws_run_thread(self):
if self.ws and not self.ws.sock:
kwargs = {"sslopt": {"cert_reqs": ssl.CERT_NONE}}
try:
self.ws.run_forever(**kwargs)
except Exception as e:
logger.error(f"Failed to run websocket. Reason: {e}")
finally:
self.loop.call_soon_threadsafe(self.loop.stop)
self.loop.close()
async def connect_ws(self, timeout=20):
if self.ws_connected:
return
if self.ws_connecting:
while not self.ws_connected:
await asyncio.sleep(0.01)
return
self.ws_connecting = True
self.ws_connected = False
self.ws_refresh = 3
while True:
self.ws_refresh -= 1
if self.ws_refresh == 0:
self.ws_refresh = 3
raise RuntimeError("Rate limit exceeded for sending requests to poe.com. Please try again later.")
try:
await self.get_channel_settings()
break
except Exception as e:
logger.error(f"Failed to get channel settings. Reason: {e}")
await asyncio.sleep(1)
continue
self.loop = asyncio.get_event_loop()
self.ws = await self.loop.run_in_executor(
None,
lambda: websocket.WebSocketApp(self.channel_url,
header={
"Origin": f"{self.BASE_URL}",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
},
on_message=lambda ws, msg: self.on_message(ws, msg),
on_open=lambda ws: self.on_ws_connect(ws),
on_error=lambda ws, error: self.on_ws_error(ws, error),
on_close=lambda ws, close_status_code, close_message: self.on_ws_close(ws, close_status_code, close_message))
)
t = threading.Thread(target=self.ws_run_thread, daemon=True)
t.start()
timer = 0
while not self.ws_connected:
await asyncio.sleep(0.01)
timer += 0.01
if timer > timeout:
self.ws_connecting = False
self.ws_connected = False
self.ws_error = True
self.ws.close()
raise RuntimeError("Timed out waiting for websocket to connect.")
def disconnect_ws(self):
self.ws_connecting = False
self.ws_connected = False
if self.ws:
self.ws.close()
logger.info("Websocket connection closed.")
def on_ws_connect(self, ws):
self.ws_connecting = False
self.ws_connected = True
def on_ws_close(self, ws, close_status_code, close_message):
self.ws_connecting = False
self.ws_connected = False
if self.ws_error:
logger.warning("Connection to remote host was lost. Reconnecting...")
self.ws_error = False
self.refresh_ws()
def on_ws_error(self, ws, error):
self.ws_connecting = False
self.ws_connected = False
self.ws_error = True
def on_message(self, ws, msg):
try:
ws_data = orjson.loads(msg)
if "error" in ws_data.keys() and ws_data["error"] == "missed_messages":
self.refresh_ws()
return
if not "messages" in ws_data:
return
for data in ws_data["messages"]:
data = orjson.loads(data)
message_type = data.get("message_type")
if message_type == "refetchChannel":
self.refresh_ws()
return
payload = data.get("payload", {})
subscriptionName = payload.get("subscription_name")
if subscriptionName not in ("messageAdded", "messageCancelled", "chatTitleUpdated"):
return
data = (payload.get("data", {}))
if not data:
return
if subscriptionName == "messageAdded" and data["messageAdded"]["author"] == "human":
return
chat_id: int = int(payload.get("unique_id")[(len(subscriptionName) + 1):])
if chat_id not in self.message_queues:
return
if chat_id in self.message_queues:
self.message_queues[chat_id].put(
{
"data": data,
"subscription": subscriptionName,
}
)
if subscriptionName == "messageAdded":
self.active_messages[chat_id] = data["messageAdded"]["messageId"]
return
except Exception:
logger.exception(f"Failed to parse message: {msg}")
self.disconnect_ws()
self.refresh_ws()
def refresh_ws(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.loop.run_in_executor(None, self.connect_ws())
async def delete_queues(self, chatId: int):
if chatId in self.message_queues:
del self.message_queues[chatId]
if chatId in self.active_messages:
del self.active_messages[chatId]
async def delete_pending_messages(self, prompt_md5: str):
if prompt_md5 in self.active_messages:
del self.active_messages[prompt_md5]
async def get_settings(self):
response_json = await self.send_request('gql_POST', 'SettingsPageQuery', {})
if response_json['data'] == None and response_json["errors"]:
raise RuntimeError(f'Failed to get settings. Raw response data: {response_json}')
return {
"subscription": response_json["data"]["viewer"]["subscription"],
"messagePointInfo": response_json["data"]["viewer"]["messagePointInfo"]
}
async def get_available_bots(self, count: int=25, get_all: bool=False):
self.bots = {}
if not (get_all or count):
raise TypeError("Please provide at least one of the following parameters: get_all=<bool>, count=<int>")
response = await self.send_request('gql_POST',"AvailableBotsSelectorModalPaginationQuery", {})
bots = [
each["node"]
for each in response["data"]["viewer"]["availableBotsConnection"]["edges"]
if each["node"]["deletionState"] == "not_deleted"
]
cursor = response["data"]["viewer"]["availableBotsConnection"]["pageInfo"]["endCursor"]
if len(bots) >= count and not get_all:
self.bots.update({bot["handle"]: {"bot": bot} for bot in bots})
return self.bots
while len(bots) < count or get_all:
response = await self.send_request("gql_POST", "AvailableBotsSelectorModalPaginationQuery", {"cursor": cursor})
new_bots = [
each["node"]
for each in response["data"]["viewer"]["availableBotsConnection"]["edges"]
if each["node"]["deletionState"] == "not_deleted"
]
cursor = response["data"]["viewer"]["availableBotsConnection"]["pageInfo"]["endCursor"]
bots += new_bots
if len(new_bots) == 0:
if not get_all:
logger.warning(f"Only {len(bots)} bots found on this account")
else:
logger.info(f"Total {len(bots)} bots found on this account")
self.bots.update({bot["handle"]: {"bot": bot} for bot in bots})
return self.bots
logger.info("Succeed to get available bots")
self.bots.update({bot["handle"]: {"bot": bot} for bot in bots})
return self.bots
async def get_chat_history(self, bot: str=None, count: int=None, interval: int=50, cursor: str=None):
chat_bots = {'data': {}, 'cursor': None}
if count != None:
interval = count
if bot == None:
response_json = await self.send_request('gql_POST', 'ChatHistoryListPaginationQuery', {'count': interval, 'cursor': cursor})
if response_json['data']['chats']['pageInfo']['hasNextPage']:
cursor = response_json['data']['chats']['pageInfo']['endCursor']
chat_bots['cursor'] = cursor
else:
chat_bots['cursor'] = None
edges = response_json['data']['chats']['edges']
for edge in edges:
chat = edge['node']
model = bot_map(chat["defaultBotObject"]["displayName"])
if model in chat_bots['data']:
chat_bots['data'][model].append({"chatId": chat["chatId"],"chatCode": chat["chatCode"], "id": chat["id"], "title": chat["title"]})
else:
chat_bots['data'][model] = [{"chatId": chat["chatId"], "chatCode": chat["chatCode"], "id": chat["id"], "title": chat["title"]}]
# Fetch more chats
if count == None:
while response_json['data']['chats']['pageInfo']['hasNextPage']:
response_json = await self.send_request('gql_POST', 'ChatHistoryListPaginationQuery', {'count': interval, 'cursor': cursor})
edges = response_json['data']['chats']['edges']
for edge in edges:
chat = edge['node']
model = bot_map(chat["defaultBotObject"]["displayName"])
if model in chat_bots['data']:
chat_bots['data'][model].append({"chatId": chat["chatId"],"chatCode": chat["chatCode"], "id": chat["id"], "title": chat["title"]})
else:
chat_bots['data'][model] = [{"chatId": chat["chatId"], "chatCode": chat["chatCode"], "id": chat["id"], "title": chat["title"]}]
cursor = response_json['data']['chats']['pageInfo']['endCursor']
chat_bots['cursor'] = cursor
if not response_json['data']['chats']['pageInfo']['hasNextPage']:
chat_bots['cursor'] = None
else:
model = bot.lower().replace(' ', '')
handle = model
for key, value in BOTS_LIST.items():
if model == value:
handle = key
break
response_json = await self.send_request('gql_POST', 'ChatHistoryFilteredListPaginationQuery', {'count': interval, 'handle': handle, 'cursor': cursor})
if response_json['data'] == None and response_json["errors"]:
raise ValueError(
f"Bot {bot} not found. Make sure the bot exists before creating new chat."
)
if response_json['data']['filteredChats']['pageInfo']['hasNextPage']:
cursor = response_json['data']['filteredChats']['pageInfo']['endCursor']
chat_bots['cursor'] = cursor
else:
chat_bots['cursor'] = None
edges = response_json['data']['filteredChats']['edges']
for edge in edges:
chat = edge['node']
try:
if model in chat_bots['data']:
chat_bots['data'][model].append({"chatId": chat["chatId"],"chatCode": chat["chatCode"], "id": chat["id"], "title": chat["title"]})
else:
chat_bots['data'][model] = [{"chatId": chat["chatId"], "chatCode": chat["chatCode"], "id": chat["id"], "title": chat["title"]}]
except Exception as e:
logger.debug(str(e))
pass
# Fetch more chats
if count == None:
while response_json['data']['filteredChats']['pageInfo']['hasNextPage']:
response_json = await self.send_request('gql_POST', 'ChatHistoryFilteredListPaginationQuery', {'count': interval, 'handle': handle, 'cursor': cursor})
edges = response_json['data']['filteredChats']['edges']
for edge in edges:
chat = edge['node']
try:
if model in chat_bots['data']:
chat_bots['data'][model].append({"chatId": chat["chatId"],"chatCode": chat["chatCode"], "id": chat["id"], "title": chat["title"]})
else:
chat_bots['data'][model] = [{"chatId": chat["chatId"], "chatCode": chat["chatCode"], "id": chat["id"], "title": chat["title"]}]
except Exception as e:
logger.debug(str(e))
pass
cursor = response_json['data']['filteredChats']['pageInfo']['endCursor']
chat_bots['cursor'] = cursor
if not response_json['data']['filteredChats']['pageInfo']['hasNextPage']:
chat_bots['cursor'] = None
return chat_bots
async def get_threadData(self, bot: str="", chatCode: str=None, chatId: int=None):
id = None
title = None
if bot not in self.current_thread or len(self.current_thread[bot]) <= 1:
temp = await self.get_chat_history(bot=bot)
self.current_thread[bot] = temp['data'][bot]
if chatCode != None:
for chat in self.current_thread[bot]:
if chat['chatCode'] == chatCode:
chatId = chat['chatId']
id = chat['id']
title = chat['title']
break
elif chatId != None:
for chat in self.current_thread[bot]:
if chat['chatId'] == chatId:
chatCode = chat['chatCode']
id = chat['id']
title = chat['title']
break
return {'chatCode': chatCode, 'chatId': chatId, 'id': id, 'title': title}
async def get_botInfo(self, handle: str):
if handle in REVERSE_BOTS_LIST:
handle = REVERSE_BOTS_LIST[handle]
else:
handle = handle.lower().replace(' ', '')
response_json = await self.send_request('gql_POST', 'HandleBotLandingPageQuery', {'botHandle': handle})
if response_json['data'] == None and response_json["errors"]:
raise ValueError(
f"Bot {handle} not found. Make sure the bot exists before creating new chat."
)
botData = response_json['data']['bot']
data = {
'handle': botData['handle'],
'model':botData['model'],
'supportsFileUpload': botData['supportsFileUpload'],
'messageTimeoutSecs': botData['messageTimeoutSecs'],
'displayMessagePointPrice': botData['messagePointLimit']['displayMessagePointPrice'],
'numRemainingMessages': botData['messagePointLimit']['numRemainingMessages'],
'viewerIsCreator': botData['viewerIsCreator'],
'id': botData['id'],
}
return data
async def retry_message(self, chatCode: str, suggest_replies: bool=False, timeout: int=20):
self.retry_attempts = 3
timer = 0
while None in self.active_messages.values() and len(self.active_messages) > self.MAX_CONCURRENT_MESSAGES:
await asyncio.sleep(0.01)
timer += 0.01
if timer > timeout:
raise RuntimeError("Timed out waiting for other messages to send.")
prompt_md5 = hashlib.md5((chatCode + generate_nonce()).encode()).hexdigest()
self.active_messages[prompt_md5] = None
while self.ws_error:
await asyncio.sleep(0.01)
await self.connect_ws()
variables = {"chatCode": chatCode}
response_json = await self.send_request('gql_POST', 'ChatPageQuery', variables)
if response_json['data'] == None and response_json["errors"]:
raise RuntimeError(f"An unknown error occurred. Raw response data: {response_json}")
elif response_json['data']['viewer']['enableRemixButton'] != True:
raise RuntimeError(f"Retry button is not enabled. Raw response data: {response_json}")
edges = response_json['data']['chatOfCode']['messagesConnection']['edges']
edges.reverse()
chatId = response_json['data']['chatOfCode']['chatId']
title = response_json['data']['chatOfCode']['title']
msgPrice = response_json['data']['chatOfCode']['defaultBotObject']['messagePointLimit']['displayMessagePointPrice']
last_message = edges[0]['node']
if last_message['author'] == 'human':
raise RuntimeError(f"Last message is not from bot. Raw response data: {response_json}")
bot = bot_map(last_message['author'])
status = last_message['state']
if status == 'error_user_message_too_long':
raise RuntimeError(f"Last message is too long. Raw response data: {response_json}")
while status != 'complete':
await asyncio.sleep(0.5)
response_json = await self.send_request('gql_POST', 'ChatPageQuery', variables)
if response_json['data'] == None and response_json["errors"]:
raise RuntimeError(f"An unknown error occurred. Raw response data: {response_json}")
edges = response_json['data']['chatOfCode']['messagesConnection']['edges']
edges.reverse()
last_message = edges[0]['node']
status = last_message['state']
if status == 'error_user_message_too_long':
raise RuntimeError(f"Last message is too long. Raw response data: {response_json}")
bot_message_id = last_message['messageId']
await self.delete_pending_messages(prompt_md5)
response_json = await self.send_request('gql_POST', 'RegenerateMessageMutation', {'messageId': bot_message_id, 'messagePointsDisplayPrice': msgPrice})
if response_json['data'] == None and response_json["errors"]:
logger.error(f"Failed to retry message {bot_message_id} of Thread {chatCode}. Raw response data: {response_json}")
else:
logger.info(f"Message {bot_message_id} of Thread {chatCode} has been retried.")
self.active_messages[chatId] = None
self.message_queues[chatId] = queue.Queue()
last_text = ""
stateChange = False
old_length = 0
suggest_attempts = 3
while True:
try:
ws_data = self.message_queues[chatId].get(timeout=timeout)
except KeyError:
await asyncio.sleep(1)
continue
except queue.Empty:
try:
if self.retry_attempts > 0:
self.retry_attempts -= 1
logger.warning(f"Retrying request {3-self.retry_attempts}/3 times...")
else:
self.retry_attempts = 3
await self.delete_queues(chatId)
raise RuntimeError("Timed out waiting for response.")
await self.connect_ws()
continue
except Exception as e:
raise e
if ws_data["subscription"] == "messageCancelled":
break
if ws_data["subscription"] == "chatTitleUpdated":
title = ws_data["data"]["chatTitleUpdated"]["title"]
if ws_data["subscription"] == "messageAdded" or title:
if ws_data["subscription"] == "messageAdded":
response = ws_data["data"]["messageAdded"]
response["chatCode"] = chatCode
response["chatId"] = chatId
response["title"] = title
response["msgPrice"] = msgPrice
response["response"] = ""
if response["state"] == "error_user_message_too_long":
response["response"] = "Message too long. Please try again!"
yield response
break
if (response["author"] == "pacarana" and response["text"].strip() == last_text.strip()):
response["response"] = ""
elif response["author"] == "pacarana" and (last_text == "" or bot != "web-search"):
response["response"] = f'{response["text"]}\n'
else:
if stateChange == False:
response["response"] = response["text"]
stateChange = True
else:
response["response"] = response["text"][len(last_text):]
if response["state"] == "complete":
if suggest_replies:
new_length = len(response["suggestedReplies"])
if response["bot"]["mayHaveSuggestedReplies"] and (suggest_attempts > 0) and (new_length == 0 or (new_length > old_length and new_length >= 1)):
old_length = len(response["suggestedReplies"])
suggest_attempts -= 1
await asyncio.sleep(1.5)
continue
else:
response["suggestedReplies"] = []
if not response["title"]:
continue
yield response
break
yield response
last_text = response["text"]
await self.delete_queues(chatId)
self.retry_attempts = 3
async def send_message(self, bot: str, message: str, chatId: int=None, chatCode: str=None, msgPrice: int=20, file_path: list=[], suggest_replies: bool=False, timeout: int=20) -> AsyncIterator[dict]:
self.retry_attempts = 3
timer = 0
while None in self.active_messages.values() and len(self.active_messages) > self.MAX_CONCURRENT_MESSAGES:
await asyncio.sleep(0.01)
timer += 0.01
if timer > timeout:
raise RuntimeError("Timed out waiting for other messages to send.")
prompt_md5 = hashlib.md5((message + generate_nonce()).encode()).hexdigest()
self.active_messages[prompt_md5] = None
while self.ws_error:
await asyncio.sleep(0.01)
await self.connect_ws()
bot = bot_map(bot)
attachments = []
if file_path == []:
apiPath = 'gql_POST'
file_form = []
else:
apiPath = 'gql_upload_POST'
file_form, file_size = generate_file(file_path, self.proxies)
if file_size > 50000000:
raise RuntimeError("File size too large. Please try again with a smaller file.")
for i in range(len(file_form)):
attachments.append(f'file{i}')
if (chatId == None and chatCode == None):
try:
variables = {
"chatId": None,
"bot": bot,
"query":message,
"shouldFetchChat": True,
"source":{"sourceType":"chat_input","chatInputMetadata":{"useVoiceRecord":False,}},
"clientNonce": generate_nonce(),
"sdid":"",
"attachments":attachments,
"existingMessageAttachmentsIds":[],
"messagePointsDisplayPrice": msgPrice
}
message_data = await self.send_request(apiPath, 'sendMessageMutation', variables, file_form)
if message_data["data"] != None and message_data["data"]["messageEdgeCreate"]["status"] == "message_points_display_price_mismatch":
msgPrice = message_data["data"]["messageEdgeCreate"]["bot"]["messagePointLimit"]["displayMessagePointPrice"]
variables = {
"chatId": None,
"bot": bot,
"query":message,
"shouldFetchChat": True,
"source":{"sourceType":"chat_input","chatInputMetadata":{"useVoiceRecord":False,}},
"clientNonce": generate_nonce(),
"sdid":"",
"attachments":attachments,
"existingMessageAttachmentsIds":[],
"messagePointsDisplayPrice": msgPrice
}
message_data = await self.send_request(apiPath, 'sendMessageMutation', variables, file_form)
if message_data["data"] == None and message_data["errors"]:
raise ValueError(
f"Bot {bot} not found. Make sure the bot exists before creating new chat."
)
else:
status = message_data['data']['messageEdgeCreate']['status']
if status == 'success' and file_path != []:
for file in file_form:
logger.info(f"File '{file[0]}' uploaded successfully")
elif status == 'unsupported_file_type' and file_path != []:
logger.warning("This file type is not supported. Please try again with a different file.")
elif status == 'reached_limit':
raise RuntimeError(f"Daily limit reached for {bot}.")
elif status == 'too_many_tokens':
raise RuntimeError(f"{message_data['data']['messageEdgeCreate']['statusMessage']}")
elif status in ('rate_limit_exceeded', 'concurrent_messages'):
await self.delete_pending_messages(prompt_md5)
await asyncio.sleep(random.randint(4, 6))
async for chunk in self.send_message(bot, message, chatId, chatCode, msgPrice, file_path, suggest_replies, timeout):
yield chunk
return
logger.info(f"New Thread created | {message_data['data']['messageEdgeCreate']['chat']['chatCode']}")
message_data = message_data['data']['messageEdgeCreate']['chat']
chatCode = message_data['chatCode']
chatId = message_data['chatId']
title = message_data['title']
if bot not in self.current_thread:
self.current_thread[bot] = [{'chatId': chatId, 'chatCode': chatCode, 'id': message_data['id'], 'title': message_data['title']}]
elif self.current_thread[bot] == []:
self.current_thread[bot] = [{'chatId': chatId, 'chatCode': chatCode, 'id': message_data['id'], 'title': message_data['title']}]
else:
self.current_thread[bot].append({'chatId': chatId, 'chatCode': chatCode, 'id': message_data['id'], 'title': message_data['title']})
await self.delete_pending_messages(prompt_md5)
except Exception as e:
await self.delete_pending_messages(prompt_md5)
raise e
else:
chatdata = await self.get_threadData(bot, chatCode, chatId)
chatCode = chatdata['chatCode']
chatId = chatdata['chatId']
title = chatdata['title']
variables = {
'chatId': chatId,
'bot': bot,
'query': message,
'shouldFetchChat': False,
'source': { "sourceType": "chat_input", "chatInputMetadata": {"useVoiceRecord": False}},
"clientNonce": generate_nonce(),
'sdid':"",
'attachments': attachments,
"existingMessageAttachmentsIds":[],
"messagePointsDisplayPrice": msgPrice
}
try:
message_data = await self.send_request(apiPath, 'sendMessageMutation', variables, file_form)
if message_data["data"] != None and message_data["data"]["messageEdgeCreate"]["status"] == "message_points_display_price_mismatch":
msgPrice = message_data["data"]["messageEdgeCreate"]["bot"]["messagePointLimit"]["displayMessagePointPrice"]
variables = {
"chatId": chatId,
"bot": bot,
"query":message,
"shouldFetchChat": True,
"source":{"sourceType":"chat_input","chatInputMetadata":{"useVoiceRecord":False,}},
"clientNonce": generate_nonce(),
"sdid":"",
"attachments":attachments,
"existingMessageAttachmentsIds":[],
"messagePointsDisplayPrice": msgPrice
}
message_data = await self.send_request(apiPath, 'sendMessageMutation', variables, file_form)
if message_data["data"] == None and message_data["errors"]:
raise RuntimeError(f"An unknown error occurred. Raw response data: {message_data}")
else:
status = message_data['data']['messageEdgeCreate']['status']
if status == 'success' and file_path != []:
for file in file_form:
logger.info(f"File '{file[0]}' uploaded successfully")
elif status == 'unsupported_file_type' and file_path != []:
logger.warning("This file type is not supported. Please try again with a different file.")
elif status == 'reached_limit':
raise RuntimeError(f"Daily limit reached for {bot}.")
elif status == 'too_many_tokens':
raise RuntimeError(f"{message_data['data']['messageEdgeCreate']['statusMessage']}")
elif status in ('rate_limit_exceeded', 'concurrent_messages'):
await self.delete_pending_messages(prompt_md5)
await asyncio.sleep(random.randint(4, 6))
async for chunk in self.send_message(bot, message, chatId, chatCode, msgPrice, file_path, suggest_replies, timeout):
yield chunk
return
await self.delete_pending_messages(prompt_md5)
except Exception as e:
await self.delete_pending_messages(prompt_md5)
raise e
self.active_messages[chatId] = None
self.message_queues[chatId] = queue.Queue()
last_text = ""
stateChange = False
old_length = 0
suggest_attempts = 3
while True:
try:
ws_data = self.message_queues[chatId].get(timeout=timeout)
except KeyError:
await asyncio.sleep(1)
continue
except queue.Empty:
try:
if self.retry_attempts > 0:
self.retry_attempts -= 1
logger.warning(f"Retrying request {3-self.retry_attempts}/3 times...")
else:
self.retry_attempts = 3
await self.delete_queues(chatId)
raise RuntimeError("Timed out waiting for response.")
await self.connect_ws()
continue
except Exception as e:
raise e
if ws_data["subscription"] == "messageCancelled":
break
if ws_data["subscription"] == "chatTitleUpdated":
title = ws_data["data"]["chatTitleUpdated"]["title"]
if ws_data["subscription"] == "messageAdded" or title:
if ws_data["subscription"] == "messageAdded":
response = ws_data["data"]["messageAdded"]
response["chatCode"] = chatCode
response["chatId"] = chatId
response["title"] = title
response["msgPrice"] = msgPrice
response["response"] = ""
if response["state"] == "error_user_message_too_long":
response["response"] = "Message too long. Please try again!"
yield response
break
if (response["author"] == "pacarana" and response["text"].strip() == last_text.strip()):
response["response"] = ""
elif response["author"] == "pacarana" and (last_text == "" or bot != "web-search"):
response["response"] = f'{response["text"]}\n'
else:
if stateChange == False:
response["response"] = response["text"]
stateChange = True
else:
response["response"] = response["text"][len(last_text):]
if response["state"] == "complete":
if suggest_replies:
new_length = len(response["suggestedReplies"])
if response["bot"]["mayHaveSuggestedReplies"] and (suggest_attempts > 0) and (new_length == 0 or (new_length > old_length and new_length >= 1)):
old_length = len(response["suggestedReplies"])
suggest_attempts -= 1
await asyncio.sleep(1.5)
continue
else:
response["suggestedReplies"] = []
if not response["title"]:
continue
yield response
break
yield response
last_text = response["text"]
await self.delete_queues(chatId)
self.retry_attempts = 3
async def cancel_message(self, chunk: dict):
variables = {"messageId": chunk["messageId"], "textLength": len(chunk["text"])}
await self.send_request('gql_POST', 'StopMessage_messageCancel_Mutation', variables)
async def chat_break(self, bot: str, chatId: int=None, chatCode: str=None):
bot = bot_map(bot)
chatdata = await self.get_threadData(bot, chatCode, chatId)
chatId = chatdata['chatId']
variables = {'chatId': chatId, 'clientNonce': generate_nonce()}
await self.send_request('gql_POST', 'SendChatBreakMutation', variables)
async def delete_message(self, message_ids):
variables = {'messageIds': message_ids}
await self.send_request('gql_POST', 'DeleteMessageMutation', variables)
async def purge_conversation(self, bot: str, chatId: int=None, chatCode: str=None, count: int=50, del_all: bool=False):
bot = bot_map(bot)
if chatId != None and chatCode == None:
chatdata = await self.get_threadData(bot, chatCode, chatId)
chatCode = chatdata['chatCode']
variables = {'chatCode': chatCode}
response_json = await self.send_request('gql_POST', 'ChatPageQuery', variables)
if response_json['data'] == None and response_json["errors"]:
raise RuntimeError(f"An unknown error occurred. Raw response data: {response_json}")
edges = response_json['data']['chatOfCode']['messagesConnection']['edges']
if del_all == True:
while True:
if len(edges) == 0:
break
message_ids = []
for edge in edges:
message_ids.append(edge['node']['messageId'])
await self.delete_message(message_ids)
await asyncio.sleep(0.5)
response_json = await self.send_request('gql_POST', 'ChatPageQuery', variables)
edges = response_json['data']['chatOfCode']['messagesConnection']['edges']
logger.info(f"Deleted {len(message_ids)} messages of {chatCode}")
else:
num = count
while True:
if len(edges) == 0 or num == 0:
break
message_ids = []
for edge in edges:
message_ids.append(edge['node']['messageId'])
await self.delete_message(message_ids)
await asyncio.sleep(0.5)
num -= len(message_ids)
if len(edges) < num:
response_json = await self.send_request('gql_POST', 'ChatPageQuery', variables)
edges = response_json['data']['chatOfCode']['messagesConnection']['edges']
logger.info(f"Deleted {count-num} messages of {chatCode}")
async def purge_all_conversations(self):
self.current_thread = {}
await self.send_request('gql_POST', 'DeleteUserMessagesMutation', {})
async def delete_chat(self, bot: str, chatId: any=None, chatCode: any=None, del_all: bool=False):
bot = bot_map(bot)
try: