-
Notifications
You must be signed in to change notification settings - Fork 0
/
discord_bot.py
262 lines (221 loc) · 7.13 KB
/
discord_bot.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
from pydantic import BaseModel, Field, ConfigDict
from typing import List, Optional, ClassVar
from openai import OpenAI, AsyncOpenAI
import os
from dotenv import load_dotenv
import requests
import discord
from discord.ext import commands
import re
from bot import Assistant
load_dotenv()
tools_selection = {
"file_search": [
"c",
"cs",
"cpp",
"doc",
"docx",
"html",
"java",
"json",
"md",
"pdf",
"php",
"pptx",
"py",
"py",
"rb",
"tex",
"txt",
"css",
"js",
"sh",
"ts"
],
"code_interpreter": [
"c",
"cs",
"cpp",
"doc",
"docx",
"html",
"java",
"json",
"md",
"pdf",
"php",
"pptx",
"py",
"rb",
"tex",
"txt",
"css",
"js",
"sh",
"ts",
"csv",
"tar",
"xlsx",
"xml",
"zip"
],
"image": [
"jpeg",
"jpg",
"gif",
"png",
"bmp",
"tiff",
"svg",
"webp",
"heic",
"ico",
"eps",
"raw",
"psd",
"tga",
"ai"
]
}
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
aclient = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
thread = client.beta.threads.create()
class UserMessage(BaseModel):
text: str | None = None
image_urls: list[str] | None = None
file_urls: list[discord.message.Attachment] | None = None
class Config:
arbitrary_types_allowed = True
def user_content(self):
text_dict = [{
"type": "text",
"text": self.text,
}] if self.text else []
image_dict = [
{
"type": "image_url",
"image_url": {
"url": image_url,
"detail": "auto"
},
} for image_url in self.image_urls
] if self.image_urls else []
content = text_dict + image_dict
return content
def download_file(self, url, local_filename):
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
return local_filename
async def attachments(self) -> List[str]:
attachments_dicts = []
if self.file_urls:
for url in self.file_urls:
local_filename = f"tmp/{url.filename}"
file_ext = url.filename.split(".")[-1]
if file_ext in tools_selection["file_search"]:
tool = "file_search"
elif file_ext in tools_selection["code_interpreter"]:
tool = "code_interpreter"
# elif file_ext in tools_selection["image"]:
# continue
else:
raise ValueError(f"Unsupported file type: {file_ext}")
self.download_file(url.url, local_filename)
with open(local_filename, "rb") as f:
response = await aclient.files.create(file=f, purpose="assistants")
file_id = response.id
attachment = {
"file_id": file_id,
"tools": [
{"type": tool}
]
}
attachments_dicts.append(attachment)
os.remove(local_filename)
return attachments_dicts
# 获取 Discord 机器人令牌
token = os.getenv("DISCORD_BOT_TOKEN")
# 设置 Discord 的 Intents
intents = discord.Intents.default()
intents.message_content = True
# 创建一个新的 bot 客户端
bot = commands.Bot(command_prefix='!', intents=intents)
tree = bot.tree
threads = {}
@bot.event
async def on_ready():
slash = await bot.tree.sync()
print(f"目前登入身份 --> {bot.user}")
print(f"載入 {len(slash)} 個斜線指令")
async def check_thread(thread_id):
try:
res = await aclient.beta.threads.retrieve(thread_id)
except Exception as e:
res = None
return res
# 当收到消息时,使用 DeepSeek 模型生成响应
@bot.event
async def on_message(message):
sender = f"{message.channel.id}-{message.author.id}"
user_name = message.author.display_name
user_id = message.author.id
channel_id = message.channel.id
print(f"user: {user_name} ({user_id}), channel: {channel_id}")
# 不响应自己的消息
if not isinstance(message.channel, discord.DMChannel):
if message.author == bot.user or (bot.user.mention not in message.content):
return
else:
if message.author == bot.user:
return
if channel_id not in threads.keys():
thread_info = await aclient.beta.threads.create()
threads[channel_id] = thread_info.id
elif await check_thread(threads[channel_id]) is None:
thread_info = await aclient.beta.threads.create()
threads[channel_id] = thread_info.id
chatbot = Assistant(aclient, threads[channel_id])
image_urls = []
files = []
if message.attachments:
for attachment in message.attachments:
file_ext = attachment.filename.split(".")[-1]
if file_ext in tools_selection["image"]:
image_urls.append(attachment.url)
elif file_ext in tools_selection["file_search"] or file_ext in tools_selection["code_interpreter"]:
files.append(attachment)
else:
await message.reply(f"Unsupported file type: {file_ext}", mention_author=False)
msg = UserMessage(
text=f"[{user_name} (id: {user_id})] {message.content}",
image_urls=image_urls if image_urls else None,
file_urls=files if files else None
)
attachments = await msg.attachments()
print(msg.user_content())
await chatbot.add_message(msg.user_content(), attachments)
async with message.channel.typing():
response = await chatbot.create_a_run()
# res.data[0].content[0].text.value
if response.data[0].role == "assistant":
for res in response.data[0].content:
if res.type == "text":
response = res.text.value
else:
response = "Unsupported message type"
# 发送响应
print(response)
await message.reply(response, mention_author=False)
@bot.tree.command(name = "clear_history", description = "清除历史记录")
async def clear_history(interaction: discord.Interaction):
channel_id = interaction.channel.id
response = await aclient.beta.threads.delete(threads[channel_id])
new_thread = await aclient.beta.threads.create()
threads[channel_id] = new_thread.id
await interaction.response.send_message("[系统消息] 聊天记录已清除", ephemeral=True)
# 运行机器人
bot.run(token)