ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

go-cqhttp智能聊天功能

2022-09-10 14:00:16  阅读:252  来源: 互联网

标签:__ group get script cqhttp gid 聊天 go message


目录

智能聊天

一、 概述

我们将我们的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"][len("[CQ:at,qq=2786631176]") + 1:]  # 获取发送过来的消息
            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))  # 发送欢迎语


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


async def handle_group(gid, message):  # 处理私聊信息
    if str(gid) in config.allow_group_id:  # 简单的判断,只是判断其是否为空
        _ = 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群号,值是欢迎语
        """
        welcome_group = {
            "default": f"[CQ:at,qq=%d] 欢迎加入本群,来了就别想走哦![CQ:face,id={43}]",
		}
        """
        await send(gid, msg)  # 发送信息


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"),
            "auto_escape": True
        }
        await client.get("/send_group_msg", params=params)

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

标签:__,group,get,script,cqhttp,gid,聊天,go,message
来源: https://www.cnblogs.com/liuzhongkun/p/16676381.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有