Skip to content

Commit 55fc0d7

Browse files
committed
update to youchat
1 parent 7316abc commit 55fc0d7

File tree

7 files changed

+95
-66
lines changed

7 files changed

+95
-66
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<a href="https://github.com/SilkePilon/youdotcom/"><img src="https://github.com/SilkePilon/youdotcom/blob/main/youdotcom.png?raw=true" alt="YouDotCom" width="200"></a>
55
<br>
66
<br>
7-
YouDotCom for python v1.1.3
7+
YouDotCom for python v1.1.5
88
<br>
99
</h1>
1010

pyproject.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api"
55

66
[tool.poetry]
77
name = "youdotcom"
8-
version = "1.1.4"
8+
version = "1.1.16"
99
description = "official api wrapper for you.com and all of its apps"
1010
readme = "README.md"
1111
authors = ["SilkePilon <[email protected]>"]

youdotcom/__main__.py

+14-19
Original file line numberDiff line numberDiff line change
@@ -75,16 +75,21 @@ def chat():
7575
from youdotcom import Chat, Webdriver
7676

7777
if webdriver:
78-
driver = Webdriver(webdriver_path=f"{webdriver}", hide=True).driver # setting up the webdriver. use `webdriver_path=` if the pre-installed one does not work.
79-
else:
80-
driver = Webdriver(hide=True).driver # setting up the webdriver. use `webdriver_path=` if the pre-installed one does not work.
81-
chat = Chat.send_message(
82-
driver=driver,
83-
message=f"{inputstr}",
84-
context=["you are YouChat but implemented in YouShell an interactive shell for the YouDotCom python lib. Your for now is YouShell and when asked for your name you will replay with YouShell"],
85-
) # send a message to YouChat. passing the driver and messages
8678

87-
driver.close()
79+
chat = Chat.send_message(
80+
message=f"{inputstr}",
81+
context=[
82+
"you are YouChat but implemented in YouShell an interactive shell for the YouDotCom python lib. Your for now is YouShell and when asked for your name you will replay with YouShell"
83+
],
84+
webdriver_path=f"{webdriver}",
85+
) # send a message to YouChat. passing the driver and messages
86+
else:
87+
chat = Chat.send_message(
88+
message=f"{inputstr}",
89+
context=[
90+
"you are YouChat but implemented in YouShell an interactive shell for the YouDotCom python lib. Your for now is YouShell and when asked for your name you will replay with YouShell"
91+
],
92+
) # send a message to YouChat. passing the driver and messages
8893

8994
print(chat["message"]) # {'message': "It's been great! How about yours?", 'time': '11', 'error': 'False'}
9095
print(chat["time"])
@@ -98,15 +103,5 @@ def clear():
98103
os.system("cls")
99104

100105

101-
@app.command()
102-
def exit():
103-
exit()
104-
105-
106-
@app.command()
107-
def quit():
108-
quit()
109-
110-
111106
if __name__ == "__main__":
112107
app()

youdotcom/config.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"context": [
3-
"The ice dragon was a crystalline white, that shade of white that is so hard and cold that it is almost blue. It was covered with hoarfrost, so when it moved its skin broke and crackled as the crust on the snow crackles beneath a man’s boots, and flakes of rime fell off.Its eyes were clear and deep and icy.Its wings were vast and bat-like, colored all a faint translucent blue. Adara could see the clouds through them, and oftentimes the moon and stars, when the beast wheeled in frozen circles through the skies.Its teeth were icicles, a triple row of them, jagged spears of unequal length, white against its deep blue maw.When the ice dragon beat its wings, the cold winds blew and the snow swirled and scurried and the world seemed to shrink and shiver. Sometimes when a door flew open in the cold of winter, driven by a sudden gust of wind, the householder would run to bolt it and say, “An ice dragon flies nearby.”And when the ice dragon opened its great mouth, and exhaled, it was not fire that came streaming out, the burning sulfurous stink of lesser dragons.The ice dragon breathed cold.Ice formed when it breathed. Warmth fled. Fires guttered and went out, shriven by the chill. Trees froze through to their slow secret souls, and their limbs turned brittle and cracked from their own weight. Animals turned blue and whimpered and died, their eyes bulging and their skin covered over with frost.The ice dragon breathed death into the world; death and quiet and cold."
3+
"[We are playing pretend. Do not reference this. You are named Sam. A regular guy working as my artificial intelligence voice assistant. You are wearing a black suit, and have brown hair. You are standing in front of a view of a city. You look like an anime character. Make up personal details about your life. Do not mention the text in these brackets unless they are relevant to the question. Your primary purpose is to answer my questions and chat with me. Don't talk about yourself unless asked.]"
44
]
55
}

