python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python QQ聊天机器人

基于Python开发简易版QQ聊天机器人

作者:超级小识

在当今数字化时代,聊天机器人已经成为日常生活和商业活动中不可或缺的一部分,本文将使用python开发一个简易版QQ聊天机器人,希望对大家有所帮助

数字化时代的聊天机器人应用

在当今数字化时代,聊天机器人已经成为日常生活和商业活动中不可或缺的一部分。根据市场研究数据显示,全球聊天机器人市场规模预计将在2026年达到102亿美元,年复合增长率达到34.75%。这些智能助手正广泛应用于以下场景:

为什么要开发QQ聊天机器人

QQ作为中国最大的即时通讯平台之一,拥有超过8亿月活跃用户。基于QQ开发聊天机器人具有以下优势:

本教程特点

本教程将详细介绍如何使用Python开发一个简易的QQ聊天机器人,特别适合编程初学者:

即使你没有任何编程经验,只要按照本教程的步骤操作,也能在1-2小时内完成你的第一个QQ聊天机器人。

开发环境准备

在开始之前,需要确保你的电脑上安装了Python环境。Python是一种广泛使用的编程语言,非常适合初学者。可以从Python官网下载最新版本并安装。

安装完成后,打开命令行工具(Windows上是CMD或PowerShell,Mac/Linux上是Terminal),输入以下命令检查是否安装成功:

python --version

如果显示Python版本号,说明安装成功。

接下来,安装必要的库。QQ聊天机器人依赖于一些第三方库,例如qqbotnonebot。这里以nonebot为例,它是一个基于Python的异步QQ机器人框架。在命令行中输入:

pip install nonebot2

创建项目结构

创建一个新的文件夹作为项目根目录,例如qq_bot。在该文件夹中创建以下文件:

项目结构如下:

qq_bot/
├── bot.py
├── config.py
└── plugins/

配置文件设置

config.py中,添加以下内容:

from nonebot.default_config import *

HOST = '127.0.0.1'
PORT = 8080
SUPERUSERS = {123456789}  # 替换为你的QQ号
COMMAND_START = {'/', '!', '/', '!'}

这里HOSTPORT是机器人运行的地址和端口,SUPERUSERS是管理员QQ号,COMMAND_START是触发机器人的命令前缀。

编写主程序

打开bot.py,添加以下代码:

from nonebot import get_driver
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.adapters.cqhttp import Bot, Event

driver = get_driver()

@on_command("hello", rule=to_me(), priority=5)
async def handle_hello(bot: Bot, event: Event):
    await bot.send(event, message="你好,我是QQ聊天机器人!")

if __name__ == "__main__":
    from nonebot import init
    init()
    from nonebot.adapters.cqhttp import Adapter
    driver.register_adapter(Adapter)
    nonebot.run()

这段代码定义了一个简单的命令hello,当用户发送/hello时,机器人会回复“你好,我是QQ聊天机器人!”。

运行机器人

在命令行中,切换到项目目录,运行以下命令启动机器人:

python bot.py

如果一切正常,机器人会启动并等待消息。你可以登录QQ,添加机器人为好友,发送/hello测试功能。

扩展功能

为了让机器人更实用,可以添加更多功能。例如,添加一个天气查询插件。在plugins文件夹中创建weather.py,添加以下代码:

from nonebot import on_command
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.typing import T_State

weather = on_command("weather", priority=5)

@weather.handle()
async def handle_weather(bot: Bot, event: Event, state: T_State):
    city = event.get_plaintext().strip()
    if not city:
        await weather.finish("请发送 /weather 城市名")
    else:
        await weather.finish(f"{city}的天气是晴天")

然后在bot.py中导入插件:

from plugins.weather import *

重启机器人后,发送/weather 北京,机器人会回复“北京的天气是晴天”。

处理异常

在实际使用中,机器人可能会遇到各种问题,例如网络错误或用户输入无效。为了提升用户体验,可以添加异常处理。修改weather.py

@weather.handle()
async def handle_weather(bot: Bot, event: Event, state: T_State):
    try:
        city = event.get_plaintext().strip()
        if not city:
            await weather.finish("请发送 /weather 城市名")
        else:
            await weather.finish(f"{city}的天气是晴天")
    except Exception as e:
        await weather.finish("出错了,请稍后再试")

部署到服务器

为了让机器人24小时运行,可以将其部署到云服务器。常见的云服务提供商有阿里云、腾讯云等。购买服务器后,按照以下步骤操作:

nohup python bot.py &

完整源码

以下是完整的bot.pyconfig.py源码:

bot.py

from nonebot import get_driver
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.adapters.cqhttp import Bot, Event

driver = get_driver()

@on_command("hello", rule=to_me(), priority=5)
async def handle_hello(bot: Bot, event: Event):
    await bot.send(event, message="你好,我是QQ聊天机器人!")

if __name__ == "__main__":
    from nonebot import init
    init()
    from nonebot.adapters.cqhttp import Adapter
    driver.register_adapter(Adapter)
    nonebot.run()

config.py

from nonebot.default_config import *

HOST = '127.0.0.1'
PORT = 8080
SUPERUSERS = {123456789}
COMMAND_START = {'/', '!', '/', '!'}

plugins/weather.py

from nonebot import on_command
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.typing import T_State

weather = on_command("weather", priority=5)

@weather.handle()
async def handle_weather(bot: Bot, event: Event, state: T_State):
    try:
        city = event.get_plaintext().strip()
        if not city:
            await weather.finish("请发送 /weather 城市名")
        else:
            await weather.finish(f"{city}的天气是晴天")
    except Exception as e:
        await weather.finish("出错了,请稍后再试")

到此这篇关于基于Python开发简易版QQ聊天机器人的文章就介绍到这了,更多相关Python QQ聊天机器人内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文