脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - go-cqhttp智能聊天功能的实现

go-cqhttp智能聊天功能的实现

2022-11-17 12:19A-L-Kun Golang

这篇文章主要介绍了go-cqhttp智能聊天功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

智能聊天

一、 概述

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

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

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

二、 使用方法

go-cqhttp智能聊天功能的实现

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

go-cqhttp智能聊天功能的实现

三、 接入程序

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

private_script.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
#!/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中,添加接口

?
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
#!/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,用于处理群聊消息

?
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
#!/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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/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]",
]

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

到此这篇关于go-cqhttp智能聊天功能的文章就介绍到这了,更多相关go-cqhttp智能聊天内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_62789540/article/details/126796017

延伸 · 阅读

精彩推荐
  • GolangGo语言实现顺序存储的线性表实例

    Go语言实现顺序存储的线性表实例

    这篇文章主要介绍了Go语言实现顺序存储的线性表的方法,实例分析了Go语言实现线性表的定义、插入、删除元素等的使用技巧,具有一定参考借鉴价值,需要的...

    OSC首席键客2922020-04-22
  • GolangGo 语言 Errgroup 库的使用方式和实现原理

    Go 语言 Errgroup 库的使用方式和实现原理

    本文我们介绍 Go 方法提供的 errgroup 库,该库最近新增了控制并发数量的功能。我们先介绍了三种使用方式,然后通过阅读源码,分析其实现原理。...

    Golang语言开发栈3302022-10-24
  • Golang解决Golang json序列化字符串时多了\的情况

    解决Golang json序列化字符串时多了\的情况

    这篇文章主要介绍了解决Golang json序列化字符串时多了\的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    Go哥10442021-03-22
  • GolangGolang中interface{}转为数组的操作

    Golang中interface{}转为数组的操作

    这篇文章主要介绍了Golang中interface{}转为数组的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    月落乌啼silence11492021-06-11
  • GolangGo 分布式令牌桶限流 + 兜底保障

    Go 分布式令牌桶限流 + 兜底保障

    上篇文章提到固定时间窗口限流无法处理突然请求洪峰情况,本文讲述的令牌桶线路算法则可以比较好的处理此场景。...

    微服务实践10212022-01-12
  • Golang使用 go 实现多线程下载器的方法

    使用 go 实现多线程下载器的方法

    本篇文章带领大家学习使用go实现一个简单的多线程下载器,给她家详细介绍了多线程下载原理及实例代码,感兴趣的朋友跟随小编一起看看吧...

    qxcheng10472021-11-18
  • Golang详解go-admin在线开发平台学习(安装、配置、启动)

    详解go-admin在线开发平台学习(安装、配置、启动)

    这篇文章主要介绍了go-admin在线开发平台学习(安装、配置、启动),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友...

    happlyfox5692021-03-28
  • GolangGO语言 复合类型专题

    GO语言 复合类型专题

    这篇文章主要介绍了GO语言 复合类型的的相关资料,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下...

    柠檬橙10242702020-07-21