go-cqhttp智能聊天

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

go-cqhttp智能聊天

A-L-Kun   2022-09-29 我要评论

智能聊天

一、 概述

我们将我们的qq聊天机器人的环境配置好后,其就可以开始接收消息啦!那么,我们除了可以接收特定的消息,是不是还需要接收那些不是我们指定的消息呢?我想是的!那么,我们要如何接入呢?

这里,我找了一个比较好用的聊天机器人的API接口。可以将其接入我们的程序中,做一个陪聊小助手。当然,如果你机器学习学的比较好的话,你也可以自己训练一个模型来实现智能聊天的接口。

我们选择的是青云客智能聊天

二、 使用方法

同时,其还有一些拓展的功能!

三、 接入程序

我们暂时只对私信消息进行处理,接入我们的智能聊天接口

private_script.py文件中,添加一个函数,同时修改处理私聊消息的接口:

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
__author__ = "A.L.Kun"
__file__ = "private_script.py.py"
__time__ = "2022/9/9 22:04"

import httpx
from datetime import datetime
async def handle_private(uid, message):  # 处理私聊信息
    if message:  # 简单的判断,只是判断其是否为空
        _ = await get_resp(message)
        ret = _.get("content", "获取回复失败")
        await send(uid, f"{ret}\n发送时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
async def get_resp(message):  # 对接口发送请求,获取响应数据
    async with httpx.AsyncClient() as client:
        params = {
            "key": "free",
            "appid": 0,
            "msg": message,
        }
        resp = await client.get("http://api.qingyunke.com/api.php", params=params)
        return resp.json()
async def send(uid, message):
    """
    用于发送消息的函数
    :param uid: 用户id
    :param message: 发送的消息
    :return: None
    """
    async with httpx.AsyncClient(base_url="http://127.0.0.1:5700") as client:
        # 如果发送的为私聊消息
        params = {
            "user_id": uid,
            "message": message,
        }
        await client.get("/send_private_msg", params=params)

这个文件负责发送私聊信息

四、 智能群聊

我们这里开发一个智能水群的功能,其可以自动的根据群消息回复,同时增加了进群欢迎的功能!

  • 实现群聊艾特回复功能
  • 实现戳一戳回复功能
  • 实现新入群成员欢迎功能

在我们的main.py中,添加接口

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
__author__ = "A.L.Kun"
__file__ = "main.py"
__time__ = "2022/9/9 22:03"

from flask import Flask, request
from flask_restful import Resource, Api
import private_script, group_script
import asyncio
app = Flask(__name__)

api = Api(app)
class AcceptMes(Resource):

    def post(self):
        # 这里对消息进行分发,暂时先设置一个简单的分发
        _ = request.json
        if _.get("message_type") == "private":  # 说明有好友发送信息过来
            uid = _["sender"]["user_id"]  # 获取发信息的好友qq号
            message = _["raw_message"]  # 获取发送过来的消息
            asyncio.run(private_script.handle_private(uid, message))
        elif _.get("message_type") == "group" and "[CQ:at,qq=2786631176]" in _["raw_message"]:  # 制作群聊消息
            message = _["raw_message"].replace("[CQ:at,qq=2786631176]", "")  # 获取发送过来的消息
            gid = _["group_id"]  # 获取发送消息的群号
            asyncio.run(group_script.handle_group(gid, message))、
        elif _.get("notice_type") == "group_increase":  # 有新成员加入
            uid = _["user_id"]  # 获取加入者的qq
            gid = _["group_id"]  # 获取群号
            asyncio.run(group_script.group_increase(uid, gid))  # 发送欢迎语
        elif _.get("sub_type") == "poke":  # 如果事件类型为戳一戳
            uid = _["user_id"]
            tid = _["target_id"]
            if str(tid) != "3500515050" and str(tid) != "2786631176":  # 判断是否戳的是自己的账号
                return
            try:
                gid = _["group_id"]
            except KeyError as e:
                gid = None
            asyncio.run(group_script.click_event(uid, gid))  # 传入群号和qq号
api.add_resource(AcceptMes, "/", endpoint="index")
if __name__ == '__main__':
    app.run("0.0.0.0", 5701, debug=True)  # 注意,这里的端口要和配置文件中的保持一致

创建一个文件group_script.py,用于处理群聊消息

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
__author__ = "A.L.Kun"
__file__ = "group_script.py"
__time__ = "2022/9/10 11:49"
import httpx
import private_script
import config
from random import choice
async def handle_group(gid, message):  # 处理群聊信息
    if str(gid) in config.allow_group_id:  # 简单的判断,只是判断其是否为空
        if message.strip() == "":
            await send(gid, "艾特我干啥?又不发消息,一巴掌呼死你![CQ:face,id=86][CQ:face,id=12]")
        else:
            _ = await private_script.get_resp(message)
            ret = _.get("content", "获取回复失败")
            await send(gid, ret)
async def group_increase(uid, gid):  # 处理有新成员加入的情况
    if str(gid) in config.allow_group_id:
        msg = config.welcome_group.get(str(gid), config.welcome_group["default"]) % uid  # welcome_group的键是qq群号,值是欢迎语
        await send(gid, msg)  # 发送信息


async def click_event(uid, gid):
    info = choice(config.click_info)  # 获取戳一戳的信息
    try:
        info = info % uid
    except TypeError:
        if gid:  # 说明其为群戳戳
            info = f"[CQ:at,qq={uid}]" + info
    if gid:
        await send(gid, info)
    else:
        await private_script.send(uid, info)
async def send(gid, message):
    """
    用于发送消息的函数
    :param gid: 群号
    :param message: 发送的消息
    :return: None
    """
    async with httpx.AsyncClient(base_url="http://127.0.0.1:5700") as client:
        # 如果发送的为私聊消息
        params = {
            "group_id": gid,
            "message": message.replace("{br}", "\n").replace("菲菲", "坤坤"),
        }
        await client.get("/send_group_msg", params=params)

设置配置文件config.py

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
__author__ = "A.L.Kun"
__file__ = "config.py"
__time__ = "2022/9/10 11:57"
allow_group_id = [
]

welcome_group = {  # 新成员进入回复信息
    "default": f"[CQ:at,qq=%d] 欢迎加入本群,来了就别想走哦![CQ:face,id={43}]",
}
click_info = [  # 戳一戳的回复信息
    "?有事吗?没事我走了![CQ:face,id=125],goodbye",
    "没问题么?〒没问题的话,我就溜了哦!",
    "睡觉去,困死了!",
    "戳我干啥!本人在叙利亚做兼职呢?没事别烦我!",
    "你好呀!我在躺平呢!请问有啥事呀?",
    "hello",
    "[CQ:poke,qq=%d]",
]

最后,我们开发的智能聊天就可以使用了!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们