基于Go-cqhttp和python开发QQ机器人(二)

概述

基于前一篇文章https://mp.csdn.net/mp_blog/creation/editor/new/128808067 

继续开发QQ机器人的一些功能, 基于chatgpt可CSDN开发,具体功能有查询博客、问答、和写代码功能,后续还可以自己添加更多代码, 注意,go-cqhttp要的位置需要放在指定位置(~/go-cqhttp),或者可以自己该写代码

代码

main.py

#!/usr/bin/python
from flask import Flask, request
import threading, os
from Api import Api

Api = Api(manager=2919465681)
app = Flask(__name__)


@app.route('/', methods=["POST", "GET"])
def post_data():
    'request.get_json().get获取数据'
    res = request.get_json()
    print(res)

    if res.get('message_type') == 'private':
        uid = res.get('sender').get('user_id')
        message = res.get('raw_message')
        Api.send(message, uid)

    if res.get('message_type') == 'group':
        uid = res.get('sender').get('user_id')
        gid = res.get('group_id')
        message = res.get('raw_message')
        message_seq = res.get('message_seq')
        message_id = res.get('message_id')
        Api.send(message, uid, gid, message_id, message_seq)

    return 'ok'


def run_QQ():
    os.system('cd ~/go-cqhttp && ./go-cqhttp')


def run_app():
    app.run(debug=False, host='127.0.0.1', port=5701)


if __name__ == '__main__':
    threading.Thread(target=run_QQ).start()
    threading.Thread(target=run_app).start()

Api.py

#!/usr/bin/python


import requests
from utils.tool import Tool

def send_group(msg, gid):
    url = "http://127.0.0.1:5700/send_group_msg"

    data = {
        "group_id": gid,
        "message": msg,
        "auto_escape": False
    }
    resp = requests.post(url, data=data)
    print("successful sending" if resp.status_code == 200 else "failed sending")

def send_private(msg, uid, gid):
    url = 'http://127.0.0.1:5700/send_private_msg'
    data = {
        "user_id": uid,
        "group_id": gid,
        "message": msg,
        "auto_escape": False
    }
    resp = requests.post(url, data=data)
    print("successful sending" if resp.status_code == 200 else "failed sending")



def isRepeate(uid, *args):
    for usr in args:
        if uid in usr:
            return False
    return True
