欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

采用python实现简单QQ单用户机器人的方法

程序员文章站 2023-11-30 19:41:52
采用python实现简单qq单用户机器人的方法如下: 一、首先我们查看一下关于3gqq的相关协议:     对此,打开一个支持wap的浏览...

采用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()

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