下面我会详细讲解使用Python的Tornado框架实现一个简单的WebQQ机器人的完整攻略。
1. 准备工作
首先,你需要申请QQ机器人账号、安装Python语言环境及Tornado框架。
2. 获取QQ机器人的cookie和ptwebqq
在Python代码中通过模拟浏览器登录QQ账号,然后从登录后的cookie和ptwebqq中获取QQ机器人的cookie和ptwebqq。获取cookie和ptwebqq的代码如下所示。
import requests
from requests.utils import cookiejar_from_dict
from urllib.parse import urlencode
# 模拟登录QQ账号并获取Cookie和ptwebqq
def login(qq, password):
url = 'https://xui.ptlogin2.qq.com/cgi-bin/xlogin'
params = {
'appid': 1003903,
's_url': 'https://im.qq.com',
'f_url': 'loginerroralert',
'low_login': 1,
'hln_css': 'https://ui.ptlogin2.qq.com/style/26/qq_login.css',
'hln_color': '000000',
'no_verifyimg': 1,
'mibao_css': 'https://ui.ptlogin2.qq.com/style/26/mb_save.css',
'aid': 1003903,
'u1': 'https://im.qq.com',
'u2': 'https://im.qq.com/cgi-bin/readtemplate?t=login',
'u3': 'https://web2.qq.com/loginproxy.html',
'u4': 'https://ui.ptlogin2.qq.com/cgi-bin/login',
'login_redirect': 1,
'pt_locale': '2052',
}
cookies = requests.get(url + '?' + urlencode(params)).cookies
params['pt_tea'] = 2
params['low_login_hour'] = 360
params['u'] = qq
params['p'] = password
params['pt_rsa'] = 1
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:86.0) Gecko/20100101 Firefox/86.0',
'Referer': 'https://xui.ptlogin2.qq.com/cgi-bin/xlogin?appid=1003903&s_url=https://im.qq.com&f_url=loginerroralert&pt_tea=2&low_login_hour=360&u1=https://im.qq.com&u2=https://im.qq.com/cgi-bin/readtemplate?t=login&u3=https://web2.qq.com/loginproxy.html&u4=https://ui.ptlogin2.qq.com/cgi-bin/login&login_redirect=1&pt_locale=2052',
}
response = requests.post(url, data=params, headers=headers, cookies=cookies, allow_redirects=False)
cookies.update(response.cookies)
ptwebqq = ''
for key, value in cookies.items():
if key == 'ptwebqq':
ptwebqq = value
break
return {'cookie': cookiejar_from_dict(requests.utils.dict_from_cookiejar(response.history[0].cookies)), 'ptwebqq': ptwebqq[1:-1]}
3. 连接WebQQ服务
连接WebQQ服务需要使用前面获取到的cookie和ptwebqq。连接WebQQ服务的代码如下所示。
import requests
import json
# 连接WebQQ服务
def connect(cookie, ptwebqq):
url = 'https://s.web2.qq.com/api/login/qrcode/qrcode'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:86.0) Gecko/20100101 Firefox/86.0',
'Referer': 'https://s.web2.qq.com/proxy.html?v=20210311001&callback=1&id=1',
'Origin': 'https://s.web2.qq.com',
'Host': 's.web2.qq.com',
}
cookies = requests.utils.dict_from_cookiejar(cookie)
cookies['ptwebqq'] = ptwebqq
response = requests.get(url, headers=headers, cookies=cookies)
result = json.loads(response.text)
if result['retcode'] != 0:
print('Error:', result['errmsg'])
else:
print('登录成功!')
4. 实现WebQQ机器人
实现WebQQ机器人需要使用Tornado框架。机器人的核心代码如下所示。
import requests
import json
from tornado.web import RequestHandler, Application
from tornado.ioloop import IOLoop
class WebQQBot(RequestHandler):
def get(self):
url = 'https://s.web2.qq.com/api/get_self_info2'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:86.0) Gecko/20100101 Firefox/86.0',
'Referer': 'https://s.web2.qq.com/proxy.html?v=20210311001&callback=1&id=1',
'Origin': 'https://s.web2.qq.com',
'Host': 's.web2.qq.com',
}
cookies = requests.utils.dict_from_cookiejar(self.application.settings['cookie'])
cookies['ptwebqq'] = self.application.settings['ptwebqq']
response = requests.get(url, headers=headers, cookies=cookies)
result = json.loads(response.text)
if result['retcode'] != 0:
self.write('获取个人信息失败:' + result['errmsg'])
else:
self.write('我的QQ号是:' + str(result['result']['uin']))
def post(self):
msg = self.get_argument('msg')
url = 'https://s.web2.qq.com/api/get_friend_uin2'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:86.0) Gecko/20100101 Firefox/86.0',
'Referer': 'https://s.web2.qq.com/proxy.html?v=20210311001&callback=1&id=1',
'Origin': 'https://s.web2.qq.com',
'Host': 's.web2.qq.com',
}
cookies = requests.utils.dict_from_cookiejar(self.application.settings['cookie'])
cookies['ptwebqq'] = self.application.settings['ptwebqq']
params = {
'type': 1,
'content': '["%s",["font",{"name":"宋体","size":10,"style":[0,0,0],"color":"000000"}]]' % msg
}
response = requests.get(url, headers=headers, cookies=cookies, params=params)
result = json.loads(response.text)
if result['retcode'] != 0:
self.write('获取好友信息失败:' + result['errmsg'])
else:
qq = result['result']['uin']
url = 'https://s.web2.qq.com/api/send_private_msg2'
cookies = requests.utils.dict_from_cookiejar(self.application.settings['cookie'])
cookies['ptwebqq'] = self.application.settings['ptwebqq']
params = {
'to': qq,
'face': 0,
'content': '["%s",["font",{"name":"宋体","size":10,"style":[0,0,0],"color":"000000"}]]' % msg
}
response = requests.post(url, headers=headers, cookies=cookies, json=params)
result = json.loads(response.text)
if result['retcode'] != 0:
self.write('发送消息失败:' + result['errmsg'])
else:
self.write('回复消息成功!')
if __name__ == '__main__':
qq = '' # 填写你的QQ号
password = '' # 填写你的QQ密码
login_result = login(qq, password)
connect(login_result['cookie'], login_result['ptwebqq'])
app = Application([
('/webqqbot', WebQQBot),
], cookie=login_result['cookie'], ptwebqq=login_result['ptwebqq'])
app.listen(8000)
print('WebQQ机器人已启动,监听端口:8000')
IOLoop.current().start()
机器人的实现示例:
当机器人收到一条QQ消息时,它会将消息回复给QQ好友,并将消息内容在控制台上输出。
class WebQQBot(RequestHandler):
def post(self):
msg = self.get_argument('msg')
# 此处省略获取好友QQ号的代码
# ...
url = 'https://s.web2.qq.com/api/send_private_msg2'
cookies = requests.utils.dict_from_cookiejar(self.application.settings['cookie'])
cookies['ptwebqq'] = self.application.settings['ptwebqq']
params = {
'to': str(qq),
'face': 0,
'content': '["%s",["font",{"name":"宋体","size":10,"style":[0,0,0],"color":"000000"}]]' % msg
}
response = requests.post(url, headers=headers, cookies=cookies, json=params)
result = json.loads(response.text)
if result['retcode'] != 0:
print('发送消息失败:' + result['errmsg'])
else:
print('回复消息成功:' + msg)
5. 启动WebQQ机器人
运行机器人的主文件,启动监听器,并在命令行上显示机器人已经启动。
if __name__ == '__main__':
qq = '' # 填写你的QQ号
password = '' # 填写你的QQ密码
login_result = login(qq, password)
connect(login_result['cookie'], login_result['ptwebqq'])
app = Application([
('/webqqbot', WebQQBot),
], cookie=login_result['cookie'], ptwebqq=login_result['ptwebqq'])
app.listen(8000)
print('WebQQ机器人已启动,监听端口:8000')
IOLoop.current().start()
以上就是使用Python的Tornado框架实现一个简单的WebQQ机器人的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:使用Python的Tornado框架实现一个简单的WebQQ机器人 - Python技术站