本文分享一份以 Python 實作、依 WebQQ 協議登入 QQ 並發送訊息的开源範例,專案位址為 https://github.com/atupal/webqq。作者也提到,之後有時間會再寫一個完整的 CLI 版 QQ 用戶端。使用方式很簡單,直接執行 python login_qq.py 即可。
以下為主要程式碼:
import urllib2
import httplib2
import re
import random
from encryption import QQmd5
import cookielib
import requests
import getpass
import time
import json
import urllib
class webqq:
def __init__(self, user, pwd):
self.cookies = cookielib.CookieJar()
self.opener = urllib2.build_opener(
urllib2.HTTPHandler(),
urllib2.HTTPSHandler(),
urllib2.HTTPCookieProcessor(self.cookies),
)
urllib2.install_opener(self.opener)
self.user = user
self.pwd = pwd
self.mycookie = ";"
self.clientid = str(random.randint(10000000, 99999999))
def getSafeCode(self):
# 取得驗證碼相關資訊,必要時下載圖形驗證碼
url = 'https://ssl.ptlogin2.qq.com/check?uin=' + str(self.user) + '&appid=1003903...'
req = urllib2.Request(url)
req = urllib2.urlopen(req)
verifycode = re.search(r"'(\d)','(.+)','(.+)'", req.read())
self.check = verifycode.group(1)
self.verifycode1 = verifycode.group(2)
self.verifycode2 = verifycode.group(3)
def loginGet(self):
# 以 QQmd5 加密密碼後送出登入請求,取得 ptwebqq 等 cookie
login_url = 'https://ssl.ptlogin2.qq.com/login?u=' + self.user + '&p=' + str(QQmd5().md5_2(self.pwd, self.verifycode1, self.verifycode2)) + '...'
req = urllib2.Request(login_url)
req.add_header("Referer", "https://ui.ptlogin2.qq.com/cgi-bin/login?...")
req = urllib2.urlopen(req)
for cookie in self.cookies:
if cookie.name == 'ptwebqq':
self.ptwebqq = cookie.value
def loginPost(self):
# 送出線上狀態登入,取得 vfwebqq 與 psessionid
url = 'https://d.web2.qq.com/channel/login2'
data = 'r=%7B%22status%22%3A%22online%22%2C%22ptwebqq%22%3A%22' + self.ptwebqq + '%22...&clientid=' + self.clientid + '&psessionid=null'
req = urllib2.Request(url, data)
req.add_header('Referer', 'https://d.web2.qq.com/proxy.html?...')
req = urllib2.urlopen(req)
self.result = json.load(req)
def getGroupList(self):
# 取得群組列表
url = 'https://s.web2.qq.com/api/get_group_name_list_mask2'
# ...
def getFriend(self):
# 取得好友列表
url = 'https://s.web2.qq.com/api/get_user_friends2'
# ...
def poll2(self):
# 輪詢新訊息
url = 'https://d.web2.qq.com/channel/poll2'
# ...
def sendMsg(self, uin, msg):
# 發送好友訊息
url = 'https://d.web2.qq.com/channel/send_buddy_msg2'
# ...
def sendQunMsg(self, uin, msg):
# 發送群訊息
url = 'https://d.web2.qq.com/channel/send_qun_msg2'
# ...
def main():
user = raw_input('QQ:')
pwd = getpass.getpass('password: ')
qq = webqq(user, pwd)
qq.getSafeCode()
qq.loginGet()
qq.loginPost()
qq.getGroupList()
qq.getFriend()
# 後續可進入輪詢與發訊流程
if __name__ == "__main__":
main()
整體流程可以拆解為:取得驗證碼 → 加密密碼並登入取得 cookie → 送出線上狀態取得 session → 抓取好友與群組列表 → 進入訊息輪詢與發送。需要提醒的是,此範例屬於較早期的 WebQQ 協議實作,如今官方介面多半已變更或停用,僅供學習協議流程與封包組裝方式參考。