采用python实现简单QQ单用户机器人的方法
采用python实现简单QQ单用户机器人的方法如下:
一、首先我们查看一下关于3GQQ的相关协议:
对此,打开一个支持WAP的浏览器,可以使用Firefox的wmlbrowser插件,打开FF后,访问地址https://addons.mozilla.org/zh-CN/firefox/search/?q=wmlbrowser&cat=all&x=17&y=11
二、进入3GQQ的进行协议分析
3GQQ的地址是:http://pt.3g.qq.com/s?aid=nLogin3gqq用安装了wmlbrowser插件的FF打开页面后,启用firebug,即可实现监视提交的数据。
三、源代码部分:
#coding:utf-8 #基于python2.6版本开发 importhttplib,urllib,os,threading,re importsys reload(sys) sys.setdefaultencoding('utf8') classPYQQ: def__init__(self): self.reqIndex=0 #HTTP请求 defhttpRequest(self,method,url,data={}): try: _urld=httplib.urlsplit(url) conn=httplib.HTTPConnection(_urld.netloc,80,True,3) conn.connect() data=urllib.urlencode(data) ifmethod=='get': conn.putrequest("GET",url,None) conn.putheader("Content-Length",'0') elifmethod=='post': conn.putrequest("POST",url) conn.putheader("Content-Length",str(len(data))) conn.putheader("Content-Type","application/x-www-form-urlencoded") conn.putheader("Connection","close") conn.endheaders() iflen(data)>0: conn.send(data) f=conn.getresponse() self.httpBody=f.read().encode('utf8') f.close() conn.close() except: self.httpBody='' returnself.httpBody #通过首尾获取字符串的内容 defgetCon(self,start,end): findex=self.httpBody.find(start) iffindex==-1:returnNone tmp=self.httpBody.split(start) eindex=tmp[1].find(end) ifeindex==-1: returntmp[1][0:] else: returntmp[1][0:eindex] #获取postfield的值 defgetField(self,fd): KeyStart='') #获取登陆验证码,并保存至当前目录的qqcode.gif defgetSafecode(self): url=self.getCon('python_实现简单QQ单用户机器人 importurllib2 pager=urllib2.urlopen(url) data=pager.read() file=open(os.getcwd()+'\qqcode.gif','w+b') file.write(data) file.close() returnTrue #登陆QQ deflogin(self): self.qq=raw_input('请输入QQ号:'.encode('gbk')) self.pwd=raw_input('请输入密码:'.encode('gbk')) s1Back=self.httpRequest('post','http://pt.3g.qq.com/handleLogin',{'r':'240971315','qq':self.qq,'pwd':self.pwd,'toQQchat':'true','q_from':'','modifySKey':0,'loginType':1}) ifs1Back.find('请输入验证码')!=-1: self.sid=self.getField('sid') self.hexpwd=self.getField('hexpwd') self.extend=self.getField('extend') self.r_sid=self.getField('r_sid') self.rip=self.getField('rip') ifself.getSafecode(): self.safeCode=raw_input('请输入验证码(本文件同目录的qqcode.gif):') else: print'验证码加载错误' postData={'sid':self.sid,'qq':self.qq,'hexpwd':self.hexpwd,'hexp':'true','auto':'0', 'logintitle':'手机腾讯网','q_from':'','modifySKey':'0','q_status':'10', 'r':'271','loginType':'1','prev_url':'10','extend':self.extend,'r_sid':self.r_sid, 'bid_code':'','bid':'-1','toQQchat':'true','rip':self.rip,'verify':self.safeCode, } s1Back=self.httpRequest('post','http://pt.3g.qq.com/handleLogin',postData) self.sid=self.getCon('sid=','&') #printself.sid print'登陆成功'.encode('gbk') self.getMsgFun() #定时获取消息 defgetMsgFun(self): self.reqIndex=self.reqIndex+1 s2Back=self.httpRequest('get','http://q32.3g.qq.com/g/s?aid=nqqchatMain&sid='+self.sid) ifs2Back.find('alt="聊天"/>(')!=-1: #有新消息,请求获取消息页面 s3back=self.httpRequest('get','http://q32.3g.qq.com/g/s?sid='+self.sid+'&aid=nqqChat&saveURL=0&r=1310115753&g_f=1653&on=1') #消息发起者的昵称 ifs3back.find('title="临时会话')!=-1: _fromName='临时对话' else: _fromName=self.getCon('title="与','聊天') #消息发起者的QQ号 _fromQQ=self.getCon('num"value="','"/>') #消息内容 _msg_tmp=self.getCon('saveURL=0">提示)',\'<inputname="msg"\') crlf='\n' if_msg_tmp.find('\r\n')!=-1:crlf='\r\n' _msg=re.findall(r'(.+) '+crlf+'(.+) ',_msg_tmp) for_datain_msg: self.getMsg({'qq':_fromQQ,'nick':_fromName,'time':_data[0],'msg':str(_data[1]).strip()}) ifself.reqIndex>=30: #保持在线 _url='http://pt5.3g.qq.com/s?aid=nLogin3gqqbysid&3gqqsid='+self.sid self.httpRequest('get',_url) self.reqIndex=0 t=threading.Timer(2.0,self.getMsgFun) t.start() #发送消息 #qq目标QQ #msg发送内容 defsendMsgFun(self,qq,msg): msg=unicode(msg,'utf8').encode('utf8') postData={'sid':self.sid,'on':'1','saveURL':'0','saveURL':'0','u':qq,'msg':str(msg),} s1Back=self.httpRequest('post','http://q16.3g.qq.com/g/s?sid='+self.sid+'&aid=sendmsg&tfor=qq',postData) print'发送消息给'.encode('gbk'),qq,'成功'.encode('gbk') #收到消息的接口,重载或重写该方法 defgetMsg(self,data): printdata['time'],"收到".encode('gbk'),data['nick'].encode('gbk'),"(",data['qq'],")的新消息".encode('gbk'),":",data['msg'].encode('gbk') self.sendMsgFun(data['qq'],data['nick']+',测试消息。。')#+data['msg']) QQ=PYQQ() QQ.login()
至此,机器人功能得以实现!