File size: 5,689 Bytes
6c22325
 
 
85efe48
 
 
6c22325
 
85efe48
6c22325
85efe48
80f9977
85efe48
86b14fc
85efe48
da57ba6
 
 
 
 
 
 
 
0cc05a6
86b14fc
 
 
 
da57ba6
85efe48
 
0a397b1
85efe48
80f9977
0a397b1
6c22325
 
 
 
 
 
 
 
 
85efe48
 
 
6c22325
 
 
 
 
 
 
85efe48
 
 
 
 
0cc05a6
1ded21a
 
 
85efe48
 
 
 
 
0cc05a6
afe4531
b89beb0
85efe48
 
 
 
 
 
 
 
9bb0311
0799696
 
ff9f74b
6c22325
 
 
85efe48
765ca76
85efe48
 
0cc05a6
85efe48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c22325
 
 
 
85efe48
 
 
6c22325
85efe48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b2fa83
 
 
 
 
 
 
 
 
 
 
 
85efe48
 
 
0cc05a6
a8bbf8d
 
 
 
1ded21a
a8bbf8d
 
 
 
 
 
 
 
 
 
 
 
85efe48
 
 
 
6c22325
 
85efe48
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
import json
import os
import re
import asyncio
import random
import datetime
from threading import Thread
import discord
from discord.ext import tasks
from PIL import Image
from colorama import Fore, Style
import streamlit as st
from huggingface_hub import InferenceClient, login
import time

import os

lock_file_path = "test.txt"

if not os.path.exists(lock_file_path):
    with open(lock_file_path, "w") as f:
        f.write("Running!")
else:
    print("Streamlit app is already running, only streaming bot activity.")
    while True:
        syncMessages()
        time.sleep(0.1)
        

try:
    os.mkdir("data")
except:
    pass


HF_TOKEN = os.environ["HF_TOKEN"]

login(HF_TOKEN)

SD = InferenceClient(model="stabilityai/stable-diffusion-2-1")
LLM = InferenceClient(model="openchat/openchat-3.5-0106")


def ec(x, fd="<image>", sd="</image>"):
    matches = re.findall(re.escape(fd) + "(.*?)" + re.escape(sd), x)
    matches = matches if matches else [""]
    return matches


intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

launch_time = datetime.datetime.utcnow()

ph = st.empty()

async def syncMessages():
    print(os.listdir(f"data"))
    if os.listdir("data") == []:
        return 0
    with ph.container():
        dirs = st.tabs(os.listdir("data"))
        i = -1
        for dir in os.listdir("data"):
            i += 1
            with dirs[i]:
                print(i, os.listdir(f"data/{dir}"))
                if os.listdir(f"data/{dir}") == []:
                  return 0
                files = st.tabs(os.listdir("data/" + dir))
                k = -1
                for file in os.listdir("data/" + dir):
                    k += 1
                    with files[k]:
                        with open(f"data/{dir}/{file}", "r") as f:
                            o = f.read().split("<|end_of_turn|>")
                            for item in o:
                                item = item.split(": ", 1)
                                if len(item) < 2:
                                    return 0
                                st.markdown(f":blue[{item[0].split('GPT4 Correct ')[1]}]: {item[1]}")

@client.event
async def on_ready():
    print(f"Logged in as {client.user}")
    presence.start()


@tasks.loop(seconds=60)
async def presence():
    delta_uptime = datetime.datetime.utcnow() - launch_time
    hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
    minutes, seconds = divmod(remainder, 60)
    days, hours = divmod(hours, 24)
    print(f"Online Time: {days:02d}d | {hours:02d}h | {minutes:02d}m | {seconds:02d}s")
    await client.change_presence(
        status=discord.Status.dnd,
        activity=discord.Activity(
            type=discord.ActivityType.playing,
            large_image="https://i.imgur.com/Kk2BvJg.jpg",
            large_text="This is Game Icon",
            name="Escaping the IRS.",
            details="",
            state=f"Running for {days:02d}d | {hours:02d}h | {minutes:02d}m",
        ),
    )


@client.event
async def on_message(message):
    for user in message.mentions:
        message.content = message.content.replace(f"<@{user.id}>",
                                                  f"@{str(user)}")
    try:
        msgchannel = message.channel
        try:
            msgchannel_name = msgchannel.name
            guild = message.guild
            guild_name = guild.name
        except:
            guild_name = "Direct"
            msgchannel_name = message.author.display_name
        s = f":green[{message.author}]: :violet[{message.content}] :blue[{msgchannel_name}] :orange[{guild_name}]"
        if message.author == client.user:
            return
        sysp = """You are Lyre, a helpful discord chatbot. Respond in markdown. Your username is lyre#9828."""
        try:
            os.mkdir("data/" + guild_name)
        except:
            pass
        try:
            with open(f"data/{guild_name}/{msgchannel_name}", "a") as f:
                n = "\n"
                f.write(
                    f"""GPT4 Correct {message.author.name}: {message.content.strip(n)}<|end_of_turn|>"""
                )
        except error:
            with open(f"data/{guild_name}/{msgchannel_name}", "w") as f:
                f.write(
                    f"GPT4 Correct system: {sysp}<|end_of_turn|>GPT4 Correct {message.author}: {message.content}<|end_of_turn|>"
                )
        finally:
            with open(f"data/{guild_name}/{msgchannel_name}", "r") as f:
                context = f.read()
        await syncMessages()
        if "Feeway" in guild_name:
            context += f"GPT4 Correct Assistant:"
            title = ec(context, "<title>", "</title>")[0]
            output = LLM.text_generation(context,
                                         stop_sequences=["<|end_of_turn|>"],
                                         max_new_tokens=4096)
            with open(f"data/{guild_name}/{msgchannel_name}", "a") as f:
                f.write(f"GPT4 Correct Assistant: {output}<|end_of_turn|>")
            embed = discord.Embed(title=title,
                                  description=output.replace(
                                      f"<title>{title}</title>", ""),
                                  color=0x1E81B0)
            embed.set_footer(
                text=
                """Information or code generated by Lyre may not always be correct. Lyre was made by Araeyn."""
            )
            e = await message.reply(embed=embed)
    except Exception as e:
        print(Fore.RED)
        print(e)
        print(Style.RESET_ALL)

token = os.environ["TOKEN"]
client.run(token)