QQ机器人搭建

使用QQ官方机器人Python SDK和三方框架搭建QQ群聊机器人

在这里插入图片描述

前言

本文基于 QQ官方Python SDK三方框架aka🐱(进群了解) 搭建QQ群聊机器人,可以实现全局监听群聊。

介绍
QQ官方机器人Python SDK是QQ提供的一个用于搭建QQ机器人的开发工具包。通过使用该SDK,我们可以编写Python代码来实现QQ机器人的各种功能,如在群聊内接收消息、发送消息等。虽然官方机器人已经满足了基本需求,但是给到开发者的权限很少,无法全局监听群聊消息,本文提供将官方和三方机器人融合的python库:QQbot_Python,实现全局监听的QQ机器人体系。

准备工作
在开始之前,确保你已经具备以下准备工作:

  • 已安装Python环境(建议使用Python 3.x版本)
  • 拥有一个QQ账号(用于创建三方机器人)
  • 获得了官方QQ机器人的APPID和APPSERCET(用于创建官方机器人)
  • 安装三方框架aka🐱(用于创建三方机器人)

安装相关SDK
使用pip命令来安装QQ官方机器人Python SDK和三方QQ机器人Python SDK:

pip install qq-botpy QQbot_Python -i https://pypi.org/simple

获取官方QQ机器人的APPID和APPSERCET
在使用SDK之前,我们需要先创建一个QQ官方机器人账号,并获取其账号的APPID和APPSERCET。具体步骤如下:

  1. 打开 QQ官方机器人管理平台
  2. 创建一个新的机器人账号,按照 教程 完成相关设置
  3. 在机器人管理平台中登录刚刚创建的机器人账号,获取其账号的APPID和APPSERCET

配置官方机器人IP白名单
在创建好了QQ机器人账号之后,我们打开 QQ官方机器人管理平台 ,在开发栏中找到开发设置,点击后在界面可以找到IP白名单,在这里你需要配置你的公网IP。如果你是本地开发,你可以使用curl ipconfig.io或者 公网IP查询网站 来获取你的公网IP(⚠️本地开发时公网IP随时会变化);如果你已经要部署在服务器上面了,一般的云服务器都配置了公网IP。最后,将你获取的公网IP填入QQ官方机器人管理平台并保存即可。

配置三方机器人服务器
你需要安装 三方框架aka🐱(进群下载) ,并且启动正向ws和http监听,ws的端口需要是3001,http的端口需要是3000。

编写机器人代码

接下来,我们开始编写机器人代码。

创建配置文件
在你自己创建的项目的目录下添加配置文件:config.yaml

appid: "" # 填入你在前面步骤获取的APPID
secret: "" # 填入你在前面步骤获取的APPSERCET
机器人监听群聊进行文字回复

首先,分为两种情况:1.你没有配置三方服务器,你将无法享受三方机器人服务。2.你配置了三方机器人并且满足前面提到的要求。


情况一:未配置三方机器人
我们导入botpy库,创建机器人实例,进行群聊事件的监听,示例代码如下:

# -*- coding: utf-8 -*-
import asyncio
import os

import botpy
from botpy import logging
from botpy.ext.cog_yaml import read
from botpy.message import GroupMessage, Message

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

_log = logging.get_logger()


class MyClient(botpy.Client):
    async def on_ready(self):
        _log.info(f"robot 「{self.robot.name}」 on_ready!")

    async def on_group_at_message_create(self, message: GroupMessage):
        messageResult = await message._api.post_group_message(
            group_openid=message.group_openid,
              msg_type=0, 
              msg_id=message.id,
              content=f"收到了消息:{message.content}")
        _log.info(messageResult)


if __name__ == "__main__":
    # 通过预设置的类型,设置需要监听的事件通道
    # intents = botpy.Intents.none()
    # intents.public_messages=True

    # 通过kwargs,设置需要监听的事件通道
    intents = botpy.Intents(public_messages=True)
    client = MyClient(intents=intents)
    client.run(appid=test_config["appid"], secret=test_config["secret"])

运行结果如下:
在这里插入图片描述
关于官方机器人更多的示例代码请参考: 官方完整示例


情况二:配置了三方机器人
我们导入QQbot_Python库,创建机器人实例,进行群聊事件的监听,示例代码如下:

# -*- coding: utf-8 -*-
import os
import QQbot_Python
from QQbot_Python import logging
from QQbot_Python.ext.cog_yaml import read
from QQbot_Python.message import GroupMessage

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

_log = logging.get_logger()


class MyClient(QQbot_Python.Client):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.show_heartbeat_info = False
        self.show_system_message = True

    async def on_group_at_message_create(self, message: GroupMessage):
        group_id = message.third_msg.get("group_id")
        user_id = message.third_msg.get("user_id")
        message_id = message.third_msg.get("message_id")
        _log.info(f"收到群{group_id}的@消息,用户{user_id},消息{message_id}")
        await message.send_text(group_id=group_id,user_id=user_id,text="你好,我是机器人")
            

if __name__ == "__main__":
    intents = QQbot_Python.Intents(public_messages=True)
    client = MyClient(intents=intents)
    client.run(appid=test_config["appid"], secret=test_config["secret"])

运行结果如下:
在这里插入图片描述

机器人监听群聊进行图片回复

目前官方机器人并不支持群聊回复本地图片,具体以官方文档更新为准。但是使用本文的思路,可以实现回复图片功能,需要配置三方。示例代码如下:

