采用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的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