class Api():

    def __init__(self, manager=None, manager_group=None):
        self.manager = manager
        self.manager_group = manager_group
        self.tool = Tool()

        self.mode1_usr = []
        self.mode2_usr = []
        self.mode3_usr = []
        self.mode4_usr = []

    def send(self, message, uid, gid=None, message_id=None, message_seq=None):
        if self.manager_group == None:
            self.manager_group = gid

        if gid: # group message
            if message == '#0' and not isRepeate(uid, self.mode1_usr, self.mode2_usr, self.mode3_usr, self.mode4_usr): # exit mode
                try:
                    self.mode1_usr.remove(uid)
                except:
                    pass
                try:
                    self.mode2_usr.remove(uid)
                except:
                    pass
                try:
                    self.mode3_usr.remove(uid)
                except:
                    pass
                try:
                    self.mode4_usr.remove(uid)
                except:
                    pass
                msg = f'''number:\n#1:{len(self.mode1_usr)} people\n#2:{len(self.mode2_usr)} people\n#3:{len(self.mode3_usr)} people\n#4:{len(self.mode4_usr)} people'''
                msg = f'[CQ:reply,id={message_id},qq={uid},time=3376656000,seq=5123]{msg}'
                send_group(msg=msg, gid=gid)

            if message == '#1' and uid not in self.mode1_usr: # start mode1
                msg = ""
                if isRepeate(uid, self.mode2_usr, self.mode3_usr, self.mode4_usr) and len(self.mode1_usr) <= 4:
                    self.mode1_usr.append(uid)
                    msg = "sucessful start #1"

                else:
                    msg = "failed start,number is full or please exit other mode"
                msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
                send_group(msg, gid)

            elif message == '#2':  # start mode2
                msg = ""
                if isRepeate(uid, self.mode1_usr, self.mode3_usr, self.mode4_usr) and len(self.mode2_usr) <= 4:
                    self.mode2_usr.append(uid)
                    msg = "sucessful start #2"
                else:
                    msg = "failed start,number is full or please exit other mode"
                msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
                send_group(msg, gid)

            elif message == '#3':  # start mode3
                msg = ""
                if isRepeate(uid, self.mode2_usr, self.mode1_usr, self.mode4_usr) and len(self.mode3_usr) <= 4:
                    self.mode3_usr.append(uid)
                    msg = "sucessful start #3"
                else:
                    msg = "failed start! \nnumber is full or please exit other mode"
                msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
                send_group(msg, gid)

            elif message == '#4':  # start mode4
                msg = ""
                if isRepeate(uid, self.mode2_usr, self.mode3_usr, self.mode1_usr) and len(self.mode4_usr) <= 4:
                    self.mode4_usr.append(uid)
                    msg = "sucessful start #4"
                else:
                    msg = "failed start! \nnumber is full or please exit other mode"
                msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
                send_group(msg, gid)

            elif uid in self.mode1_usr:
                msg = self.tool.openai_code(content=message)
                msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
                send_group(msg, gid)

            elif uid in self.mode2_usr:
                msg = self.tool.openai_QA(content=message)
                msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
                send_group(msg, gid)

            elif uid in self.mode3_usr:
                item = self.tool.get_csdn(content=message)
                for title, url in item.items():
                    msg = f'{title}[CQ:share,url={url},title={title}]'
                    send_private(msg, uid, gid)






        else: # private message
            if '博客查询' in message:
                message = message.replace('博客查询', '')
                item = self.tool.get_csdn(content=message)
                for title, url in item.items():
                    msg = f'{title}[CQ:share,url={url},title={title}]'
                    send_private(msg, uid, gid)

utils.tool

#!/usr/bin/python

import openai
import requests
import cv2

class Tool():
    
    def __init__(self):
        self.openai = openai
        self.openai.api_key = '' # 此处填写自己chatgpt的key
        self.csdn_url = 'https://so.csdn.net/api/v3/search'

    def openai_code(self, content="python写1到100累加和"):

        response = self.openai.Completion.create(
            model="code-davinci-002",
            prompt=f"\"\"\"\n{content}\n\"\"\"\n",
            temperature=0.0,
            max_tokens=1000,
            top_p=1.0,
            frequency_penalty=0.0,
            presence_penalty=0.0,
            stop=["\"\"\""]
        )
        return response.choices[0].text

    def openai_QA(self, content="你会干什么"):

        response = self.openai.Completion.create(
            model="text-davinci-003",
            prompt=f"{content}\nA:",
            temperature=0.5,
            max_tokens=300,
            top_p=1,
            frequency_penalty=0.0,
            presence_penalty=0.0,
            stop=["\n"]
        )
        return response.choices[0].text

    def get_csdn(self, content='python'):
        param = {
            'q': content
        }

        res = {}
        resp = requests.get(self.csdn_url, param).json()["result_vos"]
        num = 5
        for i in resp:
            url = i['url']
            title = i['title'].replace('<em>', '').replace('</em>', '')
            if num <= 0:
                break
            if title == 'python技能树' or title == 'C技能树':
                pass
            else:
                num -= 1
                res[title] = url
        return res




总结

这个代码还有一些功能没有实现,可以自己去填写一些功能

