采用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版本开发
import httplib,urllib,os,threading,re
import sys
reload(sys)
sys.setdefaultencoding('utf8')
class PYQQ:
  def __init__(self):
    self.reqIndex = 0
  
  #HTTP请求
  def httpRequest(self,method,url,data={}):
    try:
      _urld = httplib.urlsplit(url)
      conn = httplib.HTTPConnection(_urld.netloc,80,True,3)
      conn.connect()
      data = urllib.urlencode(data)
      if method=='get':
        conn.putrequest("GET", url, None)
        conn.putheader("Content-Length",'0')
      elif method=='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()
      
      if len(data)>0:
        conn.send(data)
      f = conn.getresponse()
      self.httpBody = f.read().encode('utf8')
      f.close()
      conn.close()
    except:
      self.httpBody=''
    return self.httpBody
  #通过首尾获取字符串的内容
  def getCon(self,start,end):
    findex = self.httpBody.find(start)
    if findex == -1 : return None
    tmp = self.httpBody.split(start)
    
    eindex = tmp[1].find(end)
    if eindex == -1:
      return tmp[1][0:]
    else:
      return tmp[1][0:eindex]
  #获取postfield的值
  def getField(self,fd):
    KeyStart = '')
  #获取登陆验证码,并保存至当前目录的qqcode.gif
  def getSafecode(self):
    url = self.getCon('python_实现简单QQ单用户机器人
    import urllib2
    pager = urllib2.urlopen(url)
    data=pager.read()
    file=open(os.getcwd()+'\qqcode.gif','w+b')
    file.write(data)
    file.close()
    return True
  #登陆QQ
  def login(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})
    if s1Back.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')
      if self.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=','&')
    #print self.sid
    print '登陆成功'.encode('gbk')
    self.getMsgFun()  
  #定时获取消息
  def getMsgFun(self):
    self.reqIndex = self.reqIndex + 1
    s2Back = self.httpRequest('get','http://q32.3g.qq.com/g/s?aid=nqqchatMain&sid='+self.sid)
    if s2Back.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')
      
      #消息发起者的昵称
      if s3back.find('title="临时会话")!=-1:
        _fromName = '临时对话'
      else:
        _fromName = self.getCon('title="与",'聊天')
      
      #消息发起者的QQ号
      _fromQQ = self.getCon('num" value="','"/>')
      
      #消息内容
      _msg_tmp = self.getCon('saveURL=0">提示)',\'<input name="msg"')
      crlf = '\n'
      if _msg_tmp.find('\r\n')!=-1: crlf = '\r\n'
      _msg = re.findall(r'(.+)
'+ crlf +'(.+)
',_msg_tmp)
      
      for _data in _msg:
        self.getMsg({'qq':_fromQQ,'nick':_fromName,'time':_data[0],'msg':str(_data[1]).strip()})
    
    if self.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 发送内容
  def sendMsgFun(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')  
  #收到消息的接口,重载或重写该方法
  def getMsg(self,data):
    print data['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()

至此,机器人功能得以实现!

以上就是采用python实现简单QQ单用户机器人的方法。生产一代,研制一代,构思一代。更多关于采用python实现简单QQ单用户机器人的方法请关注haodaima.com其它相关文章!

标签: python QQ