-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
411 lines (375 loc) · 13 KB
/
main.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import asyncio
import base64
import datetime
import os
import random
from typing import Any
import httpx
from loguru import logger
from motor.motor_asyncio import AsyncIOMotorClient
from bingimagecreator import ImageGen, GenerateImagePromptException
from qqgroupbot.core import Event, initial_openapi_client, fetch_events, get_gateway_url
from qqgroupbot.apis.reply_group_message import reply_group_message
from qqgroupbot.aichat.gemini import (
generate_content,
GenerateSafeError,
GenerateResponseError,
GenerateNetworkError,
Content as GeminiRequestContent,
Part as GeminiRequestPart,
initial_gemini_client,
is_supported_mime_type,
)
from qqgroupbot.command import command, CommandMatcher
BOT_ID = os.environ["BOT_ID"]
BOT_TOKEN = os.environ["BOT_TOKEN"]
BOT_URL = os.environ.get("BOT_URL", "https://api.sgroup.qq.com")
AUTHORIZATION = f"Bot {BOT_ID}.{BOT_TOKEN}"
GEMINI_PRO_KEY = os.environ["GEMINI_PRO_KEY"]
GEMINI_PRO_URL = os.environ.get("GEMINI_PRO_URL")
GEMINI_PRO_VISION_URL = os.environ.get("GEMINI_PRO_VISION_URL")
BING_COOKIES = os.environ.get("BING_COOKIES", "")
async def download_image(url: str) -> str:
async with httpx.AsyncClient() as client:
return base64.b64encode(await (await client.get(url)).aread()).decode()
async def generate_image(prompt: str) -> str:
async with ImageGen(BING_COOKIES) as g:
links = await g.get_images(prompt)
logger.debug(f"Generated images: {links}")
# QQ 只能发 1 张图
return str(g.session._merge_url(random.choice(links)))
client = AsyncIOMotorClient(os.environ.get("MONGODB_URI", "mongodb://localhost:27017"))
db = client["paimeng"]
collection_messages = db["messages"]
collection_multi_turn_conversations = db["turns_messages"]
class Commands(CommandMatcher):
@command("echo")
async def echo(
self,
content: str,
/,
*,
group_openid: str,
message_id: str,
**_: Any,
) -> None:
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content=content,
)
@command("status")
async def status(
self,
content: str,
/,
*,
group_openid: str,
message_id: str,
**_: Any,
) -> None:
in_conversations = (
await collection_multi_turn_conversations.count_documents(
{"group_openid": group_openid}
)
!= 0
)
more_content = (
"正在进行连续对话。" if in_conversations else "没有在进行连续对话。"
)
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content="数据库正常。" + more_content,
)
@command("画图")
async def draw(
self,
prompt: str,
/,
*,
group_openid: str,
message_id: str,
event: Event,
**_: Any,
) -> None:
if not prompt:
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content="你要我画什么呢?",
)
return
parts: list[Any] = [
{
"text": "Please generate accurate and detailed prompt for DALL-E based on the prompt words I gave. You only need to give me the prompt and do not give any additional content. I'll give you a big tip: "
+ prompt
}
]
for attachment in event.get("d", {}).get("attachments", []):
content_type = attachment["content_type"]
url = attachment["url"]
if is_supported_mime_type(content_type):
image_base64 = await download_image(url)
parts.append(
{
"inline_data": {
"mime_type": content_type,
"data": image_base64,
}
}
)
try:
image_prompt = await generate_content(
[{"parts": parts}], safety_threshold="BLOCK_LOW_AND_ABOVE"
)
image_url = await generate_image(image_prompt)
except (GenerateImagePromptException, GenerateSafeError):
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content="这个不可以画哦。",
)
return
except GenerateNetworkError as error:
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content="怎么办?怎么办?派蒙连接不上提瓦特了。",
)
logger.warning(f"Network error: {error}")
return
except GenerateResponseError as error:
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content=str(error),
)
except Exception:
logger.exception("Failed to generate image")
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content="哎呀,颜料桶打翻了。",
)
return
else:
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content=f"这是你要的画。使用了“{image_prompt}”",
image_url=image_url,
)
@command("Bing cookies")
async def bing_cookies(
self,
content: str,
/,
*,
group_openid: str,
message_id: str,
**_: Any,
) -> None:
global BING_COOKIES
if not content:
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content=BING_COOKIES,
)
return
BING_COOKIES = content.strip()
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content="好的,已经更新了。",
)
@command("连续对话")
async def start_conversation(
self,
content: str,
/,
*,
group_openid: str,
message_id: str,
**_: Any,
) -> None:
if await collection_multi_turn_conversations.count_documents(
{"group_openid": group_openid}
):
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content="正在进行连续对话。",
)
else:
await collection_multi_turn_conversations.insert_one(
{"group_openid": group_openid, "contents": []}
)
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content="好的,我们来聊些什么呢?",
)
@command("结束对话")
async def end_conversation(
self,
content: str,
/,
*,
group_openid: str,
message_id: str,
**_: Any,
) -> None:
if document := await collection_multi_turn_conversations.find_one_and_delete(
{"group_openid": group_openid}
):
await collection_messages.insert_one(
{
"group_openid": group_openid,
"contents": document["contents"],
"created_at": datetime.datetime.now(),
}
)
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content="那下次再和派蒙聊天吧。",
)
else:
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content="我们没有在聊天啊。",
)
async def unknown_command(
self,
content: str,
/,
*,
group_openid: str,
message_id: str,
event: Event,
**_: Any,
) -> None:
parts: list[GeminiRequestPart] = [{"text": content}]
for attachment in event.get("d", {}).get("attachments", []):
content_type = attachment["content_type"]
url = attachment["url"]
if is_supported_mime_type(content_type):
image_base64 = await download_image(url)
parts.append(
{
"inline_data": {
"mime_type": content_type,
"data": image_base64,
}
}
)
contents: list[GeminiRequestContent]
if document := await collection_multi_turn_conversations.find_one(
{"group_openid": group_openid}
):
contents = document["contents"]
contents.append({"role": "user", "parts": parts})
else:
contents = [{"parts": parts}]
try:
response_content = await generate_content(contents)
except GenerateSafeError as error:
response_content = "这是不可以谈的话题。"
logger.warning(f"Safe error: {error}")
except GenerateResponseError as error:
response_content = error.message
logger.exception(f"Response error: {error}")
except GenerateNetworkError as error:
response_content = "怎么办?怎么办?派蒙连接不上提瓦特了。"
logger.warning(f"Network error: {error}")
else:
update_result = await collection_multi_turn_conversations.update_one(
{"group_openid": group_openid},
{
"$push": {
"contents": {
"$each": [
{"role": "user", "parts": parts},
{
"role": "model",
"parts": [{"text": response_content}],
},
]
}
}
},
)
if update_result.modified_count == 0:
contents.append(
{
"role": "model",
"parts": [{"text": response_content}],
},
)
await collection_messages.insert_one(
{
"group_openid": group_openid,
"contents": contents,
"created_at": datetime.datetime.now(),
}
)
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content=response_content,
)
async def group_at_message_create(event: Event):
if "d" not in event:
logger.warning(f"Unexpected event: {event}")
return
logger.debug(f"Group at message create: {event}")
group_openid = event["d"]["group_openid"]
content = event["d"]["content"]
message_id = event["d"]["id"]
try:
await asyncio.wait_for(
Commands(
content, group_openid=group_openid, message_id=message_id, event=event
),
5 * 60 - 5, # 5 minutes
)
except asyncio.TimeoutError:
await reply_group_message(
group_openid=group_openid,
message_id=message_id,
content="哎呀,派蒙思考太久了。",
)
async def main():
semaphore = asyncio.Semaphore(1000)
async with (
initial_openapi_client(BOT_URL, AUTHORIZATION),
initial_gemini_client(
GEMINI_PRO_KEY, pro_url=GEMINI_PRO_URL, pro_vision_url=GEMINI_PRO_VISION_URL
),
):
async for event in fetch_events(
await get_gateway_url(BOT_URL, AUTHORIZATION),
authorization=AUTHORIZATION,
intents=0 | (1 << 0) | (1 << 1) | (1 << 12) | (1 << 25) | (1 << 30),
):
op = event["op"]
if op != 0:
logger.warning(f"Unexpected event: {event}")
continue
match event.get("t"):
case "GROUP_AT_MESSAGE_CREATE":
await semaphore.acquire()
task = asyncio.create_task(group_at_message_create(event))
task.add_done_callback(
lambda future: semaphore.release() or future.result()
)
case _:
logger.warning(f"Unhandled event: {event}")
if __name__ == "__main__":
logger.remove()
import sys
logger.add(sys.stdout, level=os.environ.get("LOG_LEVEL", "INFO"))
asyncio.run(main())