Git Product home page Git Product logo

itchat's Issues

是否应该兼容空格为@分隔符的群聊信息

群聊的时候,若@联系人,text和content属性的内容均包含了@信息,建议能够把text属性过滤为不包含@内容的,同时可以增加一个atContract属性,把@的联系人信息作为list存储(考虑@在文字前、中、后,以及多个@混合),这样程序能够更好的处理文字逻辑.
另,还有一个问题,某些微信版本发出的@联系人,系统不能正确识别,isAt为False,怀疑不同版本微信的默认分隔符不一样.

self.loginInfo中skey键未能赋值

两次报错:

  • @bibotai @237rxd
  • bibotai:在client.py中get_login_info(self, s)抓到的s是
<error><ret>1203</ret><message>check ticket failed</message></error>
  • 237rxd:经过测试可以使用浏览器登录网页版微信

报错信息:

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'

[itchat无关] python嵌套函数中return报错

函数结构类似:

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__'

msg['isAt'] BUG?

用了给的默认代码测试:

@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一直在登录网页版的。
虽然没试过那个项目,但想问下能不能实现主动发送心跳,保持在线

storage里头的memberList/chatroomList初始化时似乎没给赋值

由于我的需求需要判断消息是否来自公众号,对群ID也有需求,所以需要storage里的几个值
测试后发现memberList/chatroomList一直都是空的,于是把client.py修改了一下
auto_loginself.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

以上就是一点修改和疑问,由于不是专业程序员,不知是否正确

运行的时候提示AttributeError: 'module' object has no attribute 'msg_dealer'

/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有什么区别?

First "Python ItChat.py" Fails

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'

py3问题反馈

Chyroc以一人之力更新了py3版本的itchat,写的非常不错!
这里做一个bug收集贴,方便版本更新。

MsgType Unknown: 43

这是什么消息类型?
'''
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,希望帮忙解答!~谢谢

文档中演示代码出错

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

centos7 nohup sys.stdin.encoding为None导致编码错误

我又来问问题了,现在程序我在我的服务器上直接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`

现在又不知道该如何解决了

504 Gateway Time-out

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踢了
所以有两点关键刚好都跟是不是群主相关

  1. 是群主的群才回应对话
  2. 踢人是群主才有的功能

谢谢
命令行也ok 谢谢

py3版本bug:发送文件出错

@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

Save cookies on disk to avoid repeated relogin

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?

重复出现 Failed to get QR Code

[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()

感谢对代码的完善

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 求教,再次感谢这个项目给我带来的便利。

如何唯一确定群聊

请问群聊群聊grouplist里的哪个字段可以唯一确定群聊啊 ?
UserName是@@xxxxxxxx每一次扫码之后都会变,EncryChatRoomId也是每次都在变
PYQuanPin这个字段有可能多个群这个值相同,而且群昵称变化之后这个值也会变动
请问有么有什么方式可以唯一确定一个群,想实现类似签到的功能

另外还有一个问题,调用batchgetcontact这个接口后返回的data中 "OwnerUin"这个字段似乎是群主id(这个id值也固定),但是并没有找到一个接口可以用这个字段来查用户信息,getcontact 这个接口用的参数是UserName:@xxxxxxxxxx来查的

求解答

登陆报错:Remote end closed connection without response

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

关于定位唯一账号的问题以及BUG报告

@chyroc @littlecodersh 请教一下,关于定位唯一账号的问题。
1、
itchat.get_alias(username=msg['FromUserName'])
能否强制返回微信号而不是昵称或者备注?或者说返回值至少让我知道到底是返回了微信号还是昵称,或者是备注?

2、
itchat.set_oplog(msg['FromUserName'],'测试用户ID')
设置备注名后,在用get_alias获取到的依然是昵称,不是备注名,需要重新运行机器人后才能拿到新的名字

环境是py 3.5.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.