Giter Site home page Giter Site logo

littlecodersh / itchat Goto Github PK

View Code? Open in Web Editor NEW
25.0K 884.0 5.6K 955 KB

A complete and graceful API for Wechat. 微信个人号接口、微信机器人及命令行微信,三十行即可自定义个人号机器人。

Home Page: http://itchat.readthedocs.io

License: MIT License

Python 100.00%
itchat wechat api robot

itchat's Introduction

itchat

Gitter py27 py35 English version

itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。

使用不到三十行的代码,你就可以完成一个能够处理所有信息的微信机器人。

当然,该api的使用远不止一个机器人,更多的功能等着你来发现,比如这些

该接口与公众号接口itchatmp共享类似的操作方式,学习一次掌握两个工具。

如今微信已经成为了个人社交的很大一部分,希望这个项目能够帮助你扩展你的个人的微信号、方便自己的生活。

安装

可以通过本命令安装itchat:

pip install itchat

简单入门实例

有了itchat,如果你想要给文件传输助手发一条信息,只需要这样:

import itchat

itchat.auto_login()

itchat.send('Hello, filehelper', toUserName='filehelper')

如果你想要回复发给自己的文本消息,只需要这样:

import itchat

@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    return msg.text

itchat.auto_login()
itchat.run()

一些进阶应用可以在下面的开源机器人的源码和进阶应用中看到,或者你也可以阅览文档

试一试

这是一个基于这一项目的开源小机器人,百闻不如一见,有兴趣可以尝试一下。

由于好友数量实在增长过快,自动通过好友验证的功能演示暂时关闭。

QRCode

截屏

file-autoreply login-page

进阶应用

特殊的字典使用方式

通过打印itchat的用户以及注册消息的参数,可以发现这些值都是字典。

但实际上itchat精心构造了相应的消息、用户、群聊、公众号类。

其所有的键值都可以通过这一方式访问:

@itchat.msg_register(TEXT)
def _(msg):
    # equals to print(msg['FromUserName'])
    print(msg.fromUserName)

属性名为键值首字母小写后的内容。

author = itchat.search_friends(nickName='LittleCoder')[0]
author.send('greeting, littlecoder!')

各类型消息的注册

通过如下代码,微信已经可以就日常的各种信息进行获取与回复。

import itchat, time
from itchat.content import *

@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
    msg.user.send('%s: %s' % (msg.type, msg.text))

@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    msg.download(msg.fileName)
    typeSymbol = {
        PICTURE: 'img',
        VIDEO: 'vid', }.get(msg.type, 'fil')
    return '@%s@%s' % (typeSymbol, msg.fileName)

@itchat.msg_register(FRIENDS)
def add_friend(msg):
    msg.user.verify()
    msg.user.send('Nice to meet you!')

@itchat.msg_register(TEXT, isGroupChat=True)
def text_reply(msg):
    if msg.isAt:
        msg.user.send(u'@%s\u2005I received: %s' % (
            msg.actualNickName, msg.text))

itchat.auto_login(True)
itchat.run(True)

命令行二维码

通过以下命令可以在登陆的时候使用命令行显示二维码:

itchat.auto_login(enableCmdQR=True)

部分系统可能字幅宽度有出入,可以通过将enableCmdQR赋值为特定的倍数进行调整:

# 如部分的linux系统,块字符的宽度为一个字符(正常应为两字符),故赋值为2
itchat.auto_login(enableCmdQR=2)

默认控制台背景色为暗色(黑色),若背景色为浅色(白色),可以将enableCmdQR赋值为负值:

itchat.auto_login(enableCmdQR=-1)

退出程序后暂存登陆状态

通过如下命令登陆,即使程序关闭,一定时间内重新开启也可以不用重新扫码。

itchat.auto_login(hotReload=True)

用户搜索

使用search_friends方法可以搜索用户,有四种搜索方式:

  1. 仅获取自己的用户信息
  2. 获取特定UserName的用户信息
  3. 获取备注、微信号、昵称中的任何一项等于name键值的用户
  4. 获取备注、微信号、昵称分别等于相应键值的用户

其中三、四项可以一同使用,下面是示例程序:

# 获取自己的用户信息,返回自己的属性字典
itchat.search_friends()
# 获取特定UserName的用户信息
itchat.search_friends(userName='@abcdefg1234567')
# 获取任何一项等于name键值的用户
itchat.search_friends(name='littlecodersh')
# 获取分别对应相应键值的用户
itchat.search_friends(wechatAccount='littlecodersh')
# 三、四项功能可以一同使用
itchat.search_friends(name='LittleCoder机器人', wechatAccount='littlecodersh')

关于公众号、群聊的获取与搜索在文档中有更加详细的介绍。

附件的下载与发送

itchat的附件下载方法存储在msg的Text键中。

发送的文件的文件名(图片给出的默认文件名)都存储在msg的FileName键中。

下载方法接受一个可用的位置参数(包括文件名),并将文件相应的存储。

