summaryrefslogtreecommitdiff
path: root/robot.py
blob: 517757534cb7f13797e84db309a359c2d127f3b7 (plain)
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
import asyncio
import json
import os.path
import threading
from typing import Dict, List
from openai import OpenAI
import aiohttp
import qqbot


from qqbot.core.util.yaml_util import YamlUtil
from qqbot.model.message import MessageEmbed, MessageEmbedField, MessageEmbedThumbnail, CreateDirectMessageRequest, MessageArk, MessageArkKv, MessageArkObj, MessageArkObjKv

def load_openai_key(filepath="openai_key.txt"):
    with open(filepath, 'r') as f:
        return f.read().strip()

openai_key = load_openai_key()
test_config = YamlUtil.read(os.path.join(os.path.dirname(__file__), "config.yaml"))

clinet = OpenAI(api_key=openai_key)

gpt_instruction = YamlUtil.read(os.path.join(os.path.dirname(__file__), "gpt_instruction.yaml"))

async def _message_handler(event, message: qqbot.Message):
    msg_api = qqbot.AsyncMessageAPI(t_token, False)
    qqbot.logger.info("event %s" % event + ",receive message %s" % message.content)
    response = clinet.chat.completions.create(
        model="gpt-3.5-turbo-0125",
        messages=[
            {"role": "system", "content": gpt_instruction},
            {"role": "user", "content": message.content}
        ]
    )
    reply = response.choices[0].message
    print(reply)
    message_to_send = qqbot.MessageSendRequest(content=reply.content, msg_id=message.id)
    await msg_api.post_message(message.channel_id, message_to_send)

#write a funtion for the bot: when a message begins with "/copy", the bot will copy the message and reply it.

if __name__ == "__main__":
    t_token = qqbot.Token(test_config["token"]["appid"], test_config["token"]["token"])
    qqbot_handler = qqbot.Handler(
        qqbot.HandlerType.AT_MESSAGE_EVENT_HANDLER, _message_handler
    )

    qqbot.async_listen_events(t_token, False, qqbot_handler)