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1 |
+
import os
|
2 |
+
|
3 |
+
import discord
|
4 |
+
|
5 |
+
import traceback
|
6 |
+
|
7 |
+
import json
|
8 |
+
|
9 |
+
import logging
|
10 |
+
|
11 |
+
from flask import Flask
|
12 |
+
|
13 |
+
import random
|
14 |
+
|
15 |
+
from threading import Thread
|
16 |
+
|
17 |
+
from discord.ext import tasks
|
18 |
+
|
19 |
+
import datetime
|
20 |
+
|
21 |
+
import requests
|
22 |
+
|
23 |
+
import ast
|
24 |
+
|
25 |
+
import aiohttp
|
26 |
+
|
27 |
+
import io
|
28 |
+
|
29 |
+
from PIL import Image
|
30 |
+
|
31 |
+
import asyncio
|
32 |
+
|
33 |
+
from colorama import Fore, Back, Style
|
34 |
+
|
35 |
+
import re
|
36 |
+
|
37 |
+
def extract_content(input_string, first_delimiter="<image>", second_delimiter="</image>"):
|
38 |
+
# Define the pattern to match text inside delimiters
|
39 |
+
pattern = re.escape(first_delimiter) + '(.*?)' + re.escape(second_delimiter)
|
40 |
+
|
41 |
+
# Use re.findall to find all matches of the pattern in the input string
|
42 |
+
matches = re.findall(pattern, input_string)
|
43 |
+
if len(matches) == 0:
|
44 |
+
matches.append("")
|
45 |
+
|
46 |
+
return matches
|
47 |
+
|
48 |
+
app = Flask('')
|
49 |
+
|
50 |
+
|
51 |
+
@app.route('/')
|
52 |
+
def main():
|
53 |
+
return "Your bot is alive!"
|
54 |
+
|
55 |
+
|
56 |
+
def run():
|
57 |
+
from waitress import serve
|
58 |
+
serve(app, host="0.0.0.0", port=8080)
|
59 |
+
|
60 |
+
|
61 |
+
def ka():
|
62 |
+
server = Thread(target=run)
|
63 |
+
server.start()
|
64 |
+
|
65 |
+
|
66 |
+
HF_TOKEN = os.environ["HF_TOKEN"]
|
67 |
+
|
68 |
+
model = "openchat/openchat-3.5-1210"
|
69 |
+
API_URL = "https://api-inference.huggingface.co/models/" + model
|
70 |
+
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
71 |
+
|
72 |
+
|
73 |
+
def generate_latex_image(latex_code):
|
74 |
+
api_url = "https://latex.codecogs.com/svg.latex?"
|
75 |
+
Response = requests.get(api_url + latex_code)
|
76 |
+
return Response.content
|
77 |
+
|
78 |
+
imgmodel = "stabilityai/stable-diffusion-2-1"
|
79 |
+
IMG_URL = "https://api-inference.huggingface.co/models/" + imgmodel
|
80 |
+
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
81 |
+
|
82 |
+
def generate(prompt):
|
83 |
+
payload = {"inputs": prompt, "options":{"wait_for_model":True}}
|
84 |
+
Response = requests.post(IMG_URL, headers=headers, json=payload)
|
85 |
+
return Response.content
|
86 |
+
|
87 |
+
def query(x):
|
88 |
+
x["parameters"] = {}
|
89 |
+
x["options"] = {"wait_for_model": True}
|
90 |
+
Response = requests.post(API_URL, headers=headers, json=x)
|
91 |
+
return Response.json()
|
92 |
+
|
93 |
+
|
94 |
+
launch_time = datetime.datetime.utcnow()
|
95 |
+
|
96 |
+
intents = discord.Intents.default()
|
97 |
+
intents.message_content = True
|
98 |
+
|
99 |
+
client = discord.Client(intents=intents)
|
100 |
+
|
101 |
+
|
102 |
+
@tasks.loop(minutes=1)
|
103 |
+
async def presence():
|
104 |
+
delta_uptime = datetime.datetime.utcnow() - launch_time
|
105 |
+
hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
|
106 |
+
minutes, seconds = divmod(remainder, 60)
|
107 |
+
days, hours = divmod(hours, 24)
|
108 |
+
print(f"Online Time: {days:02d}d | {hours:02d}h | {minutes:02d}m | {seconds:02d}s")
|
109 |
+
await client.change_presence(status = discord.Status.dnd,
|
110 |
+
activity = discord.Activity(type=discord.ActivityType.playing,
|
111 |
+
large_image = "https://i.imgur.com/Kk2BvJg.jpg",
|
112 |
+
large_text = "This is Game Icon",
|
113 |
+
name = "Paying taxes💤",
|
114 |
+
details = "Crying in bed.",
|
115 |
+
state = f"{days:02d}d | {hours:02d}h | {minutes:02d}m Passed"))
|
116 |
+
|
117 |
+
@client.event
|
118 |
+
async def on_ready():
|
119 |
+
print(f'We have logged in as {client.user}')
|
120 |
+
presence.start()
|
121 |
+
|
122 |
+
|
123 |
+
@client.event
|
124 |
+
async def on_message(message:discord.Message):
|
125 |
+
for user in message.mentions:
|
126 |
+
message.content = message.content.replace(f"<@{user.id}>", f"@{user.display_name}")
|
127 |
+
try:
|
128 |
+
msgchannel = message.channel
|
129 |
+
try:
|
130 |
+
msgchannel_name = msgchannel.name
|
131 |
+
guild = message.guild
|
132 |
+
guild_name = guild.name
|
133 |
+
except:
|
134 |
+
guild_name = "Direct"
|
135 |
+
msgchannel_name = message.author.display_name
|
136 |
+
# await msgchannel.typing()
|
137 |
+
s = f"{Fore.LIGHTGREEN_EX}{message.author.display_name}#{message.author.discriminator}: {Fore.WHITE}{message.content} {Fore.LIGHTBLUE_EX} {msgchannel_name} {Fore.LIGHTMAGENTA_EX} {guild_name}"
|
138 |
+
print(Style.RESET_ALL)
|
139 |
+
print(s)
|
140 |
+
if message.author == client.user:
|
141 |
+
return
|
142 |
+
s = f"GPT4 Correct {message.author}: {message.content}<|end_of_turn|>"
|
143 |
+
try:
|
144 |
+
with open(os.path.join(guild_name, f"{msgchannel_name}.txt"), "a") as f:
|
145 |
+
f.write(s)
|
146 |
+
except:
|
147 |
+
os.mkdir(guild_name)
|
148 |
+
with open(os.path.join(guild_name, f"{msgchannel_name}.txt"), "a") as f:
|
149 |
+
f.write(
|
150 |
+
"""GPT4 Correct system: You are lr, a sassy discord chatbot. You were made by Araeyn.
|
151 |
+
You must use the markdown format for your responses.
|
152 |
+
Do not excessively use bullet points.
|
153 |
+
Use emojis at the start of your responses.
|
154 |
+
Use <title> at the start of your title for the response and </title> at the end of the title.
|
155 |
+
Your title must summarize the user's message.
|
156 |
+
If the user asks you to generate an image, use the start tag <image> and the end tag </image> around the prompt to generate it. Put this at the end of your response. Do not use a link for the image.
|
157 |
+
For example, if the user asks you to generate an image of a cat, you would say <image>A cute cat with long fur that is looking out a window with curious eyes.</image>
|
158 |
+
Always include a title.
|
159 |
+
Do not generate images unless the user speciifes that they want an image.
|
160 |
+
Do not generate images with text in them.
|
161 |
+
Do not say any bad words.
|
162 |
+
<|end_of_turn|>"""
|
163 |
+
)
|
164 |
+
f.write(s)
|
165 |
+
if client.user in message.mentions or guild_name == "Direct":
|
166 |
+
with open(os.path.join(guild_name, f"{msgchannel_name}.txt"), "a") as f:
|
167 |
+
f.write("GPT4 Correct Assistant: ")
|
168 |
+
async with msgchannel.typing():
|
169 |
+
with open(os.path.join(guild_name, f"{msgchannel_name}.txt"), "r") as f:
|
170 |
+
o = f.read()
|
171 |
+
y = query({"inputs": o})
|
172 |
+
r = y[0]["generated_text"][len(o):]
|
173 |
+
title = extract_content(r, first_delimiter="<title>", second_delimiter="</title>")[0]
|
174 |
+
embed = discord.Embed(title=title, description= r.replace("<title>" + title + "</title>", ""), color=0x1e81b0)
|
175 |
+
e = await message.reply(embed=embed)
|
176 |
+
l = 0
|
177 |
+
r = ""
|
178 |
+
while not ("<|end_of_turn|>" in y[0]["generated_text"][
|
179 |
+
len(o):] or "GPT4 Correct" in y[0]["generated_text"][len(o):]):
|
180 |
+
l += 1
|
181 |
+
r = y[0]["generated_text"][len(o):]
|
182 |
+
title = extract_content(r, "<title>", "</title>")[0]
|
183 |
+
print(title)
|
184 |
+
r = r.replace("<title>" + title + "</title>", "")
|
185 |
+
print(r)
|
186 |
+
embed.title = title
|
187 |
+
embed.description = r
|
188 |
+
await e.edit(embed=embed)
|
189 |
+
py = y[0]["generated_text"]
|
190 |
+
y = query({"inputs": y[0]["generated_text"]})
|
191 |
+
if y[0]["generated_text"] == py:
|
192 |
+
break
|
193 |
+
r = r.split("<|end_of_turn|>")[0]
|
194 |
+
r = r.split("GPT4 Correct")[0]
|
195 |
+
embed.description = r
|
196 |
+
await e.edit(embed=embed)
|
197 |
+
with open(os.path.join(guild_name, f"{msgchannel_name}.txt"), "a") as f:
|
198 |
+
f.write(r)
|
199 |
+
f.write("<|end_of_turn|>")
|
200 |
+
if "<image>" in r and "</image>" in r:
|
201 |
+
i = extract_content(r)[0]
|
202 |
+
r = r.replace("<image>" + i + "</image>", "")
|
203 |
+
load = random.choice(["https://cdn.dribbble.com/users/744913/screenshots/4094897/media/771a495231b798c0ccf7a59a19f31946.gif", "https://cdn.dribbble.com/users/563824/screenshots/3633228/media/b620ccb3ae8c14ea5447d159ebb1da58.gif", "https://cdn.dribbble.com/users/563824/screenshots/4155980/media/d3828cd14ed415eb6f90310991e06f27.gif", "https://cdn.dribbble.com/users/107759/screenshots/3498589/media/5bc45101de34a80ea71238a02f3a75b5.gif"])
|
204 |
+
if r.replace("\n", "") != "":
|
205 |
+
embed.description = r
|
206 |
+
await e.edit(embed=embed)
|
207 |
+
embed.set_image(url=load)
|
208 |
+
await e.edit(embed=embed)
|
209 |
+
else:
|
210 |
+
embed.clear_fields()
|
211 |
+
embed.set_image(url=load)
|
212 |
+
await e.edit(embed=embed)
|
213 |
+
image_bytes = generate(i)
|
214 |
+
try: image = Image.open(io.BytesIO(image_bytes))
|
215 |
+
except: print(image_bytes)
|
216 |
+
image.save(f"latest.png")
|
217 |
+
embed.set_image(url="attachment://latest.png")
|
218 |
+
await e.edit(embed=embed, attachments=[discord.File(fp=f"latest.png")])
|
219 |
+
os.system("rm " + f"latest.png")
|
220 |
+
else:
|
221 |
+
embed.description = r
|
222 |
+
await e.edit(embed=embed)
|
223 |
+
except Exception as e:
|
224 |
+
embed = discord.Embed(title="Error", description=f"```{traceback.format_exc()}```")
|
225 |
+
await message.channel.send(embed=embed)
|
226 |
+
|
227 |
+
@client.event
|
228 |
+
async def on_disconnect():
|
229 |
+
await client.change_presence(status = discord.Status.dnd,
|
230 |
+
activity = discord.Activity(type=discord.ActivityType.playing,
|
231 |
+
large_image = "https://i.imgur.com/Kk2BvJg.jpg",
|
232 |
+
large_text = "This is Game Icon",
|
233 |
+
name = "Currently on the run from the IRS.",
|
234 |
+
details = "🔫",
|
235 |
+
)
|
236 |
+
)
|
237 |
+
|
238 |
+
ka()
|
239 |
+
token = os.environ["TOKEN"]
|
240 |
+
if token == "":
|
241 |
+
raise Exception("Please add your token to the Secrets pane.")
|
242 |
+
client.run(token)
|