littlecodersh / itchat Goto Github PK
View Code? Open in Web Editor NEWA complete and graceful API for Wechat. 微信个人号接口、微信机器人及命令行微信,三十行即可自定义个人号机器人。
Home Page: http://itchat.readthedocs.io
License: MIT License
A complete and graceful API for Wechat. 微信个人号接口、微信机器人及命令行微信,三十行即可自定义个人号机器人。
Home Page: http://itchat.readthedocs.io
License: MIT License
群聊的时候,若@联系人,text和content属性的内容均包含了@信息,建议能够把text属性过滤为不包含@内容的,同时可以增加一个atContract属性,把@的联系人信息作为list存储(考虑@在文字前、中、后,以及多个@混合),这样程序能够更好的处理文字逻辑.
另,还有一个问题,某些微信版本发出的@联系人,系统不能正确识别,isAt为False,怀疑不同版本微信的默认分隔符不一样.
两次报错:
<error><ret>1203</ret><message>check ticket failed</message></error>
报错信息:
Please press confirm
Traceback (most recent call last):
File "ItChat.py", line 28, in <module>
client.login()
File "/Users/bibotai/tools/ItChat-robot/itchat/client.py", line 40, in login
voidUserList = self.get_contract()
File "/Users/bibotai/tools/ItChat-robot/itchat/client.py", line 147, in get_contract
int(time.time()), self.loginInfo['skey'])
KeyError: 'skey'
函数结构类似:
def function(self):
def function1(self):
url =
r = requests.get(url + ak + '&addr=' + self)
hjson = r.json()
if hjson["code"] == 0:
return r.text
else:
return u'error'
return function1
报错内容:
Traceback (most recent call last):
File "map_flat.py", line 115, in <module>
itchat.run()
File "/home/alarm/repos/map_flat/itchat/__init__.py", line 82, in run
configured_reply()
File "/home/alarm/repos/map_flat/itchat/__init__.py", line 60, in configured_reply
if replyFn: send(replyFn(msg), msg.get('FromUserName'))
File "/home/alarm/repos/map_flat/itchat/__init__.py", line 41, in send
if msg[:5] == '@fil@':
TypeError: 'function' object has no attribute '__getitem__'
用了给的默认代码测试:
@itchat.msg_register('Text', isGroupChat = True)
def text_reply(msg):
if msg['isAt']:
itchat.send(u'@%s\u2005I received: %s'%(msg['ActualNickName'], msg['Content']), msg['FromUserName'])
字面意思我理解的是当@本人的时候方才回复。实际用的时候不管有无@均报错
Traceback (most recent call last):
File "D:\Py35\itchat\app.py", line 34, in
itchat.run()
File "E:\Python\Python27\Lib\site-packages\itchat-1.0.8-py2.7.egg\itchat__init__.py", line 167, in run
File "E:\Python\Python27\Lib\site-packages\itchat-1.0.8-py2.7.egg\itchat__init__.py", line 135, in configured_reply
File "D:\Py35\itchat\app.py", line 30, in text_reply
if msg['isAt']:
KeyError: 'isAt'
运行环境,windows10/python3.5.2
目前在线时间有点短,不活跃的情况下过一段时间就没反应了
看 README
提到这是因为微信的心跳机制
另一个类似的基于微信机器人项目 Hubot-WeChat 提到:Hubot会定时发心跳给微信服务器, 微信服务器会认为Hubot一直在登录网页版的。
虽然没试过那个项目,但想问下能不能实现主动发送心跳,保持在线
create_chatroom(self, memberList, topic = ''): topic是什么呀
add_friend(self, status, userName, ticket): 这个函数如何传参?
谢谢了,哈哈
由于我的需求需要判断消息是否来自公众号,对群ID也有需求,所以需要storage里的几个值
测试后发现memberList/chatroomList
一直都是空的,于是把client.py
修改了一下
在auto_login
的self.get_contract()
后面加上了两行代码:
self.storageClass.memberList=self.memberList
self.storageClass.chatroomList=self.chatroomList
测试后可行。
另外判断是否来自公众号我的方法是先取得公众号的列表,之后对发来消息的ID通过是否在已知列表里进行判断。于是我参照memberList和chatroomList增加了publicList这个项,在get_contract()这个函数里和另外两个list一道进行分类。
关于在获取到的list进行普通/群/公众号的分类的过程中,我发现源代码是复制出N个数组,分别把不属于该组的数据remove掉,这就要进行N次遍历,我觉得有点低效,就把这几次遍历写到一起了,get_contract()的代码:
def get_contract(self, update=False):
if 1 < len(self.memberList) and not update:
return self.memberList
url = '%s/webwxgetcontact?r=%s&seq=0&skey=%s' % (self.loginInfo['url'],
int(time.time()),
self.loginInfo['skey'])
headers = {
'ContentType': 'application/json; charset=UTF-8'
}
r = self.s.get(url, headers=headers)
memberList = json.loads(BytesDecode(r.content.decode('utf-8', 'replace')))['MemberList']
chatroomList = []
publicList = []
while True:
i = 0
for m in memberList:
if (any([str(n) in m['UserName'] for n in range(10)])
and any([
[chr(n) in m['UserName'] for n in range(ord('a'), ord('z') + 1)],
[chr(n) in m['UserName'] for n in range(ord('A'), ord('Z') + 1)]
])):
if ('@@' in m['UserName']):
chatroomList.append(m)
elif (m['Sex'] == 0
and (m['VerifyFlag'] & 8 != 0)):
publicList.append(m)
elif (m['Sex'] != 0
or (m['VerifyFlag'] & 8 == 0)):
continue
memberList.remove(m)
i += 1
if i == 0:
break
# deal with emoji
self.memberList = tools.emoji_dealer(memberList)
self.publicList = publicList
self.chatroomList = chatroomList
return memberList
以上就是一点修改和疑问,由于不是专业程序员,不知是否正确
/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/yzl/PycharmProjects/untitled/testitchat.py
Getting uuid
Please press confirmTERM environment variable not set.
Traceback (most recent call last):
Login successfully as ***
File "/Users/yzl/PycharmProjects/untitled/testitchat.py", line 5, in
@itchat.msg_dealer(['Text', 'Map', 'Card', 'Note', 'Sharing'])
AttributeError: 'module' object has no attribute 'msg_dealer'
Process finished with exit code 1
提示没有msg_dealer属性是什么问题
client.py 280行
url = 'https://file2.wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetmedia'
貌似应该改成
url = 'https://file.wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetmedia'
file和file2有什么区别?
昨天还好好的,今天就变成了乱码,找不到原因所在,来求助
都可以在这里交流,我会及时回复的~
也欢迎加入QQ群讨论:549762872
After I cloned this repo and installed the packages mentioned as prerequisites, I typed "python ItChat.py" in the command line, but received nothing but an prompted error that reads as follows:
File "itchat.py", line 11
print 'Start auto-replying'
^
SyntaxError: Missing parentheses in call to 'print'
Chyroc以一人之力更新了py3版本的itchat,写的非常不错!
这里做一个bug收集贴,方便版本更新。
send_msg的返回值应当为True/False,目前为None.
一下两种都试了
输出内容:
Failed to get QR Code, please restart the program
这是什么消息类型?
'''
MsgType Unknown: 43
{'ActualNickName': u'\u7a0b\u80d6\u5988', u'AppInfo': {u'Type': 0, u'AppID': u''}, u'ImgWidth': 216, u'FromUserName': u'@@d2f5917f3b6d1f0a117e0567327bd2eef68f10d21a2e73bdfa9985e8bebb752c', u'PlayLength': 30, u'ImgStatus': 1, u'RecommendInfo': {u'UserName': u'', u'Province': u'', u'City': u'', u'Scene': 0, u'QQNum': 0, u'Content': u'', u'Alias': u'', u'OpCode': 0, u'Signature': u'', u'Ticket': u'', u'Sex': 0, u'NickName': u'', u'AttrStatus': 0, u'VerifyFlag': 0}, u'Content': u'<?xml version="1.0"?>
<msg>
\t<videomsg aeskey="34306334343638626661666339613136" cdnthumbaeskey="34306334343638626661666339613136" cdnvideourl="30690201000462306002010002042ebfb30202032df02a0204a9e0c2dc0204573d6171043e617570766964656f5f663939646430356439393631373737335f313436333633383936355f313432323435313930353136336361373361653533363031390201000201000400" cdnthumburl="30690201000462306002010002042ebfb30202032df02a0204a9e0c2dc0204573d6171043e617570766964656f5f663939646430356439393631373737335f313436333633383936355f313432323435313930353136336361373361653533363031390201000201000400" length="3874273" playlength="30" cdnthumblength="14622" cdnthumbwidth="216" cdnthumbheight="288" fromusername="wxid_2vbandig705a22" md5="6d774c9d0b4063b0b10afe0329415230" />
</msg>
', u'MsgType': 43, u'ImgHeight': 288, u'StatusNotifyUserName': u'', u'StatusNotifyCode': 0, u'NewMsgId': 5493764242847474377, u'Status': 3, u'VoiceLength': 0, u'MediaId': u'', u'MsgId': u'5493764242847474377', u'ToUserName': u'@962bf97e86593c5addb1195a770cc9d5651cdbffc811301dce661a63dbb8505a', u'ForwardFlag': 0, u'FileName': u'', u'Url': u'', u'HasProductId': 0, u'FileSize': u'', u'AppMsgType': 0, 'ActualUserName': u'@8a77ec2e0bdfd17cfbd8aa90185f7dec3cd7ae797e4dc1b9b932686829b6bed5', u'Ticket': u'', u'CreateTime': 1463640438, u'SubMsgType': 0}
'''
@djtu 在Issue#1中提出,确认为bug故新建issue
原文
@littlecodersh @Peteling 我的情况好像是一样的,这里是我测试的代码
测试代码
@itchat.msg_register('Text')
def text_reply(msg):
contracets = itchat.get_contract()
for contract in contracets:
info = itchat.get_friends(userName = contract['UserName'])
print 'UserName:',contract['UserName'],'and NickName:',info['NickName']
print 'msg-FromUserName:', msg['FromUserName']
print 'msg-Content:', msg['Content']
print 'itchat.get_contract()[1]-NickName:',itchat.get_contract()[1]['NickName']
print 'itchat.get_contract()[1]-UserName:',itchat.get_contract()[1]['UserName']
结果
UserName: @9bfed77c63ea8e22f445489306bab0ba730ba8b4ba5672a561df2e1816e1c839 and NickName: 晨曦
UserName: @ a4428b91ead7c17663bb087818335382 and NickName: 翩翩精品
UserName: @ 170e2fe33df1f1bee9379d3826bd5888 and NickName: 乐知-李刚
UserName: @17d427b3637b8ad570f9596fd337284b41af89b9518d0b80b4e1ad68588b65a5 and NickName: 囡囡
UserName: @ff7a9af23299a2edc017c5809af5934b96ab6f0e6c4b5b319066e31df3a99db7 and NickName: A 链家前程街店王红影13614268406
msg-FromUserName: @ 0506fd8606cae22de6eeedc9d252d885
msg-Content: 获取图片
itchat.get_contract()[1]-NickName: 翩翩精品
itchat.get_contract()[1]-UserName: @a4428b91ead7c17663bb087818335382
问题分析
其中“翩翩精品”的msg['FromUsername']: @0506fd8606cae22de6eeedc9d252d885
而itchat.get_contract()[1]-UserName: @a4428b91ead7c17663bb087818335382
两者不一样的,同时 send 消息给2个 UserName,只有msg['FromUsername']能收到信息,另一个send 失败。
不知道是我操作的问题,还是bug,希望帮忙解答!~谢谢
本issue记录个人名片、公众号、文章转发的相关讨论。
http://itchat.readthedocs.io/zh/latest/1.Start/
# 收到好友邀请自动添加好友
@itchat.msg_register('Friends')
def add_friend(msg):
itchat.add_friend(**msg['Text'])
itchat.get_contract()
itchat.send_msg(msg['RecommendInfo']['UserName'], 'Nice to meet you!')
正确
# 收到好友邀请自动添加好友
@itchat.msg_register('Friends')
def add_friend(msg):
itchat.add_friend(**msg['Text'])
itchat.get_contract()
itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName'])
对方回复一个文案,机器人能不能发送一张指定的图片?我这边一直么有实现,求教
import time
import itchat
def simple_reply():
@itchat.msg_register
def simple_reply(msg):
if msg.get('Type', '') == 'Text':
return 'I received: %s'%msg.get('Content', '')
itchat.run()
def complex_reply():
@itchat.msg_register(['Text','Picture', 'Map', 'Card', 'Note', 'Sharing'])
def text_reply(msg):
if msg['Text'] == 'q':
print itchat.send('@img@%s'%u'test.jpg');
else:
itchat.send('%s: %s'%(msg['Type'], msg['Text']), msg['FromUserName'])
# @itchat.msg_register(['Picture', 'Recording', 'Attachment', 'Video'])
# def download_files(msg):
# # fileDir = '%s%s'%(msg['Type'], int(time.time()))
# # msg['Text'](fileDir)
# fileDir = 'Picture1469703926'
# itchat.send('%s received'%msg['Type'], msg['FromUserName'])
# itchat.send('@%s@%s'%('img' if msg['Type'] == 'Picture' else 'fil', fileDir), msg['FromUserName'])
@itchat.msg_register('Friends')
def add_friend(msg):
itchat.add_friend(**msg['Text'])
itchat.get_contract()
itchat.send('Nice to meet you!', msg['RecommendInfo']['UserName'])
@itchat.msg_register('Text', isGroupChat = True)
def text_reply(msg):
if msg['isAt']:
itchat.send(u'@%s\u2005I received: %s'%(msg['ActualNickName'], msg['Content']), msg['FromUserName'])
itchat.run()
if __name__ == '__main__':
itchat.auto_login()
# simple_reply()
complex_reply()
如题。。。
我又来问问题了,现在程序我在我的服务器上直接python run.py没有问题,但是我想用nohup执行的时候,就出现了问题,nohup.out如下
File "run.py", line 49, in <module>
itchat.auto_login()
File "/var/www/html/ItChat/itchat/__init__.py", line 13, in auto_login
__client.auto_login(enableCmdQR = enableCmdQR)
File "/var/www/html/ItChat/itchat/client.py", line 58, in auto_login
open_QR()
File "/var/www/html/ItChat/itchat/client.py", line 50, in open_QR
out.print_line('Getting uuid', True)
File "/var/www/html/ItChat/itchat/out.py", line 11, in print_line
sys.stdout.write(msg.encode(sys.stdin.encoding, 'replace'
TypeError: encode() argument 1 must be string, not None`
现在又不知道该如何解决了
File "F:\python\ItChat-robot\plugin\tuling.py", line 18, in get_response
r = json.loads(requests.post(url, data = payloads).text)
File "C:\Python27\lib\json__init__.py", line 339, in loads
当tuling API 出现504 Gateway Time-out, 就会出现错误抛出
我想列出自已是群主的群,在这些群里面,才回应member的对话
如果 member 出现某些黑名单关键字,就把memeber踢了
所以有两点关键刚好都跟是不是群主相关
谢谢
命令行也ok 谢谢
@littlecodersh @chyroc 两位老大,麻烦给看看,不知道是不是我自己弄错了什么?
执行代码:
itchat.send_file('2016.xls',self.user)
错误信息:
Exception in thread Thread-3:
Traceback (most recent call last):
File "D:\Anaconda3\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "D:/code/weixinBot/weixinrot 个人号.py", line 132, in run
itchat.send_file('2016.xls',self.user)
File "D:\Anaconda3\lib\site-packages\itchat\__init__.py", line 87, in send_file
return __client.send_file(fileDir, toUserName)
File "D:\Anaconda3\lib\site-packages\itchat\client.py", line 628, in send_file
mediaId = self.__upload_file(fileDir)
File "D:\Anaconda3\lib\site-packages\itchat\client.py", line 614, in __upload_file
}, separators=(',', ':'))),
File "D:\Anaconda3\lib\json\__init__.py", line 237, in dumps
**kw).encode(obj)
File "D:\Anaconda3\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "D:\Anaconda3\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "D:\Anaconda3\lib\json\encoder.py", line 180, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'9I/loYJ4Kl4fVPsS' is not JSON serializable
@littlecodersh 我新建了一个issue,测试了确实每一次登录群的id都会改变
Why writing bots, it is often needed to restart the whole script. But each time Itchat will start a new requests.sesion(), and QR need to be re-scanned.
Could it be implemented that cookies are saved on disk and reuse it whenever possible?
[INFO] Getting uuid
[INFO] Getting QR Code
[INFO] Getting uuid
[INFO] Getting QR Code
[INFO] Getting uuid
[INFO] Getting QR Code
[INFO] Getting uuid
[INFO] Getting QR Code
[INFO] Failed to get QR Code, please restart the program
这是什么原因, 是不是哪里修改什么参数才能正常运行?
就是以便下这些代码:
import itchat
itchat.auto_login()
@itchat.msg_register
def simple_reply(msg):
if msg.get('Type', '') == 'Text':
return 'I received: %s'%msg.get('Content', '')
itchat.run()
print itchat.create_chatroom(itchat.get_contract(),"lll2l")
是空
client.py的397行,self.storageClass.groupDict[msg['FromUserName']][ActualUserName],感觉ActualUserName变量未定义。
RaspberryNetEase是我无聊时候写着玩的,代码写的很乱,今天发现你对代码进行了非常大完善工作,在此表示感谢!itchat非常有意思,已加star,多谢!
看了文档 基本都是被动的接收消息 并回复,怎么主动给别人发送消息呢? send对象中怎么给username值?
我尝试用itchat.get_frineds(),但是返回值不知道怎么处理。
如题。感谢这个项目,解决了我很多问题。
我看了示例代码:
@itchat.msg_register(['Picture', 'Recording', 'Attachment', 'Video'])
def download_files(msg):
fileDir = '%s%s'%(msg['Type'], int(time.time()))
msg['Text'](fileDir)
itchat.send('%s received'%msg['Type'], msg['FromUserName'])
itchat.send('@%s@%s'%('img' if msg['Type'] == 'Picture' else 'fil', fileDir), msg['FromUserName'])
其中fileDir取出来是一个Attachment11215464之类的一个字符串,完整的url应该怎么组合呢?
我的意思是我想要下载到别人传给微信机器人的文件,然后自动处理一些事情。
@littlecodersh 求教,再次感谢这个项目给我带来的便利。
Wechaty Wechaty is wechat for bot in Javascript(ES6). It's a Personal Account Robot Framework/Library.
交换个友情链接吧,我已经加了你的。:)
https://github.com/zixia/wechaty#see-also
如何获得发送信息的用户名字,然后在@回去?
目前 只能拿到用户的ID ,但@回去。就直接显示一长串ID 了。
请问群聊群聊grouplist里的哪个字段可以唯一确定群聊啊 ?
UserName是@@xxxxxxxx每一次扫码之后都会变,EncryChatRoomId也是每次都在变
PYQuanPin这个字段有可能多个群这个值相同,而且群昵称变化之后这个值也会变动
请问有么有什么方式可以唯一确定一个群,想实现类似签到的功能
另外还有一个问题,调用batchgetcontact这个接口后返回的data中 "OwnerUin"这个字段似乎是群主id(这个id值也固定),但是并没有找到一个接口可以用这个字段来查用户信息,getcontact 这个接口用的参数是UserName:@xxxxxxxxxx来查的
求解答
怎么给群发消息,群聊没有id,send参数里tousername 里无法传递群参数
TypeError: getresponse() got an unexpected keyword argument 'buffering'
http.client.RemoteDisconnected: Remote end closed connection without response
requests.packages.urllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))
短时间关闭程序后重连功能的文档建议的第一种用法,貌似应对改为下面的样子为宜,无论之前有无登录存档,均应当进入主循环。不知道我是否理解得正确。
import itchat
if not itchat.load_login_status():
itchat.auto_login()
itchat.dump_login_status()
print('Config stored')
@itchat.msg_register('Text')
def simple_reply(msg):
print(msg['Text'])
itchat.run()
itchat.dump_login_status()
如题
telegram有一个类似的bot
尝试改了一下,但没有成功
因为没有公网IP,所以想借用微信实现远程下载
我想给机器人弄个后台管理界面应该怎么实现?就是把机器人放服务器上,然后通过浏览器控制信息回复,记录,等等操作。就是类似公众号那样。
如题~
@chyroc @littlecodersh 请教一下,关于定位唯一账号的问题。
1、
itchat.get_alias(username=msg['FromUserName'])
能否强制返回微信号而不是昵称或者备注?或者说返回值至少让我知道到底是返回了微信号还是昵称,或者是备注?
2、
itchat.set_oplog(msg['FromUserName'],'测试用户ID')
设置备注名后,在用get_alias获取到的依然是昵称,不是备注名,需要重新运行机器人后才能拿到新的名字
环境是py 3.5.1
https://itchat.readthedocs.io/zh/latest/5.Reply/#send
send_msg send_img等小标题下的“方法”中,方法名都是send,与其下方例子不一致,似乎不合本意?
另外根据例子的话,send_img也要标注 '@ img@图片地址' 嘛?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.