# -*- coding: utf-8 -*-
import os
import QQbot_Python
from QQbot_Python import logging
from QQbot_Python.ext.cog_yaml import read
from QQbot_Python.message import GroupMessage

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

_log = logging.get_logger()


class MyClient(QQbot_Python.Client):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.show_heartbeat_info = False
        self.show_system_message = True

    async def on_group_at_message_create(self, message: GroupMessage):
        group_id = message.third_msg.get("group_id")
        user_id = message.third_msg.get("user_id")
        message_id = message.third_msg.get("message_id")
        _log.info(f"收到群{group_id}的@消息,用户{user_id},消息{message_id}")
        if "/发送图片" in message.content:
            await message.reply(content="发送成功!")
            await message.send_image(group_id=group_id,summary="这是图片描述",file_image="1.png")
            

if __name__ == "__main__":
    intents = QQbot_Python.Intents(public_messages=True)
    client = MyClient(intents=intents)
    client.run(appid=test_config["appid"], secret=test_config["secret"])

具体运行如下:
在这里插入图片描述

机器人监听群聊进行文件发送

目前官方机器人并不支持群聊回复本地文件,具体以官方文档更新为准。但是使用本文的思路,可以实现回复图片功能。需要配置三方。示例代码如下:

# -*- coding: utf-8 -*-
import os
import QQbot_Python
from QQbot_Python import logging
from QQbot_Python.ext.cog_yaml import read
from QQbot_Python.message import GroupMessage

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

_log = logging.get_logger()


class MyClient(QQbot_Python.Client):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.show_heartbeat_info = False
        self.show_system_message = True

    async def on_group_at_message_create(self, message: GroupMessage):
        group_id = message.third_msg.get("group_id")
        user_id = message.third_msg.get("user_id")
        message_id = message.third_msg.get("message_id")
        _log.info(f"收到群{group_id}的@消息,用户{user_id},消息{message_id}")
        if "/发送文件" in message.content:
            await message.reply(content="发送成功!")
            await message.send_file(group_id=group_id,file_name="名称可自定义",file_path="botpy.log")
            

if __name__ == "__main__":
    intents = QQbot_Python.Intents(public_messages=True)
    client = MyClient(intents=intents)
    client.run(appid=test_config["appid"], secret=test_config["secret"])

运行结果如下:
在这里插入图片描述

机器人监听群聊进行视频发送

目前官方机器人并不支持群聊回复本地视频,具体以官方文档更新为准。但是使用本文的思路,可以实现回复图片功能。需要配置三方。示例代码如下:

# -*- coding: utf-8 -*-
import os
import QQbot_Python
from QQbot_Python import logging
from QQbot_Python.ext.cog_yaml import read
from QQbot_Python.message import GroupMessage

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

_log = logging.get_logger()


class MyClient(QQbot_Python.Client):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.show_heartbeat_info = False
        self.show_system_message = True

    async def on_group_at_message_create(self, message: GroupMessage):
        group_id = message.third_msg.get("group_id")
        user_id = message.third_msg.get("user_id")
        message_id = message.third_msg.get("message_id")
        _log.info(f"收到群{group_id}的@消息,用户{user_id},消息{message_id}")
        if "/发送视频" in message.content:
            await message.reply(content="发送成功!")
            await message.send_voice(group_id=group_id, file_path="test.mp4",file_name="可以自定义名称")
            

if __name__ == "__main__":
    intents = QQbot_Python.Intents(public_messages=True)
    client = MyClient(intents=intents)
    client.run(appid=test_config["appid"], secret=test_config["secret"])

运行结果如下:
在这里插入图片描述

机器人监听群聊进行语音发送

目前官方机器人并不支持群聊回复语音,具体以官方文档更新为准。但是使用本文的思路,可以实现回复图片功能。发送的语音文件格式只支持silk格式。需要配置三方。示例代码如下:

# -*- coding: utf-8 -*-
import os
import QQbot_Python
from QQbot_Python import logging
from QQbot_Python.ext.cog_yaml import read
from QQbot_Python.message import GroupMessage

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

_log = logging.get_logger()


class MyClient(QQbot_Python.Client):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.show_heartbeat_info = False
        self.show_system_message = True

    async def on_group_at_message_create(self, message: GroupMessage):
        group_id = message.third_msg.get("group_id")
        user_id = message.third_msg.get("user_id")
        message_id = message.third_msg.get("message_id")
        _log.info(f"收到群{group_id}的@消息,用户{user_id},消息{message_id}")
        if "/发送语音" in message.content:
            await message.reply(content="发送成功!")
            await message.send_record(group_id=group_id,file_path="my.ntsilk")
            

if __name__ == "__main__":
    intents = QQbot_Python.Intents(public_messages=True)
    client = MyClient(intents=intents)
    client.run(appid=test_config["appid"], secret=test_config["secret"])

运行结果如下:
在这里插入图片描述


除此之外,还有发送引用消息发送私聊消息功能,在这里就不赘述了。

致谢和更新

本项目采用的都是开源技术

致谢QQ官方开发者 | 不方便透露姓名的三方

上次更新时间: 9/28/2024, PM

在这里插入图片描述
如果你想继续进行基于本文进行QQ机器人自定义搭建,请转至此篇文章阅读:
➡️ [于 2024/9/25 第2次更新] QQ 腾讯官方机器人搭建(更新中)
👻 交流学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

吃点李子

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

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

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

打赏作者

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

抵扣说明:

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

余额充值