@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    msg.download(msg.fileName)
    itchat.send('@%s@%s' % (
        'img' if msg['Type'] == 'Picture' else 'fil', msg['FileName']),
        msg['FromUserName'])
    return '%s received' % msg['Type']

如果你不需要下载到本地,仅想要读取二进制串进行进一步处理可以不传入参数,方法将会返回图片的二进制串。

@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    with open(msg.fileName, 'wb') as f:
        f.write(msg.download())

用户多开

使用如下命令可以完成多开的操作:

import itchat

newInstance = itchat.new_instance()
newInstance.auto_login(hotReload=True, statusStorageDir='newInstance.pkl')

@newInstance.msg_register(itchat.content.TEXT)
def reply(msg):
    return msg.text

newInstance.run()

退出及登陆完成后调用特定方法

登陆完成后的方法需要赋值在loginCallback中。

而退出后的方法需要赋值在exitCallback中。

import time

import itchat

def lc():
    print('finish login')
def ec():
    print('exit')

itchat.auto_login(loginCallback=lc, exitCallback=ec)
time.sleep(3)
itchat.logout()

若不设置loginCallback的值,则将会自动删除二维码图片并清空命令行显示。

常见问题与解答

Q: 如何通过这个包将自己的微信号变为控制器?

A: 有两种方式:发送、接受自己UserName的消息;发送接收文件传输助手(filehelper)的消息

Q: 为什么我发送信息的时候部分信息没有成功发出来?

A: 有些账号是天生无法给自己的账号发送信息的,建议使用filehelper代替。

作者

LittleCoder: 构架及维护Python2 Python3版本。

tempdban: 协议、构架及日常维护。

Chyroc: 完成第一版本的Python3构架。

类似项目

youfou/wxpy: 优秀的api包装和配套插件,微信机器人/优雅的微信个人号API

liuwons/wxBot: 类似的基于Python的微信机器人

zixia/wechaty: 基于Javascript(ES6)的微信个人账号机器人NodeJS框架/库

sjdy521/Mojo-Weixin: 使用Perl语言编写的微信客户端框架,可通过插件提供基于HTTP协议的api接口供其他语言调用

HanSon/vbot: 基于PHP7的微信个人号机器人,通过实现匿名函数可以方便地实现各种自定义的功能

yaphone/itchat4j: 用Java扩展个人微信号的能力

kanjielu/jeeves: 使用springboot开发的微信机器人

问题和建议

如果有什么问题或者建议都可以在这个Issue和我讨论

或者也可以在gitter上交流:Gitter

当然也可以加入我们新建的QQ群讨论:549762872, 205872856

itchat's People

Contributors

big2cat avatar cc2cc avatar congbo avatar jtr109 avatar littlecodersh avatar mymusise avatar royxiang avatar sphynx-henryay avatar sunyi00 avatar tempdban avatar up9cloud avatar whalechen avatar wwj718 avatar xiaowuyz avatar xmcp avatar youfou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

itchat's Issues

登陆后通讯录内容错误

@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,希望帮忙解答!~谢谢

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'

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

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

登陆报错: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',))

文件下载失败...

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

文档中演示代码出错

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'])

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, 就会出现错误抛出

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

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

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

环境是py 3.5.1

如何自动下载文件?

我看了示例代码:

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

发送图片问题

对方回复一个文案,机器人能不能发送一张指定的图片?我这边一直么有实现,求教

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

py3问题反馈

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

运行的时候提示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属性是什么问题

重复出现 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()

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'

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

怎样主动给特定联系人发送消息?

看了文档 基本都是被动的接收消息 并回复,怎么主动给别人发送消息呢? send对象中怎么给username值?
我尝试用itchat.get_frineds(),但是返回值不知道怎么处理。

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?

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

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

短时间关闭程序后重连功能的文档

短时间关闭程序后重连功能的文档建议的第一种用法,貌似应对改为下面的样子为宜,无论之前有无登录存档,均应当进入主循环。不知道我是否理解得正确。

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

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

请问如何判断自已是不是群主?谢谢

我想列出自已是群主的群,在这些群里面,才回应member的对话
如果 member 出现某些黑名单关键字,就把memeber踢了
所以有两点关键刚好都跟是不是群主相关

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

谢谢
命令行也ok 谢谢

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

感谢对代码的完善

RaspberryNetEase是我无聊时候写着玩的,代码写的很乱,今天发现你对代码进行了非常大完善工作,在此表示感谢!itchat非常有意思,已加star,多谢!

如何唯一确定群聊

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

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

求解答

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

能否保持在线状态

目前在线时间有点短,不活跃的情况下过一段时间就没反应了
README 提到这是因为微信的心跳机制
另一个类似的基于微信机器人项目 Hubot-WeChat 提到:Hubot会定时发心跳给微信服务器, 微信服务器会认为Hubot一直在登录网页版的。
虽然没试过那个项目,但想问下能不能实现主动发送心跳,保持在线

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`

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

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.