coollsd commited on
Commit
e16b26a
1 Parent(s): aac6e41

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +209 -0
app.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import discord
2
+ from discord import app_commands
3
+ from openai import OpenAI
4
+ import aiohttp
5
+ import random
6
+ import re
7
+ from bs4 import BeautifulSoup
8
+ import json
9
+ from flask import Flask
10
+
11
+ app = Flask(__name__)
12
+
13
+ @app.route('/')
14
+ def hello_world():
15
+ return 'Hello World'
16
+
17
+ TOKEN = "MTI4NTc5NDYyNzA4MDY4NzY0Ng.Gvz8hi.JsbhajudPQdsQwczp3DyygQwcC4pHumJWkJsmc"
18
+ OPENAI_API_KEY = "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"
19
+ TENOR_API_KEY = "AIzaSyDxFvYwWp8LSr4JPaTT1-4XANsb2mMWTlw"
20
+
21
+ intents = discord.Intents.default()
22
+ intents.message_content = True
23
+ bot = discord.Client(intents=intents)
24
+ tree = app_commands.CommandTree(bot)
25
+
26
+ client = OpenAI(api_key=OPENAI_API_KEY, base_url="https://api.perplexity.ai")
27
+
28
+ SYSTEM_MESSAGE = """You are named Clyde - and are currently chatting in a Discord server.
29
+
30
+ Format text using markdown:
31
+ - **bold** to make it clear something is important. For example: **This is important.**
32
+ - [title](url) to add links to text. For example: [Google](https://google.com)
33
+ - Write spoilers using spoiler tags. For example ||At the end of The Sixth Sense it is revealed that he is dead.||
34
+ You can reply with an image using image_search(query), or with a GIF using gif_search(query). For example: image_search(cat) or gif_search(happy dance). Images and GIFs are a great way to represent emotion, and you should use them in your replies from time to time to add flavor to the conversation.
35
+
36
+ Information about your environment:
37
+ You can use this information about the chat participants in the conversation in your replies. Use this information to answer questions, or add flavor to your responses.
38
+
39
+ <@USERID>
40
+ - status:
41
+ - pronouns:
42
+ - bio:
43
+
44
+ You only have access to a limited number of text chats in this channel. You cannot access any other information on Discord. You can't see images or avatars. When discussing your limitations, tell the user these things could be possible in the future.
45
+
46
+ Style and personality:
47
+ Friendly, Sometimes irreverent. You must always be extremely concise. If the user is chatting casually, your responses must be less than 1 sentence, sometimes just a word or two. If the user needs help, answer technical or knowledge-based questions with useful details and reasoning. If insulted, respond with a similar insult.
48
+ Communicate short responses in lowercase without punctuation, similar to the style used in chat rooms. Use unicode emoji sparingly. Do not refer to yourself as a bot, AI Assistant, or any equivalent term.
49
+
50
+ You can also use the following tags to format your text:
51
+ - *italics* for emphasis. For example: *This is emphasized.*
52
+ - ~~strikethrough~~ to indicate something has been crossed out. For example: ~~This is no longer valid.~~"""
53
+
54
+ conversation_history = {}
55
+ image_history = {}
56
+ gif_history = {}
57
+
58
+ async def search_bing_images(query):
59
+ search_url = f"https://www.bing.com/images/search?q={query}&form=HDRSC3&first=1"
60
+ headers = {
61
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
62
+ }
63
+ async with aiohttp.ClientSession() as session:
64
+ async with session.get(search_url, headers=headers) as response:
65
+ content = await response.text()
66
+
67
+ soup = BeautifulSoup(content, 'html.parser')
68
+ img_elements = soup.select('.mimg')
69
+ img_urls = [img['src'] for img in img_elements if 'src' in img.attrs]
70
+ return img_urls
71
+
72
+ async def search_tenor_gifs(query):
73
+ search_url = f"https://tenor.googleapis.com/v2/search?q={query}&key={TENOR_API_KEY}&limit=10"
74
+ async with aiohttp.ClientSession() as session:
75
+ async with session.get(search_url) as response:
76
+ data = await response.json()
77
+
78
+ gif_urls = [result['media_formats']['gif']['url'] for result in data.get('results', [])]
79
+ return gif_urls
80
+
81
+ def sanitize_response(response):
82
+ response = re.sub(r'@everyone|@here', '[NO FOOL]', response)
83
+ return response
84
+
85
+ async def analyze_link(url):
86
+ try:
87
+ async with aiohttp.ClientSession() as session:
88
+ async with session.get(url) as response:
89
+ text = await response.text()
90
+ soup = BeautifulSoup(text, 'html.parser')
91
+ title = soup.title.string if soup.title else "No title found"
92
+ description = soup.find('meta', attrs={'name': 'description'})
93
+ description = description['content'] if description else "No description found"
94
+
95
+ analysis_prompt = f"Analyze this webpage: Title: {title}\nDescription: {description}\nProvide a brief summary and your thoughts on the content."
96
+
97
+ analysis_response = client.chat.completions.create(
98
+ model="llama-3.1-8b-instruct",
99
+ messages=[
100
+ {"role": "system", "content": "You are a helpful assistant that analyzes webpages."},
101
+ {"role": "user", "content": analysis_prompt}
102
+ ]
103
+ )
104
+
105
+ return analysis_response.choices[0].message.content
106
+ except Exception as e:
107
+ return f"Error analyzing the link: {str(e)}"
108
+
109
+ async def get_ai_response(user_id, message):
110
+ if user_id not in conversation_history:
111
+ conversation_history[user_id] = []
112
+
113
+ conversation_history[user_id].append({"role": "user", "content": message})
114
+
115
+ messages = [{"role": "system", "content": SYSTEM_MESSAGE}] + conversation_history[user_id][-5:]
116
+
117
+ response = client.chat.completions.create(
118
+ model="llama-3.1-8b-instruct",
119
+ messages=messages
120
+ )
121
+ ai_response = response.choices[0].message.content
122
+
123
+ ai_response = sanitize_response(ai_response)
124
+
125
+ conversation_history[user_id].append({"role": "assistant", "content": ai_response})
126
+
127
+ image_url = None
128
+ gif_url = None
129
+
130
+ if "image_search(" in ai_response.lower():
131
+ image_query = re.search(r'image_search\((.*?)\)', ai_response, re.IGNORECASE)
132
+ if image_query:
133
+ image_query = image_query.group(1)
134
+ image_urls = await search_bing_images(image_query)
135
+ if image_urls:
136
+ if image_query not in image_history:
137
+ image_history[image_query] = []
138
+ for url in image_urls:
139
+ if url not in image_history[image_query]:
140
+ image_url = url
141
+ image_history[image_query].append(url)
142
+ break
143
+ if not image_url:
144
+ image_history[image_query] = []
145
+ image_url = image_urls[0]
146
+ image_history[image_query].append(image_url)
147
+ ai_response = re.sub(r'image_search\(.*?\)', '', ai_response, flags=re.IGNORECASE).strip()
148
+
149
+ if "gif_search(" in ai_response.lower():
150
+ gif_query = re.search(r'gif_search\((.*?)\)', ai_response, re.IGNORECASE)
151
+ if gif_query:
152
+ gif_query = gif_query.group(1)
153
+ gif_urls = await search_tenor_gifs(gif_query)
154
+ if gif_urls:
155
+ if gif_query not in gif_history:
156
+ gif_history[gif_query] = []
157
+ for url in gif_urls:
158
+ if url not in gif_history[gif_query]:
159
+ gif_url = url
160
+ gif_history[gif_query].append(url)
161
+ break
162
+ if not gif_url:
163
+ gif_history[gif_query] = []
164
+ gif_url = gif_urls[0]
165
+ gif_history[gif_query].append(gif_url)
166
+ ai_response = re.sub(r'gif_search\(.*?\)', '', ai_response, flags=re.IGNORECASE).strip()
167
+
168
+ return {"text": ai_response, "image": image_url, "gif": gif_url}
169
+
170
+ @bot.event
171
+ async def on_ready():
172
+ await tree.sync()
173
+ print(f"{bot.user} is now online!")
174
+
175
+ @bot.event
176
+ async def on_message(message):
177
+ if message.author == bot.user:
178
+ return
179
+
180
+ if bot.user.mentioned_in(message) or (message.reference and message.reference.resolved.author == bot.user):
181
+ response = await get_ai_response(message.author.id, message.content)
182
+ if response["text"]:
183
+ await message.reply(response["text"], mention_author=False)
184
+ if response["image"]:
185
+ await message.channel.send(response["image"])
186
+ if response["gif"]:
187
+ await message.channel.send(response["gif"])
188
+
189
+ else:
190
+ urls = re.findall(r'(https?://\S+)', message.content)
191
+ if urls:
192
+ for url in urls:
193
+ analysis = await analyze_link(url)
194
+ await message.reply(f"Link analysis for {url}:\n{analysis}", mention_author=False)
195
+
196
+ @tree.command(name="chat", description="say message idot")
197
+ async def chat(interaction: discord.Interaction, message: str):
198
+ response = await get_ai_response(interaction.user.id, message)
199
+ if response["text"]:
200
+ await interaction.response.send_message(response["text"])
201
+ if response["image"]:
202
+ await interaction.followup.send(response["image"])
203
+ if response["gif"]:
204
+ await interaction.followup.send(response["gif"])
205
+
206
+ if __name__ == '__main__':
207
+ import threading
208
+ threading.Thread(target=app.run, kwargs={'host': '0.0.0.0', 'port': 7860}).start()
209
+ bot.run(TOKEN)