-
Notifications
You must be signed in to change notification settings - Fork 0
/
youchat.py
75 lines (63 loc) · 2.57 KB
/
youchat.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
from seleniumbase import SB
import json
import urllib
import argparse
import time
def you_message(text: str, out_type: str = 'json', timeout: int = 20):
"""Function to send a message and get results from YouChat.com
Args:
text (str): text to send
out_type (str): type of result (json, string). Defaults to 'json'.
timeout (int): timeout in seconds to wait for a result. Defaults to 20.
Returns:
str: response of the message
"""
qoted_text = urllib.parse.quote_plus(text)
result = {}
data = ""
with SB(uc=True, xvfb=True) as sb:
sb.uc_open_with_reconnect(
f"https://you.com/api/streamingSearch?q={qoted_text}&domain=youchat", 4)
timeout_delta = time.time() + timeout
stream_available = False
while time.time() <= timeout_delta:
# START Try to easy solve captcha challenge
try:
sb.uc_gui_click_captcha()
except Exception:
result['error'] = 'Selenium was detected! Try again later. Captcha not solved automaticly.'
try:
sb.assert_text("event: youChatIntent", timeout=8.45)
if 'error' in result:
result.pop('error')
data = sb.get_text("body pre")
break
except Exception:
pass
if time.time() > timeout_delta:
# sb.save_screenshot('sel-timeout.png') # Debug
result['error'] = 'Timeout while getting data from Selenium! Try again later.'
# END Try to easy solve captcha challenge
res_message = ""
for line in data.split("\n"):
if line.startswith("data: {"):
json_data = json.loads(line[5:])
if 'youChatToken' in json_data:
res_message += json_data['youChatToken']
result['generated_text'] = res_message
if out_type == 'json':
return json.dumps(result)
else:
str_res = result['error'] if (
'error' in result) else result['generated_text']
return str_res
def main_cli():
parser = argparse.ArgumentParser()
parser.add_argument('MESSAGE', help="Message to YouChat")
parser.add_argument('-out_type', '-ot', help="Output type (json/string)", default="string")
parser.add_argument(
'-timeout', '-t', help="Timeout to wait response", default=20, type=int)
args = parser.parse_args()
print(you_message(args.MESSAGE, args.out_type, args.timeout))
if __name__ == '__main__':
main_cli()