mirror of
https://github.com/aljazceru/chatgpt-telegram-bot.git
synced 2026-01-10 08:26:01 +01:00
use revchatgpt and .env
This commit is contained in:
3
.env.example
Normal file
3
.env.example
Normal file
@@ -0,0 +1,3 @@
|
||||
OPENAI_EMAIL="<YOUR_OPENAI_EMAIL>"
|
||||
OPENAI_PASSWORD="YOUR_OPENAI_PASSWORD"
|
||||
TELEGRAM_BOT_TOKEN="YOUR_TELEGRAM_BOT_TOKEN"
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,3 +1,3 @@
|
||||
/__pycache__
|
||||
/.idea
|
||||
*.json
|
||||
.env
|
||||
|
||||
2
Pipfile
2
Pipfile
@@ -6,6 +6,8 @@ name = "pypi"
|
||||
[packages]
|
||||
requests = "*"
|
||||
python-telegram-bot = "==20.0a6"
|
||||
revchatgpt = "==0.0.23"
|
||||
python-dotenv = "*"
|
||||
|
||||
[dev-packages]
|
||||
|
||||
|
||||
46
Pipfile.lock
generated
46
Pipfile.lock
generated
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"_meta": {
|
||||
"hash": {
|
||||
"sha256": "afe5ec33aa2bc81d2ef71666431c7bed193c76a95219aed5eaa6325730e06029"
|
||||
"sha256": "c385e1532654febce55b8fa092ef31ad42f5f4bcd49fe9fe4a7a01bb5ec157f9"
|
||||
},
|
||||
"pipfile-spec": 6,
|
||||
"requires": {
|
||||
@@ -24,6 +24,20 @@
|
||||
"markers": "python_full_version >= '3.6.2'",
|
||||
"version": "==3.6.2"
|
||||
},
|
||||
"beautifulsoup4": {
|
||||
"hashes": [
|
||||
"sha256:58d5c3d29f5a36ffeb94f02f0d786cd53014cf9b3b3951d42e0080d8a9498d30",
|
||||
"sha256:ad9aa55b65ef2808eb405f46cf74df7fcb7044d5cbc26487f96eb2ef2e436693"
|
||||
],
|
||||
"markers": "python_full_version >= '3.6.0'",
|
||||
"version": "==4.11.1"
|
||||
},
|
||||
"bs4": {
|
||||
"hashes": [
|
||||
"sha256:36ecea1fd7cc5c0c6e4a1ff075df26d50da647b75376626cc186e2212886dd3a"
|
||||
],
|
||||
"version": "==0.0.1"
|
||||
},
|
||||
"certifi": {
|
||||
"hashes": [
|
||||
"sha256:0d9c601124e5a6ba9712dbc60d9c53c21e34f5f641fe83002317394311bdce14",
|
||||
@@ -72,6 +86,14 @@
|
||||
"markers": "python_version >= '3.5'",
|
||||
"version": "==3.4"
|
||||
},
|
||||
"python-dotenv": {
|
||||
"hashes": [
|
||||
"sha256:1684eb44636dd462b66c3ee016599815514527ad99965de77f43e0944634a7e5",
|
||||
"sha256:b77d08274639e3d34145dfa6c7008e66df0f04b7be7a75fd0d5292c191d79045"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.21.0"
|
||||
},
|
||||
"python-telegram-bot": {
|
||||
"hashes": [
|
||||
"sha256:0279d0d727ab36e4b42a8819656098485bcd0724961c2f5fced3218b15b26c02",
|
||||
@@ -88,6 +110,14 @@
|
||||
"index": "pypi",
|
||||
"version": "==2.28.1"
|
||||
},
|
||||
"revchatgpt": {
|
||||
"hashes": [
|
||||
"sha256:1da440f7b82918baf323a958c1dcb698d2c27d1832ec11cf901ff935752dc3cc",
|
||||
"sha256:bfe474174c83810898d1bc50e2fa06d6b974eead82c623f7a4dae410791bc0d9"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.0.23"
|
||||
},
|
||||
"rfc3986": {
|
||||
"extras": [
|
||||
"idna2008"
|
||||
@@ -106,6 +136,20 @@
|
||||
"markers": "python_version >= '3.7'",
|
||||
"version": "==1.3.0"
|
||||
},
|
||||
"soupsieve": {
|
||||
"hashes": [
|
||||
"sha256:3b2503d3c7084a42b1ebd08116e5f81aadfaea95863628c80a3b774a11b7c759",
|
||||
"sha256:fc53893b3da2c33de295667a0e19f078c14bf86544af307354de5fcf12a3f30d"
|
||||
],
|
||||
"markers": "python_version >= '3.6'",
|
||||
"version": "==2.3.2.post1"
|
||||
},
|
||||
"tls-client": {
|
||||
"hashes": [
|
||||
"sha256:cd65d7b1405cd2075050fca4e59abc6e04207b29ea47eabc6f406ce16735421f"
|
||||
],
|
||||
"version": "==0.1.5"
|
||||
},
|
||||
"urllib3": {
|
||||
"hashes": [
|
||||
"sha256:47cc05d99aaa09c9e72ed5809b60e7ba354e64b59c9c173ac3018642d8bb41fc",
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
class ChatGPT3Bot:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
self.check_access_token()
|
||||
self.parent_id = self.generate_uuid()
|
||||
self.conversation_id = None
|
||||
|
||||
def check_access_token(self, force_refresh=False):
|
||||
filename = 'access_token.json'
|
||||
|
||||
def fetch_access_token():
|
||||
logging.info("Fetching access token...")
|
||||
response = self.extract_openai_access_token(self.config['openai_session_token'])
|
||||
if response:
|
||||
self.access_token = response['access_token']
|
||||
with open(filename, 'w') as f:
|
||||
f.write(json.dumps(response))
|
||||
else:
|
||||
raise ValueError("Error: Unable to extract access token")
|
||||
|
||||
if force_refresh or not os.path.exists(filename):
|
||||
fetch_access_token()
|
||||
else:
|
||||
with open(filename, 'r') as f:
|
||||
response = json.loads(f.read())
|
||||
if datetime.datetime.strptime(response["expires"], '%Y-%m-%d %H:%M:%S') < datetime.datetime.now():
|
||||
logging.info("Access token expired, re-fetching...")
|
||||
fetch_access_token()
|
||||
else:
|
||||
self.access_token = response['access_token']
|
||||
|
||||
# Credits: https://github.com/acheong08/ChatGPT
|
||||
def extract_openai_access_token(self, session_token) -> json:
|
||||
s = requests.Session()
|
||||
s.cookies.set("__Secure-next-auth.session-token", session_token)
|
||||
response = s.get("https://chat.openai.com/api/auth/session")
|
||||
response_json = response.json()
|
||||
expiration_date = datetime.datetime.now() + datetime.timedelta(hours=1)
|
||||
return {
|
||||
'access_token': response_json['accessToken'],
|
||||
'expires': expiration_date.strftime('%Y-%m-%d %H:%M:%S')
|
||||
}
|
||||
|
||||
def generate_uuid(self) -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
# Credits: https://github.com/acheong08/ChatGPT
|
||||
def get_chat_response(self, prompt, on_force_refresh=False) -> json:
|
||||
self.check_access_token()
|
||||
|
||||
headers = {
|
||||
"Accept": "application/json",
|
||||
"Authorization": "Bearer " + self.access_token,
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
data = {
|
||||
"action": "next",
|
||||
"messages": [{
|
||||
"id": self.generate_uuid(),
|
||||
"role": "user",
|
||||
"content": {"content_type": "text", "parts": [prompt]}
|
||||
}],
|
||||
"conversation_id": self.conversation_id,
|
||||
"parent_message_id": self.parent_id,
|
||||
"model": "text-davinci-002-render"
|
||||
}
|
||||
response = requests.post(
|
||||
"https://chat.openai.com/backend-api/conversation",
|
||||
headers=headers,
|
||||
data=json.dumps(data)
|
||||
)
|
||||
|
||||
try:
|
||||
if not on_force_refresh and response.status_code == 500:
|
||||
self.check_access_token(force_refresh=True)
|
||||
return self.get_chat_response(prompt, on_force_refresh=True)
|
||||
else:
|
||||
response = response.text.splitlines()[-4][6:]
|
||||
response = json.loads(response)
|
||||
self.parent_id = response["message"]["id"]
|
||||
self.conversation_id = response["conversation_id"]
|
||||
message = response["message"]["content"]["parts"][0]
|
||||
return {'message': message}
|
||||
except:
|
||||
raise ValueError("Error: " + response.text)
|
||||
|
||||
def reset(self):
|
||||
self.conversation_id = None
|
||||
self.parent_id = self.generate_uuid()
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"openai_session_token": "<YOUR_OPENAI_SESSION_TOKEN>",
|
||||
"telegram_bot_token": "<YOUR_TELEGRAM_BOT_TOKEN>"
|
||||
}
|
||||
21
main.py
21
main.py
@@ -1,21 +1,28 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
|
||||
from chat_gpt3_bot import ChatGPT3Bot
|
||||
from dotenv import load_dotenv
|
||||
from revChatGPT.revChatGPT import Chatbot as ChatGPT3Bot
|
||||
from telegram_bot import ChatGPT3TelegramBot
|
||||
|
||||
|
||||
def main():
|
||||
load_dotenv()
|
||||
|
||||
logging.basicConfig(
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
level=logging.INFO
|
||||
)
|
||||
|
||||
with open("config.json", "r") as f:
|
||||
config = json.load(f)
|
||||
chatgpt_config = {
|
||||
'email': os.environ['OPENAI_EMAIL'],
|
||||
'password': os.environ['OPENAI_PASSWORD'],
|
||||
}
|
||||
telegram_config = {
|
||||
'telegram_bot_token': os.environ['TELEGRAM_BOT_TOKEN']
|
||||
}
|
||||
|
||||
gpt3_bot = ChatGPT3Bot(config=config)
|
||||
telegram_bot = ChatGPT3TelegramBot(config=config, gpt3_bot=gpt3_bot)
|
||||
gpt3_bot = ChatGPT3Bot(config=chatgpt_config)
|
||||
telegram_bot = ChatGPT3TelegramBot(config=telegram_config, gpt3_bot=gpt3_bot)
|
||||
telegram_bot.run()
|
||||
|
||||
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import sys
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
|
||||
def extract_openai_session_token(email, password):
|
||||
with sync_playwright() as p:
|
||||
browser = p.webkit.launch(headless=True)
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
# ---------------------
|
||||
page.goto("https://chat.openai.com/auth/login")
|
||||
page.get_by_role("button", name="Log in").click()
|
||||
page.get_by_label("Email address").fill(email)
|
||||
page.locator("button[name=\"action\"]").click()
|
||||
page.get_by_label("Password").click()
|
||||
page.get_by_label("Password").fill(password)
|
||||
page.get_by_role("button", name="Continue").click()
|
||||
# ---------------------
|
||||
with page.expect_response('**/auth/session', timeout=3000):
|
||||
cookies = context.cookies()
|
||||
session_token = [cookie['value'] for cookie in cookies if cookie['name'] == '__Secure-next-auth.session-token'][0]
|
||||
print('Your session token is:')
|
||||
print(session_token)
|
||||
print()
|
||||
print('You can now copy and paste it in your config.json file!')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
openai_email = sys.argv[1]
|
||||
openai_password = sys.argv[2]
|
||||
extract_openai_session_token(openai_email, openai_password)
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
import logging
|
||||
|
||||
import telegram.constants
|
||||
@@ -22,21 +23,31 @@ class ChatGPT3TelegramBot:
|
||||
# Reset the conversation
|
||||
async def reset(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
logging.info('Resetting the conversation...')
|
||||
self.gpt3_bot.reset()
|
||||
self.gpt3_bot.reset_chat()
|
||||
await context.bot.send_message(chat_id=update.effective_chat.id, text="Done!")
|
||||
|
||||
# React to messages
|
||||
async def prompt(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
logging.info('New message received')
|
||||
await context.bot.send_chat_action(chat_id=update.effective_chat.id, action=telegram.constants.ChatAction.TYPING)
|
||||
response = self.gpt3_bot.get_chat_response(update.message.text)
|
||||
response = self.get_chatgpt_response(update.message.text)
|
||||
await context.bot.send_message(
|
||||
chat_id=update.effective_chat.id,
|
||||
reply_to_message_id=update.message.message_id,
|
||||
text=response["message"],
|
||||
parse_mode=telegram.constants.ParseMode.MARKDOWN
|
||||
)
|
||||
logging.info('Sent response')
|
||||
|
||||
def get_chatgpt_response(self, message, retry=False) -> dict:
|
||||
response = self.gpt3_bot.get_chat_response(message)
|
||||
if isinstance(response, dict):
|
||||
return response
|
||||
else:
|
||||
if not retry:
|
||||
self.gpt3_bot.refresh_session()
|
||||
return self.get_chatgpt_response(message, retry=True)
|
||||
else:
|
||||
return {"message": "I'm having some trouble talking to you, please try again later."}
|
||||
|
||||
def run(self):
|
||||
application = ApplicationBuilder().token(self.config['telegram_bot_token']).build()
|
||||
|
||||
Reference in New Issue
Block a user