forked from rj1/chatgpt-irc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatgpt-irc.py
238 lines (189 loc) · 7.17 KB
/
chatgpt-irc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import asyncio
from collections import namedtuple
import functools
import json
import requests
import uuid
class ChatGPT:
def __init__(self):
self.auth_token = options["auth_token"]
self.conversation_id = ""
self.parent_message_id = str(uuid.uuid4())
self.message_id = self.parent_message_id
self.new_conversation = True
def reset(self):
self.message_id = str(uuid.uuid4())
self.new_conversation = True
def prompt(self, message):
self.parent_message_id = self.message_id
self.message_id = str(uuid.uuid4())
#url = "https://chat.openai.com/backend-api/conversation"
url = "https://ai.fakeopen.com/v1/chat/completions"
payload = {
"action": "next",
"messages": [
{
"id": self.message_id,
"role": "user",
"content": message,
#"content": {"content_type": "text", "parts": [message]},
}
],
"conversation_id": self.conversation_id,
"parent_message_id": self.parent_message_id,
"model": "gpt-3.5-turbo"
}
if self.new_conversation == True:
del payload["conversation_id"]
payload = json.dumps(payload)
if self.auth_token.startswith("Bearer "):
self.auth_token = self.auth_token[7:]
headers = {
'Authorization': f'Bearer {self.auth_token}',
'Content-Type': 'application/json'
#"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
#"User-Agent": self.useragent,
#"Cookie": self.cookie,
#"Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
#"Accept-Encoding": "gzip, deflate, br",
#"Connection": "keep-alive",
}
query = requests.request("POST", url, headers=headers, data=payload)
response = query.text
try:
last = response
data = json.loads(last)
message = data["choices"][0]["message"]["content"]
print(message)
if self.new_conversation == True:
self.conversation_id = data["id"]
self.new_conversation = False
messages = parse_outgoing(message)
return messages
except IndexError:
# raise IndexError()
return ["We couldn't get a response for you, please try again"]
# irc
Message = namedtuple("Message", "prefix command params")
Prefix = namedtuple("Prefix", "nick ident host")
def parse_line(line):
prefix = None
if line.startswith(":"):
prefix, line = line.split(None, 1)
name = prefix[1:]
ident = None
host = None
if "!" in name:
name, ident = name.split("!", 1)
if "@" in ident:
ident, host = ident.split("@", 1)
elif "@" in name:
name, host = name.split("@", 1)
prefix = Prefix(name, ident, host)
command, *line = line.split(None, 1)
command = command.upper()
params = []
if line:
line = line[0]
while line:
if line.startswith(":"):
params.append(line[1:])
line = ""
else:
param, *line = line.split(None, 1)
params.append(param)
if line:
line = line[0]
return Message(prefix, command, params)
def send_line_to_writer(writer: asyncio.StreamWriter, line):
print("->", line)
writer.write(line.encode("utf-8") + b"\r\n")
def send_cmd_to_writer(writer: asyncio.StreamWriter, cmd, *params):
params = list(params)
if params:
if " " in params[-1]:
params[-1] = ":" + params[-1]
params = [cmd] + params
send_line_to_writer(writer, " ".join(params))
def send_msg(writer: asyncio.StreamWriter, target, msg):
send_cmd_to_writer(writer, "PRIVMSG", target, msg)
def parse_outgoing(message):
lines = message.split("\n")
messages = []
for line in lines:
if len(line) > 350:
words = line.split(" ")
current_message = ""
for word in words:
if len(current_message) + len(word) + 1 <= 350:
current_message += word + " "
else:
messages.append(current_message)
current_message = word + " "
messages.append(current_message)
else:
messages.append(line)
while "" in messages:
messages.remove("")
return messages
async def main_loop(**options):
print(options.get("host"))
reader, writer = await asyncio.open_connection(
host=options.get("server"), port=options.get("port"), ssl=options.get("ssl")
)
sendline = functools.partial(send_line_to_writer, writer)
sendcmd = functools.partial(send_cmd_to_writer, writer)
if options.get("password"):
sendcmd("PASS", options["password"])
sendline("NICK {nickname}".format(**options))
sendline("USER {ident} * * :{realname}".format(**options))
chatgpt = ChatGPT()
while not reader.at_eof():
line = await reader.readline()
try:
line = line.decode("utf-8")
except UnicodeDecodeError:
line = line.decode("latin1")
line = line.strip()
if line:
message = parse_line(line)
if message.command.isdigit() and int(message.command) >= 400:
# error?
print(message)
if message.command == "PING":
sendcmd("PONG", *message.params)
elif message.command == "001":
sendcmd("MODE", options["nickname"], "+B")
for channel in options["channels"]:
sendcmd("JOIN", channel)
elif message.command == "PRIVMSG":
target = str(message.params[0]) # channel or nick
text = str(message.params[1]) # msg text
host = str(message.prefix.host) # user's hostname
source = str(message.prefix.nick) # nick
print(f"[{target}] <{source}> {text}")
parts = text.split()
if len(parts) == 0:
continue
if parts[0] == "!reset":
sendcmd("PRIVMSG", target, f"{source}: Let's start fresh")
chatgpt.reset()
continue
if len(parts) <= 1:
continue
if parts[0] == f"{options['nickname']}:":
sendcmd(
"PRIVMSG",
target,
f"{source}: hold on, I'm thinking..",
)
prompt = parts[1:]
prompt = " ".join(prompt)
messages = chatgpt.prompt(prompt)
for i, message in enumerate(messages):
if i == 0:
message = f"{source}: {message}"
sendcmd("PRIVMSG", target, f"{message}")
with open("config.json", "r") as f:
options = json.load(f)
asyncio.run(main_loop(**options))