### 回答1: 要用 Python 写一个基于 go-cqhttp 的 QQ 机器人,你可以使用第三方库,如 CoolQ HTTP API 插件的 Python SDK,它封装了 go-cqhttp 提供的 HTTP API,使用起来更方便。 以下是一个简单的示例: ``` from cqhttp import CQHttp bot = CQHttp(api_root='http://127.0.0.1:5700/') @bot.on_message() def handle_msg(context): # 实现你的机器人逻辑 return {'reply': '你好,我是机器人!'} bot.run() ``` 这段代码中,我们定义了一个 handle_msg 函数来处理消息,并返回一个回复。运行这段代码后,你的机器人就会自动对收到的消息进行回复。 当然,你还可以根据需要添加更多的处理逻辑,例如:处理私聊消息,实现智能问答等。 ### 回答2: 基于go-cqhttp,使用Python编写QQ机器人可以通过与go-cqhttp插件的HTTP API进行交互来实现。 首先,将Python的requests库导入项目中,以便发送HTTP请求。 接下来,我们需要处理机器人收到的消息。通过模拟用户发送消息时,go-cqhttp发送的HTTP POST请求,我们可以使用Python的Flask框架来接收和处理这些消息。 在接收消息的路由上,我们可以使用Flask的`@app.route('/message')`来定义一个路由函数。在这个函数中,我们可以提取出消息中的关键信息,例如发送者QQ号码、发送的消息内容等。 接下来,我们可以使用条件语句对接收到的消息进行分类处理。例如,我们可以根据关键字回复不同的内容,或者调用外部API来进行一些其他操作。可以根据情况,编写不同的函数作为消息处理器。 在处理完消息后,我们需要将最终的回复发送给发送者。我们可以通过构造一个回复消息的字典,并将其转化为JSON格式,然后使用requests库发送POST请求到你自己的go-cqhttp插件上的HTTP API。 最后,我们可以利用go-cqhttp插件的事件上报功能,来处理一些其他的事件。例如好友申请、群聊消息等。 总结起来,基于go-cqhttp,用Python写一个QQ机器人可以通过与go-cqhttp插件的HTTP API进行交互,处理接收的消息和事件,并根据需要编写不同的函数作为消息处理器、事件处理器。最后,将回复消息发送给发送者。通过这些步骤,我们可以实现一个简单的QQ机器人。 ### 回答3: 基于go-cqhttp,我们可以使用Python来编写一个QQ机器人。首先,我们需要使用Python的 requests 库与go-cqhttp建立通信。 首先,我们需要在go-cqhttp的配置文件中开启HTTP、WS(WebSocket)接口。然后,我们可以使用python的requests库向go-cqhttp发送HTTP请求来完成一些操作,例如发送私聊消息: ```python import requests url = "http://127.0.0.1:5700/send_private_msg" data = { "user_id": 你的QQ号, "message": "Hello, World!" } response = requests.post(url, json=data) ``` 这将向你的QQ号发送私聊消息"Hello, World!"。 然后,我们可以使用Python来监听go-cqhttp发送给QQ机器人的消息,这里我们可以使用WebSocket连接进行实时通信。我们可以使用Python的websocket库来实现WebSocket通信: ```python import websocket def on_message(ws, message): print(message) def on_error(ws, error): print(error) def on_close(ws): print("连接已关闭") def on_open(ws): print("连接已打开") # 创建WebSocket连接对象 ws = websocket.WebSocketApp("ws://127.0.0.1:6700") # 绑定回调函数 ws.on_message = on_message ws.on_error = on_error ws.on_close = on_close ws.on_open = on_open # 开始监听消息 ws.run_forever() ``` 这将打开一个WebSocket连接,接收go-cqhttp发送给QQ机器人的消息,并将其打印出来。 当然,以上只是一个简单的例子,对于一个完整的QQ机器人,我们还可以做很多其他的操作,例如发送群聊消息、处理命令、响应事件等等。这些操作都可以通过向go-cqhttp发送HTTP请求来实现。 综上所述,使用Python编写一个基于go-cqhttpQQ机器人是十分可行的,我们可以利用Python提供的各种库与go-cqhttp进行通信,实现丰富的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜如影

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值