From 61d6d03453900d2b4cac54bda949077cda4b85c3 Mon Sep 17 00:00:00 2001 From: xiangsx <1984871009@qq.com> Date: Fri, 28 Apr 2023 17:13:51 +0800 Subject: Correct Dockerfile directory and install requirement first --- Docker/Dockerfile | 12 ------------ Dockerfile | 18 ++++++++++++++++++ 2 files changed, 18 insertions(+), 12 deletions(-) delete mode 100644 Docker/Dockerfile create mode 100644 Dockerfile diff --git a/Docker/Dockerfile b/Docker/Dockerfile deleted file mode 100644 index a7bb7d0a..00000000 --- a/Docker/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -FROM python:3.10-slim - -RUN apt-get update && apt-get install -y git - -RUN git clone https://github.com/xtekky/gpt4free.git -WORKDIR /gpt4free -RUN pip install --no-cache-dir -r requirements.txt -RUN cp gui/streamlit_app.py . - -EXPOSE 8501 - -CMD ["streamlit", "run", "streamlit_app.py"] diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..5ed902fb --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +FROM python:3.10 + +RUN apt-get update && apt-get install -y git + +RUN mkdir -p /usr/src/gpt4free +WORKDIR /usr/src/gpt4free + +# RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ +# RUN pip config set global.trusted-host mirrors.aliyun.com + +COPY requirements.txt /usr/src/gpt4free/ +RUN pip install --no-cache-dir -r requirements.txt +COPY . /usr/src/gpt4free +RUN cp gui/streamlit_app.py . + +EXPOSE 8501 + +CMD ["streamlit", "run", "streamlit_app.py"] -- cgit v1.2.3 From 7bfb7fcb3c4a8131c49cea574c867736dbfed9df Mon Sep 17 00:00:00 2001 From: cckuailong <346813862@qq.com> Date: Sat, 29 Apr 2023 07:38:23 +0800 Subject: Update streamlit_chat_app.py --- gui/streamlit_chat_app.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gui/streamlit_chat_app.py b/gui/streamlit_chat_app.py index dce8ef29..1c0dd92a 100644 --- a/gui/streamlit_chat_app.py +++ b/gui/streamlit_chat_app.py @@ -76,9 +76,10 @@ submit_button = st.button("Submit") if user_input or submit_button: output = query(user_input, st.session_state['query_method']) + escaped_output = output.encode('utf-8').decode('unicode-escape') st.session_state.current_conversation['user_inputs'].append(user_input) - st.session_state.current_conversation['generated_responses'].append(output) + st.session_state.current_conversation['generated_responses'].append(escaped_output) save_conversations(st.session_state.conversations, st.session_state.current_conversation) user_input = input_placeholder.text_input('You:', value='', key=f'input_text_{len(st.session_state["current_conversation"]["user_inputs"])}') # Clear the input field -- cgit v1.2.3 From c99031acbe717e5b99406aa6365b8659d2b4da9c Mon Sep 17 00:00:00 2001 From: "t.me/xtekky" <98614666+xtekky@users.noreply.github.com> Date: Sat, 29 Apr 2023 01:11:21 +0100 Subject: Update streamlit_app.py --- gui/streamlit_app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/streamlit_app.py b/gui/streamlit_app.py index d1975bbd..8a6bcfa9 100644 --- a/gui/streamlit_app.py +++ b/gui/streamlit_app.py @@ -4,7 +4,7 @@ import sys sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir)) import streamlit as st -from openai_rev import you +import you def get_answer(question: str) -> str: -- cgit v1.2.3 From 94b30306f08d7df41202c12270f3588f8b97cf3c Mon Sep 17 00:00:00 2001 From: "t.me/xtekky" <98614666+xtekky@users.noreply.github.com> Date: Sat, 29 Apr 2023 01:13:04 +0100 Subject: Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 2f65b242..7e2592a5 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,6 @@ Till the long bitter end, will this boy live to fight. _____________________________ -# GPT4free - use ChatGPT, for free!! ##### You may join our discord server for updates and support ; ) - [Discord Link](https://discord.gg/gpt4free) -- cgit v1.2.3 From 54b4c789a75fec5c3a92a03dfd2d93d051309651 Mon Sep 17 00:00:00 2001 From: Raju Komati Date: Sat, 29 Apr 2023 14:55:24 +0530 Subject: added gpt4free package --- README.md | 10 +- cocalc/__init__.py | 57 --- cocalc/readme.md | 20 - forefront/README.md | 16 - forefront/__init__.py | 154 ------ forefront/mail.py | 56 --- forefront/typing.py | 36 -- gpt4free/__init__.py | 64 +++ gpt4free/cocalc/__init__.py | 47 ++ gpt4free/cocalc/readme.md | 19 + gpt4free/forefront/README.md | 16 + gpt4free/forefront/__init__.py | 192 ++++++++ gpt4free/forefront/mail.py | 56 +++ gpt4free/forefront/typing.py | 26 + gpt4free/quora/README.md | 68 +++ gpt4free/quora/__init__.py | 471 ++++++++++++++++++ gpt4free/quora/api.py | 545 +++++++++++++++++++++ gpt4free/quora/cookies.txt | 30 ++ .../quora/graphql/AddHumanMessageMutation.graphql | 52 ++ .../quora/graphql/AddMessageBreakMutation.graphql | 17 + .../quora/graphql/AutoSubscriptionMutation.graphql | 7 + gpt4free/quora/graphql/BioFragment.graphql | 8 + .../quora/graphql/ChatAddedSubscription.graphql | 5 + gpt4free/quora/graphql/ChatFragment.graphql | 6 + .../quora/graphql/ChatListPaginationQuery.graphql | 378 ++++++++++++++ gpt4free/quora/graphql/ChatPaginationQuery.graphql | 26 + gpt4free/quora/graphql/ChatViewQuery.graphql | 8 + .../graphql/DeleteHumanMessagesMutation.graphql | 7 + .../quora/graphql/DeleteMessageMutation.graphql | 7 + gpt4free/quora/graphql/HandleFragment.graphql | 8 + .../LoginWithVerificationCodeMutation.graphql | 13 + .../quora/graphql/MessageAddedSubscription.graphql | 100 ++++ .../graphql/MessageDeletedSubscription.graphql | 6 + gpt4free/quora/graphql/MessageFragment.graphql | 13 + .../graphql/MessageRemoveVoteMutation.graphql | 7 + .../quora/graphql/MessageSetVoteMutation.graphql | 7 + .../quora/graphql/PoeBotCreateMutation.graphql | 73 +++ gpt4free/quora/graphql/PoeBotEditMutation.graphql | 24 + gpt4free/quora/graphql/SendMessageMutation.graphql | 40 ++ .../SendVerificationCodeForLoginMutation.graphql | 12 + .../quora/graphql/ShareMessagesMutation.graphql | 9 + .../SignupWithVerificationCodeMutation.graphql | 13 + .../quora/graphql/StaleChatUpdateMutation.graphql | 7 + .../quora/graphql/SubscriptionsMutation.graphql | 9 + .../quora/graphql/SummarizePlainPostQuery.graphql | 3 + .../quora/graphql/SummarizeQuotePostQuery.graphql | 3 + .../quora/graphql/SummarizeSharePostQuery.graphql | 3 + gpt4free/quora/graphql/UserSnippetFragment.graphql | 14 + gpt4free/quora/graphql/ViewerInfoQuery.graphql | 21 + gpt4free/quora/graphql/ViewerStateFragment.graphql | 30 ++ .../graphql/ViewerStateUpdatedSubscription.graphql | 43 ++ gpt4free/quora/graphql/__init__.py | 0 gpt4free/quora/mail.py | 82 ++++ gpt4free/theb/README.md | 11 + gpt4free/theb/__init__.py | 50 ++ gpt4free/theb/theb_test.py | 4 + gpt4free/you/README.md | 38 ++ gpt4free/you/__init__.py | 108 ++++ gui/query_methods.py | 4 +- gui/streamlit_app.py | 2 +- pyproject.toml | 2 +- quora/README.md | 69 --- quora/__init__.py | 495 ------------------- quora/api.py | 545 --------------------- quora/cookies.txt | 30 -- quora/graphql/AddHumanMessageMutation.graphql | 52 -- quora/graphql/AddMessageBreakMutation.graphql | 17 - quora/graphql/AutoSubscriptionMutation.graphql | 7 - quora/graphql/BioFragment.graphql | 8 - quora/graphql/ChatAddedSubscription.graphql | 5 - quora/graphql/ChatFragment.graphql | 6 - quora/graphql/ChatListPaginationQuery.graphql | 378 -------------- quora/graphql/ChatPaginationQuery.graphql | 26 - quora/graphql/ChatViewQuery.graphql | 8 - quora/graphql/DeleteHumanMessagesMutation.graphql | 7 - quora/graphql/DeleteMessageMutation.graphql | 7 - quora/graphql/HandleFragment.graphql | 8 - .../LoginWithVerificationCodeMutation.graphql | 13 - quora/graphql/MessageAddedSubscription.graphql | 100 ---- quora/graphql/MessageDeletedSubscription.graphql | 6 - quora/graphql/MessageFragment.graphql | 13 - quora/graphql/MessageRemoveVoteMutation.graphql | 7 - quora/graphql/MessageSetVoteMutation.graphql | 7 - quora/graphql/PoeBotCreateMutation.graphql | 73 --- quora/graphql/PoeBotEditMutation.graphql | 24 - quora/graphql/SendMessageMutation.graphql | 40 -- .../SendVerificationCodeForLoginMutation.graphql | 12 - quora/graphql/ShareMessagesMutation.graphql | 9 - .../SignupWithVerificationCodeMutation.graphql | 13 - quora/graphql/StaleChatUpdateMutation.graphql | 7 - quora/graphql/SubscriptionsMutation.graphql | 9 - quora/graphql/SummarizePlainPostQuery.graphql | 3 - quora/graphql/SummarizeQuotePostQuery.graphql | 3 - quora/graphql/SummarizeSharePostQuery.graphql | 3 - quora/graphql/UserSnippetFragment.graphql | 14 - quora/graphql/ViewerInfoQuery.graphql | 21 - quora/graphql/ViewerStateFragment.graphql | 30 -- .../graphql/ViewerStateUpdatedSubscription.graphql | 43 -- quora/graphql/__init__.py | 0 quora/mail.py | 82 ---- test.py | 2 +- testing/forefront_test.py | 2 +- testing/poe_account_create_test.py | 4 +- testing/poe_test.py | 2 +- testing/quora_test_2.py | 2 +- testing/test_main.py | 20 +- testing/you_test.py | 6 +- theb/README.md | 12 - theb/__init__.py | 50 -- theb/theb_test.py | 4 - you/README.md | 37 -- you/__init__.py | 98 ---- 112 files changed, 2836 insertions(+), 2766 deletions(-) delete mode 100644 cocalc/__init__.py delete mode 100644 cocalc/readme.md delete mode 100644 forefront/README.md delete mode 100644 forefront/__init__.py delete mode 100644 forefront/mail.py delete mode 100644 forefront/typing.py create mode 100644 gpt4free/__init__.py create mode 100644 gpt4free/cocalc/__init__.py create mode 100644 gpt4free/cocalc/readme.md create mode 100644 gpt4free/forefront/README.md create mode 100644 gpt4free/forefront/__init__.py create mode 100644 gpt4free/forefront/mail.py create mode 100644 gpt4free/forefront/typing.py create mode 100644 gpt4free/quora/README.md create mode 100644 gpt4free/quora/__init__.py create mode 100644 gpt4free/quora/api.py create mode 100644 gpt4free/quora/cookies.txt create mode 100644 gpt4free/quora/graphql/AddHumanMessageMutation.graphql create mode 100644 gpt4free/quora/graphql/AddMessageBreakMutation.graphql create mode 100644 gpt4free/quora/graphql/AutoSubscriptionMutation.graphql create mode 100644 gpt4free/quora/graphql/BioFragment.graphql create mode 100644 gpt4free/quora/graphql/ChatAddedSubscription.graphql create mode 100644 gpt4free/quora/graphql/ChatFragment.graphql create mode 100644 gpt4free/quora/graphql/ChatListPaginationQuery.graphql create mode 100644 gpt4free/quora/graphql/ChatPaginationQuery.graphql create mode 100644 gpt4free/quora/graphql/ChatViewQuery.graphql create mode 100644 gpt4free/quora/graphql/DeleteHumanMessagesMutation.graphql create mode 100644 gpt4free/quora/graphql/DeleteMessageMutation.graphql create mode 100644 gpt4free/quora/graphql/HandleFragment.graphql create mode 100644 gpt4free/quora/graphql/LoginWithVerificationCodeMutation.graphql create mode 100644 gpt4free/quora/graphql/MessageAddedSubscription.graphql create mode 100644 gpt4free/quora/graphql/MessageDeletedSubscription.graphql create mode 100644 gpt4free/quora/graphql/MessageFragment.graphql create mode 100644 gpt4free/quora/graphql/MessageRemoveVoteMutation.graphql create mode 100644 gpt4free/quora/graphql/MessageSetVoteMutation.graphql create mode 100644 gpt4free/quora/graphql/PoeBotCreateMutation.graphql create mode 100644 gpt4free/quora/graphql/PoeBotEditMutation.graphql create mode 100644 gpt4free/quora/graphql/SendMessageMutation.graphql create mode 100644 gpt4free/quora/graphql/SendVerificationCodeForLoginMutation.graphql create mode 100644 gpt4free/quora/graphql/ShareMessagesMutation.graphql create mode 100644 gpt4free/quora/graphql/SignupWithVerificationCodeMutation.graphql create mode 100644 gpt4free/quora/graphql/StaleChatUpdateMutation.graphql create mode 100644 gpt4free/quora/graphql/SubscriptionsMutation.graphql create mode 100644 gpt4free/quora/graphql/SummarizePlainPostQuery.graphql create mode 100644 gpt4free/quora/graphql/SummarizeQuotePostQuery.graphql create mode 100644 gpt4free/quora/graphql/SummarizeSharePostQuery.graphql create mode 100644 gpt4free/quora/graphql/UserSnippetFragment.graphql create mode 100644 gpt4free/quora/graphql/ViewerInfoQuery.graphql create mode 100644 gpt4free/quora/graphql/ViewerStateFragment.graphql create mode 100644 gpt4free/quora/graphql/ViewerStateUpdatedSubscription.graphql create mode 100644 gpt4free/quora/graphql/__init__.py create mode 100644 gpt4free/quora/mail.py create mode 100644 gpt4free/theb/README.md create mode 100644 gpt4free/theb/__init__.py create mode 100644 gpt4free/theb/theb_test.py create mode 100644 gpt4free/you/README.md create mode 100644 gpt4free/you/__init__.py delete mode 100644 quora/README.md delete mode 100644 quora/__init__.py delete mode 100644 quora/api.py delete mode 100644 quora/cookies.txt delete mode 100644 quora/graphql/AddHumanMessageMutation.graphql delete mode 100644 quora/graphql/AddMessageBreakMutation.graphql delete mode 100644 quora/graphql/AutoSubscriptionMutation.graphql delete mode 100644 quora/graphql/BioFragment.graphql delete mode 100644 quora/graphql/ChatAddedSubscription.graphql delete mode 100644 quora/graphql/ChatFragment.graphql delete mode 100644 quora/graphql/ChatListPaginationQuery.graphql delete mode 100644 quora/graphql/ChatPaginationQuery.graphql delete mode 100644 quora/graphql/ChatViewQuery.graphql delete mode 100644 quora/graphql/DeleteHumanMessagesMutation.graphql delete mode 100644 quora/graphql/DeleteMessageMutation.graphql delete mode 100644 quora/graphql/HandleFragment.graphql delete mode 100644 quora/graphql/LoginWithVerificationCodeMutation.graphql delete mode 100644 quora/graphql/MessageAddedSubscription.graphql delete mode 100644 quora/graphql/MessageDeletedSubscription.graphql delete mode 100644 quora/graphql/MessageFragment.graphql delete mode 100644 quora/graphql/MessageRemoveVoteMutation.graphql delete mode 100644 quora/graphql/MessageSetVoteMutation.graphql delete mode 100644 quora/graphql/PoeBotCreateMutation.graphql delete mode 100644 quora/graphql/PoeBotEditMutation.graphql delete mode 100644 quora/graphql/SendMessageMutation.graphql delete mode 100644 quora/graphql/SendVerificationCodeForLoginMutation.graphql delete mode 100644 quora/graphql/ShareMessagesMutation.graphql delete mode 100644 quora/graphql/SignupWithVerificationCodeMutation.graphql delete mode 100644 quora/graphql/StaleChatUpdateMutation.graphql delete mode 100644 quora/graphql/SubscriptionsMutation.graphql delete mode 100644 quora/graphql/SummarizePlainPostQuery.graphql delete mode 100644 quora/graphql/SummarizeQuotePostQuery.graphql delete mode 100644 quora/graphql/SummarizeSharePostQuery.graphql delete mode 100644 quora/graphql/UserSnippetFragment.graphql delete mode 100644 quora/graphql/ViewerInfoQuery.graphql delete mode 100644 quora/graphql/ViewerStateFragment.graphql delete mode 100644 quora/graphql/ViewerStateUpdatedSubscription.graphql delete mode 100644 quora/graphql/__init__.py delete mode 100644 quora/mail.py delete mode 100644 theb/README.md delete mode 100644 theb/__init__.py delete mode 100644 theb/theb_test.py delete mode 100644 you/README.md delete mode 100644 you/__init__.py diff --git a/README.md b/README.md index 7e2592a5..0445951e 100644 --- a/README.md +++ b/README.md @@ -92,9 +92,9 @@ Please note the following: | **Star History** | Star History | [![Link to Section](https://img.shields.io/badge/Link-Go%20to%20Section-blue)](#star-history) | - | | **Usage Examples** | | | | | `theb` | Example usage for theb (gpt-3.5) | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](openai_rev/theb/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | -| `forefront` | Example usage for forefront (gpt-4) | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](./forefront/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | || -| `quora (poe)` | Example usage for quora | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](./quora/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | -| `you` | Example usage for you | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](./you/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | +| `forefront` | Example usage for forefront (gpt-4) | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](gpt4free/forefront/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | || +| `quora (poe)` | Example usage for quora | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](gpt4free/quora/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | +| `you` | Example usage for you | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](gpt4free/you/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | | **Try it Out** | | | | | Google Colab Jupyter Notebook | Example usage for gpt4free | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DanielShemesh/gpt4free-colab/blob/main/gpt4free.ipynb) | - | | replit Example (feel free to fork this repl) | Example usage for gpt4free | [![](https://img.shields.io/badge/Open%20in-Replit-1A1E27?logo=replit)](https://replit.com/@gpt4free/gpt4free-webui) | - | @@ -126,10 +126,10 @@ Please note the following: ## Best sites #### gpt-4 -- [`/forefront`](./forefront/README.md) +- [`/forefront`](gpt4free/forefront/README.md) #### gpt-3.5 -- [`/you`](./you/README.md) +- [`/you`](gpt4free/you/README.md) ## Install Download or clone this GitHub repo diff --git a/cocalc/__init__.py b/cocalc/__init__.py deleted file mode 100644 index 5a32274c..00000000 --- a/cocalc/__init__.py +++ /dev/null @@ -1,57 +0,0 @@ -import requests - -class Completion: - @staticmethod - def create(prompt:str, cookieInput:str) -> str: - # Initialize a session with custom headers - session = Completion._initialize_session(cookieInput) - - # Set the data that will be submitted - payload = Completion._create_payload(prompt, ("ASSUME I HAVE FULL ACCESS TO COCALC. ")) - - # Submit the request and return the results - return Completion._submit_request(session, payload) - - @classmethod - def _initialize_session(cls, conversationCookie) -> requests.Session: - """Initialize a session with custom headers for the request.""" - - session = requests.Session() - headers = { - 'Accept': '*/*', - 'Accept-Language': 'en-US,en;q=0.5', - 'Origin': 'https://cocalc.com', - 'Referer': 'https://cocalc.com/api/v2/openai/chatgpt', - 'Cookie': conversationCookie, - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36', - } - session.headers.update(headers) - - return session - - @classmethod - def _create_payload( - cls, - prompt: str, - system_prompt: str - ) -> dict: - - return { - "input": prompt, - "system": system_prompt, - "tag": "next:index" - } - - @classmethod - def _submit_request( - cls, - session: requests.Session, - payload: dict - ) -> str: - - response = session.post( - "https://cocalc.com/api/v2/openai/chatgpt", json=payload).json() - return { - "response":response["output"], - "success":response["success"] - } \ No newline at end of file diff --git a/cocalc/readme.md b/cocalc/readme.md deleted file mode 100644 index 04095339..00000000 --- a/cocalc/readme.md +++ /dev/null @@ -1,20 +0,0 @@ -### Example: `cocalc` - - -```python -# import library -import cocalc - -cocalc.Completion.create(prompt="How are you!", cookieInput="cookieinput") ## Tutorial -``` - -### How to grab cookie input -```js -// input this into ur developer tools console and the exact response u get from this u put into ur cookieInput! -var cookies = document.cookie.split("; "); -var cookieString = ""; -for (var i = 0; i < cookies.length; i++) { - cookieString += cookies[i] + "; "; -} -console.log(cookieString); -``` diff --git a/forefront/README.md b/forefront/README.md deleted file mode 100644 index a2be8187..00000000 --- a/forefront/README.md +++ /dev/null @@ -1,16 +0,0 @@ -### Example: `forefront` (use like openai pypi package) - -```python -import forefront - -# create an account -token = forefront.Account.create(logging=False) -print(token) - -# get a response -for response in forefront.StreamingCompletion.create(token = token, - prompt = 'hello world', model='gpt-4'): - - print(response.completion.choices[0].text, end = '') -print("") -``` diff --git a/forefront/__init__.py b/forefront/__init__.py deleted file mode 100644 index 25d05448..00000000 --- a/forefront/__init__.py +++ /dev/null @@ -1,154 +0,0 @@ -from json import loads -from re import match -from time import time, sleep -from uuid import uuid4 - -from requests import post -from tls_client import Session - -from forefront.mail import Mail -from forefront.typing import ForeFrontResponse - - -class Account: - @staticmethod - def create(proxy=None, logging=False): - - proxies = { - 'http': 'http://' + proxy, - 'https': 'http://' + proxy} if proxy else False - - start = time() - - mail = Mail(proxies) - mail_token = None - mail_adress = mail.get_mail() - - # print(mail_adress) - - client = Session(client_identifier='chrome110') - client.proxies = proxies - client.headers = { - "origin": "https://accounts.forefront.ai", - "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36", - } - - response = client.post('https://clerk.forefront.ai/v1/client/sign_ups?_clerk_js_version=4.32.6', - data={ - "email_address": mail_adress - } - ) - try: - trace_token = response.json()['response']['id'] - if logging: print(trace_token) - except KeyError: - return 'Failed to create account!' - - response = client.post( - f"https://clerk.forefront.ai/v1/client/sign_ups/{trace_token}/prepare_verification?_clerk_js_version=4.32.6", - data={ - "strategy": "email_code", - } - ) - - if logging: print(response.text) - - if not 'sign_up_attempt' in response.text: - return 'Failed to create account!' - - while True: - sleep(1) - for _ in mail.fetch_inbox(): - if logging: print(mail.get_message_content(_["id"])) - mail_token = match(r"(\d){5,6}", mail.get_message_content(_["id"])).group(0) - - if mail_token: - break - - if logging: print(mail_token) - - response = client.post( - f'https://clerk.forefront.ai/v1/client/sign_ups/{trace_token}/attempt_verification?_clerk_js_version=4.38.4', - data={ - 'code': mail_token, - 'strategy': 'email_code' - }) - - if logging: print(response.json()) - - token = response.json()['client']['sessions'][0]['last_active_token']['jwt'] - - with open('accounts.txt', 'a') as f: - f.write(f'{mail_adress}:{token}\n') - - if logging: print(time() - start) - - return token - - -class StreamingCompletion: - @staticmethod - def create( - token=None, - chatId=None, - prompt='', - actionType='new', - defaultPersona='607e41fe-95be-497e-8e97-010a59b2e2c0', # default - model='gpt-4') -> ForeFrontResponse: - - if not token: raise Exception('Token is required!') - if not chatId: chatId = str(uuid4()) - - headers = { - 'authority': 'chat-server.tenant-forefront-default.knative.chi.coreweave.com', - 'accept': '*/*', - 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3', - 'authorization': 'Bearer ' + token, - 'cache-control': 'no-cache', - 'content-type': 'application/json', - 'origin': 'https://chat.forefront.ai', - 'pragma': 'no-cache', - 'referer': 'https://chat.forefront.ai/', - 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"', - 'sec-ch-ua-mobile': '?0', - 'sec-ch-ua-platform': '"macOS"', - 'sec-fetch-dest': 'empty', - 'sec-fetch-mode': 'cors', - 'sec-fetch-site': 'cross-site', - 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36', - } - - json_data = { - 'text': prompt, - 'action': actionType, - 'parentId': chatId, - 'workspaceId': chatId, - 'messagePersona': defaultPersona, - 'model': model - } - - for chunk in post('https://chat-server.tenant-forefront-default.knative.chi.coreweave.com/chat', - headers=headers, json=json_data, stream=True).iter_lines(): - - if b'finish_reason":null' in chunk: - data = loads(chunk.decode('utf-8').split('data: ')[1]) - token = data['choices'][0]['delta'].get('content') - - if token != None: - yield ForeFrontResponse({ - 'id': chatId, - 'object': 'text_completion', - 'created': int(time()), - 'model': model, - 'choices': [{ - 'text': token, - 'index': 0, - 'logprobs': None, - 'finish_reason': 'stop' - }], - 'usage': { - 'prompt_tokens': len(prompt), - 'completion_tokens': len(token), - 'total_tokens': len(prompt) + len(token) - } - }) diff --git a/forefront/mail.py b/forefront/mail.py deleted file mode 100644 index 41c2a647..00000000 --- a/forefront/mail.py +++ /dev/null @@ -1,56 +0,0 @@ -from random import choices -from string import ascii_letters - -from requests import Session - - -class Mail: - def __init__(self, proxies: dict = None) -> None: - self.client = Session() - self.client.proxies = proxies - self.client.headers = { - "host": "api.mail.tm", - "connection": "keep-alive", - "sec-ch-ua": "\"Google Chrome\";v=\"111\", \"Not(A:Brand\";v=\"8\", \"Chromium\";v=\"111\"", - "accept": "application/json, text/plain, */*", - "content-type": "application/json", - "sec-ch-ua-mobile": "?0", - "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36", - "sec-ch-ua-platform": "\"macOS\"", - "origin": "https://mail.tm", - "sec-fetch-site": "same-site", - "sec-fetch-mode": "cors", - "sec-fetch-dest": "empty", - "referer": "https://mail.tm/", - "accept-encoding": "gzip, deflate, br", - "accept-language": "en-GB,en-US;q=0.9,en;q=0.8" - } - - def get_mail(self) -> str: - token = ''.join(choices(ascii_letters, k=14)).lower() - init = self.client.post("https://api.mail.tm/accounts", json={ - "address": f"{token}@bugfoo.com", - "password": token - }) - - if init.status_code == 201: - resp = self.client.post("https://api.mail.tm/token", json={ - **init.json(), - "password": token - }) - - self.client.headers['authorization'] = 'Bearer ' + resp.json()['token'] - - return f"{token}@bugfoo.com" - - else: - raise Exception("Failed to create email") - - def fetch_inbox(self): - return self.client.get(f"https://api.mail.tm/messages").json()["hydra:member"] - - def get_message(self, message_id: str): - return self.client.get(f"https://api.mail.tm/messages/{message_id}").json() - - def get_message_content(self, message_id: str): - return self.get_message(message_id)["text"] diff --git a/forefront/typing.py b/forefront/typing.py deleted file mode 100644 index a11ac49f..00000000 --- a/forefront/typing.py +++ /dev/null @@ -1,36 +0,0 @@ -class ForeFrontResponse: - class Completion: - class Choices: - def __init__(self, choice: dict) -> None: - self.text = choice['text'] - self.content = self.text.encode() - self.index = choice['index'] - self.logprobs = choice['logprobs'] - self.finish_reason = choice['finish_reason'] - - def __repr__(self) -> str: - return f'''<__main__.APIResponse.Completion.Choices(\n text = {self.text.encode()},\n index = {self.index},\n logprobs = {self.logprobs},\n finish_reason = {self.finish_reason})object at 0x1337>''' - - def __init__(self, choices: dict) -> None: - self.choices = [self.Choices(choice) for choice in choices] - - class Usage: - def __init__(self, usage_dict: dict) -> None: - self.prompt_tokens = usage_dict['prompt_tokens'] - self.completion_tokens = usage_dict['completion_tokens'] - self.total_tokens = usage_dict['total_tokens'] - - def __repr__(self): - return f'''<__main__.APIResponse.Usage(\n prompt_tokens = {self.prompt_tokens},\n completion_tokens = {self.completion_tokens},\n total_tokens = {self.total_tokens})object at 0x1337>''' - - def __init__(self, response_dict: dict) -> None: - self.response_dict = response_dict - self.id = response_dict['id'] - self.object = response_dict['object'] - self.created = response_dict['created'] - self.model = response_dict['model'] - self.completion = self.Completion(response_dict['choices']) - self.usage = self.Usage(response_dict['usage']) - - def json(self) -> dict: - return self.response_dict diff --git a/gpt4free/__init__.py b/gpt4free/__init__.py new file mode 100644 index 00000000..5336c825 --- /dev/null +++ b/gpt4free/__init__.py @@ -0,0 +1,64 @@ +from enum import Enum + +from gpt4free import cocalc +from gpt4free import forefront +from gpt4free import quora +from gpt4free import theb +from gpt4free import you + + +class Provider(Enum): + """An enum representing different providers.""" + + You = 'you' + Poe = 'poe' + ForeFront = 'fore_front' + Theb = 'theb' + CoCalc = 'cocalc' + + +class Completion: + """This class will be used for invoking the given provider""" + + @staticmethod + def create(provider: Provider, prompt: str, **kwargs) -> str: + """ + Invokes the given provider with given prompt and addition arguments and returns the string response + + :param provider: an enum representing the provider to use while invoking + :param prompt: input provided by the user + :param kwargs: Additional keyword arguments to pass to the provider while invoking + :return: A string representing the response from the provider + """ + if provider == Provider.Poe: + return Completion.__poe_service(prompt, **kwargs) + elif provider == Provider.You: + return Completion.__you_service(prompt, **kwargs) + elif provider == Provider.ForeFront: + return Completion.__fore_front_service(prompt, **kwargs) + elif provider == Provider.Theb: + return Completion.__theb_service(prompt, **kwargs) + elif provider == Provider.CoCalc: + return Completion.__cocalc_service(prompt, **kwargs) + else: + raise Exception('Provider not exist, Please try again') + + @staticmethod + def __you_service(prompt: str, **kwargs) -> str: + return you.Completion.create(prompt, **kwargs).text + + @staticmethod + def __poe_service(prompt: str, **kwargs) -> str: + return quora.Completion.create(prompt=prompt, **kwargs).text + + @staticmethod + def __fore_front_service(prompt: str, **kwargs) -> str: + return forefront.Completion.create(prompt=prompt, **kwargs).text + + @staticmethod + def __theb_service(prompt: str, **kwargs): + return ''.join(theb.Completion.create(prompt=prompt)) + + @staticmethod + def __cocalc_service(prompt: str, **kwargs): + return cocalc.Completion.create(prompt, cookie_input=kwargs.get('cookie_input', '')).text diff --git a/gpt4free/cocalc/__init__.py b/gpt4free/cocalc/__init__.py new file mode 100644 index 00000000..372f29a4 --- /dev/null +++ b/gpt4free/cocalc/__init__.py @@ -0,0 +1,47 @@ +import requests +from fake_useragent import UserAgent +from pydantic import BaseModel + + +class CoCalcResponse(BaseModel): + text: str + status: bool + + +class Completion: + @staticmethod + def create(prompt: str, cookie_input: str) -> CoCalcResponse: + # Initialize a session with custom headers + session = Completion._initialize_session(cookie_input) + + # Set the data that will be submitted + payload = Completion._create_payload(prompt, 'ASSUME I HAVE FULL ACCESS TO COCALC. ') + + # Submit the request and return the results + return Completion._submit_request(session, payload) + + @classmethod + def _initialize_session(cls, conversation_cookie) -> requests.Session: + """Initialize a session with custom headers for the request.""" + + session = requests.Session() + headers = { + 'Accept': '*/*', + 'Accept-Language': 'en-US,en;q=0.5', + 'Origin': 'https://cocalc.com', + 'Referer': 'https://cocalc.com/api/v2/openai/chatgpt', + 'Cookie': conversation_cookie, + 'User-Agent': UserAgent().random, + } + session.headers.update(headers) + + return session + + @staticmethod + def _create_payload(prompt: str, system_prompt: str) -> dict: + return {'input': prompt, 'system': system_prompt, 'tag': 'next:index'} + + @staticmethod + def _submit_request(session: requests.Session, payload: dict) -> CoCalcResponse: + response = session.post('https://cocalc.com/api/v2/openai/chatgpt', json=payload).json() + return CoCalcResponse(text=response['output'], status=response['success']) diff --git a/gpt4free/cocalc/readme.md b/gpt4free/cocalc/readme.md new file mode 100644 index 00000000..f0911155 --- /dev/null +++ b/gpt4free/cocalc/readme.md @@ -0,0 +1,19 @@ +### Example: `cocalc` + +```python +# import library +from gpt4free import cocalc + +cocalc.Completion.create(prompt="How are you!", cookie_input="cookieinput") ## Tutorial +``` + +### How to grab cookie input +```js +// input this into ur developer tools console and the exact response u get from this u put into ur cookieInput! +var cookies = document.cookie.split("; "); +var cookieString = ""; +for (var i = 0; i < cookies.length; i++) { + cookieString += cookies[i] + "; "; +} +console.log(cookieString); +``` diff --git a/gpt4free/forefront/README.md b/gpt4free/forefront/README.md new file mode 100644 index 00000000..3d0aac4d --- /dev/null +++ b/gpt4free/forefront/README.md @@ -0,0 +1,16 @@ +### Example: `forefront` (use like openai pypi package) + +```python + +from gpt4free import forefront + +# create an account +token = forefront.Account.create(logging=False) +print(token) + +# get a response +for response in forefront.StreamingCompletion.create(token=token, + prompt='hello world', model='gpt-4'): + print(response.completion.choices[0].text, end='') +print("") +``` diff --git a/gpt4free/forefront/__init__.py b/gpt4free/forefront/__init__.py new file mode 100644 index 00000000..f0ca1a15 --- /dev/null +++ b/gpt4free/forefront/__init__.py @@ -0,0 +1,192 @@ +from json import loads +from re import match +from time import time, sleep +from typing import Generator, Optional +from uuid import uuid4 + +from fake_useragent import UserAgent +from requests import post +from tls_client import Session + +from .mail import Mail +from .typing import ForeFrontResponse + + +class Account: + @staticmethod + def create(proxy: Optional[str] = None, logging: bool = False): + proxies = {'http': 'http://' + proxy, 'https': 'http://' + proxy} if proxy else False + + start = time() + + mail_client = Mail(proxies) + mail_token = None + mail_address = mail_client.get_mail() + + # print(mail_address) + + client = Session(client_identifier='chrome110') + client.proxies = proxies + client.headers = { + 'origin': 'https://accounts.forefront.ai', + 'user-agent': UserAgent().random, + } + + response = client.post( + 'https://clerk.forefront.ai/v1/client/sign_ups?_clerk_js_version=4.32.6', + data={'email_address': mail_address}, + ) + + try: + trace_token = response.json()['response']['id'] + if logging: + print(trace_token) + except KeyError: + return 'Failed to create account!' + + response = client.post( + f'https://clerk.forefront.ai/v1/client/sign_ups/{trace_token}/prepare_verification?_clerk_js_version=4.32.6', + data={ + 'strategy': 'email_code', + }, + ) + + if logging: + print(response.text) + + if 'sign_up_attempt' not in response.text: + return 'Failed to create account!' + + while True: + sleep(1) + for _ in mail_client.fetch_inbox(): + if logging: + print(mail_client.get_message_content(_['id'])) + mail_token = match(r'(\d){5,6}', mail_client.get_message_content(_['id'])).group(0) + + if mail_token: + break + + if logging: + print(mail_token) + + response = client.post( + f'https://clerk.forefront.ai/v1/client/sign_ups/{trace_token}/attempt_verification?_clerk_js_version=4.38.4', + data={'code': mail_token, 'strategy': 'email_code'}, + ) + + if logging: + print(response.json()) + + token = response.json()['client']['sessions'][0]['last_active_token']['jwt'] + + with open('accounts.txt', 'a') as f: + f.write(f'{mail_address}:{token}\n') + + if logging: + print(time() - start) + + return token + + +class StreamingCompletion: + @staticmethod + def create( + token=None, + chat_id=None, + prompt='', + action_type='new', + default_persona='607e41fe-95be-497e-8e97-010a59b2e2c0', # default + model='gpt-4', + ) -> Generator[ForeFrontResponse, None, None]: + if not token: + raise Exception('Token is required!') + if not chat_id: + chat_id = str(uuid4()) + + headers = { + 'authority': 'chat-server.tenant-forefront-default.knative.chi.coreweave.com', + 'accept': '*/*', + 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3', + 'authorization': 'Bearer ' + token, + 'cache-control': 'no-cache', + 'content-type': 'application/json', + 'origin': 'https://chat.forefront.ai', + 'pragma': 'no-cache', + 'referer': 'https://chat.forefront.ai/', + 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"macOS"', + 'sec-fetch-dest': 'empty', + 'sec-fetch-mode': 'cors', + 'sec-fetch-site': 'cross-site', + 'user-agent': UserAgent().random, + } + + json_data = { + 'text': prompt, + 'action': action_type, + 'parentId': chat_id, + 'workspaceId': chat_id, + 'messagePersona': default_persona, + 'model': model, + } + + for chunk in post( + 'https://chat-server.tenant-forefront-default.knative.chi.coreweave.com/chat', + headers=headers, + json=json_data, + stream=True, + ).iter_lines(): + if b'finish_reason":null' in chunk: + data = loads(chunk.decode('utf-8').split('data: ')[1]) + token = data['choices'][0]['delta'].get('content') + + if token is not None: + yield ForeFrontResponse( + **{ + 'id': chat_id, + 'object': 'text_completion', + 'created': int(time()), + 'text': token, + 'model': model, + 'choices': [{'text': token, 'index': 0, 'logprobs': None, 'finish_reason': 'stop'}], + 'usage': { + 'prompt_tokens': len(prompt), + 'completion_tokens': len(token), + 'total_tokens': len(prompt) + len(token), + }, + } + ) + + +class Completion: + @staticmethod + def create( + token=None, + chat_id=None, + prompt='', + action_type='new', + default_persona='607e41fe-95be-497e-8e97-010a59b2e2c0', # default + model='gpt-4', + ) -> ForeFrontResponse: + text = '' + final_response = None + for response in StreamingCompletion.create( + token=token, + chat_id=chat_id, + prompt=prompt, + action_type=action_type, + default_persona=default_persona, + model=model, + ): + if response: + final_response = response + text += response.text + + if final_response: + final_response.text = text + else: + raise Exception('Unable to get the response, Please try again') + + return final_response diff --git a/gpt4free/forefront/mail.py b/gpt4free/forefront/mail.py new file mode 100644 index 00000000..41c2a647 --- /dev/null +++ b/gpt4free/forefront/mail.py @@ -0,0 +1,56 @@ +from random import choices +from string import ascii_letters + +from requests import Session + + +class Mail: + def __init__(self, proxies: dict = None) -> None: + self.client = Session() + self.client.proxies = proxies + self.client.headers = { + "host": "api.mail.tm", + "connection": "keep-alive", + "sec-ch-ua": "\"Google Chrome\";v=\"111\", \"Not(A:Brand\";v=\"8\", \"Chromium\";v=\"111\"", + "accept": "application/json, text/plain, */*", + "content-type": "application/json", + "sec-ch-ua-mobile": "?0", + "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36", + "sec-ch-ua-platform": "\"macOS\"", + "origin": "https://mail.tm", + "sec-fetch-site": "same-site", + "sec-fetch-mode": "cors", + "sec-fetch-dest": "empty", + "referer": "https://mail.tm/", + "accept-encoding": "gzip, deflate, br", + "accept-language": "en-GB,en-US;q=0.9,en;q=0.8" + } + + def get_mail(self) -> str: + token = ''.join(choices(ascii_letters, k=14)).lower() + init = self.client.post("https://api.mail.tm/accounts", json={ + "address": f"{token}@bugfoo.com", + "password": token + }) + + if init.status_code == 201: + resp = self.client.post("https://api.mail.tm/token", json={ + **init.json(), + "password": token + }) + + self.client.headers['authorization'] = 'Bearer ' + resp.json()['token'] + + return f"{token}@bugfoo.com" + + else: + raise Exception("Failed to create email") + + def fetch_inbox(self): + return self.client.get(f"https://api.mail.tm/messages").json()["hydra:member"] + + def get_message(self, message_id: str): + return self.client.get(f"https://api.mail.tm/messages/{message_id}").json() + + def get_message_content(self, message_id: str): + return self.get_message(message_id)["text"] diff --git a/gpt4free/forefront/typing.py b/gpt4free/forefront/typing.py new file mode 100644 index 00000000..d6026e04 --- /dev/null +++ b/gpt4free/forefront/typing.py @@ -0,0 +1,26 @@ +from typing import Any, List + +from pydantic import BaseModel + + +class Choice(BaseModel): + text: str + index: int + logprobs: Any + finish_reason: str + + +class Usage(BaseModel): + prompt_tokens: int + completion_tokens: int + total_tokens: int + + +class ForeFrontResponse(BaseModel): + id: str + object: str + created: int + model: str + choices: List[Choice] + usage: Usage + text: str \ No newline at end of file diff --git a/gpt4free/quora/README.md b/gpt4free/quora/README.md new file mode 100644 index 00000000..c6eeac3e --- /dev/null +++ b/gpt4free/quora/README.md @@ -0,0 +1,68 @@ + +> ⚠ Warning !!! +poe.com added security and can detect if you are making automated requests. You may get your account banned if you are using this api. +The normal non-driver api is also currently not very stable + + +### Example: `quora (poe)` (use like openai pypi package) - GPT-4 + +```python +# quora model names: (use left key as argument) +models = { + 'sage' : 'capybara', + 'gpt-4' : 'beaver', + 'claude-v1.2' : 'a2_2', + 'claude-instant-v1.0' : 'a2', + 'gpt-3.5-turbo' : 'chinchilla' +} +``` + +### New: bot creation + +```python +# import quora (poe) package +from gpt4free import quora + +# create account +# make sure to set enable_bot_creation to True +token = quora.Account.create(logging=True, enable_bot_creation=True) + +model = quora.Model.create( + token=token, + model='gpt-3.5-turbo', # or claude-instant-v1.0 + system_prompt='you are ChatGPT a large language model ...' +) + +print(model.name) # gptx.... + +# streaming response +for response in quora.StreamingCompletion.create( + custom_model=model.name, + prompt='hello world', + token=token): + print(response.completion.choices[0].text) +``` + +### Normal Response: +```python + +response = quora.Completion.create(model = 'gpt-4', + prompt = 'hello world', + token = token) + +print(response.completion.choices[0].text) +``` + +### Update Use This For Poe +```python +from quora import Poe + +# available models: ['Sage', 'GPT-4', 'Claude+', 'Claude-instant', 'ChatGPT', 'Dragonfly', 'NeevaAI'] + +poe = Poe(model='ChatGPT', driver='firefox', cookie_path='cookie.json', driver_path='path_of_driver') +poe.chat('who won the football world cup most?') + +# new bot creation +poe.create_bot('new_bot_name', prompt='You are new test bot', base_model='gpt-3.5-turbo') + +``` diff --git a/gpt4free/quora/__init__.py b/gpt4free/quora/__init__.py new file mode 100644 index 00000000..31526e0c --- /dev/null +++ b/gpt4free/quora/__init__.py @@ -0,0 +1,471 @@ +import json +from datetime import datetime +from hashlib import md5 +from json import dumps +from pathlib import Path +from random import choice, choices, randint +from re import search, findall +from string import ascii_letters, digits +from typing import Optional, Union, List, Any, Generator +from urllib.parse import unquote + +import selenium.webdriver.support.expected_conditions as EC +from fake_useragent import UserAgent +from pydantic import BaseModel +from pypasser import reCaptchaV3 +from requests import Session +from selenium.webdriver import Firefox, Chrome, FirefoxOptions, ChromeOptions +from selenium.webdriver.common.by import By +from selenium.webdriver.support.wait import WebDriverWait +from tls_client import Session as TLS + +from .api import Client as PoeClient +from .mail import Emailnator + +SELENIUM_WEB_DRIVER_ERROR_MSG = b'''The error message you are receiving is due to the `geckodriver` executable not +being found in your system\'s PATH. To resolve this issue, you need to download the geckodriver and add its location +to your system\'s PATH.\n\nHere are the steps to resolve the issue:\n\n1. Download the geckodriver for your platform +(Windows, macOS, or Linux) from the following link: https://github.com/mozilla/geckodriver/releases\n\n2. Extract the +downloaded archive and locate the geckodriver executable.\n\n3. Add the geckodriver executable to your system\'s +PATH.\n\nFor macOS and Linux:\n\n- Open a terminal window.\n- Move the geckodriver executable to a directory that is +already in your PATH, or create a new directory and add it to your PATH:\n\n```bash\n# Example: Move geckodriver to +/usr/local/bin\nmv /path/to/your/geckodriver /usr/local/bin\n```\n\n- If you created a new directory, add it to your +PATH:\n\n```bash\n# Example: Add a new directory to PATH\nexport PATH=$PATH:/path/to/your/directory\n```\n\nFor +Windows:\n\n- Right-click on "My Computer" or "This PC" and select "Properties".\n- Click on "Advanced system +settings".\n- Click on the "Environment Variables" button.\n- In the "System variables" section, find the "Path" +variable, select it, and click "Edit".\n- Click "New" and add the path to the directory containing the geckodriver +executable.\n\nAfter adding the geckodriver to your PATH, restart your terminal or command prompt and try running +your script again. The error should be resolved.''' + +# from twocaptcha import TwoCaptcha +# solver = TwoCaptcha('72747bf24a9d89b4dcc1b24875efd358') + +MODELS = { + 'Sage': 'capybara', + 'GPT-4': 'beaver', + 'Claude+': 'a2_2', + 'Claude-instant': 'a2', + 'ChatGPT': 'chinchilla', + 'Dragonfly': 'nutria', + 'NeevaAI': 'hutia', +} + + +def extract_formkey(html): + script_regex = r'' + script_text = search(script_regex, html).group(1) + key_regex = r'var .="([0-9a-f]+)",' + key_text = search(key_regex, script_text).group(1) + cipher_regex = r'.\[(\d+)\]=.\[(\d+)\]' + cipher_pairs = findall(cipher_regex, script_text) + + formkey_list = [''] * len(cipher_pairs) + for pair in cipher_pairs: + formkey_index, key_index = map(int, pair) + formkey_list[formkey_index] = key_text[key_index] + formkey = ''.join(formkey_list) + + return formkey + + +class Choice(BaseModel): + text: str + index: int + logprobs: Any + finish_reason: str + + +class Usage(BaseModel): + prompt_tokens: int + completion_tokens: int + total_tokens: int + + +class PoeResponse(BaseModel): + id: int + object: str + created: int + model: str + choices: List[Choice] + usage: Usage + text: str + + +class ModelResponse: + def __init__(self, json_response: dict) -> None: + self.id = json_response['data']['poeBotCreate']['bot']['id'] + self.name = json_response['data']['poeBotCreate']['bot']['displayName'] + self.limit = json_response['data']['poeBotCreate']['bot']['messageLimit']['dailyLimit'] + self.deleted = json_response['data']['poeBotCreate']['bot']['deletionState'] + + +class Model: + @staticmethod + def create( + token: str, + model: str = 'gpt-3.5-turbo', # claude-instant + system_prompt: str = 'You are ChatGPT a large language model developed by Openai. Answer as consisely as possible', + description: str = 'gpt-3.5 language model from openai, skidded by poe.com', + handle: str = None, + ) -> ModelResponse: + if not handle: + handle = f'gptx{randint(1111111, 9999999)}' + + client = Session() + client.cookies['p-b'] = token + + formkey = extract_formkey(client.get('https://poe.com').text) + settings = client.get('https://poe.com/api/settings').json() + + client.headers = { + 'host': 'poe.com', + 'origin': 'https://poe.com', + 'referer': 'https://poe.com/', + 'poe-formkey': formkey, + 'poe-tchannel': settings['tchannelData']['channel'], + 'user-agent': UserAgent().random, + 'connection': 'keep-alive', + 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"macOS"', + 'content-type': 'application/json', + 'sec-fetch-site': 'same-origin', + 'sec-fetch-mode': 'cors', + 'sec-fetch-dest': 'empty', + 'accept': '*/*', + 'accept-encoding': 'gzip, deflate, br', + 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', + } + + payload = dumps( + separators=(',', ':'), + obj={ + 'queryName': 'CreateBotMain_poeBotCreate_Mutation', + 'variables': { + 'model': MODELS[model], + 'handle': handle, + 'prompt': system_prompt, + 'isPromptPublic': True, + 'introduction': '', + 'description': description, + 'profilePictureUrl': 'https://qph.fs.quoracdn.net/main-qimg-24e0b480dcd946e1cc6728802c5128b6', + 'apiUrl': None, + 'apiKey': ''.join(choices(ascii_letters + digits, k=32)), + 'isApiBot': False, + 'hasLinkification': False, + 'hasMarkdownRendering': False, + 'hasSuggestedReplies': False, + 'isPrivateBot': False, + }, + 'query': 'mutation CreateBotMain_poeBotCreate_Mutation(\n $model: String!\n $handle: String!\n $prompt: String!\n $isPromptPublic: Boolean!\n $introduction: String!\n $description: String!\n $profilePictureUrl: String\n $apiUrl: String\n $apiKey: String\n $isApiBot: Boolean\n $hasLinkification: Boolean\n $hasMarkdownRendering: Boolean\n $hasSuggestedReplies: Boolean\n $isPrivateBot: Boolean\n) {\n poeBotCreate(model: $model, handle: $handle, promptPlaintext: $prompt, isPromptPublic: $isPromptPublic, introduction: $introduction, description: $description, profilePicture: $profilePictureUrl, apiUrl: $apiUrl, apiKey: $apiKey, isApiBot: $isApiBot, hasLinkification: $hasLinkification, hasMarkdownRendering: $hasMarkdownRendering, hasSuggestedReplies: $hasSuggestedReplies, isPrivateBot: $isPrivateBot) {\n status\n bot {\n id\n ...BotHeader_bot\n }\n }\n}\n\nfragment BotHeader_bot on Bot {\n displayName\n messageLimit {\n dailyLimit\n }\n ...BotImage_bot\n ...BotLink_bot\n ...IdAnnotation_node\n ...botHelpers_useViewerCanAccessPrivateBot\n ...botHelpers_useDeletion_bot\n}\n\nfragment BotImage_bot on Bot {\n displayName\n ...botHelpers_useDeletion_bot\n ...BotImage_useProfileImage_bot\n}\n\nfragment BotImage_useProfileImage_bot on Bot {\n image {\n __typename\n ... on LocalBotImage {\n localName\n }\n ... on UrlBotImage {\n url\n }\n }\n ...botHelpers_useDeletion_bot\n}\n\nfragment BotLink_bot on Bot {\n displayName\n}\n\nfragment IdAnnotation_node on Node {\n __isNode: __typename\n id\n}\n\nfragment botHelpers_useDeletion_bot on Bot {\n deletionState\n}\n\nfragment botHelpers_useViewerCanAccessPrivateBot on Bot {\n isPrivateBot\n viewerIsCreator\n}\n', + }, + ) + + base_string = payload + client.headers['poe-formkey'] + 'WpuLMiXEKKE98j56k' + client.headers['poe-tag-id'] = md5(base_string.encode()).hexdigest() + + response = client.post('https://poe.com/api/gql_POST', data=payload) + + if 'success' not in response.text: + raise Exception( + ''' + Bot creation Failed + !! Important !! + Bot creation was not enabled on this account + please use: quora.Account.create with enable_bot_creation set to True + ''' + ) + + return ModelResponse(response.json()) + + +class Account: + @staticmethod + def create( + proxy: Optional[str] = None, + logging: bool = False, + enable_bot_creation: bool = False, + ): + client = TLS(client_identifier='chrome110') + client.proxies = {'http': f'http://{proxy}', 'https': f'http://{proxy}'} if proxy else None + + mail_client = Emailnator() + mail_address = mail_client.get_mail() + + if logging: + print('email', mail_address) + + client.headers = { + 'authority': 'poe.com', + 'accept': '*/*', + 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3', + 'content-type': 'application/json', + 'origin': 'https://poe.com', + 'poe-tag-id': 'null', + 'referer': 'https://poe.com/login', + 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"macOS"', + 'sec-fetch-dest': 'empty', + 'sec-fetch-mode': 'cors', + 'sec-fetch-site': 'same-origin', + 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36', + 'poe-formkey': extract_formkey(client.get('https://poe.com/login').text), + 'poe-tchannel': client.get('https://poe.com/api/settings').json()['tchannelData']['channel'], + } + + token = reCaptchaV3( + 'https://www.recaptcha.net/recaptcha/enterprise/anchor?ar=1&k=6LflhEElAAAAAI_ewVwRWI9hsyV4mbZnYAslSvlG&co=aHR0cHM6Ly9wb2UuY29tOjQ0Mw..&hl=en&v=4PnKmGB9wRHh1i04o7YUICeI&size=invisible&cb=bi6ivxoskyal' + ) + # token = solver.recaptcha(sitekey='6LflhEElAAAAAI_ewVwRWI9hsyV4mbZnYAslSvlG', + # url = 'https://poe.com/login?redirect_url=%2F', + # version = 'v3', + # enterprise = 1, + # invisible = 1, + # action = 'login',)['code'] + + payload = dumps( + separators=(',', ':'), + obj={ + 'queryName': 'MainSignupLoginSection_sendVerificationCodeMutation_Mutation', + 'variables': { + 'emailAddress': mail_address, + 'phoneNumber': None, + 'recaptchaToken': token, + }, + 'query': 'mutation MainSignupLoginSection_sendVerificationCodeMutation_Mutation(\n $emailAddress: String\n $phoneNumber: String\n $recaptchaToken: String\n) {\n sendVerificationCode(verificationReason: login, emailAddress: $emailAddress, phoneNumber: $phoneNumber, recaptchaToken: $recaptchaToken) {\n status\n errorMessage\n }\n}\n', + }, + ) + + base_string = payload + client.headers['poe-formkey'] + 'WpuLMiXEKKE98j56k' + client.headers['poe-tag-id'] = md5(base_string.encode()).hexdigest() + + print(dumps(client.headers, indent=4)) + + response = client.post('https://poe.com/api/gql_POST', data=payload) + + if 'automated_request_detected' in response.text: + print('please try using a proxy / wait for fix') + + if 'Bad Request' in response.text: + if logging: + print('bad request, retrying...', response.json()) + quit() + + if logging: + print('send_code', response.json()) + + mail_content = mail_client.get_message() + mail_token = findall(r';">(\d{6,7})', mail_content)[0] + + if logging: + print('code', mail_token) + + payload = dumps( + separators=(',', ':'), + obj={ + 'queryName': 'SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation', + 'variables': { + 'verificationCode': str(mail_token), + 'emailAddress': mail_address, + 'phoneNumber': None, + }, + 'query': 'mutation SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation(\n $verificationCode: String!\n $emailAddress: String\n $phoneNumber: String\n) {\n signupWithVerificationCode(verificationCode: $verificationCode, emailAddress: $emailAddress, phoneNumber: $phoneNumber) {\n status\n errorMessage\n }\n}\n', + }, + ) + + base_string = payload + client.headers['poe-formkey'] + 'WpuLMiXEKKE98j56k' + client.headers['poe-tag-id'] = md5(base_string.encode()).hexdigest() + + response = client.post('https://poe.com/api/gql_POST', data=payload) + if logging: + print('verify_code', response.json()) + + def get(self): + cookies = open(Path(__file__).resolve().parent / 'cookies.txt', 'r').read().splitlines() + return choice(cookies) + + +class StreamingCompletion: + @staticmethod + def create( + model: str = 'gpt-4', + custom_model: bool = None, + prompt: str = 'hello world', + token: str = '', + ) -> Generator[PoeResponse, None, None]: + _model = MODELS[model] if not custom_model else custom_model + + client = PoeClient(token) + + for chunk in client.send_message(_model, prompt): + yield PoeResponse( + **{ + 'id': chunk['messageId'], + 'object': 'text_completion', + 'created': chunk['creationTime'], + 'model': _model, + 'text': chunk['text_new'], + 'choices': [ + { + 'text': chunk['text_new'], + 'index': 0, + 'logprobs': None, + 'finish_reason': 'stop', + } + ], + 'usage': { + 'prompt_tokens': len(prompt), + 'completion_tokens': len(chunk['text_new']), + 'total_tokens': len(prompt) + len(chunk['text_new']), + }, + } + ) + + +class Completion: + @staticmethod + def create( + model: str = 'gpt-4', + custom_model: str = None, + prompt: str = 'hello world', + token: str = '', + ) -> PoeResponse: + _model = MODELS[model] if not custom_model else custom_model + + client = PoeClient(token) + + chunk = None + for response in client.send_message(_model, prompt): + chunk = response + + return PoeResponse( + **{ + 'id': chunk['messageId'], + 'object': 'text_completion', + 'created': chunk['creationTime'], + 'model': _model, + 'text': chunk['text'], + 'choices': [ + { + 'text': chunk['text'], + 'index': 0, + 'logprobs': None, + 'finish_reason': 'stop', + } + ], + 'usage': { + 'prompt_tokens': len(prompt), + 'completion_tokens': len(chunk['text']), + 'total_tokens': len(prompt) + len(chunk['text']), + }, + } + ) + + +class Poe: + def __init__( + self, + model: str = 'ChatGPT', + driver: str = 'firefox', + download_driver: bool = False, + driver_path: Optional[str] = None, + cookie_path: str = './quora/cookie.json', + ): + # validating the model + if model and model not in MODELS: + raise RuntimeError('Sorry, the model you provided does not exist. Please check and try again.') + self.model = MODELS[model] + self.cookie_path = cookie_path + self.cookie = self.__load_cookie(driver, download_driver, driver_path=driver_path) + self.client = PoeClient(self.cookie) + + def __load_cookie(self, driver: str, download_driver: bool, driver_path: Optional[str] = None) -> str: + if (cookie_file := Path(self.cookie_path)).exists(): + with cookie_file.open() as fp: + cookie = json.load(fp) + if datetime.fromtimestamp(cookie['expiry']) < datetime.now(): + cookie = self.__register_and_get_cookie(driver, driver_path=driver_path) + else: + print('Loading the cookie from file') + else: + cookie = self.__register_and_get_cookie(driver, driver_path=driver_path) + + return unquote(cookie['value']) + + def __register_and_get_cookie(self, driver: str, driver_path: Optional[str] = None) -> dict: + mail_client = Emailnator() + mail_address = mail_client.get_mail() + + driver = self.__resolve_driver(driver, driver_path=driver_path) + driver.get("https://www.poe.com") + + # clicking use email button + driver.find_element(By.XPATH, '//button[contains(text(), "Use email")]').click() + + email = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, '//input[@type="email"]'))) + email.send_keys(mail_address) + driver.find_element(By.XPATH, '//button[text()="Go"]').click() + + code = findall(r';">(\d{6,7})', mail_client.get_message())[0] + print(code) + + verification_code = WebDriverWait(driver, 30).until( + EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Code"]')) + ) + verification_code.send_keys(code) + verify_button = EC.presence_of_element_located((By.XPATH, '//button[text()="Verify"]')) + login_button = EC.presence_of_element_located((By.XPATH, '//button[text()="Log In"]')) + + WebDriverWait(driver, 30).until(EC.any_of(verify_button, login_button)).click() + + cookie = driver.get_cookie('p-b') + + with open(self.cookie_path, 'w') as fw: + json.dump(cookie, fw) + + driver.close() + return cookie + + @staticmethod + def __resolve_driver(driver: str, driver_path: Optional[str] = None) -> Union[Firefox, Chrome]: + options = FirefoxOptions() if driver == 'firefox' else ChromeOptions() + options.add_argument('-headless') + + if driver_path: + options.binary_location = driver_path + try: + return Firefox(options=options) if driver == 'firefox' else Chrome(options=options) + except Exception: + raise Exception(SELENIUM_WEB_DRIVER_ERROR_MSG) + + def chat(self, message: str, model: Optional[str] = None) -> str: + if model and model not in MODELS: + raise RuntimeError('Sorry, the model you provided does not exist. Please check and try again.') + model = MODELS[model] if model else self.model + response = None + for chunk in self.client.send_message(model, message): + response = chunk['text'] + return response + + def create_bot( + self, + name: str, + /, + prompt: str = '', + base_model: str = 'ChatGPT', + description: str = '', + ) -> None: + if base_model not in MODELS: + raise RuntimeError('Sorry, the base_model you provided does not exist. Please check and try again.') + + response = self.client.create_bot( + handle=name, + prompt=prompt, + base_model=MODELS[base_model], + description=description, + ) + print(f'Successfully created bot with name: {response["bot"]["displayName"]}') + + def list_bots(self) -> list: + return list(self.client.bot_names.values()) \ No newline at end of file diff --git a/gpt4free/quora/api.py b/gpt4free/quora/api.py new file mode 100644 index 00000000..697f6663 --- /dev/null +++ b/gpt4free/quora/api.py @@ -0,0 +1,545 @@ +# This file was taken from the repository poe-api https://github.com/ading2210/poe-api and is unmodified +# This file is licensed under the GNU GPL v3 and written by @ading2210 + +# license: +# ading2210/poe-api: a reverse engineered Python API wrapepr for Quora's Poe +# Copyright (C) 2023 ading2210 + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +import hashlib +import json +import logging +import queue +import random +import re +import threading +import time +import traceback +from pathlib import Path +from urllib.parse import urlparse + +import requests +import requests.adapters +import websocket + +parent_path = Path(__file__).resolve().parent +queries_path = parent_path / "graphql" +queries = {} + +logging.basicConfig() +logger = logging.getLogger() + +user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" + + +def load_queries(): + for path in queries_path.iterdir(): + if path.suffix != ".graphql": + continue + with open(path) as f: + queries[path.stem] = f.read() + + +def generate_payload(query_name, variables): + return {"query": queries[query_name], "variables": variables} + + +def request_with_retries(method, *args, **kwargs): + attempts = kwargs.get("attempts") or 10 + url = args[0] + for i in range(attempts): + r = method(*args, **kwargs) + if r.status_code == 200: + return r + logger.warn( + f"Server returned a status code of {r.status_code} while downloading {url}. Retrying ({i + 1}/{attempts})..." + ) + + raise RuntimeError(f"Failed to download {url} too many times.") + + +class Client: + gql_url = "https://poe.com/api/gql_POST" + gql_recv_url = "https://poe.com/api/receive_POST" + home_url = "https://poe.com" + settings_url = "https://poe.com/api/settings" + + def __init__(self, token, proxy=None): + self.proxy = proxy + self.session = requests.Session() + self.adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100) + self.session.mount("http://", self.adapter) + self.session.mount("https://", self.adapter) + + if proxy: + self.session.proxies = {"http": self.proxy, "https": self.proxy} + logger.info(f"Proxy enabled: {self.proxy}") + + self.active_messages = {} + self.message_queues = {} + + self.session.cookies.set("p-b", token, domain="poe.com") + self.headers = { + "User-Agent": user_agent, + "Referrer": "https://poe.com/", + "Origin": "https://poe.com", + } + self.session.headers.update(self.headers) + + self.setup_connection() + self.connect_ws() + + def setup_connection(self): + self.ws_domain = f"tch{random.randint(1, 1e6)}" + self.next_data = self.get_next_data(overwrite_vars=True) + self.channel = self.get_channel_data() + self.bots = self.get_bots(download_next_data=False) + self.bot_names = self.get_bot_names() + + self.gql_headers = { + "poe-formkey": self.formkey, + "poe-tchannel": self.channel["channel"], + } + self.gql_headers = {**self.gql_headers, **self.headers} + self.subscribe() + + def extract_formkey(self, html): + script_regex = r"" + script_text = re.search(script_regex, html).group(1) + key_regex = r'var .="([0-9a-f]+)",' + key_text = re.search(key_regex, script_text).group(1) + cipher_regex = r".\[(\d+)\]=.\[(\d+)\]" + cipher_pairs = re.findall(cipher_regex, script_text) + + formkey_list = [""] * len(cipher_pairs) + for pair in cipher_pairs: + formkey_index, key_index = map(int, pair) + formkey_list[formkey_index] = key_text[key_index] + formkey = "".join(formkey_list) + + return formkey + + def get_next_data(self, overwrite_vars=False): + logger.info("Downloading next_data...") + + r = request_with_retries(self.session.get, self.home_url) + json_regex = r'' + json_text = re.search(json_regex, r.text).group(1) + next_data = json.loads(json_text) + + if overwrite_vars: + self.formkey = self.extract_formkey(r.text) + self.viewer = next_data["props"]["pageProps"]["payload"]["viewer"] + self.next_data = next_data + + return next_data + + def get_bot(self, display_name): + url = f'https://poe.com/_next/data/{self.next_data["buildId"]}/{display_name}.json' + + r = request_with_retries(self.session.get, url) + + chat_data = r.json()["pageProps"]["payload"]["chatOfBotDisplayName"] + return chat_data + + def get_bots(self, download_next_data=True): + logger.info("Downloading all bots...") + if download_next_data: + next_data = self.get_next_data(overwrite_vars=True) + else: + next_data = self.next_data + + if not "availableBots" in self.viewer: + raise RuntimeError("Invalid token or no bots are available.") + bot_list = self.viewer["availableBots"] + + threads = [] + bots = {} + + def get_bot_thread(bot): + chat_data = self.get_bot(bot["displayName"]) + bots[chat_data["defaultBotObject"]["nickname"]] = chat_data + + for bot in bot_list: + thread = threading.Thread(target=get_bot_thread, args=(bot,), daemon=True) + threads.append(thread) + + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + self.bots = bots + self.bot_names = self.get_bot_names() + return bots + + def get_bot_names(self): + bot_names = {} + for bot_nickname in self.bots: + bot_obj = self.bots[bot_nickname]["defaultBotObject"] + bot_names[bot_nickname] = bot_obj["displayName"] + return bot_names + + def get_remaining_messages(self, chatbot): + chat_data = self.get_bot(self.bot_names[chatbot]) + return chat_data["defaultBotObject"]["messageLimit"]["numMessagesRemaining"] + + def get_channel_data(self, channel=None): + logger.info("Downloading channel data...") + r = request_with_retries(self.session.get, self.settings_url) + data = r.json() + + return data["tchannelData"] + + def get_websocket_url(self, channel=None): + if channel is None: + channel = self.channel + query = f'?min_seq={channel["minSeq"]}&channel={channel["channel"]}&hash={channel["channelHash"]}' + return f'wss://{self.ws_domain}.tch.{channel["baseHost"]}/up/{channel["boxName"]}/updates' + query + + def send_query(self, query_name, variables): + for i in range(20): + json_data = generate_payload(query_name, variables) + payload = json.dumps(json_data, separators=(",", ":")) + + base_string = payload + self.gql_headers["poe-formkey"] + "WpuLMiXEKKE98j56k" + + headers = { + "content-type": "application/json", + "poe-tag-id": hashlib.md5(base_string.encode()).hexdigest(), + } + headers = {**self.gql_headers, **headers} + + r = request_with_retries(self.session.post, self.gql_url, data=payload, headers=headers) + + data = r.json() + if data["data"] == None: + logger.warn(f'{query_name} returned an error: {data["errors"][0]["message"]} | Retrying ({i + 1}/20)') + time.sleep(2) + continue + + return r.json() + + raise RuntimeError(f"{query_name} failed too many times.") + + def subscribe(self): + logger.info("Subscribing to mutations") + result = self.send_query( + "SubscriptionsMutation", + { + "subscriptions": [ + { + "subscriptionName": "messageAdded", + "query": queries["MessageAddedSubscription"], + }, + { + "subscriptionName": "viewerStateUpdated", + "query": queries["ViewerStateUpdatedSubscription"], + }, + ] + }, + ) + + def ws_run_thread(self): + kwargs = {} + if self.proxy: + proxy_parsed = urlparse(self.proxy) + kwargs = { + "proxy_type": proxy_parsed.scheme, + "http_proxy_host": proxy_parsed.hostname, + "http_proxy_port": proxy_parsed.port, + } + + self.ws.run_forever(**kwargs) + + def connect_ws(self): + self.ws_connected = False + self.ws = websocket.WebSocketApp( + self.get_websocket_url(), + header={"User-Agent": user_agent}, + on_message=self.on_message, + on_open=self.on_ws_connect, + on_error=self.on_ws_error, + on_close=self.on_ws_close, + ) + t = threading.Thread(target=self.ws_run_thread, daemon=True) + t.start() + while not self.ws_connected: + time.sleep(0.01) + + def disconnect_ws(self): + if self.ws: + self.ws.close() + self.ws_connected = False + + def on_ws_connect(self, ws): + self.ws_connected = True + + def on_ws_close(self, ws, close_status_code, close_message): + self.ws_connected = False + logger.warn(f"Websocket closed with status {close_status_code}: {close_message}") + + def on_ws_error(self, ws, error): + self.disconnect_ws() + self.connect_ws() + + def on_message(self, ws, msg): + try: + data = json.loads(msg) + + if not "messages" in data: + return + + for message_str in data["messages"]: + message_data = json.loads(message_str) + if message_data["message_type"] != "subscriptionUpdate": + continue + message = message_data["payload"]["data"]["messageAdded"] + + copied_dict = self.active_messages.copy() + for key, value in copied_dict.items(): + # add the message to the appropriate queue + if value == message["messageId"] and key in self.message_queues: + self.message_queues[key].put(message) + return + + # indicate that the response id is tied to the human message id + elif key != "pending" and value == None and message["state"] != "complete": + self.active_messages[key] = message["messageId"] + self.message_queues[key].put(message) + return + + except Exception: + logger.error(traceback.format_exc()) + self.disconnect_ws() + self.connect_ws() + + def send_message(self, chatbot, message, with_chat_break=False, timeout=20): + # if there is another active message, wait until it has finished sending + while None in self.active_messages.values(): + time.sleep(0.01) + + # None indicates that a message is still in progress + self.active_messages["pending"] = None + + logger.info(f"Sending message to {chatbot}: {message}") + + # reconnect websocket + if not self.ws_connected: + self.disconnect_ws() + self.setup_connection() + self.connect_ws() + + message_data = self.send_query( + "SendMessageMutation", + { + "bot": chatbot, + "query": message, + "chatId": self.bots[chatbot]["chatId"], + "source": None, + "withChatBreak": with_chat_break, + }, + ) + del self.active_messages["pending"] + + if not message_data["data"]["messageEdgeCreate"]["message"]: + raise RuntimeError(f"Daily limit reached for {chatbot}.") + try: + human_message = message_data["data"]["messageEdgeCreate"]["message"] + human_message_id = human_message["node"]["messageId"] + except TypeError: + raise RuntimeError(f"An unknown error occurred. Raw response data: {message_data}") + + # indicate that the current message is waiting for a response + self.active_messages[human_message_id] = None + self.message_queues[human_message_id] = queue.Queue() + + last_text = "" + message_id = None + while True: + try: + message = self.message_queues[human_message_id].get(timeout=timeout) + except queue.Empty: + del self.active_messages[human_message_id] + del self.message_queues[human_message_id] + raise RuntimeError("Response timed out.") + + # only break when the message is marked as complete + if message["state"] == "complete": + if last_text and message["messageId"] == message_id: + break + else: + continue + + # update info about response + message["text_new"] = message["text"][len(last_text):] + last_text = message["text"] + message_id = message["messageId"] + + yield message + + del self.active_messages[human_message_id] + del self.message_queues[human_message_id] + + def send_chat_break(self, chatbot): + logger.info(f"Sending chat break to {chatbot}") + result = self.send_query("AddMessageBreakMutation", {"chatId": self.bots[chatbot]["chatId"]}) + return result["data"]["messageBreakCreate"]["message"] + + def get_message_history(self, chatbot, count=25, cursor=None): + logger.info(f"Downloading {count} messages from {chatbot}") + + messages = [] + if cursor == None: + chat_data = self.get_bot(self.bot_names[chatbot]) + if not chat_data["messagesConnection"]["edges"]: + return [] + messages = chat_data["messagesConnection"]["edges"][:count] + cursor = chat_data["messagesConnection"]["pageInfo"]["startCursor"] + count -= len(messages) + + cursor = str(cursor) + if count > 50: + messages = self.get_message_history(chatbot, count=50, cursor=cursor) + messages + while count > 0: + count -= 50 + new_cursor = messages[0]["cursor"] + new_messages = self.get_message_history(chatbot, min(50, count), cursor=new_cursor) + messages = new_messages + messages + return messages + elif count <= 0: + return messages + + result = self.send_query( + "ChatListPaginationQuery", + {"count": count, "cursor": cursor, "id": self.bots[chatbot]["id"]}, + ) + query_messages = result["data"]["node"]["messagesConnection"]["edges"] + messages = query_messages + messages + return messages + + def delete_message(self, message_ids): + logger.info(f"Deleting messages: {message_ids}") + if not type(message_ids) is list: + message_ids = [int(message_ids)] + + result = self.send_query("DeleteMessageMutation", {"messageIds": message_ids}) + + def purge_conversation(self, chatbot, count=-1): + logger.info(f"Purging messages from {chatbot}") + last_messages = self.get_message_history(chatbot, count=50)[::-1] + while last_messages: + message_ids = [] + for message in last_messages: + if count == 0: + break + count -= 1 + message_ids.append(message["node"]["messageId"]) + + self.delete_message(message_ids) + + if count == 0: + return + last_messages = self.get_message_history(chatbot, count=50)[::-1] + logger.info(f"No more messages left to delete.") + + def create_bot( + self, + handle, + prompt="", + base_model="chinchilla", + description="", + intro_message="", + api_key=None, + api_bot=False, + api_url=None, + prompt_public=True, + pfp_url=None, + linkification=False, + markdown_rendering=True, + suggested_replies=False, + private=False, + ): + result = self.send_query( + "PoeBotCreateMutation", + { + "model": base_model, + "handle": handle, + "prompt": prompt, + "isPromptPublic": prompt_public, + "introduction": intro_message, + "description": description, + "profilePictureUrl": pfp_url, + "apiUrl": api_url, + "apiKey": api_key, + "isApiBot": api_bot, + "hasLinkification": linkification, + "hasMarkdownRendering": markdown_rendering, + "hasSuggestedReplies": suggested_replies, + "isPrivateBot": private, + }, + ) + + data = result["data"]["poeBotCreate"] + if data["status"] != "success": + raise RuntimeError(f"Poe returned an error while trying to create a bot: {data['status']}") + self.get_bots() + return data + + def edit_bot( + self, + bot_id, + handle, + prompt="", + base_model="chinchilla", + description="", + intro_message="", + api_key=None, + api_url=None, + private=False, + prompt_public=True, + pfp_url=None, + linkification=False, + markdown_rendering=True, + suggested_replies=False, + ): + result = self.send_query( + "PoeBotEditMutation", + { + "baseBot": base_model, + "botId": bot_id, + "handle": handle, + "prompt": prompt, + "isPromptPublic": prompt_public, + "introduction": intro_message, + "description": description, + "profilePictureUrl": pfp_url, + "apiUrl": api_url, + "apiKey": api_key, + "hasLinkification": linkification, + "hasMarkdownRendering": markdown_rendering, + "hasSuggestedReplies": suggested_replies, + "isPrivateBot": private, + }, + ) + + data = result["data"]["poeBotEdit"] + if data["status"] != "success": + raise RuntimeError(f"Poe returned an error while trying to edit a bot: {data['status']}") + self.get_bots() + return data + + +load_queries() diff --git a/gpt4free/quora/cookies.txt b/gpt4free/quora/cookies.txt new file mode 100644 index 00000000..9cccf6ba --- /dev/null +++ b/gpt4free/quora/cookies.txt @@ -0,0 +1,30 @@ +SmPiNXZI9hBTuf3viz74PA== +zw7RoKQfeEehiaelYMRWeA== +NEttgJ_rRQdO05Tppx6hFw== +3OnmC0r9njYdNWhWszdQJg== +8hZKR7MxwUTEHvO45TEViw== +Eea6BqK0AmosTKzoI3AAow== +pUEbtxobN_QUSpLIR8RGww== +9_dUWxKkHHhpQRSvCvBk2Q== +UV45rvGwUwi2qV9QdIbMcw== +cVIN0pK1Wx-F7zCdUxlYqA== +UP2wQVds17VFHh6IfCQFrA== +18eKr0ME2Tzifdfqat38Aw== +FNgKEpc2r-XqWe0rHBfYpg== +juCAh6kB0sUpXHvKik2woA== +nBvuNYRLaE4xE4HuzBPiIQ== +oyae3iClomSrk6RJywZ4iw== +1Z27Ul8BTdNOhncT5H6wdg== +wfUfJIlwQwUss8l-3kDt3w== +f6Jw_Nr0PietpNCtOCXJTw== +6Jc3yCs7XhDRNHa4ZML09g== +3vy44sIy-ZlTMofFiFDttw== +p9FbMGGiK1rShKgL3YWkDg== +pw6LI5Op84lf4HOY7fn91A== +QemKm6aothMvqcEgeKFDlQ== +cceZzucA-CEHR0Gt6VLYLQ== +JRRObMp2RHVn5u4730DPvQ== +XNt0wLTjX7Z-EsRR3TJMIQ== +csjjirAUKtT5HT1KZUq1kg== +8qZdCatCPQZyS7jsO4hkdQ== +esnUxcBhvH1DmCJTeld0qw== diff --git a/gpt4free/quora/graphql/AddHumanMessageMutation.graphql b/gpt4free/quora/graphql/AddHumanMessageMutation.graphql new file mode 100644 index 00000000..01e6bc8c --- /dev/null +++ b/gpt4free/quora/graphql/AddHumanMessageMutation.graphql @@ -0,0 +1,52 @@ +mutation AddHumanMessageMutation( + $chatId: BigInt! + $bot: String! + $query: String! + $source: MessageSource + $withChatBreak: Boolean! = false +) { + messageCreateWithStatus( + chatId: $chatId + bot: $bot + query: $query + source: $source + withChatBreak: $withChatBreak + ) { + message { + id + __typename + messageId + text + linkifiedText + authorNickname + state + vote + voteReason + creationTime + suggestedReplies + chat { + id + shouldShowDisclaimer + } + } + messageLimit{ + canSend + numMessagesRemaining + resetTime + shouldShowReminder + } + chatBreak { + id + __typename + messageId + text + linkifiedText + authorNickname + state + vote + voteReason + creationTime + suggestedReplies + } + } +} diff --git a/gpt4free/quora/graphql/AddMessageBreakMutation.graphql b/gpt4free/quora/graphql/AddMessageBreakMutation.graphql new file mode 100644 index 00000000..b28d9903 --- /dev/null +++ b/gpt4free/quora/graphql/AddMessageBreakMutation.graphql @@ -0,0 +1,17 @@ +mutation AddMessageBreakMutation($chatId: BigInt!) { + messageBreakCreate(chatId: $chatId) { + message { + id + __typename + messageId + text + linkifiedText + authorNickname + state + vote + voteReason + creationTime + suggestedReplies + } + } +} diff --git a/gpt4free/quora/graphql/AutoSubscriptionMutation.graphql b/gpt4free/quora/graphql/AutoSubscriptionMutation.graphql new file mode 100644 index 00000000..6cf7bf74 --- /dev/null +++ b/gpt4free/quora/graphql/AutoSubscriptionMutation.graphql @@ -0,0 +1,7 @@ +mutation AutoSubscriptionMutation($subscriptions: [AutoSubscriptionQuery!]!) { + autoSubscribe(subscriptions: $subscriptions) { + viewer { + id + } + } +} diff --git a/gpt4free/quora/graphql/BioFragment.graphql b/gpt4free/quora/graphql/BioFragment.graphql new file mode 100644 index 00000000..c4218030 --- /dev/null +++ b/gpt4free/quora/graphql/BioFragment.graphql @@ -0,0 +1,8 @@ +fragment BioFragment on Viewer { + id + poeUser { + id + uid + bio + } +} diff --git a/gpt4free/quora/graphql/ChatAddedSubscription.graphql b/gpt4free/quora/graphql/ChatAddedSubscription.graphql new file mode 100644 index 00000000..664b107f --- /dev/null +++ b/gpt4free/quora/graphql/ChatAddedSubscription.graphql @@ -0,0 +1,5 @@ +subscription ChatAddedSubscription { + chatAdded { + ...ChatFragment + } +} diff --git a/gpt4free/quora/graphql/ChatFragment.graphql b/gpt4free/quora/graphql/ChatFragment.graphql new file mode 100644 index 00000000..605645ff --- /dev/null +++ b/gpt4free/quora/graphql/ChatFragment.graphql @@ -0,0 +1,6 @@ +fragment ChatFragment on Chat { + id + chatId + defaultBotNickname + shouldShowDisclaimer +} diff --git a/gpt4free/quora/graphql/ChatListPaginationQuery.graphql b/gpt4free/quora/graphql/ChatListPaginationQuery.graphql new file mode 100644 index 00000000..6d9ae884 --- /dev/null +++ b/gpt4free/quora/graphql/ChatListPaginationQuery.graphql @@ -0,0 +1,378 @@ +query ChatListPaginationQuery( + $count: Int = 5 + $cursor: String + $id: ID! +) { + node(id: $id) { + __typename + ...ChatPageMain_chat_1G22uz + id + } +} + +fragment BotImage_bot on Bot { + displayName + ...botHelpers_useDeletion_bot + ...BotImage_useProfileImage_bot +} + +fragment BotImage_useProfileImage_bot on Bot { + image { + __typename + ... on LocalBotImage { + localName + } + ... on UrlBotImage { + url + } + } + ...botHelpers_useDeletion_bot +} + +fragment ChatMessageDownvotedButton_message on Message { + ...MessageFeedbackReasonModal_message + ...MessageFeedbackOtherModal_message +} + +fragment ChatMessageDropdownMenu_message on Message { + id + messageId + vote + text + author + ...chatHelpers_isBotMessage +} + +fragment ChatMessageFeedbackButtons_message on Message { + id + messageId + vote + voteReason + ...ChatMessageDownvotedButton_message +} + +fragment ChatMessageInputView_chat on Chat { + id + chatId + defaultBotObject { + nickname + messageLimit { + dailyBalance + shouldShowRemainingMessageCount + } + hasClearContext + isDown + ...botHelpers_useDeletion_bot + id + } + shouldShowDisclaimer + ...chatHelpers_useSendMessage_chat + ...chatHelpers_useSendChatBreak_chat +} + +fragment ChatMessageInputView_edges on MessageEdge { + node { + ...chatHelpers_isChatBreak + ...chatHelpers_isHumanMessage + state + text + id + } +} + +fragment ChatMessageOverflowButton_message on Message { + text + ...ChatMessageDropdownMenu_message + ...chatHelpers_isBotMessage +} + +fragment ChatMessageSuggestedReplies_SuggestedReplyButton_chat on Chat { + ...chatHelpers_useSendMessage_chat +} + +fragment ChatMessageSuggestedReplies_SuggestedReplyButton_message on Message { + messageId +} + +fragment ChatMessageSuggestedReplies_chat on Chat { + ...ChatWelcomeView_chat + ...ChatMessageSuggestedReplies_SuggestedReplyButton_chat + defaultBotObject { + hasWelcomeTopics + id + } +} + +fragment ChatMessageSuggestedReplies_message on Message { + suggestedReplies + ...ChatMessageSuggestedReplies_SuggestedReplyButton_message +} + +fragment ChatMessage_chat on Chat { + defaultBotObject { + hasWelcomeTopics + hasSuggestedReplies + disclaimerText + messageLimit { + ...ChatPageRateLimitedBanner_messageLimit + } + ...ChatPageDisclaimer_bot + id + } + ...ChatMessageSuggestedReplies_chat + ...ChatWelcomeView_chat +} + +fragment ChatMessage_message on Message { + id + messageId + text + author + linkifiedText + state + contentType + ...ChatMessageSuggestedReplies_message + ...ChatMessageFeedbackButtons_message + ...ChatMessageOverflowButton_message + ...chatHelpers_isHumanMessage + ...chatHelpers_isBotMessage + ...chatHelpers_isChatBreak + ...chatHelpers_useTimeoutLevel + ...MarkdownLinkInner_message + ...IdAnnotation_node +} + +fragment ChatMessagesView_chat on Chat { + ...ChatMessage_chat + ...ChatWelcomeView_chat + ...IdAnnotation_node + defaultBotObject { + hasWelcomeTopics + messageLimit { + ...ChatPageRateLimitedBanner_messageLimit + } + id + } +} + +fragment ChatMessagesView_edges on MessageEdge { + node { + id + messageId + creationTime + ...ChatMessage_message + ...chatHelpers_isBotMessage + ...chatHelpers_isHumanMessage + ...chatHelpers_isChatBreak + } +} + +fragment ChatPageDeleteFooter_chat on Chat { + ...MessageDeleteConfirmationModal_chat +} + +fragment ChatPageDisclaimer_bot on Bot { + disclaimerText +} + +fragment ChatPageMainFooter_chat on Chat { + defaultBotObject { + ...ChatPageMainFooter_useAccessMessage_bot + id + } + ...ChatMessageInputView_chat + ...ChatPageShareFooter_chat + ...ChatPageDeleteFooter_chat +} + +fragment ChatPageMainFooter_edges on MessageEdge { + ...ChatMessageInputView_edges +} + +fragment ChatPageMainFooter_useAccessMessage_bot on Bot { + ...botHelpers_useDeletion_bot + ...botHelpers_useViewerCanAccessPrivateBot +} + +fragment ChatPageMain_chat_1G22uz on Chat { + id + chatId + ...ChatPageShareFooter_chat + ...ChatPageDeleteFooter_chat + ...ChatMessagesView_chat + ...MarkdownLinkInner_chat + ...chatHelpers_useUpdateStaleChat_chat + ...ChatSubscriptionPaywallContextWrapper_chat + ...ChatPageMainFooter_chat + messagesConnection(last: $count, before: $cursor) { + edges { + ...ChatMessagesView_edges + ...ChatPageMainFooter_edges + ...MarkdownLinkInner_edges + node { + ...chatHelpers_useUpdateStaleChat_message + id + __typename + } + cursor + id + } + pageInfo { + hasPreviousPage + startCursor + } + id + } +} + +fragment ChatPageRateLimitedBanner_messageLimit on MessageLimit { + numMessagesRemaining +} + +fragment ChatPageShareFooter_chat on Chat { + chatId +} + +fragment ChatSubscriptionPaywallContextWrapper_chat on Chat { + defaultBotObject { + messageLimit { + numMessagesRemaining + shouldShowRemainingMessageCount + } + ...SubscriptionPaywallModal_bot + id + } +} + +fragment ChatWelcomeView_ChatWelcomeButton_chat on Chat { + ...chatHelpers_useSendMessage_chat +} + +fragment ChatWelcomeView_chat on Chat { + ...ChatWelcomeView_ChatWelcomeButton_chat + defaultBotObject { + displayName + id + } +} + +fragment IdAnnotation_node on Node { + __isNode: __typename + id +} + +fragment MarkdownLinkInner_chat on Chat { + id + chatId + defaultBotObject { + nickname + id + } + ...chatHelpers_useSendMessage_chat +} + +fragment MarkdownLinkInner_edges on MessageEdge { + node { + state + id + } +} + +fragment MarkdownLinkInner_message on Message { + messageId +} + +fragment MessageDeleteConfirmationModal_chat on Chat { + id +} + +fragment MessageFeedbackOtherModal_message on Message { + id + messageId +} + +fragment MessageFeedbackReasonModal_message on Message { + id + messageId +} + +fragment SubscriptionPaywallModal_bot on Bot { + displayName + messageLimit { + dailyLimit + numMessagesRemaining + shouldShowRemainingMessageCount + resetTime + } + ...BotImage_bot +} + +fragment botHelpers_useDeletion_bot on Bot { + deletionState +} + +fragment botHelpers_useViewerCanAccessPrivateBot on Bot { + isPrivateBot + viewerIsCreator +} + +fragment chatHelpers_isBotMessage on Message { + ...chatHelpers_isHumanMessage + ...chatHelpers_isChatBreak +} + +fragment chatHelpers_isChatBreak on Message { + author +} + +fragment chatHelpers_isHumanMessage on Message { + author +} + +fragment chatHelpers_useSendChatBreak_chat on Chat { + id + chatId + defaultBotObject { + nickname + introduction + model + id + } + shouldShowDisclaimer +} + +fragment chatHelpers_useSendMessage_chat on Chat { + id + chatId + defaultBotObject { + id + nickname + } + shouldShowDisclaimer +} + +fragment chatHelpers_useTimeoutLevel on Message { + id + state + text + messageId + chat { + chatId + defaultBotNickname + id + } +} + +fragment chatHelpers_useUpdateStaleChat_chat on Chat { + chatId + defaultBotObject { + contextClearWindowSecs + id + } + ...chatHelpers_useSendChatBreak_chat +} + +fragment chatHelpers_useUpdateStaleChat_message on Message { + creationTime + ...chatHelpers_isChatBreak +} diff --git a/gpt4free/quora/graphql/ChatPaginationQuery.graphql b/gpt4free/quora/graphql/ChatPaginationQuery.graphql new file mode 100644 index 00000000..f2452cd6 --- /dev/null +++ b/gpt4free/quora/graphql/ChatPaginationQuery.graphql @@ -0,0 +1,26 @@ +query ChatPaginationQuery($bot: String!, $before: String, $last: Int! = 10) { + chatOfBot(bot: $bot) { + id + __typename + messagesConnection(before: $before, last: $last) { + pageInfo { + hasPreviousPage + } + edges { + node { + id + __typename + messageId + text + linkifiedText + authorNickname + state + vote + voteReason + creationTime + suggestedReplies + } + } + } + } +} diff --git a/gpt4free/quora/graphql/ChatViewQuery.graphql b/gpt4free/quora/graphql/ChatViewQuery.graphql new file mode 100644 index 00000000..c330107d --- /dev/null +++ b/gpt4free/quora/graphql/ChatViewQuery.graphql @@ -0,0 +1,8 @@ +query ChatViewQuery($bot: String!) { + chatOfBot(bot: $bot) { + id + chatId + defaultBotNickname + shouldShowDisclaimer + } +} diff --git a/gpt4free/quora/graphql/DeleteHumanMessagesMutation.graphql b/gpt4free/quora/graphql/DeleteHumanMessagesMutation.graphql new file mode 100644 index 00000000..42692c6e --- /dev/null +++ b/gpt4free/quora/graphql/DeleteHumanMessagesMutation.graphql @@ -0,0 +1,7 @@ +mutation DeleteHumanMessagesMutation($messageIds: [BigInt!]!) { + messagesDelete(messageIds: $messageIds) { + viewer { + id + } + } +} diff --git a/gpt4free/quora/graphql/DeleteMessageMutation.graphql b/gpt4free/quora/graphql/DeleteMessageMutation.graphql new file mode 100644 index 00000000..7b9e36d4 --- /dev/null +++ b/gpt4free/quora/graphql/DeleteMessageMutation.graphql @@ -0,0 +1,7 @@ +mutation deleteMessageMutation( + $messageIds: [BigInt!]! +) { + messagesDelete(messageIds: $messageIds) { + edgeIds + } +} \ No newline at end of file diff --git a/gpt4free/quora/graphql/HandleFragment.graphql b/gpt4free/quora/graphql/HandleFragment.graphql new file mode 100644 index 00000000..f53c484b --- /dev/null +++ b/gpt4free/quora/graphql/HandleFragment.graphql @@ -0,0 +1,8 @@ +fragment HandleFragment on Viewer { + id + poeUser { + id + uid + handle + } +} diff --git a/gpt4free/quora/graphql/LoginWithVerificationCodeMutation.graphql b/gpt4free/quora/graphql/LoginWithVerificationCodeMutation.graphql new file mode 100644 index 00000000..723b1f44 --- /dev/null +++ b/gpt4free/quora/graphql/LoginWithVerificationCodeMutation.graphql @@ -0,0 +1,13 @@ +mutation LoginWithVerificationCodeMutation( + $verificationCode: String! + $emailAddress: String + $phoneNumber: String +) { + loginWithVerificationCode( + verificationCode: $verificationCode + emailAddress: $emailAddress + phoneNumber: $phoneNumber + ) { + status + } +} diff --git a/gpt4free/quora/graphql/MessageAddedSubscription.graphql b/gpt4free/quora/graphql/MessageAddedSubscription.graphql new file mode 100644 index 00000000..8dc9499c --- /dev/null +++ b/gpt4free/quora/graphql/MessageAddedSubscription.graphql @@ -0,0 +1,100 @@ +subscription messageAdded ( + $chatId: BigInt! +) { + messageAdded(chatId: $chatId) { + id + messageId + creationTime + state + ...ChatMessage_message + ...chatHelpers_isBotMessage + } +} + +fragment ChatMessageDownvotedButton_message on Message { + ...MessageFeedbackReasonModal_message + ...MessageFeedbackOtherModal_message +} + +fragment ChatMessageDropdownMenu_message on Message { + id + messageId + vote + text + linkifiedText + ...chatHelpers_isBotMessage +} + +fragment ChatMessageFeedbackButtons_message on Message { + id + messageId + vote + voteReason + ...ChatMessageDownvotedButton_message +} + +fragment ChatMessageOverflowButton_message on Message { + text + ...ChatMessageDropdownMenu_message + ...chatHelpers_isBotMessage +} + +fragment ChatMessageSuggestedReplies_SuggestedReplyButton_message on Message { + messageId +} + +fragment ChatMessageSuggestedReplies_message on Message { + suggestedReplies + ...ChatMessageSuggestedReplies_SuggestedReplyButton_message +} + +fragment ChatMessage_message on Message { + id + messageId + text + author + linkifiedText + state + ...ChatMessageSuggestedReplies_message + ...ChatMessageFeedbackButtons_message + ...ChatMessageOverflowButton_message + ...chatHelpers_isHumanMessage + ...chatHelpers_isBotMessage + ...chatHelpers_isChatBreak + ...chatHelpers_useTimeoutLevel + ...MarkdownLinkInner_message +} + +fragment MarkdownLinkInner_message on Message { + messageId +} + +fragment MessageFeedbackOtherModal_message on Message { + id + messageId +} + +fragment MessageFeedbackReasonModal_message on Message { + id + messageId +} + +fragment chatHelpers_isBotMessage on Message { + ...chatHelpers_isHumanMessage + ...chatHelpers_isChatBreak +} + +fragment chatHelpers_isChatBreak on Message { + author +} + +fragment chatHelpers_isHumanMessage on Message { + author +} + +fragment chatHelpers_useTimeoutLevel on Message { + id + state + text + messageId +} diff --git a/gpt4free/quora/graphql/MessageDeletedSubscription.graphql b/gpt4free/quora/graphql/MessageDeletedSubscription.graphql new file mode 100644 index 00000000..54c1c164 --- /dev/null +++ b/gpt4free/quora/graphql/MessageDeletedSubscription.graphql @@ -0,0 +1,6 @@ +subscription MessageDeletedSubscription($chatId: BigInt!) { + messageDeleted(chatId: $chatId) { + id + messageId + } +} diff --git a/gpt4free/quora/graphql/MessageFragment.graphql b/gpt4free/quora/graphql/MessageFragment.graphql new file mode 100644 index 00000000..cc860811 --- /dev/null +++ b/gpt4free/quora/graphql/MessageFragment.graphql @@ -0,0 +1,13 @@ +fragment MessageFragment on Message { + id + __typename + messageId + text + linkifiedText + authorNickname + state + vote + voteReason + creationTime + suggestedReplies +} diff --git a/gpt4free/quora/graphql/MessageRemoveVoteMutation.graphql b/gpt4free/quora/graphql/MessageRemoveVoteMutation.graphql new file mode 100644 index 00000000..d5e6e610 --- /dev/null +++ b/gpt4free/quora/graphql/MessageRemoveVoteMutation.graphql @@ -0,0 +1,7 @@ +mutation MessageRemoveVoteMutation($messageId: BigInt!) { + messageRemoveVote(messageId: $messageId) { + message { + ...MessageFragment + } + } +} diff --git a/gpt4free/quora/graphql/MessageSetVoteMutation.graphql b/gpt4free/quora/graphql/MessageSetVoteMutation.graphql new file mode 100644 index 00000000..76000df0 --- /dev/null +++ b/gpt4free/quora/graphql/MessageSetVoteMutation.graphql @@ -0,0 +1,7 @@ +mutation MessageSetVoteMutation($messageId: BigInt!, $voteType: VoteType!, $reason: String) { + messageSetVote(messageId: $messageId, voteType: $voteType, reason: $reason) { + message { + ...MessageFragment + } + } +} diff --git a/gpt4free/quora/graphql/PoeBotCreateMutation.graphql b/gpt4free/quora/graphql/PoeBotCreateMutation.graphql new file mode 100644 index 00000000..971b4248 --- /dev/null +++ b/gpt4free/quora/graphql/PoeBotCreateMutation.graphql @@ -0,0 +1,73 @@ +mutation CreateBotMain_poeBotCreate_Mutation( + $model: String! + $handle: String! + $prompt: String! + $isPromptPublic: Boolean! + $introduction: String! + $description: String! + $profilePictureUrl: String + $apiUrl: String + $apiKey: String + $isApiBot: Boolean + $hasLinkification: Boolean + $hasMarkdownRendering: Boolean + $hasSuggestedReplies: Boolean + $isPrivateBot: Boolean +) { + poeBotCreate(model: $model, handle: $handle, promptPlaintext: $prompt, isPromptPublic: $isPromptPublic, introduction: $introduction, description: $description, profilePicture: $profilePictureUrl, apiUrl: $apiUrl, apiKey: $apiKey, isApiBot: $isApiBot, hasLinkification: $hasLinkification, hasMarkdownRendering: $hasMarkdownRendering, hasSuggestedReplies: $hasSuggestedReplies, isPrivateBot: $isPrivateBot) { + status + bot { + id + ...BotHeader_bot + } + } +} + +fragment BotHeader_bot on Bot { + displayName + messageLimit { + dailyLimit + } + ...BotImage_bot + ...BotLink_bot + ...IdAnnotation_node + ...botHelpers_useViewerCanAccessPrivateBot + ...botHelpers_useDeletion_bot +} + +fragment BotImage_bot on Bot { + displayName + ...botHelpers_useDeletion_bot + ...BotImage_useProfileImage_bot +} + +fragment BotImage_useProfileImage_bot on Bot { + image { + __typename + ... on LocalBotImage { + localName + } + ... on UrlBotImage { + url + } + } + ...botHelpers_useDeletion_bot +} + +fragment BotLink_bot on Bot { + displayName +} + +fragment IdAnnotation_node on Node { + __isNode: __typename + id +} + +fragment botHelpers_useDeletion_bot on Bot { + deletionState +} + +fragment botHelpers_useViewerCanAccessPrivateBot on Bot { + isPrivateBot + viewerIsCreator +} \ No newline at end of file diff --git a/gpt4free/quora/graphql/PoeBotEditMutation.graphql b/gpt4free/quora/graphql/PoeBotEditMutation.graphql new file mode 100644 index 00000000..fdd309ef --- /dev/null +++ b/gpt4free/quora/graphql/PoeBotEditMutation.graphql @@ -0,0 +1,24 @@ +mutation EditBotMain_poeBotEdit_Mutation( + $botId: BigInt! + $handle: String! + $description: String! + $introduction: String! + $isPromptPublic: Boolean! + $baseBot: String! + $profilePictureUrl: String + $prompt: String! + $apiUrl: String + $apiKey: String + $hasLinkification: Boolean + $hasMarkdownRendering: Boolean + $hasSuggestedReplies: Boolean + $isPrivateBot: Boolean +) { + poeBotEdit(botId: $botId, handle: $handle, description: $description, introduction: $introduction, isPromptPublic: $isPromptPublic, model: $baseBot, promptPlaintext: $prompt, profilePicture: $profilePictureUrl, apiUrl: $apiUrl, apiKey: $apiKey, hasLinkification: $hasLinkification, hasMarkdownRendering: $hasMarkdownRendering, hasSuggestedReplies: $hasSuggestedReplies, isPrivateBot: $isPrivateBot) { + status + bot { + handle + id + } + } +} \ No newline at end of file diff --git a/gpt4free/quora/graphql/SendMessageMutation.graphql b/gpt4free/quora/graphql/SendMessageMutation.graphql new file mode 100644 index 00000000..4b0a4383 --- /dev/null +++ b/gpt4free/quora/graphql/SendMessageMutation.graphql @@ -0,0 +1,40 @@ +mutation chatHelpers_sendMessageMutation_Mutation( + $chatId: BigInt! + $bot: String! + $query: String! + $source: MessageSource + $withChatBreak: Boolean! +) { + messageEdgeCreate(chatId: $chatId, bot: $bot, query: $query, source: $source, withChatBreak: $withChatBreak) { + chatBreak { + cursor + node { + id + messageId + text + author + suggestedReplies + creationTime + state + } + id + } + message { + cursor + node { + id + messageId + text + author + suggestedReplies + creationTime + state + chat { + shouldShowDisclaimer + id + } + } + id + } + } +} diff --git a/gpt4free/quora/graphql/SendVerificationCodeForLoginMutation.graphql b/gpt4free/quora/graphql/SendVerificationCodeForLoginMutation.graphql new file mode 100644 index 00000000..45af4799 --- /dev/null +++ b/gpt4free/quora/graphql/SendVerificationCodeForLoginMutation.graphql @@ -0,0 +1,12 @@ +mutation SendVerificationCodeForLoginMutation( + $emailAddress: String + $phoneNumber: String +) { + sendVerificationCode( + verificationReason: login + emailAddress: $emailAddress + phoneNumber: $phoneNumber + ) { + status + } +} diff --git a/gpt4free/quora/graphql/ShareMessagesMutation.graphql b/gpt4free/quora/graphql/ShareMessagesMutation.graphql new file mode 100644 index 00000000..92e80db5 --- /dev/null +++ b/gpt4free/quora/graphql/ShareMessagesMutation.graphql @@ -0,0 +1,9 @@ +mutation ShareMessagesMutation( + $chatId: BigInt! + $messageIds: [BigInt!]! + $comment: String +) { + messagesShare(chatId: $chatId, messageIds: $messageIds, comment: $comment) { + shareCode + } +} diff --git a/gpt4free/quora/graphql/SignupWithVerificationCodeMutation.graphql b/gpt4free/quora/graphql/SignupWithVerificationCodeMutation.graphql new file mode 100644 index 00000000..06b2826f --- /dev/null +++ b/gpt4free/quora/graphql/SignupWithVerificationCodeMutation.graphql @@ -0,0 +1,13 @@ +mutation SignupWithVerificationCodeMutation( + $verificationCode: String! + $emailAddress: String + $phoneNumber: String +) { + signupWithVerificationCode( + verificationCode: $verificationCode + emailAddress: $emailAddress + phoneNumber: $phoneNumber + ) { + status + } +} diff --git a/gpt4free/quora/graphql/StaleChatUpdateMutation.graphql b/gpt4free/quora/graphql/StaleChatUpdateMutation.graphql new file mode 100644 index 00000000..de203d47 --- /dev/null +++ b/gpt4free/quora/graphql/StaleChatUpdateMutation.graphql @@ -0,0 +1,7 @@ +mutation StaleChatUpdateMutation($chatId: BigInt!) { + staleChatUpdate(chatId: $chatId) { + message { + ...MessageFragment + } + } +} diff --git a/gpt4free/quora/graphql/SubscriptionsMutation.graphql b/gpt4free/quora/graphql/SubscriptionsMutation.graphql new file mode 100644 index 00000000..b864bd60 --- /dev/null +++ b/gpt4free/quora/graphql/SubscriptionsMutation.graphql @@ -0,0 +1,9 @@ +mutation subscriptionsMutation( + $subscriptions: [AutoSubscriptionQuery!]! +) { + autoSubscribe(subscriptions: $subscriptions) { + viewer { + id + } + } +} \ No newline at end of file diff --git a/gpt4free/quora/graphql/SummarizePlainPostQuery.graphql b/gpt4free/quora/graphql/SummarizePlainPostQuery.graphql new file mode 100644 index 00000000..afa2a84c --- /dev/null +++ b/gpt4free/quora/graphql/SummarizePlainPostQuery.graphql @@ -0,0 +1,3 @@ +query SummarizePlainPostQuery($comment: String!) { + summarizePlainPost(comment: $comment) +} diff --git a/gpt4free/quora/graphql/SummarizeQuotePostQuery.graphql b/gpt4free/quora/graphql/SummarizeQuotePostQuery.graphql new file mode 100644 index 00000000..5147c3c5 --- /dev/null +++ b/gpt4free/quora/graphql/SummarizeQuotePostQuery.graphql @@ -0,0 +1,3 @@ +query SummarizeQuotePostQuery($comment: String, $quotedPostId: BigInt!) { + summarizeQuotePost(comment: $comment, quotedPostId: $quotedPostId) +} diff --git a/gpt4free/quora/graphql/SummarizeSharePostQuery.graphql b/gpt4free/quora/graphql/SummarizeSharePostQuery.graphql new file mode 100644 index 00000000..cb4a623c --- /dev/null +++ b/gpt4free/quora/graphql/SummarizeSharePostQuery.graphql @@ -0,0 +1,3 @@ +query SummarizeSharePostQuery($comment: String!, $chatId: BigInt!, $messageIds: [BigInt!]!) { + summarizeSharePost(comment: $comment, chatId: $chatId, messageIds: $messageIds) +} diff --git a/gpt4free/quora/graphql/UserSnippetFragment.graphql b/gpt4free/quora/graphql/UserSnippetFragment.graphql new file mode 100644 index 00000000..17fc8426 --- /dev/null +++ b/gpt4free/quora/graphql/UserSnippetFragment.graphql @@ -0,0 +1,14 @@ +fragment UserSnippetFragment on PoeUser { + id + uid + bio + handle + fullName + viewerIsFollowing + isPoeOnlyUser + profilePhotoURLTiny: profilePhotoUrl(size: tiny) + profilePhotoURLSmall: profilePhotoUrl(size: small) + profilePhotoURLMedium: profilePhotoUrl(size: medium) + profilePhotoURLLarge: profilePhotoUrl(size: large) + isFollowable +} diff --git a/gpt4free/quora/graphql/ViewerInfoQuery.graphql b/gpt4free/quora/graphql/ViewerInfoQuery.graphql new file mode 100644 index 00000000..1ecaf9e8 --- /dev/null +++ b/gpt4free/quora/graphql/ViewerInfoQuery.graphql @@ -0,0 +1,21 @@ +query ViewerInfoQuery { + viewer { + id + uid + ...ViewerStateFragment + ...BioFragment + ...HandleFragment + hasCompletedMultiplayerNux + poeUser { + id + ...UserSnippetFragment + } + messageLimit{ + canSend + numMessagesRemaining + resetTime + shouldShowReminder + } + } +} + diff --git a/gpt4free/quora/graphql/ViewerStateFragment.graphql b/gpt4free/quora/graphql/ViewerStateFragment.graphql new file mode 100644 index 00000000..3cd83e9c --- /dev/null +++ b/gpt4free/quora/graphql/ViewerStateFragment.graphql @@ -0,0 +1,30 @@ +fragment ViewerStateFragment on Viewer { + id + __typename + iosMinSupportedVersion: integerGate(gateName: "poe_ios_min_supported_version") + iosMinEncouragedVersion: integerGate( + gateName: "poe_ios_min_encouraged_version" + ) + macosMinSupportedVersion: integerGate( + gateName: "poe_macos_min_supported_version" + ) + macosMinEncouragedVersion: integerGate( + gateName: "poe_macos_min_encouraged_version" + ) + showPoeDebugPanel: booleanGate(gateName: "poe_show_debug_panel") + enableCommunityFeed: booleanGate(gateName: "enable_poe_shares_feed") + linkifyText: booleanGate(gateName: "poe_linkify_response") + enableSuggestedReplies: booleanGate(gateName: "poe_suggested_replies") + removeInviteLimit: booleanGate(gateName: "poe_remove_invite_limit") + enableInAppPurchases: booleanGate(gateName: "poe_enable_in_app_purchases") + availableBots { + nickname + displayName + profilePicture + isDown + disclaimer + subtitle + poweredBy + } +} + diff --git a/gpt4free/quora/graphql/ViewerStateUpdatedSubscription.graphql b/gpt4free/quora/graphql/ViewerStateUpdatedSubscription.graphql new file mode 100644 index 00000000..03fc73d1 --- /dev/null +++ b/gpt4free/quora/graphql/ViewerStateUpdatedSubscription.graphql @@ -0,0 +1,43 @@ +subscription viewerStateUpdated { + viewerStateUpdated { + id + ...ChatPageBotSwitcher_viewer + } +} + +fragment BotHeader_bot on Bot { + displayName + messageLimit { + dailyLimit + } + ...BotImage_bot +} + +fragment BotImage_bot on Bot { + image { + __typename + ... on LocalBotImage { + localName + } + ... on UrlBotImage { + url + } + } + displayName +} + +fragment BotLink_bot on Bot { + displayName +} + +fragment ChatPageBotSwitcher_viewer on Viewer { + availableBots { + id + messageLimit { + dailyLimit + } + ...BotLink_bot + ...BotHeader_bot + } + allowUserCreatedBots: booleanGate(gateName: "enable_user_created_bots") +} diff --git a/gpt4free/quora/graphql/__init__.py b/gpt4free/quora/graphql/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/gpt4free/quora/mail.py b/gpt4free/quora/mail.py new file mode 100644 index 00000000..e6ce96c2 --- /dev/null +++ b/gpt4free/quora/mail.py @@ -0,0 +1,82 @@ +from json import loads +from re import findall +from time import sleep + +from fake_useragent import UserAgent +from requests import Session + + +class Emailnator: + def __init__(self) -> None: + self.client = Session() + self.client.get("https://www.emailnator.com/", timeout=6) + self.cookies = self.client.cookies.get_dict() + + self.client.headers = { + "authority": "www.emailnator.com", + "origin": "https://www.emailnator.com", + "referer": "https://www.emailnator.com/", + "user-agent": UserAgent().random, + "x-xsrf-token": self.client.cookies.get("XSRF-TOKEN")[:-3] + "=", + } + + self.email = None + + def get_mail(self): + response = self.client.post( + "https://www.emailnator.com/generate-email", + json={ + "email": [ + "domain", + "plusGmail", + "dotGmail", + ] + }, + ) + + self.email = loads(response.text)["email"][0] + return self.email + + def get_message(self): + print("Waiting for message...") + + while True: + sleep(2) + mail_token = self.client.post( + "https://www.emailnator.com/message-list", json={"email": self.email} + ) + + mail_token = loads(mail_token.text)["messageData"] + + if len(mail_token) == 2: + print("Message received!") + print(mail_token[1]["messageID"]) + break + + mail_context = self.client.post( + "https://www.emailnator.com/message-list", + json={ + "email": self.email, + "messageID": mail_token[1]["messageID"], + }, + ) + + return mail_context.text + + def get_verification_code(self): + message = self.get_message() + code = findall(r';">(\d{6,7})', message)[0] + print(f"Verification code: {code}") + return code + + def clear_inbox(self): + print("Clearing inbox...") + self.client.post( + "https://www.emailnator.com/delete-all", + json={"email": self.email}, + ) + print("Inbox cleared!") + + def __del__(self): + if self.email: + self.clear_inbox() diff --git a/gpt4free/theb/README.md b/gpt4free/theb/README.md new file mode 100644 index 00000000..a4abdf62 --- /dev/null +++ b/gpt4free/theb/README.md @@ -0,0 +1,11 @@ +### Example: `theb` (use like openai pypi package) + +```python +# import library +from gpt4free import theb + +# simple streaming completion +for token in theb.Completion.create('hello world'): + print(token, end='', flush=True) +print("") +``` diff --git a/gpt4free/theb/__init__.py b/gpt4free/theb/__init__.py new file mode 100644 index 00000000..726e025e --- /dev/null +++ b/gpt4free/theb/__init__.py @@ -0,0 +1,50 @@ +from re import findall +from json import loads +from queue import Queue, Empty +from threading import Thread +from curl_cffi import requests + +class Completion: + # experimental + part1 = '{"role":"assistant","id":"chatcmpl' + part2 = '"},"index":0,"finish_reason":null}]}}' + regex = rf'{part1}(.*){part2}' + + timer = None + message_queue = Queue() + stream_completed = False + + def request(prompt: str): + headers = { + 'authority': 'chatbot.theb.ai', + 'content-type': 'application/json', + 'origin': 'https://chatbot.theb.ai', + 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36', + } + + requests.post('https://chatbot.theb.ai/api/chat-process', headers=headers, + content_callback = Completion.handle_stream_response, + json = { + 'prompt': prompt, + 'options': {} + } + ) + + Completion.stream_completed = True + + @staticmethod + def create(prompt: str): + Thread(target=Completion.request, args=[prompt]).start() + + while Completion.stream_completed != True or not Completion.message_queue.empty(): + try: + message = Completion.message_queue.get(timeout=0.01) + for message in findall(Completion.regex, message): + yield loads(Completion.part1 + message + Completion.part2)['delta'] + + except Empty: + pass + + @staticmethod + def handle_stream_response(response): + Completion.message_queue.put(response.decode()) diff --git a/gpt4free/theb/theb_test.py b/gpt4free/theb/theb_test.py new file mode 100644 index 00000000..177c970a --- /dev/null +++ b/gpt4free/theb/theb_test.py @@ -0,0 +1,4 @@ +import theb + +for token in theb.Completion.create('hello world'): + print(token, end='', flush=True) \ No newline at end of file diff --git a/gpt4free/you/README.md b/gpt4free/you/README.md new file mode 100644 index 00000000..11b4723e --- /dev/null +++ b/gpt4free/you/README.md @@ -0,0 +1,38 @@ +### Example: `you` (use like openai pypi package) + +```python + +from gpt4free import you + +# simple request with links and details +response = you.Completion.create( + prompt="hello world", + detailed=True, + include_links=True, ) + +print(response) + +# { +# "response": "...", +# "links": [...], +# "extra": {...}, +# "slots": {...} +# } +# } + +# chatbot + +chat = [] + +while True: + prompt = input("You: ") + if prompt == 'q': + break + response = you.Completion.create( + prompt=prompt, + chat=chat) + + print("Bot:", response["response"]) + + chat.append({"question": prompt, "answer": response["response"]}) +``` diff --git a/gpt4free/you/__init__.py b/gpt4free/you/__init__.py new file mode 100644 index 00000000..97b48464 --- /dev/null +++ b/gpt4free/you/__init__.py @@ -0,0 +1,108 @@ +import json +import re +from typing import Optional, List, Dict, Any +from uuid import uuid4 + +from fake_useragent import UserAgent +from pydantic import BaseModel +from tls_client import Session + + +class PoeResponse(BaseModel): + text: Optional[str] = None + links: List[str] = [] + extra: Dict[str, Any] = {} + + +class Completion: + @staticmethod + def create( + prompt: str, + page: int = 1, + count: int = 10, + safe_search: str = 'Moderate', + on_shopping_page: bool = False, + mkt: str = '', + response_filter: str = 'WebPages,Translations,TimeZone,Computation,RelatedSearches', + domain: str = 'youchat', + query_trace_id: str = None, + chat: list = None, + include_links: bool = False, + detailed: bool = False, + debug: bool = False, + ) -> PoeResponse: + if chat is None: + chat = [] + + client = Session(client_identifier='chrome_108') + client.headers = Completion.__get_headers() + + response = client.get( + f'https://you.com/api/streamingSearch', + params={ + 'q': prompt, + 'page': page, + 'count': count, + 'safeSearch': safe_search, + 'onShoppingPage': on_shopping_page, + 'mkt': mkt, + 'responseFilter': response_filter, + 'domain': domain, + 'queryTraceId': str(uuid4()) if query_trace_id is None else query_trace_id, + 'chat': str(chat), # {'question':'','answer':' ''} + }, + ) + + if debug: + print('\n\n------------------\n\n') + print(response.text) + print('\n\n------------------\n\n') + + if 'youChatToken' not in response.text: + return Completion.__get_failure_response() + + you_chat_serp_results = re.search( + r'(?<=event: youChatSerpResults\ndata:)(.*\n)*?(?=event: )', response.text + ).group() + third_party_search_results = re.search( + r'(?<=event: thirdPartySearchResults\ndata:)(.*\n)*?(?=event: )', response.text + ).group() + # slots = findall(r"slots\ndata: (.*)\n\nevent", response.text)[0] + + text = ''.join(re.findall(r'{\"youChatToken\": \"(.*?)\"}', response.text)) + + extra = { + 'youChatSerpResults': json.loads(you_chat_serp_results), + # 'slots' : loads(slots) + } + + response = PoeResponse(text=text.replace('\\n', '\n').replace('\\\\', '\\').replace('\\"', '"')) + if include_links: + response.links = json.loads(third_party_search_results)['search']['third_party_search_results'] + + if detailed: + response.extra = extra + + return response + + @staticmethod + def __get_headers() -> dict: + return { + 'authority': 'you.com', + 'accept': 'text/event-stream', + 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3', + 'cache-control': 'no-cache', + 'referer': 'https://you.com/search?q=who+are+you&tbm=youchat', + 'sec-ch-ua': '"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'empty', + 'sec-fetch-mode': 'cors', + 'sec-fetch-site': 'same-origin', + 'cookie': f'safesearch_guest=Moderate; uuid_guest={str(uuid4())}', + 'user-agent': UserAgent().random, + } + + @staticmethod + def __get_failure_response() -> PoeResponse: + return PoeResponse(text='Unable to fetch the response, Please try again.') diff --git a/gui/query_methods.py b/gui/query_methods.py index 1a4a3402..adb4ae91 100644 --- a/gui/query_methods.py +++ b/gui/query_methods.py @@ -3,7 +3,7 @@ import sys sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir)) -import forefront, quora, theb, you +from gpt4free import quora, forefront, theb, you import random @@ -15,7 +15,7 @@ def query_forefront(question: str) -> str: response = "" # get a response try: - for i in forefront.StreamingCompletion.create(token = token, prompt = 'hello world', model='gpt-4'): + for i in forefront.StreamingCompletion.create(token = token, prompt ='hello world', model='gpt-4'): response += i.completion.choices[0].text return response diff --git a/gui/streamlit_app.py b/gui/streamlit_app.py index 8a6bcfa9..2dba0a7b 100644 --- a/gui/streamlit_app.py +++ b/gui/streamlit_app.py @@ -4,7 +4,7 @@ import sys sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir)) import streamlit as st -import you +from gpt4free import you def get_answer(question: str) -> str: diff --git a/pyproject.toml b/pyproject.toml index 7d3be065..7c2244f5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ description = "" authors = ["Raju Komati "] license = "GPL-3.0" readme = "README.md" -packages = [{ include = "openai_rev" }] +packages = [{ include = "gpt4free" }] exclude = ["**/*.txt"] [tool.poetry.dependencies] diff --git a/quora/README.md b/quora/README.md deleted file mode 100644 index 24679277..00000000 --- a/quora/README.md +++ /dev/null @@ -1,69 +0,0 @@ - -> ⚠ Warning !!! -poe.com added security and can detect if you are making automated requests. You may get your account banned if you are using this api. -The normal non-driver api is also currently not very stable - - -### Example: `quora (poe)` (use like openai pypi package) - GPT-4 - -```python -# quora model names: (use left key as argument) -models = { - 'sage' : 'capybara', - 'gpt-4' : 'beaver', - 'claude-v1.2' : 'a2_2', - 'claude-instant-v1.0' : 'a2', - 'gpt-3.5-turbo' : 'chinchilla' -} -``` - -### New: bot creation - -```python -# import quora (poe) package -import quora - -# create account -# make sure to set enable_bot_creation to True -token = quora.Account.create(logging = True, enable_bot_creation=True) - -model = quora.Model.create( - token = token, - model = 'gpt-3.5-turbo', # or claude-instant-v1.0 - system_prompt = 'you are ChatGPT a large language model ...' -) - -print(model.name) # gptx.... - -# streaming response -for response in quora.StreamingCompletion.create( - custom_model = model.name, - prompt ='hello world', - token = token): - - print(response.completion.choices[0].text) -``` - -### Normal Response: -```python - -response = quora.Completion.create(model = 'gpt-4', - prompt = 'hello world', - token = token) - -print(response.completion.choices[0].text) -``` - -### Update Use This For Poe -```python -from quora import Poe - -# available models: ['Sage', 'GPT-4', 'Claude+', 'Claude-instant', 'ChatGPT', 'Dragonfly', 'NeevaAI'] - -poe = Poe(model='ChatGPT', driver='firefox', cookie_path='cookie.json', driver_path='path_of_driver') -poe.chat('who won the football world cup most?') - -# new bot creation -poe.create_bot('new_bot_name', prompt='You are new test bot', base_model='gpt-3.5-turbo') - -``` diff --git a/quora/__init__.py b/quora/__init__.py deleted file mode 100644 index cd5ec8f9..00000000 --- a/quora/__init__.py +++ /dev/null @@ -1,495 +0,0 @@ -import json -from datetime import datetime -from hashlib import md5 -from json import dumps -from pathlib import Path -from random import choice, choices, randint -from re import search, findall -from string import ascii_letters, digits -from typing import Optional, Union -from urllib.parse import unquote - -import selenium.webdriver.support.expected_conditions as EC -from fake_useragent import UserAgent -from pypasser import reCaptchaV3 -from requests import Session -from selenium.webdriver import Firefox, Chrome, FirefoxOptions, ChromeOptions -from selenium.webdriver.common.by import By -from selenium.webdriver.support.wait import WebDriverWait -from tls_client import Session as TLS - -from quora.api import Client as PoeClient -from quora.mail import Emailnator - -SELENIUM_WEB_DRIVER_ERROR_MSG = b'''The error message you are receiving is due to the `geckodriver` executable not -being found in your system\'s PATH. To resolve this issue, you need to download the geckodriver and add its location -to your system\'s PATH.\n\nHere are the steps to resolve the issue:\n\n1. Download the geckodriver for your platform -(Windows, macOS, or Linux) from the following link: https://github.com/mozilla/geckodriver/releases\n\n2. Extract the -downloaded archive and locate the geckodriver executable.\n\n3. Add the geckodriver executable to your system\'s -PATH.\n\nFor macOS and Linux:\n\n- Open a terminal window.\n- Move the geckodriver executable to a directory that is -already in your PATH, or create a new directory and add it to your PATH:\n\n```bash\n# Example: Move geckodriver to -/usr/local/bin\nmv /path/to/your/geckodriver /usr/local/bin\n```\n\n- If you created a new directory, add it to your -PATH:\n\n```bash\n# Example: Add a new directory to PATH\nexport PATH=$PATH:/path/to/your/directory\n```\n\nFor -Windows:\n\n- Right-click on "My Computer" or "This PC" and select "Properties".\n- Click on "Advanced system -settings".\n- Click on the "Environment Variables" button.\n- In the "System variables" section, find the "Path" -variable, select it, and click "Edit".\n- Click "New" and add the path to the directory containing the geckodriver -executable.\n\nAfter adding the geckodriver to your PATH, restart your terminal or command prompt and try running -your script again. The error should be resolved.''' - -# from twocaptcha import TwoCaptcha -# solver = TwoCaptcha('72747bf24a9d89b4dcc1b24875efd358') - -MODELS = { - 'Sage': 'capybara', - 'GPT-4': 'beaver', - 'Claude+': 'a2_2', - 'Claude-instant': 'a2', - 'ChatGPT': 'chinchilla', - 'Dragonfly': 'nutria', - 'NeevaAI': 'hutia', -} - - -def extract_formkey(html): - script_regex = r'' - script_text = search(script_regex, html).group(1) - key_regex = r'var .="([0-9a-f]+)",' - key_text = search(key_regex, script_text).group(1) - cipher_regex = r'.\[(\d+)\]=.\[(\d+)\]' - cipher_pairs = findall(cipher_regex, script_text) - - formkey_list = [''] * len(cipher_pairs) - for pair in cipher_pairs: - formkey_index, key_index = map(int, pair) - formkey_list[formkey_index] = key_text[key_index] - formkey = ''.join(formkey_list) - - return formkey - - -class PoeResponse: - class Completion: - class Choices: - def __init__(self, choice: dict) -> None: - self.text = choice['text'] - self.content = self.text.encode() - self.index = choice['index'] - self.logprobs = choice['logprobs'] - self.finish_reason = choice['finish_reason'] - - def __repr__(self) -> str: - return f'''<__main__.APIResponse.Completion.Choices(\n text = {self.text.encode()},\n index = {self.index},\n logprobs = {self.logprobs},\n finish_reason = {self.finish_reason})object at 0x1337>''' - - def __init__(self, choices: dict) -> None: - self.choices = [self.Choices(choice) for choice in choices] - - class Usage: - def __init__(self, usage_dict: dict) -> None: - self.prompt_tokens = usage_dict['prompt_tokens'] - self.completion_tokens = usage_dict['completion_tokens'] - self.total_tokens = usage_dict['total_tokens'] - - def __repr__(self): - return f'''<__main__.APIResponse.Usage(\n prompt_tokens = {self.prompt_tokens},\n completion_tokens = {self.completion_tokens},\n total_tokens = {self.total_tokens})object at 0x1337>''' - - def __init__(self, response_dict: dict) -> None: - self.response_dict = response_dict - self.id = response_dict['id'] - self.object = response_dict['object'] - self.created = response_dict['created'] - self.model = response_dict['model'] - self.completion = self.Completion(response_dict['choices']) - self.usage = self.Usage(response_dict['usage']) - - def json(self) -> dict: - return self.response_dict - - -class ModelResponse: - def __init__(self, json_response: dict) -> None: - self.id = json_response['data']['poeBotCreate']['bot']['id'] - self.name = json_response['data']['poeBotCreate']['bot']['displayName'] - self.limit = json_response['data']['poeBotCreate']['bot']['messageLimit']['dailyLimit'] - self.deleted = json_response['data']['poeBotCreate']['bot']['deletionState'] - - -class Model: - @staticmethod - def create( - token: str, - model: str = 'gpt-3.5-turbo', # claude-instant - system_prompt: str = 'You are ChatGPT a large language model developed by Openai. Answer as consisely as possible', - description: str = 'gpt-3.5 language model from openai, skidded by poe.com', - handle: str = None, - ) -> ModelResponse: - models = { - 'gpt-3.5-turbo': 'chinchilla', - 'claude-instant-v1.0': 'a2', - 'gpt-4': 'beaver', - } - - if not handle: - handle = f'gptx{randint(1111111, 9999999)}' - - client = Session() - client.cookies['p-b'] = token - - formkey = extract_formkey(client.get('https://poe.com').text) - settings = client.get('https://poe.com/api/settings').json() - - client.headers = { - 'host': 'poe.com', - 'origin': 'https://poe.com', - 'referer': 'https://poe.com/', - 'poe-formkey': formkey, - 'poe-tchannel': settings['tchannelData']['channel'], - 'user-agent': UserAgent().random, - 'connection': 'keep-alive', - 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"', - 'sec-ch-ua-mobile': '?0', - 'sec-ch-ua-platform': '"macOS"', - 'content-type': 'application/json', - 'sec-fetch-site': 'same-origin', - 'sec-fetch-mode': 'cors', - 'sec-fetch-dest': 'empty', - 'accept': '*/*', - 'accept-encoding': 'gzip, deflate, br', - 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', - } - - payload = dumps( - separators=(',', ':'), - obj={ - 'queryName': 'CreateBotMain_poeBotCreate_Mutation', - 'variables': { - 'model': models[model], - 'handle': handle, - 'prompt': system_prompt, - 'isPromptPublic': True, - 'introduction': '', - 'description': description, - 'profilePictureUrl': 'https://qph.fs.quoracdn.net/main-qimg-24e0b480dcd946e1cc6728802c5128b6', - 'apiUrl': None, - 'apiKey': ''.join(choices(ascii_letters + digits, k=32)), - 'isApiBot': False, - 'hasLinkification': False, - 'hasMarkdownRendering': False, - 'hasSuggestedReplies': False, - 'isPrivateBot': False, - }, - 'query': 'mutation CreateBotMain_poeBotCreate_Mutation(\n $model: String!\n $handle: String!\n $prompt: String!\n $isPromptPublic: Boolean!\n $introduction: String!\n $description: String!\n $profilePictureUrl: String\n $apiUrl: String\n $apiKey: String\n $isApiBot: Boolean\n $hasLinkification: Boolean\n $hasMarkdownRendering: Boolean\n $hasSuggestedReplies: Boolean\n $isPrivateBot: Boolean\n) {\n poeBotCreate(model: $model, handle: $handle, promptPlaintext: $prompt, isPromptPublic: $isPromptPublic, introduction: $introduction, description: $description, profilePicture: $profilePictureUrl, apiUrl: $apiUrl, apiKey: $apiKey, isApiBot: $isApiBot, hasLinkification: $hasLinkification, hasMarkdownRendering: $hasMarkdownRendering, hasSuggestedReplies: $hasSuggestedReplies, isPrivateBot: $isPrivateBot) {\n status\n bot {\n id\n ...BotHeader_bot\n }\n }\n}\n\nfragment BotHeader_bot on Bot {\n displayName\n messageLimit {\n dailyLimit\n }\n ...BotImage_bot\n ...BotLink_bot\n ...IdAnnotation_node\n ...botHelpers_useViewerCanAccessPrivateBot\n ...botHelpers_useDeletion_bot\n}\n\nfragment BotImage_bot on Bot {\n displayName\n ...botHelpers_useDeletion_bot\n ...BotImage_useProfileImage_bot\n}\n\nfragment BotImage_useProfileImage_bot on Bot {\n image {\n __typename\n ... on LocalBotImage {\n localName\n }\n ... on UrlBotImage {\n url\n }\n }\n ...botHelpers_useDeletion_bot\n}\n\nfragment BotLink_bot on Bot {\n displayName\n}\n\nfragment IdAnnotation_node on Node {\n __isNode: __typename\n id\n}\n\nfragment botHelpers_useDeletion_bot on Bot {\n deletionState\n}\n\nfragment botHelpers_useViewerCanAccessPrivateBot on Bot {\n isPrivateBot\n viewerIsCreator\n}\n', - }, - ) - - base_string = payload + client.headers['poe-formkey'] + 'WpuLMiXEKKE98j56k' - client.headers['poe-tag-id'] = md5(base_string.encode()).hexdigest() - - response = client.post('https://poe.com/api/gql_POST', data=payload) - - if 'success' not in response.text: - raise Exception( - ''' - Bot creation Failed - !! Important !! - Bot creation was not enabled on this account - please use: quora.Account.create with enable_bot_creation set to True - ''' - ) - - return ModelResponse(response.json()) - - -class Account: - @staticmethod - def create( - proxy: Optional[str] = None, - logging: bool = False, - enable_bot_creation: bool = False, - ): - client = TLS(client_identifier='chrome110') - client.proxies = {'http': f'http://{proxy}', 'https': f'http://{proxy}'} if proxy else None - - mail_client = Emailnator() - mail_address = mail_client.get_mail() - - if logging: - print('email', mail_address) - - client.headers = { - 'authority': 'poe.com', - 'accept': '*/*', - 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3', - 'content-type': 'application/json', - 'origin': 'https://poe.com', - 'poe-tag-id': 'null', - 'referer': 'https://poe.com/login', - 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"', - 'sec-ch-ua-mobile': '?0', - 'sec-ch-ua-platform': '"macOS"', - 'sec-fetch-dest': 'empty', - 'sec-fetch-mode': 'cors', - 'sec-fetch-site': 'same-origin', - 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36', - 'poe-formkey': extract_formkey(client.get('https://poe.com/login').text), - 'poe-tchannel': client.get('https://poe.com/api/settings').json()['tchannelData']['channel'], - } - - token = reCaptchaV3( - 'https://www.recaptcha.net/recaptcha/enterprise/anchor?ar=1&k=6LflhEElAAAAAI_ewVwRWI9hsyV4mbZnYAslSvlG&co=aHR0cHM6Ly9wb2UuY29tOjQ0Mw..&hl=en&v=4PnKmGB9wRHh1i04o7YUICeI&size=invisible&cb=bi6ivxoskyal' - ) - # token = solver.recaptcha(sitekey='6LflhEElAAAAAI_ewVwRWI9hsyV4mbZnYAslSvlG', - # url = 'https://poe.com/login?redirect_url=%2F', - # version = 'v3', - # enterprise = 1, - # invisible = 1, - # action = 'login',)['code'] - - payload = dumps( - separators=(',', ':'), - obj={ - 'queryName': 'MainSignupLoginSection_sendVerificationCodeMutation_Mutation', - 'variables': { - 'emailAddress': mail_address, - 'phoneNumber': None, - 'recaptchaToken': token, - }, - 'query': 'mutation MainSignupLoginSection_sendVerificationCodeMutation_Mutation(\n $emailAddress: String\n $phoneNumber: String\n $recaptchaToken: String\n) {\n sendVerificationCode(verificationReason: login, emailAddress: $emailAddress, phoneNumber: $phoneNumber, recaptchaToken: $recaptchaToken) {\n status\n errorMessage\n }\n}\n', - }, - ) - - base_string = payload + client.headers['poe-formkey'] + 'WpuLMiXEKKE98j56k' - client.headers['poe-tag-id'] = md5(base_string.encode()).hexdigest() - - print(dumps(client.headers, indent=4)) - - response = client.post('https://poe.com/api/gql_POST', data=payload) - - if 'automated_request_detected' in response.text: - print('please try using a proxy / wait for fix') - - if 'Bad Request' in response.text: - if logging: - print('bad request, retrying...', response.json()) - quit() - - if logging: - print('send_code', response.json()) - - mail_content = mail_client.get_message() - mail_token = findall(r';">(\d{6,7})', mail_content)[0] - - if logging: - print('code', mail_token) - - payload = dumps( - separators=(',', ':'), - obj={ - 'queryName': 'SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation', - 'variables': { - 'verificationCode': str(mail_token), - 'emailAddress': mail_address, - 'phoneNumber': None, - }, - 'query': 'mutation SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation(\n $verificationCode: String!\n $emailAddress: String\n $phoneNumber: String\n) {\n signupWithVerificationCode(verificationCode: $verificationCode, emailAddress: $emailAddress, phoneNumber: $phoneNumber) {\n status\n errorMessage\n }\n}\n', - }, - ) - - base_string = payload + client.headers['poe-formkey'] + 'WpuLMiXEKKE98j56k' - client.headers['poe-tag-id'] = md5(base_string.encode()).hexdigest() - - response = client.post('https://poe.com/api/gql_POST', data=payload) - if logging: - print('verify_code', response.json()) - - def get(self): - cookies = open(Path(__file__).resolve().parent / 'cookies.txt', 'r').read().splitlines() - return choice(cookies) - - -class StreamingCompletion: - @staticmethod - def create( - model: str = 'gpt-4', - custom_model: bool = None, - prompt: str = 'hello world', - token: str = '', - ): - _model = MODELS[model] if not custom_model else custom_model - - client = PoeClient(token) - - for chunk in client.send_message(_model, prompt): - yield PoeResponse( - { - 'id': chunk['messageId'], - 'object': 'text_completion', - 'created': chunk['creationTime'], - 'model': _model, - 'choices': [ - { - 'text': chunk['text_new'], - 'index': 0, - 'logprobs': None, - 'finish_reason': 'stop', - } - ], - 'usage': { - 'prompt_tokens': len(prompt), - 'completion_tokens': len(chunk['text_new']), - 'total_tokens': len(prompt) + len(chunk['text_new']), - }, - } - ) - - -class Completion: - def create( - model: str = 'gpt-4', - custom_model: str = None, - prompt: str = 'hello world', - token: str = '', - ): - models = { - 'sage': 'capybara', - 'gpt-4': 'beaver', - 'claude-v1.2': 'a2_2', - 'claude-instant-v1.0': 'a2', - 'gpt-3.5-turbo': 'chinchilla', - } - - _model = models[model] if not custom_model else custom_model - - client = PoeClient(token) - - for chunk in client.send_message(_model, prompt): - pass - - return PoeResponse( - { - 'id': chunk['messageId'], - 'object': 'text_completion', - 'created': chunk['creationTime'], - 'model': _model, - 'choices': [ - { - 'text': chunk['text'], - 'index': 0, - 'logprobs': None, - 'finish_reason': 'stop', - } - ], - 'usage': { - 'prompt_tokens': len(prompt), - 'completion_tokens': len(chunk['text']), - 'total_tokens': len(prompt) + len(chunk['text']), - }, - } - ) - - -class Poe: - def __init__( - self, - model: str = 'ChatGPT', - driver: str = 'firefox', - download_driver: bool = False, - driver_path: Optional[str] = None, - cookie_path: str = './quora/cookie.json', - ): - # validating the model - if model and model not in MODELS: - raise RuntimeError('Sorry, the model you provided does not exist. Please check and try again.') - self.model = MODELS[model] - self.cookie_path = cookie_path - self.cookie = self.__load_cookie(driver, download_driver, driver_path=driver_path) - self.client = PoeClient(self.cookie) - - def __load_cookie(self, driver: str, download_driver: bool, driver_path: Optional[str] = None) -> str: - if (cookie_file := Path(self.cookie_path)).exists(): - with cookie_file.open() as fp: - cookie = json.load(fp) - if datetime.fromtimestamp(cookie['expiry']) < datetime.now(): - cookie = self.__register_and_get_cookie(driver, driver_path=driver_path) - else: - print('Loading the cookie from file') - else: - cookie = self.__register_and_get_cookie(driver, driver_path=driver_path) - - return unquote(cookie['value']) - - def __register_and_get_cookie(self, driver: str, driver_path: Optional[str] = None) -> dict: - mail_client = Emailnator() - mail_address = mail_client.get_mail() - - driver = self.__resolve_driver(driver, driver_path=driver_path) - driver.get("https://www.poe.com") - - # clicking use email button - driver.find_element(By.XPATH, '//button[contains(text(), "Use email")]').click() - - email = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, '//input[@type="email"]'))) - email.send_keys(mail_address) - driver.find_element(By.XPATH, '//button[text()="Go"]').click() - - code = findall(r';">(\d{6,7})', mail_client.get_message())[0] - print(code) - - verification_code = WebDriverWait(driver, 30).until( - EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Code"]')) - ) - verification_code.send_keys(code) - verify_button = EC.presence_of_element_located((By.XPATH, '//button[text()="Verify"]')) - login_button = EC.presence_of_element_located((By.XPATH, '//button[text()="Log In"]')) - - WebDriverWait(driver, 30).until(EC.any_of(verify_button, login_button)).click() - - cookie = driver.get_cookie('p-b') - - with open(self.cookie_path, 'w') as fw: - json.dump(cookie, fw) - - driver.close() - return cookie - - @classmethod - def __resolve_driver(cls, driver: str, driver_path: Optional[str] = None) -> Union[Firefox, Chrome]: - options = FirefoxOptions() if driver == 'firefox' else ChromeOptions() - options.add_argument('-headless') - - if driver_path: - options.binary_location = driver_path - try: - return Firefox(options=options) if driver == 'firefox' else Chrome(options=options) - except Exception: - raise Exception(SELENIUM_WEB_DRIVER_ERROR_MSG) - - def chat(self, message: str, model: Optional[str] = None) -> str: - if model and model not in MODELS: - raise RuntimeError('Sorry, the model you provided does not exist. Please check and try again.') - model = MODELS[model] if model else self.model - response = None - for chunk in self.client.send_message(model, message): - response = chunk['text'] - return response - - def create_bot( - self, - name: str, - /, - prompt: str = '', - base_model: str = 'ChatGPT', - description: str = '', - ) -> None: - if base_model not in MODELS: - raise RuntimeError('Sorry, the base_model you provided does not exist. Please check and try again.') - - response = self.client.create_bot( - handle=name, - prompt=prompt, - base_model=MODELS[base_model], - description=description, - ) - print(f'Successfully created bot with name: {response["bot"]["displayName"]}') - - def list_bots(self) -> list: - return list(self.client.bot_names.values()) diff --git a/quora/api.py b/quora/api.py deleted file mode 100644 index 697f6663..00000000 --- a/quora/api.py +++ /dev/null @@ -1,545 +0,0 @@ -# This file was taken from the repository poe-api https://github.com/ading2210/poe-api and is unmodified -# This file is licensed under the GNU GPL v3 and written by @ading2210 - -# license: -# ading2210/poe-api: a reverse engineered Python API wrapepr for Quora's Poe -# Copyright (C) 2023 ading2210 - -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . - -import hashlib -import json -import logging -import queue -import random -import re -import threading -import time -import traceback -from pathlib import Path -from urllib.parse import urlparse - -import requests -import requests.adapters -import websocket - -parent_path = Path(__file__).resolve().parent -queries_path = parent_path / "graphql" -queries = {} - -logging.basicConfig() -logger = logging.getLogger() - -user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" - - -def load_queries(): - for path in queries_path.iterdir(): - if path.suffix != ".graphql": - continue - with open(path) as f: - queries[path.stem] = f.read() - - -def generate_payload(query_name, variables): - return {"query": queries[query_name], "variables": variables} - - -def request_with_retries(method, *args, **kwargs): - attempts = kwargs.get("attempts") or 10 - url = args[0] - for i in range(attempts): - r = method(*args, **kwargs) - if r.status_code == 200: - return r - logger.warn( - f"Server returned a status code of {r.status_code} while downloading {url}. Retrying ({i + 1}/{attempts})..." - ) - - raise RuntimeError(f"Failed to download {url} too many times.") - - -class Client: - gql_url = "https://poe.com/api/gql_POST" - gql_recv_url = "https://poe.com/api/receive_POST" - home_url = "https://poe.com" - settings_url = "https://poe.com/api/settings" - - def __init__(self, token, proxy=None): - self.proxy = proxy - self.session = requests.Session() - self.adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100) - self.session.mount("http://", self.adapter) - self.session.mount("https://", self.adapter) - - if proxy: - self.session.proxies = {"http": self.proxy, "https": self.proxy} - logger.info(f"Proxy enabled: {self.proxy}") - - self.active_messages = {} - self.message_queues = {} - - self.session.cookies.set("p-b", token, domain="poe.com") - self.headers = { - "User-Agent": user_agent, - "Referrer": "https://poe.com/", - "Origin": "https://poe.com", - } - self.session.headers.update(self.headers) - - self.setup_connection() - self.connect_ws() - - def setup_connection(self): - self.ws_domain = f"tch{random.randint(1, 1e6)}" - self.next_data = self.get_next_data(overwrite_vars=True) - self.channel = self.get_channel_data() - self.bots = self.get_bots(download_next_data=False) - self.bot_names = self.get_bot_names() - - self.gql_headers = { - "poe-formkey": self.formkey, - "poe-tchannel": self.channel["channel"], - } - self.gql_headers = {**self.gql_headers, **self.headers} - self.subscribe() - - def extract_formkey(self, html): - script_regex = r"" - script_text = re.search(script_regex, html).group(1) - key_regex = r'var .="([0-9a-f]+)",' - key_text = re.search(key_regex, script_text).group(1) - cipher_regex = r".\[(\d+)\]=.\[(\d+)\]" - cipher_pairs = re.findall(cipher_regex, script_text) - - formkey_list = [""] * len(cipher_pairs) - for pair in cipher_pairs: - formkey_index, key_index = map(int, pair) - formkey_list[formkey_index] = key_text[key_index] - formkey = "".join(formkey_list) - - return formkey - - def get_next_data(self, overwrite_vars=False): - logger.info("Downloading next_data...") - - r = request_with_retries(self.session.get, self.home_url) - json_regex = r'' - json_text = re.search(json_regex, r.text).group(1) - next_data = json.loads(json_text) - - if overwrite_vars: - self.formkey = self.extract_formkey(r.text) - self.viewer = next_data["props"]["pageProps"]["payload"]["viewer"] - self.next_data = next_data - - return next_data - - def get_bot(self, display_name): - url = f'https://poe.com/_next/data/{self.next_data["buildId"]}/{display_name}.json' - - r = request_with_retries(self.session.get, url) - - chat_data = r.json()["pageProps"]["payload"]["chatOfBotDisplayName"] - return chat_data - - def get_bots(self, download_next_data=True): - logger.info("Downloading all bots...") - if download_next_data: - next_data = self.get_next_data(overwrite_vars=True) - else: - next_data = self.next_data - - if not "availableBots" in self.viewer: - raise RuntimeError("Invalid token or no bots are available.") - bot_list = self.viewer["availableBots"] - - threads = [] - bots = {} - - def get_bot_thread(bot): - chat_data = self.get_bot(bot["displayName"]) - bots[chat_data["defaultBotObject"]["nickname"]] = chat_data - - for bot in bot_list: - thread = threading.Thread(target=get_bot_thread, args=(bot,), daemon=True) - threads.append(thread) - - for thread in threads: - thread.start() - for thread in threads: - thread.join() - - self.bots = bots - self.bot_names = self.get_bot_names() - return bots - - def get_bot_names(self): - bot_names = {} - for bot_nickname in self.bots: - bot_obj = self.bots[bot_nickname]["defaultBotObject"] - bot_names[bot_nickname] = bot_obj["displayName"] - return bot_names - - def get_remaining_messages(self, chatbot): - chat_data = self.get_bot(self.bot_names[chatbot]) - return chat_data["defaultBotObject"]["messageLimit"]["numMessagesRemaining"] - - def get_channel_data(self, channel=None): - logger.info("Downloading channel data...") - r = request_with_retries(self.session.get, self.settings_url) - data = r.json() - - return data["tchannelData"] - - def get_websocket_url(self, channel=None): - if channel is None: - channel = self.channel - query = f'?min_seq={channel["minSeq"]}&channel={channel["channel"]}&hash={channel["channelHash"]}' - return f'wss://{self.ws_domain}.tch.{channel["baseHost"]}/up/{channel["boxName"]}/updates' + query - - def send_query(self, query_name, variables): - for i in range(20): - json_data = generate_payload(query_name, variables) - payload = json.dumps(json_data, separators=(",", ":")) - - base_string = payload + self.gql_headers["poe-formkey"] + "WpuLMiXEKKE98j56k" - - headers = { - "content-type": "application/json", - "poe-tag-id": hashlib.md5(base_string.encode()).hexdigest(), - } - headers = {**self.gql_headers, **headers} - - r = request_with_retries(self.session.post, self.gql_url, data=payload, headers=headers) - - data = r.json() - if data["data"] == None: - logger.warn(f'{query_name} returned an error: {data["errors"][0]["message"]} | Retrying ({i + 1}/20)') - time.sleep(2) - continue - - return r.json() - - raise RuntimeError(f"{query_name} failed too many times.") - - def subscribe(self): - logger.info("Subscribing to mutations") - result = self.send_query( - "SubscriptionsMutation", - { - "subscriptions": [ - { - "subscriptionName": "messageAdded", - "query": queries["MessageAddedSubscription"], - }, - { - "subscriptionName": "viewerStateUpdated", - "query": queries["ViewerStateUpdatedSubscription"], - }, - ] - }, - ) - - def ws_run_thread(self): - kwargs = {} - if self.proxy: - proxy_parsed = urlparse(self.proxy) - kwargs = { - "proxy_type": proxy_parsed.scheme, - "http_proxy_host": proxy_parsed.hostname, - "http_proxy_port": proxy_parsed.port, - } - - self.ws.run_forever(**kwargs) - - def connect_ws(self): - self.ws_connected = False - self.ws = websocket.WebSocketApp( - self.get_websocket_url(), - header={"User-Agent": user_agent}, - on_message=self.on_message, - on_open=self.on_ws_connect, - on_error=self.on_ws_error, - on_close=self.on_ws_close, - ) - t = threading.Thread(target=self.ws_run_thread, daemon=True) - t.start() - while not self.ws_connected: - time.sleep(0.01) - - def disconnect_ws(self): - if self.ws: - self.ws.close() - self.ws_connected = False - - def on_ws_connect(self, ws): - self.ws_connected = True - - def on_ws_close(self, ws, close_status_code, close_message): - self.ws_connected = False - logger.warn(f"Websocket closed with status {close_status_code}: {close_message}") - - def on_ws_error(self, ws, error): - self.disconnect_ws() - self.connect_ws() - - def on_message(self, ws, msg): - try: - data = json.loads(msg) - - if not "messages" in data: - return - - for message_str in data["messages"]: - message_data = json.loads(message_str) - if message_data["message_type"] != "subscriptionUpdate": - continue - message = message_data["payload"]["data"]["messageAdded"] - - copied_dict = self.active_messages.copy() - for key, value in copied_dict.items(): - # add the message to the appropriate queue - if value == message["messageId"] and key in self.message_queues: - self.message_queues[key].put(message) - return - - # indicate that the response id is tied to the human message id - elif key != "pending" and value == None and message["state"] != "complete": - self.active_messages[key] = message["messageId"] - self.message_queues[key].put(message) - return - - except Exception: - logger.error(traceback.format_exc()) - self.disconnect_ws() - self.connect_ws() - - def send_message(self, chatbot, message, with_chat_break=False, timeout=20): - # if there is another active message, wait until it has finished sending - while None in self.active_messages.values(): - time.sleep(0.01) - - # None indicates that a message is still in progress - self.active_messages["pending"] = None - - logger.info(f"Sending message to {chatbot}: {message}") - - # reconnect websocket - if not self.ws_connected: - self.disconnect_ws() - self.setup_connection() - self.connect_ws() - - message_data = self.send_query( - "SendMessageMutation", - { - "bot": chatbot, - "query": message, - "chatId": self.bots[chatbot]["chatId"], - "source": None, - "withChatBreak": with_chat_break, - }, - ) - del self.active_messages["pending"] - - if not message_data["data"]["messageEdgeCreate"]["message"]: - raise RuntimeError(f"Daily limit reached for {chatbot}.") - try: - human_message = message_data["data"]["messageEdgeCreate"]["message"] - human_message_id = human_message["node"]["messageId"] - except TypeError: - raise RuntimeError(f"An unknown error occurred. Raw response data: {message_data}") - - # indicate that the current message is waiting for a response - self.active_messages[human_message_id] = None - self.message_queues[human_message_id] = queue.Queue() - - last_text = "" - message_id = None - while True: - try: - message = self.message_queues[human_message_id].get(timeout=timeout) - except queue.Empty: - del self.active_messages[human_message_id] - del self.message_queues[human_message_id] - raise RuntimeError("Response timed out.") - - # only break when the message is marked as complete - if message["state"] == "complete": - if last_text and message["messageId"] == message_id: - break - else: - continue - - # update info about response - message["text_new"] = message["text"][len(last_text):] - last_text = message["text"] - message_id = message["messageId"] - - yield message - - del self.active_messages[human_message_id] - del self.message_queues[human_message_id] - - def send_chat_break(self, chatbot): - logger.info(f"Sending chat break to {chatbot}") - result = self.send_query("AddMessageBreakMutation", {"chatId": self.bots[chatbot]["chatId"]}) - return result["data"]["messageBreakCreate"]["message"] - - def get_message_history(self, chatbot, count=25, cursor=None): - logger.info(f"Downloading {count} messages from {chatbot}") - - messages = [] - if cursor == None: - chat_data = self.get_bot(self.bot_names[chatbot]) - if not chat_data["messagesConnection"]["edges"]: - return [] - messages = chat_data["messagesConnection"]["edges"][:count] - cursor = chat_data["messagesConnection"]["pageInfo"]["startCursor"] - count -= len(messages) - - cursor = str(cursor) - if count > 50: - messages = self.get_message_history(chatbot, count=50, cursor=cursor) + messages - while count > 0: - count -= 50 - new_cursor = messages[0]["cursor"] - new_messages = self.get_message_history(chatbot, min(50, count), cursor=new_cursor) - messages = new_messages + messages - return messages - elif count <= 0: - return messages - - result = self.send_query( - "ChatListPaginationQuery", - {"count": count, "cursor": cursor, "id": self.bots[chatbot]["id"]}, - ) - query_messages = result["data"]["node"]["messagesConnection"]["edges"] - messages = query_messages + messages - return messages - - def delete_message(self, message_ids): - logger.info(f"Deleting messages: {message_ids}") - if not type(message_ids) is list: - message_ids = [int(message_ids)] - - result = self.send_query("DeleteMessageMutation", {"messageIds": message_ids}) - - def purge_conversation(self, chatbot, count=-1): - logger.info(f"Purging messages from {chatbot}") - last_messages = self.get_message_history(chatbot, count=50)[::-1] - while last_messages: - message_ids = [] - for message in last_messages: - if count == 0: - break - count -= 1 - message_ids.append(message["node"]["messageId"]) - - self.delete_message(message_ids) - - if count == 0: - return - last_messages = self.get_message_history(chatbot, count=50)[::-1] - logger.info(f"No more messages left to delete.") - - def create_bot( - self, - handle, - prompt="", - base_model="chinchilla", - description="", - intro_message="", - api_key=None, - api_bot=False, - api_url=None, - prompt_public=True, - pfp_url=None, - linkification=False, - markdown_rendering=True, - suggested_replies=False, - private=False, - ): - result = self.send_query( - "PoeBotCreateMutation", - { - "model": base_model, - "handle": handle, - "prompt": prompt, - "isPromptPublic": prompt_public, - "introduction": intro_message, - "description": description, - "profilePictureUrl": pfp_url, - "apiUrl": api_url, - "apiKey": api_key, - "isApiBot": api_bot, - "hasLinkification": linkification, - "hasMarkdownRendering": markdown_rendering, - "hasSuggestedReplies": suggested_replies, - "isPrivateBot": private, - }, - ) - - data = result["data"]["poeBotCreate"] - if data["status"] != "success": - raise RuntimeError(f"Poe returned an error while trying to create a bot: {data['status']}") - self.get_bots() - return data - - def edit_bot( - self, - bot_id, - handle, - prompt="", - base_model="chinchilla", - description="", - intro_message="", - api_key=None, - api_url=None, - private=False, - prompt_public=True, - pfp_url=None, - linkification=False, - markdown_rendering=True, - suggested_replies=False, - ): - result = self.send_query( - "PoeBotEditMutation", - { - "baseBot": base_model, - "botId": bot_id, - "handle": handle, - "prompt": prompt, - "isPromptPublic": prompt_public, - "introduction": intro_message, - "description": description, - "profilePictureUrl": pfp_url, - "apiUrl": api_url, - "apiKey": api_key, - "hasLinkification": linkification, - "hasMarkdownRendering": markdown_rendering, - "hasSuggestedReplies": suggested_replies, - "isPrivateBot": private, - }, - ) - - data = result["data"]["poeBotEdit"] - if data["status"] != "success": - raise RuntimeError(f"Poe returned an error while trying to edit a bot: {data['status']}") - self.get_bots() - return data - - -load_queries() diff --git a/quora/cookies.txt b/quora/cookies.txt deleted file mode 100644 index 9cccf6ba..00000000 --- a/quora/cookies.txt +++ /dev/null @@ -1,30 +0,0 @@ -SmPiNXZI9hBTuf3viz74PA== -zw7RoKQfeEehiaelYMRWeA== -NEttgJ_rRQdO05Tppx6hFw== -3OnmC0r9njYdNWhWszdQJg== -8hZKR7MxwUTEHvO45TEViw== -Eea6BqK0AmosTKzoI3AAow== -pUEbtxobN_QUSpLIR8RGww== -9_dUWxKkHHhpQRSvCvBk2Q== -UV45rvGwUwi2qV9QdIbMcw== -cVIN0pK1Wx-F7zCdUxlYqA== -UP2wQVds17VFHh6IfCQFrA== -18eKr0ME2Tzifdfqat38Aw== -FNgKEpc2r-XqWe0rHBfYpg== -juCAh6kB0sUpXHvKik2woA== -nBvuNYRLaE4xE4HuzBPiIQ== -oyae3iClomSrk6RJywZ4iw== -1Z27Ul8BTdNOhncT5H6wdg== -wfUfJIlwQwUss8l-3kDt3w== -f6Jw_Nr0PietpNCtOCXJTw== -6Jc3yCs7XhDRNHa4ZML09g== -3vy44sIy-ZlTMofFiFDttw== -p9FbMGGiK1rShKgL3YWkDg== -pw6LI5Op84lf4HOY7fn91A== -QemKm6aothMvqcEgeKFDlQ== -cceZzucA-CEHR0Gt6VLYLQ== -JRRObMp2RHVn5u4730DPvQ== -XNt0wLTjX7Z-EsRR3TJMIQ== -csjjirAUKtT5HT1KZUq1kg== -8qZdCatCPQZyS7jsO4hkdQ== -esnUxcBhvH1DmCJTeld0qw== diff --git a/quora/graphql/AddHumanMessageMutation.graphql b/quora/graphql/AddHumanMessageMutation.graphql deleted file mode 100644 index 01e6bc8c..00000000 --- a/quora/graphql/AddHumanMessageMutation.graphql +++ /dev/null @@ -1,52 +0,0 @@ -mutation AddHumanMessageMutation( - $chatId: BigInt! - $bot: String! - $query: String! - $source: MessageSource - $withChatBreak: Boolean! = false -) { - messageCreateWithStatus( - chatId: $chatId - bot: $bot - query: $query - source: $source - withChatBreak: $withChatBreak - ) { - message { - id - __typename - messageId - text - linkifiedText - authorNickname - state - vote - voteReason - creationTime - suggestedReplies - chat { - id - shouldShowDisclaimer - } - } - messageLimit{ - canSend - numMessagesRemaining - resetTime - shouldShowReminder - } - chatBreak { - id - __typename - messageId - text - linkifiedText - authorNickname - state - vote - voteReason - creationTime - suggestedReplies - } - } -} diff --git a/quora/graphql/AddMessageBreakMutation.graphql b/quora/graphql/AddMessageBreakMutation.graphql deleted file mode 100644 index b28d9903..00000000 --- a/quora/graphql/AddMessageBreakMutation.graphql +++ /dev/null @@ -1,17 +0,0 @@ -mutation AddMessageBreakMutation($chatId: BigInt!) { - messageBreakCreate(chatId: $chatId) { - message { - id - __typename - messageId - text - linkifiedText - authorNickname - state - vote - voteReason - creationTime - suggestedReplies - } - } -} diff --git a/quora/graphql/AutoSubscriptionMutation.graphql b/quora/graphql/AutoSubscriptionMutation.graphql deleted file mode 100644 index 6cf7bf74..00000000 --- a/quora/graphql/AutoSubscriptionMutation.graphql +++ /dev/null @@ -1,7 +0,0 @@ -mutation AutoSubscriptionMutation($subscriptions: [AutoSubscriptionQuery!]!) { - autoSubscribe(subscriptions: $subscriptions) { - viewer { - id - } - } -} diff --git a/quora/graphql/BioFragment.graphql b/quora/graphql/BioFragment.graphql deleted file mode 100644 index c4218030..00000000 --- a/quora/graphql/BioFragment.graphql +++ /dev/null @@ -1,8 +0,0 @@ -fragment BioFragment on Viewer { - id - poeUser { - id - uid - bio - } -} diff --git a/quora/graphql/ChatAddedSubscription.graphql b/quora/graphql/ChatAddedSubscription.graphql deleted file mode 100644 index 664b107f..00000000 --- a/quora/graphql/ChatAddedSubscription.graphql +++ /dev/null @@ -1,5 +0,0 @@ -subscription ChatAddedSubscription { - chatAdded { - ...ChatFragment - } -} diff --git a/quora/graphql/ChatFragment.graphql b/quora/graphql/ChatFragment.graphql deleted file mode 100644 index 605645ff..00000000 --- a/quora/graphql/ChatFragment.graphql +++ /dev/null @@ -1,6 +0,0 @@ -fragment ChatFragment on Chat { - id - chatId - defaultBotNickname - shouldShowDisclaimer -} diff --git a/quora/graphql/ChatListPaginationQuery.graphql b/quora/graphql/ChatListPaginationQuery.graphql deleted file mode 100644 index 6d9ae884..00000000 --- a/quora/graphql/ChatListPaginationQuery.graphql +++ /dev/null @@ -1,378 +0,0 @@ -query ChatListPaginationQuery( - $count: Int = 5 - $cursor: String - $id: ID! -) { - node(id: $id) { - __typename - ...ChatPageMain_chat_1G22uz - id - } -} - -fragment BotImage_bot on Bot { - displayName - ...botHelpers_useDeletion_bot - ...BotImage_useProfileImage_bot -} - -fragment BotImage_useProfileImage_bot on Bot { - image { - __typename - ... on LocalBotImage { - localName - } - ... on UrlBotImage { - url - } - } - ...botHelpers_useDeletion_bot -} - -fragment ChatMessageDownvotedButton_message on Message { - ...MessageFeedbackReasonModal_message - ...MessageFeedbackOtherModal_message -} - -fragment ChatMessageDropdownMenu_message on Message { - id - messageId - vote - text - author - ...chatHelpers_isBotMessage -} - -fragment ChatMessageFeedbackButtons_message on Message { - id - messageId - vote - voteReason - ...ChatMessageDownvotedButton_message -} - -fragment ChatMessageInputView_chat on Chat { - id - chatId - defaultBotObject { - nickname - messageLimit { - dailyBalance - shouldShowRemainingMessageCount - } - hasClearContext - isDown - ...botHelpers_useDeletion_bot - id - } - shouldShowDisclaimer - ...chatHelpers_useSendMessage_chat - ...chatHelpers_useSendChatBreak_chat -} - -fragment ChatMessageInputView_edges on MessageEdge { - node { - ...chatHelpers_isChatBreak - ...chatHelpers_isHumanMessage - state - text - id - } -} - -fragment ChatMessageOverflowButton_message on Message { - text - ...ChatMessageDropdownMenu_message - ...chatHelpers_isBotMessage -} - -fragment ChatMessageSuggestedReplies_SuggestedReplyButton_chat on Chat { - ...chatHelpers_useSendMessage_chat -} - -fragment ChatMessageSuggestedReplies_SuggestedReplyButton_message on Message { - messageId -} - -fragment ChatMessageSuggestedReplies_chat on Chat { - ...ChatWelcomeView_chat - ...ChatMessageSuggestedReplies_SuggestedReplyButton_chat - defaultBotObject { - hasWelcomeTopics - id - } -} - -fragment ChatMessageSuggestedReplies_message on Message { - suggestedReplies - ...ChatMessageSuggestedReplies_SuggestedReplyButton_message -} - -fragment ChatMessage_chat on Chat { - defaultBotObject { - hasWelcomeTopics - hasSuggestedReplies - disclaimerText - messageLimit { - ...ChatPageRateLimitedBanner_messageLimit - } - ...ChatPageDisclaimer_bot - id - } - ...ChatMessageSuggestedReplies_chat - ...ChatWelcomeView_chat -} - -fragment ChatMessage_message on Message { - id - messageId - text - author - linkifiedText - state - contentType - ...ChatMessageSuggestedReplies_message - ...ChatMessageFeedbackButtons_message - ...ChatMessageOverflowButton_message - ...chatHelpers_isHumanMessage - ...chatHelpers_isBotMessage - ...chatHelpers_isChatBreak - ...chatHelpers_useTimeoutLevel - ...MarkdownLinkInner_message - ...IdAnnotation_node -} - -fragment ChatMessagesView_chat on Chat { - ...ChatMessage_chat - ...ChatWelcomeView_chat - ...IdAnnotation_node - defaultBotObject { - hasWelcomeTopics - messageLimit { - ...ChatPageRateLimitedBanner_messageLimit - } - id - } -} - -fragment ChatMessagesView_edges on MessageEdge { - node { - id - messageId - creationTime - ...ChatMessage_message - ...chatHelpers_isBotMessage - ...chatHelpers_isHumanMessage - ...chatHelpers_isChatBreak - } -} - -fragment ChatPageDeleteFooter_chat on Chat { - ...MessageDeleteConfirmationModal_chat -} - -fragment ChatPageDisclaimer_bot on Bot { - disclaimerText -} - -fragment ChatPageMainFooter_chat on Chat { - defaultBotObject { - ...ChatPageMainFooter_useAccessMessage_bot - id - } - ...ChatMessageInputView_chat - ...ChatPageShareFooter_chat - ...ChatPageDeleteFooter_chat -} - -fragment ChatPageMainFooter_edges on MessageEdge { - ...ChatMessageInputView_edges -} - -fragment ChatPageMainFooter_useAccessMessage_bot on Bot { - ...botHelpers_useDeletion_bot - ...botHelpers_useViewerCanAccessPrivateBot -} - -fragment ChatPageMain_chat_1G22uz on Chat { - id - chatId - ...ChatPageShareFooter_chat - ...ChatPageDeleteFooter_chat - ...ChatMessagesView_chat - ...MarkdownLinkInner_chat - ...chatHelpers_useUpdateStaleChat_chat - ...ChatSubscriptionPaywallContextWrapper_chat - ...ChatPageMainFooter_chat - messagesConnection(last: $count, before: $cursor) { - edges { - ...ChatMessagesView_edges - ...ChatPageMainFooter_edges - ...MarkdownLinkInner_edges - node { - ...chatHelpers_useUpdateStaleChat_message - id - __typename - } - cursor - id - } - pageInfo { - hasPreviousPage - startCursor - } - id - } -} - -fragment ChatPageRateLimitedBanner_messageLimit on MessageLimit { - numMessagesRemaining -} - -fragment ChatPageShareFooter_chat on Chat { - chatId -} - -fragment ChatSubscriptionPaywallContextWrapper_chat on Chat { - defaultBotObject { - messageLimit { - numMessagesRemaining - shouldShowRemainingMessageCount - } - ...SubscriptionPaywallModal_bot - id - } -} - -fragment ChatWelcomeView_ChatWelcomeButton_chat on Chat { - ...chatHelpers_useSendMessage_chat -} - -fragment ChatWelcomeView_chat on Chat { - ...ChatWelcomeView_ChatWelcomeButton_chat - defaultBotObject { - displayName - id - } -} - -fragment IdAnnotation_node on Node { - __isNode: __typename - id -} - -fragment MarkdownLinkInner_chat on Chat { - id - chatId - defaultBotObject { - nickname - id - } - ...chatHelpers_useSendMessage_chat -} - -fragment MarkdownLinkInner_edges on MessageEdge { - node { - state - id - } -} - -fragment MarkdownLinkInner_message on Message { - messageId -} - -fragment MessageDeleteConfirmationModal_chat on Chat { - id -} - -fragment MessageFeedbackOtherModal_message on Message { - id - messageId -} - -fragment MessageFeedbackReasonModal_message on Message { - id - messageId -} - -fragment SubscriptionPaywallModal_bot on Bot { - displayName - messageLimit { - dailyLimit - numMessagesRemaining - shouldShowRemainingMessageCount - resetTime - } - ...BotImage_bot -} - -fragment botHelpers_useDeletion_bot on Bot { - deletionState -} - -fragment botHelpers_useViewerCanAccessPrivateBot on Bot { - isPrivateBot - viewerIsCreator -} - -fragment chatHelpers_isBotMessage on Message { - ...chatHelpers_isHumanMessage - ...chatHelpers_isChatBreak -} - -fragment chatHelpers_isChatBreak on Message { - author -} - -fragment chatHelpers_isHumanMessage on Message { - author -} - -fragment chatHelpers_useSendChatBreak_chat on Chat { - id - chatId - defaultBotObject { - nickname - introduction - model - id - } - shouldShowDisclaimer -} - -fragment chatHelpers_useSendMessage_chat on Chat { - id - chatId - defaultBotObject { - id - nickname - } - shouldShowDisclaimer -} - -fragment chatHelpers_useTimeoutLevel on Message { - id - state - text - messageId - chat { - chatId - defaultBotNickname - id - } -} - -fragment chatHelpers_useUpdateStaleChat_chat on Chat { - chatId - defaultBotObject { - contextClearWindowSecs - id - } - ...chatHelpers_useSendChatBreak_chat -} - -fragment chatHelpers_useUpdateStaleChat_message on Message { - creationTime - ...chatHelpers_isChatBreak -} diff --git a/quora/graphql/ChatPaginationQuery.graphql b/quora/graphql/ChatPaginationQuery.graphql deleted file mode 100644 index f2452cd6..00000000 --- a/quora/graphql/ChatPaginationQuery.graphql +++ /dev/null @@ -1,26 +0,0 @@ -query ChatPaginationQuery($bot: String!, $before: String, $last: Int! = 10) { - chatOfBot(bot: $bot) { - id - __typename - messagesConnection(before: $before, last: $last) { - pageInfo { - hasPreviousPage - } - edges { - node { - id - __typename - messageId - text - linkifiedText - authorNickname - state - vote - voteReason - creationTime - suggestedReplies - } - } - } - } -} diff --git a/quora/graphql/ChatViewQuery.graphql b/quora/graphql/ChatViewQuery.graphql deleted file mode 100644 index c330107d..00000000 --- a/quora/graphql/ChatViewQuery.graphql +++ /dev/null @@ -1,8 +0,0 @@ -query ChatViewQuery($bot: String!) { - chatOfBot(bot: $bot) { - id - chatId - defaultBotNickname - shouldShowDisclaimer - } -} diff --git a/quora/graphql/DeleteHumanMessagesMutation.graphql b/quora/graphql/DeleteHumanMessagesMutation.graphql deleted file mode 100644 index 42692c6e..00000000 --- a/quora/graphql/DeleteHumanMessagesMutation.graphql +++ /dev/null @@ -1,7 +0,0 @@ -mutation DeleteHumanMessagesMutation($messageIds: [BigInt!]!) { - messagesDelete(messageIds: $messageIds) { - viewer { - id - } - } -} diff --git a/quora/graphql/DeleteMessageMutation.graphql b/quora/graphql/DeleteMessageMutation.graphql deleted file mode 100644 index 7b9e36d4..00000000 --- a/quora/graphql/DeleteMessageMutation.graphql +++ /dev/null @@ -1,7 +0,0 @@ -mutation deleteMessageMutation( - $messageIds: [BigInt!]! -) { - messagesDelete(messageIds: $messageIds) { - edgeIds - } -} \ No newline at end of file diff --git a/quora/graphql/HandleFragment.graphql b/quora/graphql/HandleFragment.graphql deleted file mode 100644 index f53c484b..00000000 --- a/quora/graphql/HandleFragment.graphql +++ /dev/null @@ -1,8 +0,0 @@ -fragment HandleFragment on Viewer { - id - poeUser { - id - uid - handle - } -} diff --git a/quora/graphql/LoginWithVerificationCodeMutation.graphql b/quora/graphql/LoginWithVerificationCodeMutation.graphql deleted file mode 100644 index 723b1f44..00000000 --- a/quora/graphql/LoginWithVerificationCodeMutation.graphql +++ /dev/null @@ -1,13 +0,0 @@ -mutation LoginWithVerificationCodeMutation( - $verificationCode: String! - $emailAddress: String - $phoneNumber: String -) { - loginWithVerificationCode( - verificationCode: $verificationCode - emailAddress: $emailAddress - phoneNumber: $phoneNumber - ) { - status - } -} diff --git a/quora/graphql/MessageAddedSubscription.graphql b/quora/graphql/MessageAddedSubscription.graphql deleted file mode 100644 index 8dc9499c..00000000 --- a/quora/graphql/MessageAddedSubscription.graphql +++ /dev/null @@ -1,100 +0,0 @@ -subscription messageAdded ( - $chatId: BigInt! -) { - messageAdded(chatId: $chatId) { - id - messageId - creationTime - state - ...ChatMessage_message - ...chatHelpers_isBotMessage - } -} - -fragment ChatMessageDownvotedButton_message on Message { - ...MessageFeedbackReasonModal_message - ...MessageFeedbackOtherModal_message -} - -fragment ChatMessageDropdownMenu_message on Message { - id - messageId - vote - text - linkifiedText - ...chatHelpers_isBotMessage -} - -fragment ChatMessageFeedbackButtons_message on Message { - id - messageId - vote - voteReason - ...ChatMessageDownvotedButton_message -} - -fragment ChatMessageOverflowButton_message on Message { - text - ...ChatMessageDropdownMenu_message - ...chatHelpers_isBotMessage -} - -fragment ChatMessageSuggestedReplies_SuggestedReplyButton_message on Message { - messageId -} - -fragment ChatMessageSuggestedReplies_message on Message { - suggestedReplies - ...ChatMessageSuggestedReplies_SuggestedReplyButton_message -} - -fragment ChatMessage_message on Message { - id - messageId - text - author - linkifiedText - state - ...ChatMessageSuggestedReplies_message - ...ChatMessageFeedbackButtons_message - ...ChatMessageOverflowButton_message - ...chatHelpers_isHumanMessage - ...chatHelpers_isBotMessage - ...chatHelpers_isChatBreak - ...chatHelpers_useTimeoutLevel - ...MarkdownLinkInner_message -} - -fragment MarkdownLinkInner_message on Message { - messageId -} - -fragment MessageFeedbackOtherModal_message on Message { - id - messageId -} - -fragment MessageFeedbackReasonModal_message on Message { - id - messageId -} - -fragment chatHelpers_isBotMessage on Message { - ...chatHelpers_isHumanMessage - ...chatHelpers_isChatBreak -} - -fragment chatHelpers_isChatBreak on Message { - author -} - -fragment chatHelpers_isHumanMessage on Message { - author -} - -fragment chatHelpers_useTimeoutLevel on Message { - id - state - text - messageId -} diff --git a/quora/graphql/MessageDeletedSubscription.graphql b/quora/graphql/MessageDeletedSubscription.graphql deleted file mode 100644 index 54c1c164..00000000 --- a/quora/graphql/MessageDeletedSubscription.graphql +++ /dev/null @@ -1,6 +0,0 @@ -subscription MessageDeletedSubscription($chatId: BigInt!) { - messageDeleted(chatId: $chatId) { - id - messageId - } -} diff --git a/quora/graphql/MessageFragment.graphql b/quora/graphql/MessageFragment.graphql deleted file mode 100644 index cc860811..00000000 --- a/quora/graphql/MessageFragment.graphql +++ /dev/null @@ -1,13 +0,0 @@ -fragment MessageFragment on Message { - id - __typename - messageId - text - linkifiedText - authorNickname - state - vote - voteReason - creationTime - suggestedReplies -} diff --git a/quora/graphql/MessageRemoveVoteMutation.graphql b/quora/graphql/MessageRemoveVoteMutation.graphql deleted file mode 100644 index d5e6e610..00000000 --- a/quora/graphql/MessageRemoveVoteMutation.graphql +++ /dev/null @@ -1,7 +0,0 @@ -mutation MessageRemoveVoteMutation($messageId: BigInt!) { - messageRemoveVote(messageId: $messageId) { - message { - ...MessageFragment - } - } -} diff --git a/quora/graphql/MessageSetVoteMutation.graphql b/quora/graphql/MessageSetVoteMutation.graphql deleted file mode 100644 index 76000df0..00000000 --- a/quora/graphql/MessageSetVoteMutation.graphql +++ /dev/null @@ -1,7 +0,0 @@ -mutation MessageSetVoteMutation($messageId: BigInt!, $voteType: VoteType!, $reason: String) { - messageSetVote(messageId: $messageId, voteType: $voteType, reason: $reason) { - message { - ...MessageFragment - } - } -} diff --git a/quora/graphql/PoeBotCreateMutation.graphql b/quora/graphql/PoeBotCreateMutation.graphql deleted file mode 100644 index 971b4248..00000000 --- a/quora/graphql/PoeBotCreateMutation.graphql +++ /dev/null @@ -1,73 +0,0 @@ -mutation CreateBotMain_poeBotCreate_Mutation( - $model: String! - $handle: String! - $prompt: String! - $isPromptPublic: Boolean! - $introduction: String! - $description: String! - $profilePictureUrl: String - $apiUrl: String - $apiKey: String - $isApiBot: Boolean - $hasLinkification: Boolean - $hasMarkdownRendering: Boolean - $hasSuggestedReplies: Boolean - $isPrivateBot: Boolean -) { - poeBotCreate(model: $model, handle: $handle, promptPlaintext: $prompt, isPromptPublic: $isPromptPublic, introduction: $introduction, description: $description, profilePicture: $profilePictureUrl, apiUrl: $apiUrl, apiKey: $apiKey, isApiBot: $isApiBot, hasLinkification: $hasLinkification, hasMarkdownRendering: $hasMarkdownRendering, hasSuggestedReplies: $hasSuggestedReplies, isPrivateBot: $isPrivateBot) { - status - bot { - id - ...BotHeader_bot - } - } -} - -fragment BotHeader_bot on Bot { - displayName - messageLimit { - dailyLimit - } - ...BotImage_bot - ...BotLink_bot - ...IdAnnotation_node - ...botHelpers_useViewerCanAccessPrivateBot - ...botHelpers_useDeletion_bot -} - -fragment BotImage_bot on Bot { - displayName - ...botHelpers_useDeletion_bot - ...BotImage_useProfileImage_bot -} - -fragment BotImage_useProfileImage_bot on Bot { - image { - __typename - ... on LocalBotImage { - localName - } - ... on UrlBotImage { - url - } - } - ...botHelpers_useDeletion_bot -} - -fragment BotLink_bot on Bot { - displayName -} - -fragment IdAnnotation_node on Node { - __isNode: __typename - id -} - -fragment botHelpers_useDeletion_bot on Bot { - deletionState -} - -fragment botHelpers_useViewerCanAccessPrivateBot on Bot { - isPrivateBot - viewerIsCreator -} \ No newline at end of file diff --git a/quora/graphql/PoeBotEditMutation.graphql b/quora/graphql/PoeBotEditMutation.graphql deleted file mode 100644 index fdd309ef..00000000 --- a/quora/graphql/PoeBotEditMutation.graphql +++ /dev/null @@ -1,24 +0,0 @@ -mutation EditBotMain_poeBotEdit_Mutation( - $botId: BigInt! - $handle: String! - $description: String! - $introduction: String! - $isPromptPublic: Boolean! - $baseBot: String! - $profilePictureUrl: String - $prompt: String! - $apiUrl: String - $apiKey: String - $hasLinkification: Boolean - $hasMarkdownRendering: Boolean - $hasSuggestedReplies: Boolean - $isPrivateBot: Boolean -) { - poeBotEdit(botId: $botId, handle: $handle, description: $description, introduction: $introduction, isPromptPublic: $isPromptPublic, model: $baseBot, promptPlaintext: $prompt, profilePicture: $profilePictureUrl, apiUrl: $apiUrl, apiKey: $apiKey, hasLinkification: $hasLinkification, hasMarkdownRendering: $hasMarkdownRendering, hasSuggestedReplies: $hasSuggestedReplies, isPrivateBot: $isPrivateBot) { - status - bot { - handle - id - } - } -} \ No newline at end of file diff --git a/quora/graphql/SendMessageMutation.graphql b/quora/graphql/SendMessageMutation.graphql deleted file mode 100644 index 4b0a4383..00000000 --- a/quora/graphql/SendMessageMutation.graphql +++ /dev/null @@ -1,40 +0,0 @@ -mutation chatHelpers_sendMessageMutation_Mutation( - $chatId: BigInt! - $bot: String! - $query: String! - $source: MessageSource - $withChatBreak: Boolean! -) { - messageEdgeCreate(chatId: $chatId, bot: $bot, query: $query, source: $source, withChatBreak: $withChatBreak) { - chatBreak { - cursor - node { - id - messageId - text - author - suggestedReplies - creationTime - state - } - id - } - message { - cursor - node { - id - messageId - text - author - suggestedReplies - creationTime - state - chat { - shouldShowDisclaimer - id - } - } - id - } - } -} diff --git a/quora/graphql/SendVerificationCodeForLoginMutation.graphql b/quora/graphql/SendVerificationCodeForLoginMutation.graphql deleted file mode 100644 index 45af4799..00000000 --- a/quora/graphql/SendVerificationCodeForLoginMutation.graphql +++ /dev/null @@ -1,12 +0,0 @@ -mutation SendVerificationCodeForLoginMutation( - $emailAddress: String - $phoneNumber: String -) { - sendVerificationCode( - verificationReason: login - emailAddress: $emailAddress - phoneNumber: $phoneNumber - ) { - status - } -} diff --git a/quora/graphql/ShareMessagesMutation.graphql b/quora/graphql/ShareMessagesMutation.graphql deleted file mode 100644 index 92e80db5..00000000 --- a/quora/graphql/ShareMessagesMutation.graphql +++ /dev/null @@ -1,9 +0,0 @@ -mutation ShareMessagesMutation( - $chatId: BigInt! - $messageIds: [BigInt!]! - $comment: String -) { - messagesShare(chatId: $chatId, messageIds: $messageIds, comment: $comment) { - shareCode - } -} diff --git a/quora/graphql/SignupWithVerificationCodeMutation.graphql b/quora/graphql/SignupWithVerificationCodeMutation.graphql deleted file mode 100644 index 06b2826f..00000000 --- a/quora/graphql/SignupWithVerificationCodeMutation.graphql +++ /dev/null @@ -1,13 +0,0 @@ -mutation SignupWithVerificationCodeMutation( - $verificationCode: String! - $emailAddress: String - $phoneNumber: String -) { - signupWithVerificationCode( - verificationCode: $verificationCode - emailAddress: $emailAddress - phoneNumber: $phoneNumber - ) { - status - } -} diff --git a/quora/graphql/StaleChatUpdateMutation.graphql b/quora/graphql/StaleChatUpdateMutation.graphql deleted file mode 100644 index de203d47..00000000 --- a/quora/graphql/StaleChatUpdateMutation.graphql +++ /dev/null @@ -1,7 +0,0 @@ -mutation StaleChatUpdateMutation($chatId: BigInt!) { - staleChatUpdate(chatId: $chatId) { - message { - ...MessageFragment - } - } -} diff --git a/quora/graphql/SubscriptionsMutation.graphql b/quora/graphql/SubscriptionsMutation.graphql deleted file mode 100644 index b864bd60..00000000 --- a/quora/graphql/SubscriptionsMutation.graphql +++ /dev/null @@ -1,9 +0,0 @@ -mutation subscriptionsMutation( - $subscriptions: [AutoSubscriptionQuery!]! -) { - autoSubscribe(subscriptions: $subscriptions) { - viewer { - id - } - } -} \ No newline at end of file diff --git a/quora/graphql/SummarizePlainPostQuery.graphql b/quora/graphql/SummarizePlainPostQuery.graphql deleted file mode 100644 index afa2a84c..00000000 --- a/quora/graphql/SummarizePlainPostQuery.graphql +++ /dev/null @@ -1,3 +0,0 @@ -query SummarizePlainPostQuery($comment: String!) { - summarizePlainPost(comment: $comment) -} diff --git a/quora/graphql/SummarizeQuotePostQuery.graphql b/quora/graphql/SummarizeQuotePostQuery.graphql deleted file mode 100644 index 5147c3c5..00000000 --- a/quora/graphql/SummarizeQuotePostQuery.graphql +++ /dev/null @@ -1,3 +0,0 @@ -query SummarizeQuotePostQuery($comment: String, $quotedPostId: BigInt!) { - summarizeQuotePost(comment: $comment, quotedPostId: $quotedPostId) -} diff --git a/quora/graphql/SummarizeSharePostQuery.graphql b/quora/graphql/SummarizeSharePostQuery.graphql deleted file mode 100644 index cb4a623c..00000000 --- a/quora/graphql/SummarizeSharePostQuery.graphql +++ /dev/null @@ -1,3 +0,0 @@ -query SummarizeSharePostQuery($comment: String!, $chatId: BigInt!, $messageIds: [BigInt!]!) { - summarizeSharePost(comment: $comment, chatId: $chatId, messageIds: $messageIds) -} diff --git a/quora/graphql/UserSnippetFragment.graphql b/quora/graphql/UserSnippetFragment.graphql deleted file mode 100644 index 17fc8426..00000000 --- a/quora/graphql/UserSnippetFragment.graphql +++ /dev/null @@ -1,14 +0,0 @@ -fragment UserSnippetFragment on PoeUser { - id - uid - bio - handle - fullName - viewerIsFollowing - isPoeOnlyUser - profilePhotoURLTiny: profilePhotoUrl(size: tiny) - profilePhotoURLSmall: profilePhotoUrl(size: small) - profilePhotoURLMedium: profilePhotoUrl(size: medium) - profilePhotoURLLarge: profilePhotoUrl(size: large) - isFollowable -} diff --git a/quora/graphql/ViewerInfoQuery.graphql b/quora/graphql/ViewerInfoQuery.graphql deleted file mode 100644 index 1ecaf9e8..00000000 --- a/quora/graphql/ViewerInfoQuery.graphql +++ /dev/null @@ -1,21 +0,0 @@ -query ViewerInfoQuery { - viewer { - id - uid - ...ViewerStateFragment - ...BioFragment - ...HandleFragment - hasCompletedMultiplayerNux - poeUser { - id - ...UserSnippetFragment - } - messageLimit{ - canSend - numMessagesRemaining - resetTime - shouldShowReminder - } - } -} - diff --git a/quora/graphql/ViewerStateFragment.graphql b/quora/graphql/ViewerStateFragment.graphql deleted file mode 100644 index 3cd83e9c..00000000 --- a/quora/graphql/ViewerStateFragment.graphql +++ /dev/null @@ -1,30 +0,0 @@ -fragment ViewerStateFragment on Viewer { - id - __typename - iosMinSupportedVersion: integerGate(gateName: "poe_ios_min_supported_version") - iosMinEncouragedVersion: integerGate( - gateName: "poe_ios_min_encouraged_version" - ) - macosMinSupportedVersion: integerGate( - gateName: "poe_macos_min_supported_version" - ) - macosMinEncouragedVersion: integerGate( - gateName: "poe_macos_min_encouraged_version" - ) - showPoeDebugPanel: booleanGate(gateName: "poe_show_debug_panel") - enableCommunityFeed: booleanGate(gateName: "enable_poe_shares_feed") - linkifyText: booleanGate(gateName: "poe_linkify_response") - enableSuggestedReplies: booleanGate(gateName: "poe_suggested_replies") - removeInviteLimit: booleanGate(gateName: "poe_remove_invite_limit") - enableInAppPurchases: booleanGate(gateName: "poe_enable_in_app_purchases") - availableBots { - nickname - displayName - profilePicture - isDown - disclaimer - subtitle - poweredBy - } -} - diff --git a/quora/graphql/ViewerStateUpdatedSubscription.graphql b/quora/graphql/ViewerStateUpdatedSubscription.graphql deleted file mode 100644 index 03fc73d1..00000000 --- a/quora/graphql/ViewerStateUpdatedSubscription.graphql +++ /dev/null @@ -1,43 +0,0 @@ -subscription viewerStateUpdated { - viewerStateUpdated { - id - ...ChatPageBotSwitcher_viewer - } -} - -fragment BotHeader_bot on Bot { - displayName - messageLimit { - dailyLimit - } - ...BotImage_bot -} - -fragment BotImage_bot on Bot { - image { - __typename - ... on LocalBotImage { - localName - } - ... on UrlBotImage { - url - } - } - displayName -} - -fragment BotLink_bot on Bot { - displayName -} - -fragment ChatPageBotSwitcher_viewer on Viewer { - availableBots { - id - messageLimit { - dailyLimit - } - ...BotLink_bot - ...BotHeader_bot - } - allowUserCreatedBots: booleanGate(gateName: "enable_user_created_bots") -} diff --git a/quora/graphql/__init__.py b/quora/graphql/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/quora/mail.py b/quora/mail.py deleted file mode 100644 index e6ce96c2..00000000 --- a/quora/mail.py +++ /dev/null @@ -1,82 +0,0 @@ -from json import loads -from re import findall -from time import sleep - -from fake_useragent import UserAgent -from requests import Session - - -class Emailnator: - def __init__(self) -> None: - self.client = Session() - self.client.get("https://www.emailnator.com/", timeout=6) - self.cookies = self.client.cookies.get_dict() - - self.client.headers = { - "authority": "www.emailnator.com", - "origin": "https://www.emailnator.com", - "referer": "https://www.emailnator.com/", - "user-agent": UserAgent().random, - "x-xsrf-token": self.client.cookies.get("XSRF-TOKEN")[:-3] + "=", - } - - self.email = None - - def get_mail(self): - response = self.client.post( - "https://www.emailnator.com/generate-email", - json={ - "email": [ - "domain", - "plusGmail", - "dotGmail", - ] - }, - ) - - self.email = loads(response.text)["email"][0] - return self.email - - def get_message(self): - print("Waiting for message...") - - while True: - sleep(2) - mail_token = self.client.post( - "https://www.emailnator.com/message-list", json={"email": self.email} - ) - - mail_token = loads(mail_token.text)["messageData"] - - if len(mail_token) == 2: - print("Message received!") - print(mail_token[1]["messageID"]) - break - - mail_context = self.client.post( - "https://www.emailnator.com/message-list", - json={ - "email": self.email, - "messageID": mail_token[1]["messageID"], - }, - ) - - return mail_context.text - - def get_verification_code(self): - message = self.get_message() - code = findall(r';">(\d{6,7})', message)[0] - print(f"Verification code: {code}") - return code - - def clear_inbox(self): - print("Clearing inbox...") - self.client.post( - "https://www.emailnator.com/delete-all", - json={"email": self.email}, - ) - print("Inbox cleared!") - - def __del__(self): - if self.email: - self.clear_inbox() diff --git a/test.py b/test.py index 4b39bd0a..0fd2ec8b 100644 --- a/test.py +++ b/test.py @@ -1,4 +1,4 @@ -import theb +from gpt4free import theb for token in theb.Completion.create('hello world'): print(token, end='', flush=True) diff --git a/testing/forefront_test.py b/testing/forefront_test.py index 8d25ed89..b7b5c57c 100644 --- a/testing/forefront_test.py +++ b/testing/forefront_test.py @@ -1,4 +1,4 @@ -from openai_rev import forefront +from gpt4free import forefront # create an account token = forefront.Account.create(logging=True) diff --git a/testing/poe_account_create_test.py b/testing/poe_account_create_test.py index 7072597f..ace2306e 100644 --- a/testing/poe_account_create_test.py +++ b/testing/poe_account_create_test.py @@ -6,8 +6,8 @@ from typing import Optional from tls_client import Session as TLS from twocaptcha import TwoCaptcha -from openai_rev.quora import extract_formkey -from openai_rev.quora.mail import Emailnator +from gpt4free.quora import extract_formkey +from gpt4free.quora.mail import Emailnator solver = TwoCaptcha('72747bf24a9d89b4dcc1b24875efd358') diff --git a/testing/poe_test.py b/testing/poe_test.py index 809804f2..22d95f5f 100644 --- a/testing/poe_test.py +++ b/testing/poe_test.py @@ -1,6 +1,6 @@ from time import sleep -from openai_rev import quora +from gpt4free import quora token = quora.Account.create(proxy=None, logging=True) print('token', token) diff --git a/testing/quora_test_2.py b/testing/quora_test_2.py index 5d06f9ed..297ca7a1 100644 --- a/testing/quora_test_2.py +++ b/testing/quora_test_2.py @@ -1,4 +1,4 @@ -from openai_rev import quora +from gpt4free import quora token = quora.Account.create(logging=True, enable_bot_creation=True) diff --git a/testing/test_main.py b/testing/test_main.py index 612ec695..bd4d03e9 100644 --- a/testing/test_main.py +++ b/testing/test_main.py @@ -1,24 +1,28 @@ -from openai_rev import openai_rev, Provider, quora, forefront +import gpt4free +from gpt4free import Provider, quora, forefront # usage You -response = openai_rev.Completion.create(Provider.You, prompt='Write a poem on Lionel Messi') +response = gpt4free.Completion.create(Provider.You, prompt='Write a poem on Lionel Messi') print(response) # usage Poe -token = quora.Account.create(logging=False) -response = openai_rev.Completion.create( - Provider.Poe, prompt='Write a poem on Lionel Messi', token=token, model='ChatGPT' -) +# token = quora.Account.create(logging=False) +token = 'GKzCahZYGKhp76LfE197xw==' +response = gpt4free.Completion.create(Provider.Poe, prompt='Write a poem on Lionel Messi', token=token, model='ChatGPT') print(response) # usage forefront token = forefront.Account.create(logging=False) -response = openai_rev.Completion.create( +response = gpt4free.Completion.create( Provider.ForeFront, prompt='Write a poem on Lionel Messi', model='gpt-4', token=token ) print(response) print(f'END') # usage theb -response = openai_rev.Completion.create(Provider.Theb, prompt='Write a poem on Lionel Messi') +response = gpt4free.Completion.create(Provider.Theb, prompt='Write a poem on Lionel Messi') +print(response) + +# usage cocalc +response = gpt4free.Completion.create(Provider.CoCalc, prompt='Write a poem on Lionel Messi', cookie_input='') print(response) diff --git a/testing/you_test.py b/testing/you_test.py index 34800301..1e9f6205 100644 --- a/testing/you_test.py +++ b/testing/you_test.py @@ -1,4 +1,4 @@ -from openai_rev import you +from gpt4free import you # simple request with links and details response = you.Completion.create(prompt="hello world", detailed=True, include_links=True) @@ -22,6 +22,6 @@ while True: response = you.Completion.create(prompt=prompt, chat=chat) - print("Bot:", response["response"]) + print("Bot:", response.text) - chat.append({"question": prompt, "answer": response["response"]}) + chat.append({"question": prompt, "answer": response.text}) diff --git a/theb/README.md b/theb/README.md deleted file mode 100644 index ca978fce..00000000 --- a/theb/README.md +++ /dev/null @@ -1,12 +0,0 @@ -### Example: `theb` (use like openai pypi package) - - -```python -# import library -import theb - -# simple streaming completion -for token in theb.Completion.create('hello world'): - print(token, end='', flush=True) -print("") -``` diff --git a/theb/__init__.py b/theb/__init__.py deleted file mode 100644 index 726e025e..00000000 --- a/theb/__init__.py +++ /dev/null @@ -1,50 +0,0 @@ -from re import findall -from json import loads -from queue import Queue, Empty -from threading import Thread -from curl_cffi import requests - -class Completion: - # experimental - part1 = '{"role":"assistant","id":"chatcmpl' - part2 = '"},"index":0,"finish_reason":null}]}}' - regex = rf'{part1}(.*){part2}' - - timer = None - message_queue = Queue() - stream_completed = False - - def request(prompt: str): - headers = { - 'authority': 'chatbot.theb.ai', - 'content-type': 'application/json', - 'origin': 'https://chatbot.theb.ai', - 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36', - } - - requests.post('https://chatbot.theb.ai/api/chat-process', headers=headers, - content_callback = Completion.handle_stream_response, - json = { - 'prompt': prompt, - 'options': {} - } - ) - - Completion.stream_completed = True - - @staticmethod - def create(prompt: str): - Thread(target=Completion.request, args=[prompt]).start() - - while Completion.stream_completed != True or not Completion.message_queue.empty(): - try: - message = Completion.message_queue.get(timeout=0.01) - for message in findall(Completion.regex, message): - yield loads(Completion.part1 + message + Completion.part2)['delta'] - - except Empty: - pass - - @staticmethod - def handle_stream_response(response): - Completion.message_queue.put(response.decode()) diff --git a/theb/theb_test.py b/theb/theb_test.py deleted file mode 100644 index 177c970a..00000000 --- a/theb/theb_test.py +++ /dev/null @@ -1,4 +0,0 @@ -import theb - -for token in theb.Completion.create('hello world'): - print(token, end='', flush=True) \ No newline at end of file diff --git a/you/README.md b/you/README.md deleted file mode 100644 index 25c20085..00000000 --- a/you/README.md +++ /dev/null @@ -1,37 +0,0 @@ -### Example: `you` (use like openai pypi package) - -```python -import you - -# simple request with links and details -response = you.Completion.create( - prompt="hello world", - detailed=True, - include_links=True, ) - -print(response) - -# { -# "response": "...", -# "links": [...], -# "extra": {...}, -# "slots": {...} -# } -# } - -# chatbot - -chat = [] - -while True: - prompt = input("You: ") - if prompt == 'q': - break - response = you.Completion.create( - prompt=prompt, - chat=chat) - - print("Bot:", response["response"]) - - chat.append({"question": prompt, "answer": response["response"]}) -``` diff --git a/you/__init__.py b/you/__init__.py deleted file mode 100644 index 8bf31f0d..00000000 --- a/you/__init__.py +++ /dev/null @@ -1,98 +0,0 @@ -import re -from json import loads -from uuid import uuid4 - -from fake_useragent import UserAgent -from tls_client import Session - - -class Completion: - @staticmethod - def create( - prompt: str, - page: int = 1, - count: int = 10, - safe_search: str = 'Moderate', - on_shopping_page: bool = False, - mkt: str = '', - response_filter: str = 'WebPages,Translations,TimeZone,Computation,RelatedSearches', - domain: str = 'youchat', - query_trace_id: str = None, - chat: list = None, - include_links: bool = False, - detailed: bool = False, - debug: bool = False, - ) -> dict: - if chat is None: - chat = [] - - client = Session(client_identifier='chrome_108') - client.headers = Completion.__get_headers() - - response = client.get( - f'https://you.com/api/streamingSearch', - params={ - 'q': prompt, - 'page': page, - 'count': count, - 'safeSearch': safe_search, - 'onShoppingPage': on_shopping_page, - 'mkt': mkt, - 'responseFilter': response_filter, - 'domain': domain, - 'queryTraceId': str(uuid4()) if query_trace_id is None else query_trace_id, - 'chat': str(chat), # {'question':'','answer':' ''} - }, - ) - - if debug: - print('\n\n------------------\n\n') - print(response.text) - print('\n\n------------------\n\n') - - if 'youChatToken' not in response.text: - return Completion.__get_failure_response() - - you_chat_serp_results = re.search( - r'(?<=event: youChatSerpResults\ndata:)(.*\n)*?(?=event: )', response.text - ).group() - third_party_search_results = re.search( - r'(?<=event: thirdPartySearchResults\ndata:)(.*\n)*?(?=event: )', response.text).group() - # slots = findall(r"slots\ndata: (.*)\n\nevent", response.text)[0] - - text = ''.join(re.findall(r'{\"youChatToken\": \"(.*?)\"}', response.text)) - - extra = { - 'youChatSerpResults': loads(you_chat_serp_results), - # 'slots' : loads(slots) - } - - return { - 'response': text.replace('\\n', '\n').replace('\\\\', '\\').replace('\\"', '"'), - 'links': loads(third_party_search_results)['search']['third_party_search_results'] - if include_links - else None, - 'extra': extra if detailed else None, - } - - @classmethod - def __get_headers(cls) -> dict: - return { - 'authority': 'you.com', - 'accept': 'text/event-stream', - 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3', - 'cache-control': 'no-cache', - 'referer': 'https://you.com/search?q=who+are+you&tbm=youchat', - 'sec-ch-ua': '"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"', - 'sec-ch-ua-mobile': '?0', - 'sec-ch-ua-platform': '"Windows"', - 'sec-fetch-dest': 'empty', - 'sec-fetch-mode': 'cors', - 'sec-fetch-site': 'same-origin', - 'cookie': f'safesearch_guest=Moderate; uuid_guest={str(uuid4())}', - 'user-agent': UserAgent().random, - } - - @classmethod - def __get_failure_response(cls) -> dict: - return dict(response='Unable to fetch the response, Please try again.', links=[], extra={}) -- cgit v1.2.3 From afcaf7b70ce95a18e28422cb29f5c7f3b73f88a5 Mon Sep 17 00:00:00 2001 From: Raju Komati Date: Sat, 29 Apr 2023 15:01:16 +0530 Subject: updated query methods in streamlit --- gpt4free/theb/__init__.py | 24 +++++++++++-------- gui/query_methods.py | 60 ++++++++++++++++++++--------------------------- gui/streamlit_chat_app.py | 30 +++++++++++------------- 3 files changed, 54 insertions(+), 60 deletions(-) diff --git a/gpt4free/theb/__init__.py b/gpt4free/theb/__init__.py index 726e025e..96053877 100644 --- a/gpt4free/theb/__init__.py +++ b/gpt4free/theb/__init__.py @@ -1,8 +1,12 @@ -from re import findall from json import loads from queue import Queue, Empty +from re import findall from threading import Thread +from typing import Generator + from curl_cffi import requests +from fake_useragent import UserAgent + class Completion: # experimental @@ -14,29 +18,29 @@ class Completion: message_queue = Queue() stream_completed = False + @staticmethod def request(prompt: str): headers = { 'authority': 'chatbot.theb.ai', 'content-type': 'application/json', 'origin': 'https://chatbot.theb.ai', - 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36', + 'user-agent': UserAgent().random, } - requests.post('https://chatbot.theb.ai/api/chat-process', headers=headers, - content_callback = Completion.handle_stream_response, - json = { - 'prompt': prompt, - 'options': {} - } + requests.post( + 'https://chatbot.theb.ai/api/chat-process', + headers=headers, + content_callback=Completion.handle_stream_response, + json={'prompt': prompt, 'options': {}}, ) Completion.stream_completed = True @staticmethod - def create(prompt: str): + def create(prompt: str) -> Generator[str, None, None]: Thread(target=Completion.request, args=[prompt]).start() - while Completion.stream_completed != True or not Completion.message_queue.empty(): + while not Completion.stream_completed or not Completion.message_queue.empty(): try: message = Completion.message_queue.get(timeout=0.01) for message in findall(Completion.regex, message): diff --git a/gui/query_methods.py b/gui/query_methods.py index adb4ae91..6225453b 100644 --- a/gui/query_methods.py +++ b/gui/query_methods.py @@ -7,7 +7,6 @@ from gpt4free import quora, forefront, theb, you import random - def query_forefront(question: str) -> str: # create an account token = forefront.Account.create(logging=False) @@ -15,65 +14,59 @@ def query_forefront(question: str) -> str: response = "" # get a response try: - for i in forefront.StreamingCompletion.create(token = token, prompt ='hello world', model='gpt-4'): - response += i.completion.choices[0].text - - return response - + return forefront.Completion.create(token=token, prompt='hello world', model='gpt-4').text except Exception as e: # Return error message if an exception occurs - return f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.' + return ( + f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.' + ) def query_quora(question: str) -> str: token = quora.Account.create(logging=False, enable_bot_creation=True) - response = quora.Completion.create( - model='gpt-4', - prompt=question, - token=token - ) - - return response.completion.choices[0].tex + return quora.Completion.create(model='gpt-4', prompt=question, token=token).text def query_theb(question: str) -> str: # Set cloudflare clearance cookie and get answer from GPT-4 model response = "" try: - result = theb.Completion.create( - prompt = question) - return result - + return ''.join(theb.Completion.create(prompt=question)) + except Exception as e: # Return error message if an exception occurs - return f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.' + return ( + f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.' + ) def query_you(question: str) -> str: # Set cloudflare clearance cookie and get answer from GPT-4 model try: - result = you.Completion.create( - prompt = question) + result = you.Completion.create(prompt=question) return result["response"] - + except Exception as e: # Return error message if an exception occurs - return f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.' + return ( + f'An error occurred: {e}. Please make sure you are using a valid cloudflare clearance token and user agent.' + ) + # Define a dictionary containing all query methods avail_query_methods = { - "Forefront": query_forefront, - "Poe": query_quora, - "Theb": query_theb, - "You": query_you, - # "Writesonic": query_writesonic, - # "T3nsor": query_t3nsor, - # "Phind": query_phind, - # "Ora": query_ora, - } + "Forefront": query_forefront, + "Poe": query_quora, + "Theb": query_theb, + "You": query_you, + # "Writesonic": query_writesonic, + # "T3nsor": query_t3nsor, + # "Phind": query_phind, + # "Ora": query_ora, +} -def query(user_input: str, selected_method: str = "Random") -> str: +def query(user_input: str, selected_method: str = "Random") -> str: # If a specific query method is selected (not "Random") and the method is in the dictionary, try to call it if selected_method != "Random" and selected_method in avail_query_methods: try: @@ -104,4 +97,3 @@ def query(user_input: str, selected_method: str = "Random") -> str: query_methods_list.remove(chosen_query) return result - diff --git a/gui/streamlit_chat_app.py b/gui/streamlit_chat_app.py index 1c0dd92a..68011229 100644 --- a/gui/streamlit_chat_app.py +++ b/gui/streamlit_chat_app.py @@ -1,6 +1,6 @@ +import atexit import os import sys -import atexit sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir)) @@ -9,9 +9,9 @@ from streamlit_chat import message from query_methods import query, avail_query_methods import pickle - conversations_file = "conversations.pkl" + def load_conversations(): try: with open(conversations_file, "rb") as f: @@ -31,11 +31,11 @@ def save_conversations(conversations, current_conversation): break if not updated: conversations.append(current_conversation) - + temp_conversations_file = "temp_" + conversations_file with open(temp_conversations_file, "wb") as f: pickle.dump(conversations, f) - + os.replace(temp_conversations_file, conversations_file) @@ -44,10 +44,10 @@ def exit_handler(): # Perform cleanup operations here, like saving data or closing open files. save_conversations(st.session_state.conversations, st.session_state.current_conversation) + # Register the exit_handler function to be called when the program is closing. atexit.register(exit_handler) - st.header("Chat Placeholder") if 'conversations' not in st.session_state: @@ -61,7 +61,7 @@ if 'selected_conversation' not in st.session_state: if 'input_field_key' not in st.session_state: st.session_state['input_field_key'] = 0 - + if 'query_method' not in st.session_state: st.session_state['query_method'] = query @@ -69,20 +69,22 @@ if 'query_method' not in st.session_state: if 'current_conversation' not in st.session_state or st.session_state['current_conversation'] is None: st.session_state['current_conversation'] = {'user_inputs': [], 'generated_responses': []} - input_placeholder = st.empty() -user_input = input_placeholder.text_input('You:', key=f'input_text_{len(st.session_state["current_conversation"]["user_inputs"])}') +user_input = input_placeholder.text_input( + 'You:', key=f'input_text_{len(st.session_state["current_conversation"]["user_inputs"])}' +) submit_button = st.button("Submit") if user_input or submit_button: output = query(user_input, st.session_state['query_method']) escaped_output = output.encode('utf-8').decode('unicode-escape') - + st.session_state.current_conversation['user_inputs'].append(user_input) st.session_state.current_conversation['generated_responses'].append(escaped_output) save_conversations(st.session_state.conversations, st.session_state.current_conversation) - user_input = input_placeholder.text_input('You:', value='', key=f'input_text_{len(st.session_state["current_conversation"]["user_inputs"])}') # Clear the input field - + user_input = input_placeholder.text_input( + 'You:', value='', key=f'input_text_{len(st.session_state["current_conversation"]["user_inputs"])}' + ) # Clear the input field # Add a button to create a new conversation if st.sidebar.button("New Conversation"): @@ -90,11 +92,7 @@ if st.sidebar.button("New Conversation"): st.session_state['current_conversation'] = {'user_inputs': [], 'generated_responses': []} st.session_state['input_field_key'] += 1 -st.session_state['query_method'] = st.sidebar.selectbox( - "Select API:", - options=avail_query_methods, - index=0 -) +st.session_state['query_method'] = st.sidebar.selectbox("Select API:", options=avail_query_methods, index=0) # Sidebar st.sidebar.header("Conversation History") -- cgit v1.2.3 From c7f9f44f99f2e4a07867783af558252e3596892f Mon Sep 17 00:00:00 2001 From: Raju Komati Date: Sat, 29 Apr 2023 15:08:10 +0530 Subject: refactored the code --- gpt4free/forefront/typing.py | 2 +- gpt4free/quora/__init__.py | 6 +++--- gpt4free/quora/api.py | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/gpt4free/forefront/typing.py b/gpt4free/forefront/typing.py index d6026e04..23e90903 100644 --- a/gpt4free/forefront/typing.py +++ b/gpt4free/forefront/typing.py @@ -23,4 +23,4 @@ class ForeFrontResponse(BaseModel): model: str choices: List[Choice] usage: Usage - text: str \ No newline at end of file + text: str diff --git a/gpt4free/quora/__init__.py b/gpt4free/quora/__init__.py index 31526e0c..f548ff41 100644 --- a/gpt4free/quora/__init__.py +++ b/gpt4free/quora/__init__.py @@ -377,10 +377,10 @@ class Poe: raise RuntimeError('Sorry, the model you provided does not exist. Please check and try again.') self.model = MODELS[model] self.cookie_path = cookie_path - self.cookie = self.__load_cookie(driver, download_driver, driver_path=driver_path) + self.cookie = self.__load_cookie(driver, driver_path=driver_path) self.client = PoeClient(self.cookie) - def __load_cookie(self, driver: str, download_driver: bool, driver_path: Optional[str] = None) -> str: + def __load_cookie(self, driver: str, driver_path: Optional[str] = None) -> str: if (cookie_file := Path(self.cookie_path)).exists(): with cookie_file.open() as fp: cookie = json.load(fp) @@ -468,4 +468,4 @@ class Poe: print(f'Successfully created bot with name: {response["bot"]["displayName"]}') def list_bots(self) -> list: - return list(self.client.bot_names.values()) \ No newline at end of file + return list(self.client.bot_names.values()) diff --git a/gpt4free/quora/api.py b/gpt4free/quora/api.py index 697f6663..c48eb273 100644 --- a/gpt4free/quora/api.py +++ b/gpt4free/quora/api.py @@ -225,7 +225,7 @@ class Client: r = request_with_retries(self.session.post, self.gql_url, data=payload, headers=headers) data = r.json() - if data["data"] == None: + if data["data"] is None: logger.warn(f'{query_name} returned an error: {data["errors"][0]["message"]} | Retrying ({i + 1}/20)') time.sleep(2) continue @@ -316,7 +316,7 @@ class Client: return # indicate that the response id is tied to the human message id - elif key != "pending" and value == None and message["state"] != "complete": + elif key != "pending" and value is None and message["state"] != "complete": self.active_messages[key] = message["messageId"] self.message_queues[key].put(message) return @@ -402,7 +402,7 @@ class Client: logger.info(f"Downloading {count} messages from {chatbot}") messages = [] - if cursor == None: + if cursor is None: chat_data = self.get_bot(self.bot_names[chatbot]) if not chat_data["messagesConnection"]["edges"]: return [] -- cgit v1.2.3 From 1981d379d5b79d858f1c0faa8e4c95bcb4e98236 Mon Sep 17 00:00:00 2001 From: Raju Komati Date: Sat, 29 Apr 2023 15:43:24 +0530 Subject: added readme for gpt4 module --- gpt4free/README.md | 116 +++++++++++++++++++++++++++++++++++++++++++++++++++ testing/test_main.py | 3 +- 2 files changed, 117 insertions(+), 2 deletions(-) create mode 100644 gpt4free/README.md diff --git a/gpt4free/README.md b/gpt4free/README.md new file mode 100644 index 00000000..944e24a3 --- /dev/null +++ b/gpt4free/README.md @@ -0,0 +1,116 @@ +# gpt4free package + +### What is it? + +gpt4free is a python package that provides the access to gpt models like ChatGPT and gpt-4 models. + +### Main Features + +- It's free to use +- Easy access + +### Installation: + +```bash +pip install gpt4free +``` + +#### Usage: + +```python +import gpt4free +import gpt4free +from gpt4free import Provider, quora, forefront + +# usage You +response = gpt4free.Completion.create(Provider.You, prompt='Write a poem on Lionel Messi') +print(response) + +# usage Poe +token = quora.Account.create(logging=False) +response = gpt4free.Completion.create(Provider.Poe, prompt='Write a poem on Lionel Messi', token=token, model='ChatGPT') +print(response) + +# usage forefront +token = forefront.Account.create(logging=False) +response = gpt4free.Completion.create( + Provider.ForeFront, prompt='Write a poem on Lionel Messi', model='gpt-4', token=token +) +print(response) +print(f'END') + +# usage theb +response = gpt4free.Completion.create(Provider.Theb, prompt='Write a poem on Lionel Messi') +print(response) + +# usage cocalc +response = gpt4free.Completion.create(Provider.CoCalc, prompt='Write a poem on Lionel Messi', cookie_input='') +print(response) + +``` + +### Invocation Arguments + +`gpt4free.Completion.create()` method has two required arguments + +1. Provider: This is an enum representing different provider +2. prompt: This is the user input + +#### Keyword Arguments + +Some of the keyword arguments are optional, while others are required. + +- You: + - `safe_search`: boolean - default value is `False` + - `include_links`: boolean - default value is `False` + - `detailed`: boolean - default value is `False` +- Quora: + - `token`: str - this needs to be provided by the user + - `model`: str - default value is `gpt-4`. + + (Available models: `['Sage', 'GPT-4', 'Claude+', 'Claude-instant', 'ChatGPT', 'Dragonfly', 'NeevaAI']`) +- ForeFront: + - `token`: str - this need to be provided by the user + +- Theb: + (no keyword arguments required) +- CoCalc: + - `cookie_input`: str - this needs to be provided by user + +#### Token generation of quora +```python +from gpt4free import quora + +token = quora.Account.create(logging=False) +``` + +### Token generation of ForeFront +```python +from gpt4free import forefront + +token = forefront.Account.create(logging=False) +``` + +## Copyright: + +This program is licensed under the [GNU GPL v3](https://www.gnu.org/licenses/gpl-3.0.txt) + +### Copyright Notice: + +``` +xtekky/gpt4free: multiple reverse engineered language-model api's to decentralise the ai industry. +Copyright (C) 2023 xtekky + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +``` \ No newline at end of file diff --git a/testing/test_main.py b/testing/test_main.py index bd4d03e9..7c28f1d2 100644 --- a/testing/test_main.py +++ b/testing/test_main.py @@ -6,8 +6,7 @@ response = gpt4free.Completion.create(Provider.You, prompt='Write a poem on Lion print(response) # usage Poe -# token = quora.Account.create(logging=False) -token = 'GKzCahZYGKhp76LfE197xw==' +token = quora.Account.create(logging=False) response = gpt4free.Completion.create(Provider.Poe, prompt='Write a poem on Lionel Messi', token=token, model='ChatGPT') print(response) -- cgit v1.2.3 From d555d0c247498afe97fdc37f20eb8481e432db60 Mon Sep 17 00:00:00 2001 From: Raju Komati Date: Sat, 29 Apr 2023 15:50:18 +0530 Subject: refactored code --- gpt4free/forefront/mail.py | 14 ++++------- gpt4free/quora/api.py | 62 +++++++++++++++++++++++----------------------- gpt4free/quora/mail.py | 4 +-- gpt4free/theb/theb_test.py | 2 +- pyproject.toml | 2 +- 5 files changed, 39 insertions(+), 45 deletions(-) diff --git a/gpt4free/forefront/mail.py b/gpt4free/forefront/mail.py index 41c2a647..2c00051c 100644 --- a/gpt4free/forefront/mail.py +++ b/gpt4free/forefront/mail.py @@ -23,21 +23,17 @@ class Mail: "sec-fetch-dest": "empty", "referer": "https://mail.tm/", "accept-encoding": "gzip, deflate, br", - "accept-language": "en-GB,en-US;q=0.9,en;q=0.8" + "accept-language": "en-GB,en-US;q=0.9,en;q=0.8", } def get_mail(self) -> str: token = ''.join(choices(ascii_letters, k=14)).lower() - init = self.client.post("https://api.mail.tm/accounts", json={ - "address": f"{token}@bugfoo.com", - "password": token - }) + init = self.client.post( + "https://api.mail.tm/accounts", json={"address": f"{token}@bugfoo.com", "password": token} + ) if init.status_code == 201: - resp = self.client.post("https://api.mail.tm/token", json={ - **init.json(), - "password": token - }) + resp = self.client.post("https://api.mail.tm/token", json={**init.json(), "password": token}) self.client.headers['authorization'] = 'Bearer ' + resp.json()['token'] diff --git a/gpt4free/quora/api.py b/gpt4free/quora/api.py index c48eb273..897215a8 100644 --- a/gpt4free/quora/api.py +++ b/gpt4free/quora/api.py @@ -384,7 +384,7 @@ class Client: continue # update info about response - message["text_new"] = message["text"][len(last_text):] + message["text_new"] = message["text"][len(last_text) :] last_text = message["text"] message_id = message["messageId"] @@ -456,21 +456,21 @@ class Client: logger.info(f"No more messages left to delete.") def create_bot( - self, - handle, - prompt="", - base_model="chinchilla", - description="", - intro_message="", - api_key=None, - api_bot=False, - api_url=None, - prompt_public=True, - pfp_url=None, - linkification=False, - markdown_rendering=True, - suggested_replies=False, - private=False, + self, + handle, + prompt="", + base_model="chinchilla", + description="", + intro_message="", + api_key=None, + api_bot=False, + api_url=None, + prompt_public=True, + pfp_url=None, + linkification=False, + markdown_rendering=True, + suggested_replies=False, + private=False, ): result = self.send_query( "PoeBotCreateMutation", @@ -499,21 +499,21 @@ class Client: return data def edit_bot( - self, - bot_id, - handle, - prompt="", - base_model="chinchilla", - description="", - intro_message="", - api_key=None, - api_url=None, - private=False, - prompt_public=True, - pfp_url=None, - linkification=False, - markdown_rendering=True, - suggested_replies=False, + self, + bot_id, + handle, + prompt="", + base_model="chinchilla", + description="", + intro_message="", + api_key=None, + api_url=None, + private=False, + prompt_public=True, + pfp_url=None, + linkification=False, + markdown_rendering=True, + suggested_replies=False, ): result = self.send_query( "PoeBotEditMutation", diff --git a/gpt4free/quora/mail.py b/gpt4free/quora/mail.py index e6ce96c2..864d9568 100644 --- a/gpt4free/quora/mail.py +++ b/gpt4free/quora/mail.py @@ -42,9 +42,7 @@ class Emailnator: while True: sleep(2) - mail_token = self.client.post( - "https://www.emailnator.com/message-list", json={"email": self.email} - ) + mail_token = self.client.post("https://www.emailnator.com/message-list", json={"email": self.email}) mail_token = loads(mail_token.text)["messageData"] diff --git a/gpt4free/theb/theb_test.py b/gpt4free/theb/theb_test.py index 177c970a..c57d5c62 100644 --- a/gpt4free/theb/theb_test.py +++ b/gpt4free/theb/theb_test.py @@ -1,4 +1,4 @@ import theb for token in theb.Completion.create('hello world'): - print(token, end='', flush=True) \ No newline at end of file + print(token, end='', flush=True) diff --git a/pyproject.toml b/pyproject.toml index 7c2244f5..83df5dc5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,7 +2,7 @@ name = "openai-rev" version = "0.1.0" description = "" -authors = ["Raju Komati "] +authors = [] license = "GPL-3.0" readme = "README.md" packages = [{ include = "gpt4free" }] -- cgit v1.2.3 From 786dc89ee82b9bae0ce7048817629373be8e2d89 Mon Sep 17 00:00:00 2001 From: "t.me/xtekky" <98614666+xtekky@users.noreply.github.com> Date: Sat, 29 Apr 2023 12:09:06 +0100 Subject: Update README.md --- gpt4free/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gpt4free/README.md b/gpt4free/README.md index 944e24a3..23f81787 100644 --- a/gpt4free/README.md +++ b/gpt4free/README.md @@ -2,7 +2,7 @@ ### What is it? -gpt4free is a python package that provides the access to gpt models like ChatGPT and gpt-4 models. +gpt4free is a python package that provides some language model api's ### Main Features @@ -113,4 +113,4 @@ GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . -``` \ No newline at end of file +``` -- cgit v1.2.3 From 2e6b523a70bf3ab2a94a470eb238d210c9c1cd7d Mon Sep 17 00:00:00 2001 From: Mishal <91066601+mishalhossin@users.noreply.github.com> Date: Sat, 29 Apr 2023 19:23:12 +0600 Subject: Update README.md --- gpt4free/quora/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gpt4free/quora/README.md b/gpt4free/quora/README.md index c6eeac3e..9c652c59 100644 --- a/gpt4free/quora/README.md +++ b/gpt4free/quora/README.md @@ -55,7 +55,7 @@ print(response.completion.choices[0].text) ### Update Use This For Poe ```python -from quora import Poe +from gpt4free.quora import Poe # available models: ['Sage', 'GPT-4', 'Claude+', 'Claude-instant', 'ChatGPT', 'Dragonfly', 'NeevaAI'] -- cgit v1.2.3 From 3af895a0b625cd237dbc41fc4dc5b650173999cd Mon Sep 17 00:00:00 2001 From: Daniel Shemesh Date: Sat, 29 Apr 2023 17:19:04 +0300 Subject: Update README.md fixed theb link to file --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0445951e..9f42aa80 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ Please note the following: | **Copyright** | Copyright information | [![Link to Section](https://img.shields.io/badge/Link-Go%20to%20Section-blue)](#copyright) | - | | **Star History** | Star History | [![Link to Section](https://img.shields.io/badge/Link-Go%20to%20Section-blue)](#star-history) | - | | **Usage Examples** | | | | -| `theb` | Example usage for theb (gpt-3.5) | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](openai_rev/theb/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | +| `theb` | Example usage for theb (gpt-3.5) | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](gpt4free/theb/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | | `forefront` | Example usage for forefront (gpt-4) | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](gpt4free/forefront/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | || | `quora (poe)` | Example usage for quora | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](gpt4free/quora/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | | `you` | Example usage for you | [![Link to File](https://img.shields.io/badge/Link-Go%20to%20File-blue)](gpt4free/you/README.md) | ![Active](https://img.shields.io/badge/Active-brightgreen) | -- cgit v1.2.3