前言
承接上文,我们来继续开发QQ机器人
程序开发
消息事件
接口
上面我们实现了自我学习的机器人系统,这样就确保了日常对话已经不是问题。
下面我们来实现一些特殊功能,例如一些推送效果等
这里我们需要用到一些互联网上的API,我个人用的是这个网页的
在special_function目录中新建了一个help_msg.py文件,来返回帮助信息
def private_chat_help():
content="[CQ:face,id=63][CQ:face,id=63][CQ:face,id=63]%20专有命令:%0a"
content+="1-调教:%27#学习%20[目标语]%20[自动回复语]%27%20%0a"
content+="2-翻译:%27翻译%20[待翻译内容]%27%20%0a"
content+="3-手机号码信息:%27号码信息%20[手机号码]%27%20%0a"
content+="4-壁纸:%27壁纸%7C高清壁纸%27%20%0a"
content+="5-头像推荐:%27头像%20[女%7C男%7C动漫]%27%20%0a"
return content
特殊字符要url转码
然后还是这个目录,新建一个web_api_use.py,承载对网上api的调用,例如我们这里先做翻译功能:
#可用接口文档:https://api.66mz8.com/docs-translation.html
#可用接口文档:https://alapi.cn/doc/show/32.html
import requests
import json
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'
}
#翻译接口
def translate_api(content):
# 带参数的get请求
resp=requests.get(url='https://api.66mz8.com/api/translation.php', params={'info': content},headers=headers)
resp_dict=json.loads(resp.text)
if resp_dict["code"]==200:
return resp_dict["fanyi"]
else:
return "我不会!"
这里我又新建了一个handle目录下的文件,叫command_handle.py,来处理特殊的指令,这样我们就将message_handle.py进行一下重构
#message_handle.py
#对于 消息事件 的处理
from socket_operate.client import send_msg
from handle.command_handle import command_study_handle,command_help_handle,command_translate_handle
from handle.msg_handle import get_raw_message,get_number,get_user_id,get_message_type
from special_function.logging_tool import logging_put
from special_function.study import get_reply,random
#---------------------------------------------------------------
#私聊信息的普通检测
def private_msg_general_detection(message):
reply=''
#得到特殊指令
command=get_raw_message(message).split(' ')[0]
if command=="#学习":
reply=command_study_handle(message)
elif command=="帮助":
reply=command_help_handle()
elif command=="翻译":
reply=command_translate_handle(message)
# elif command==""
return reply
#私聊信息的数据库检测(通过数据库来找对应的回复)
def private_msg_db_detection(message):
reply=''
reply=get_reply(get_raw_message(message))
return reply
#私聊信息的错误处理
def private_msg_error():
rand = random.randint(1,4)
msg="超出我的知识上限"
if rand == 1:
msg = "消息太复杂"
elif rand == 2:
msg = "江湖险恶,我不会答"
elif rand == 3:
msg = "啊?"
elif rand == 4:
msg = "听不懂~"
return msg
#私聊消息处理
def private_msg_handle(message):
msg_dict={
"msg_type":"private",
"number":get_number(message),
"msg":"我听不懂"
}
#检测
general_detect=private_msg_general_detection(message)
db_detect=private_msg_db_detection(message)
no_reply=False
if general_detect!='':
msg_dict["msg"]=general_detect
elif db_detect!='':
msg_dict["msg"]=db_detect
else:
no_reply=True
logging_put("私聊中用户请求没有对应的信息:"+str(get_user_id(message))+"-"+get_raw_message(message))
msg_dict["msg"]=private_msg_error()
#若没有对应消息,则有四分之一的概率不会回复
if no_reply:
if random.randint(1,4)!=1:
send_msg(msg_dict)
else:
send_msg(msg_dict)
return
#---------------------------------------------------------------
#群聊信息的普通检测
def group_msg_general_detection(message):
reply=''
return reply
#群聊信息的数据库检测(通过数据库来找对应的回复)
def group_msg_db_detection(message):
reply=''
reply=get_reply(get_raw_message(message))
return reply
#群聊信息的错误处理
def group_msg_error():
rand = random.randint(1,5)
msg="超出我的知识上限"
if rand == 1:
msg = "消息太复杂"
elif rand == 5:
msg = "群里有人知道怎么回答ta吗?"
elif rand == 2:
msg = "江湖险恶,我不会答"
elif rand == 3:
msg = "啊?"
elif rand == 4:
msg = "听不懂~"
return msg
#群聊消息处理
def group_msg_handle(message):
msg_dict={
"msg_type":"group",
"number":get_number(message),
"msg":"我听不懂"
}
#检测
general_detect=group_msg_general_detection(message)
db_detect=group_msg_db_detection(message)
no_reply=False
if general_detect!='':
msg_dict["msg"]=general_detect
elif db_detect!='':
msg_dict["msg"]=db_detect
else:
no_reply=True
logging_put("群聊中用户请求没有对应的信息:"+str(get_user_id(message))+"-"+get_raw_message(message))
msg_dict["msg"]=group_msg_error()
#若没有对应消息,则有四分之一的概率不会回复
if no_reply:
if random.randint(1,4)!=1:
send_msg(msg_dict)
else:
send_msg(msg_dict)
return
#---------------------------------------------------------------
def message_handle(message):
if get_message_type(message)=='private':
private_msg_handle(message)
elif get_message_type(message)=='group':
group_msg_handle(message)
return 0
#command_handle.py
from handle.msg_handle import get_message_type,get_number,get_raw_message,get_user_id
from special_function.study import study_info
from special_function.logging_tool import logging_put
from special_function.help_msg import *
from special_function.web_api_use import translate_api
def command_study_handle(message):
if len(get_raw_message(message).split(' '))==3:
new_quest=get_raw_message(message).split(' ')[1]
new_reply=get_raw_message(message).split(' ')[2]
if study_info(new_quest,new_reply):
logging_put("用户"+str(get_user_id(message))+"教我新内容:"+new_quest+"--"+new_reply)
return '学习成功,收获新知识'
else:
return '学习失败'
else:
return '命令格式有误,发送“帮助”获得更多信息'
def command_help_handle():
#显示帮助信息
return private_chat_help()
def command_translate_handle(message):
if len(get_raw_message(message).split(' '))>=2:
content=""
for i in range(len(get_raw_message(message).split(' '))):
if i==0:
continue
content+=" "+get_raw_message(message).split(' ')[i]
return translate_api(content)
else:
return '命令格式有误,发送“帮助”获得更多信息'
OK,这样一个翻译的特殊指令就做好了。
特殊指令访问接口的内容大致都是这个思路,这里就不一一列举了。
部署
数据库
下面我们就来将完成的程序部署在服务器上,
首先是数据库问题,我们在服务器上运行起来数据库
[root@VM-0-3-centos ~]# systemctl start mysqld
[root@VM-0-3-centos ~]# systemctl status mysqld
● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: active (running) since Sat 2021-02-20 19:56:58 CST; 21s ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 2792 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 2815 (mysqld)
Status: "Server is operational"
CGroup: /system.slice/mysqld.service
└─2815 /usr/sbin/mysqld
Feb 20 19:56:56 VM-0-3-centos systemd[1]: Starting MySQL Server...
Feb 20 19:56:58 VM-0-3-centos systemd[1]: Started MySQL Server.
进入数据库,执行SQL语句
CREATE DATABASE qqrobot;
USE qqrobot;
CREATE TABLE words(
id INT PRIMARY KEY AUTO_INCREMENT,
quest VARCHAR(90),
reply VARCHAR(90)
);
创建对应的库和表。
修改你的python项目的配置,确保运行之后可以连接服务器上的mysql,mysql的端口也要注意能不能连同。
Python环境
配置python环境
将我们的程序上传到服务器上。
这里我传了一个压缩包,还需要配置Linux解压RAR,配置方法:
下载 rar 安装包
官方下载地址:http://www.rarsoft.com/download.htm
wget http://www.rarsoft.com/rar/rarlinux-x64-5.4.0.tar.gz
安装
- 解压缩安装包
tar -xvf rarlinux-x64-5.4.0.tar.gz
- 执行安装
cd rar sudo make
- 现在可以执行
unrar
对 .rar 文件进行解压缩了。
unrar e filename.rar
转载于:https://my.oschina.net/iblackangel/blog/882246
下面,我们来给CentOS7配置python环境:
在/usr目录下创建文件夹Downloads
mkdir /usr/Downloads
切换到Downloads目录
cd /usr/Downloads
下载Python wget https://www.python.org/ftp/python/3.9.2/Python-3.9.2.tgz 解压安装包 tar -xvf Python-3.9.2.tgz 将解压后文件夹迁移至/usr/local mv Python-3.9.2 /usr/local
进入Python目录 cd /usr/local/Python-3.9.2/ 执行配置文件 ./configure 编译安装 make make install 在/usr/bin路径下生成python3的软链接 ln -s /usr/local/Python-3.9.2/python /usr/bin/python3
下面我们执行python,应该就会看到命令行界面了。
顺手我们安装一下项目需要的pymysql、requests(使用pip3)
pip3 install requests
启动项目
确保服务器配置都OK,例如项目里写的数据库地址、账户密码,主机mysql是否开启……
然后我们启动main.py即可(注意一定是python3,否则会使用python2的解释器,就会找不到pymysql)
nohub:不间断地执行
&:挂在后台
nohub python3 main.py &
再启动我们的go-cqhttp
nohup ~/QQBOT/go-cqhttp &
jobs:查看后台任务
fg %job编号:将某编号任务发到前台
我踩过的大坑
- go-cq的配置文件中POST反向HTTP的地址一定一定要和python程序监听的写成写成一样,我都写成“127.0.0.1”好像还不行,最后都换成局域网地址才解决问题
- 字符串的拼接,特别是logging方法传参时候,一定要将数字转换成str
- 发送消息时候的特殊字符,空格、回车这样的,一定要url编码
玩法可以多样,我的文章就写到这里,你的脑洞远不止这里,配合好参考文档,在我这个框架上继续深挖,打造属于自己的个性机器人!
文章只处理了消息事件,其实另外两个事件也是同样的处理法子,分发、调用
这个文章的进度这里我放到github上了,对你有帮助可以给个星嘛
商业转载 请联系作者获得授权,非商业转载 请标明出处,谢谢