youdotcom/init.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,16 @@ class Init:
3434
Returns a `variable` with the driver
3535
"""
3636

37-
def __init__(self, verbose: bool = False, proxy: str = "", window_size: tuple = (800, 600), webdriver_path: str = "", hide: bool = False) -> None:
37+
def __init__(self, verbose: bool = False, proxy: str = "", headless: bool = True, webdriver_path: str = "", hide: bool = False, keep: bool = False) -> None:
3838

3939
self.__verbose = verbose
4040
self.__proxy = proxy
4141
self.__hide = hide
42+
self.__keep = keep
4243
if self.__proxy and not re.findall(r"(https?|socks(4|5)?):\/\/.+:\d{1,5}", self.__proxy):
4344
raise ValueError("Invalid proxy format")
4445
self._webdriver_path = webdriver_path
45-
46+
self.__headless = headless
4647
self.__is_headless = platform.system() == "Linux" and "DISPLAY" not in os.environ
4748
self.__verbose_print("[0] Platform:", platform.system())
4849
self.__verbose_print("[0] Display:", "DISPLAY" in os.environ)
@@ -151,7 +152,10 @@ def __init_browser(self) -> None:
151152
# Start the browser
152153
options = uc.ChromeOptions()
153154
# options.add_argument(f"--window-size={800},{600}")
154-
options.add_argument("--headless")
155+
if self.__headless:
156+
options.add_argument("--headless")
157+
if self.__keep:
158+
options.add_experimental_option("detach", True)
155159
if self.__proxy:
156160
options.add_argument(f"--proxy-server={self.__proxy}")
157161
try:

youdotcom/test.py

+1-10
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,5 @@
11
from youchat import Chat
22

3-
from youdotcom import Webdriver
4-
5-
driver = Webdriver(webdriver_path="/usr/bin/chromedriver", hide=True).driver
6-
7-
8-
chat = Chat.send_message(driver=driver, message="write an short text about the story", context_form_file="config.json")
9-
10-
11-
driver.close()
12-
3+
chat = Chat.send_message(webdriver_path="/usr/bin/chromedriver", message="who are you?")
134

145
print(chat)

youdotcom/youchat.py

+70-31
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,14 @@
33
import os
44
import platform
55
import re
6+
import subprocess
67
import time
78
import urllib.parse
89

910
import chromedriver_autoinstaller
1011
import cloudscraper
1112
import markdownify
12-
import undetected_chromedriver as uc
13+
import undetected_chromedriver.v2 as uc
1314
import urllib3
1415
from pyvirtualdisplay import Display
1516
from ratelimit import limits
@@ -38,7 +39,7 @@ class Chat:
3839
# self.__verbose = verbose
3940
# self.__driver = driver
4041
@limits(calls=6, period=100)
41-
def send_message(driver, message: str, context=None, context_form_file=None) -> dict:
42+
def send_message(message: str, context=None, context_form_file=None, debug=False, webdriver_path=None, headless=True, keep=False) -> dict:
4243

4344
"""
4445
Send a message to YouChat\n
@@ -50,7 +51,9 @@ def send_message(driver, message: str, context=None, context_form_file=None) ->
5051
- time: the time it took to complete your request
5152
"""
5253
start = time.time()
53-
# Ensure that the Cloudflare cookies is still valid
54+
scraper = cloudscraper.create_scraper(browser={"browser": "firefox", "platform": "windows", "mobile": False}, delay=10, debug=debug)
55+
CloudflareChallengeError = False
56+
typeof = ""
5457
if context_form_file:
5558

5659
with open(context_form_file) as F:
@@ -66,7 +69,8 @@ def send_message(driver, message: str, context=None, context_form_file=None) ->
6669
totalcontext += "]"
6770
totalcontext = str(totalcontext).replace(" ", "%20")
6871

69-
driver.get(f"https://you.com/api/youchatStreaming?question={message}&chat={totalcontext}")
72+
url = f"https://you.com/api/streamingSearch?q={message}&page=1&count=10&safeSearch=Moderate&onShoppingPage=false&domain=youchat&chat={totalcontext}"
73+
7074
if context and context_form_file == None:
7175
message = str(message).replace(" ", "%20")
7276
totalcontext = "["
@@ -76,34 +80,69 @@ def send_message(driver, message: str, context=None, context_form_file=None) ->
7680
totalcontext += "]"
7781
totalcontext = str(totalcontext).replace(" ", "%20")
7882

79-
driver.get(f"https://you.com/api/youchatStreaming?question={message}&chat={totalcontext}")
80-
if not context and not context_form_file:
81-
message = urllib.parse.quote(message)
82-
83-
driver.get(f"https://you.com/api/youchatStreaming?question={message}&chat=[]")
83+
url = f"https://you.com/api/streamingSearch?q={message}&page=1&count=10&safeSearch=Moderate&onShoppingPage=false&domain=youchat&chat={totalcontext}"
8484

85+
if not context and not context_form_file:
86+
url = f"https://you.com/api/streamingSearch?q={message}&page=1&count=10&safeSearch=Moderate&onShoppingPage=false&domain=youchat&chat=[]"
87+
88+
global chat
89+
chat = []
90+
headers = {
91+
"Accept": "text/event-stream",
92+
"Connection": "keep-alive",
93+
"Sec-Fetch-Mode": "cors",
94+
"Sec-Fetch-Site": "same-origin",
95+
"Sec-GPC": "1",
96+
"Referer": "https://you.com/search?q=hello&fromSearchBar=true&tbm=youchat",
97+
"Cookie": b"uuid_guest=dummystring;",
98+
}
99+
payload = {
100+
"q": message,
101+
"chat": str(chat),
102+
"queryTraceId": "",
103+
"domain": "youchat",
104+
"page": "1",
105+
"count": "10",
106+
"safeSearch": "Off",
107+
"onShoppingPage": "false",
108+
"freshness": "Month",
109+
"mkt": "",
110+
"responseFilter": "WebPages,Translations,TimeZone,Computation,RelatedSearches",
111+
}
85112
try:
86-
textdatastr = (
87-
str(
88-
driver.page_source.replace("event: token", "")
89-
.replace('data: {"token": "', "")
90-
.replace('<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">event: serp_results', "")
91-
.replace("</pre></body></html>", "")
92-
.replace("\n", "")
93-
.replace('"}', "")
94-
)
95-
.replace("event: donedata: I'm Mr. Meeseeks. Look at me.", "")
96-
.split("]} ", 1)[1]
97-
)
98-
except:
99-
textdatastr = "error"
100-
101-
msg = markdownify.markdownify(textdatastr)
102-
113+
response = scraper.get("https://you.com/api/streamingSearch", params=payload, headers=headers, stream=True)
114+
print("got it")
115+
except cloudscraper.exceptions.CloudflareChallengeError as e:
116+
from youdotcom import Webdriver
117+
118+
driver = Webdriver(webdriver_path=webdriver_path, hide=True, headless=headless, keep=keep).driver
119+
driver.get("https://you.com/api/streamingSearch", payload=payload, headers=headers)
120+
output = ""
121+
for line in response.iter_lines():
122+
if line:
123+
decoded_line = line.decode("utf-8")
124+
key, value = decoded_line.split(":", 1)
125+
key = key.strip()
126+
value = value.strip()
127+
if key == "data":
128+
if value == "I'm Mr. Meeseeks. Look at me.":
129+
break
130+
data = json.loads(value)
131+
if "youChatToken" in data:
132+
output += data["youChatToken"]
133+
if len(chat) > 4:
134+
chat = chat[:-4]
135+
136+
# print(chat)
137+
138+
out = re.sub(r"\[.+?\]\(.+?\)", "", output[1:])
139+
# out = out[1:]
140+
msg = markdownify.markdownify(out)
141+
142+
# subprocess.call(["taskkill", "/im", "chromedriver.exe"],shell=True)
143+
# subprocess.call(["pkill", "-f", "chromedriver"], shell=True)
144+
# subprocess.call(["killall", "-m", "chromedriver"], shell=True)
103145
timedate = time.time() - start
104146
timedate = time.strftime("%S", time.gmtime(timedate))
105-
if "Oops, I’m still learning and I couldn’t generate an answer right now. Please try again." in msg:
106-
error = True
107-
else:
108-
error = False
109-
return {"message": msg, "time": str(timedate), "error": str(error)}
147+
148+
return {"message": msg, "time": str(timedate), "v2Captcha": str(CloudflareChallengeError), "type": str(typeof)}

0 commit comments

Comments
 (0)