NoneBot 是一個基於 酷Q 的 Python 異步 QQ 機器人框架,它會對 QQ 機器人收到的消息進行解析和處理,並以插件化的形式,分發給消息所對應的命令處理器和自然語言處理器,來完成具體的功能。
一 、軟件安裝
- 安裝 NoneBot 庫,NoneBot github地址為:https://github.com/richardchien/nonebot
1 pip install nonebot
-
安裝酷Q 軟件
酷Q 軟件可以直接到官網下載,https://cqp.cc/t/23253,本教程使用的是 酷Q Air 小i版。
- 安裝 HTTP API 插件
HTTP API 插件下載地址 https://github.com/richardchien/coolq-http-api/releases
首先將下載好的 HTTP API 插件放到 app 目錄下,然后雙擊 CQA.exe 文件,輸入機器人對應的 QQ 號和密碼,登陸之后,在應用管理中,啟動 HTTP API 插件。
二、配置 HTTP API 插件
進入酷Q 的 data/app/io.github.richardchien.coolqhttpapi/config/ 目錄,有一個.json 的文件,user-id 為剛剛登陸的 QQ 號。修改這個文件的如下配置
三、構建應用程序
nonebot 的官方文檔地址:https://none.rclab.tk/guide/getting-started.html,
下面我們先跑一下官網上的基礎例子:
import nonebot if __name__ == "__main__": nonebot.init() nonebot.load_builtin_plugins() nonebot.run(host='127.0.0.1', port=8080)
運行該程序(在普通的IDLE下即可,某些集成環境反而可能報錯),我們可以在控制台看到如下日志:
可以看到現在程序運行在了本地的 8080 端口,而且本地的 4081和 4080 端口也連接到了本服務,就是我們在 HTTP API 插件的配置文件中做的配置。
"ws_reverse_api_url": "ws://127.0.0.1:8080/ws/api/", "ws_reverse_event_url": "ws://127.0.0.1:8080/ws/event/",
# 增強機器人功能之配置文件
增加 config.py 文件,輸入內容如下:
from nonebot.default_config import * SUPERUSERS = {QQ號}#1 COMMAND_START = {'', '/', '!', '/', '!'} HOST = '0.0.0.0' PORT = 8080
SUPERUSERS:是配置一個超級 QQ 用戶,我們可以為這個超級用戶配置一些特殊的操作;
COMMAND_START:是配置命令起始字符,我們增加了空字符串,所以不需要任何起始字符也能調用命令;
另外就是配置了 host 和 端口 port。
編寫自己的插件
創建一個 plugins 文件夾,在里面創建 daily.py 文件,編寫如下代碼:
1 from nonebot import on_command, CommandSession 2 2from utils import getdata 3 4 5 @on_command('daily', aliases=('每日一句',)) 6 async def daily(session: CommandSession): 7 daily_send = await get_daily() 8 await session.send(daily_send[0]) 9 await session.send(daily_send[1]) 10 11 12 async def get_daily(): 13 daily_sentence = getdata.get_content() 14 return daily_sentence
完整代碼
bot.py
1 import nonebot 2 import config 3 from os import path 4 if __name__ == '__main__': 5 nonebot.init(config) 6 nonebot.load_plugins(path.join(path.dirname(__file__), 'plugins'), 'plugins') 7 8 nonebot.run() 9 #nonebot.run(host='127.0.0.1', port=8080)
config.py
1 #!/usr/bin/env python 2 # encoding: utf-8 3 from nonebot.default_config import * 4 5 SUPERUSERS = {qq號}#qq號
6 COMMAND_START = {'', '/', '!', '/', '!'}
7 HOST = '0.0.0.0'
8 PORT = 8080
/plugins/daily.py
1 #!/usr/bin/env python 2 # encoding: utf-8 3 4 from nonebot import on_command, CommandSession 5 6 import requests 7 @on_command('daily', aliases=('每日一句',)) 8 async def daily(session: CommandSession): 9 daily_send = await get_daily() 10 await session.send(daily_send[0]) 11 await session.send(daily_send[1]) 12 13 14 async def get_daily(): 15 daily_sentence = get_content() 16 return daily_sentence 17 18 def get_content(): 19 url = 'http://open.iciba.com/dsapi/' 20 res = requests.get(url) 21 content_e = res.json()['content'] 22 content_c = res.json()['note'] 23 return [content_c, content_e]