Convert Figma logo to code with AI

littlecodersh logoItChat

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

25,429
5,624
25,429
289

Top Related Projects

13,948

微信机器人 / 可能是最优雅的微信个人号 API ✨✨

19,998

Conversational RPA SDK for Chatbot Makers. Join our Discord: https://discord.gg/7q8NBZbQzt

Python Wechaty is a Conversational RPA SDK for Chatbot Makers written in Python

Mac微信功能拓展/微信插件/微信小助手(A plugin for Mac WeChat)

Quick Overview

ItChat is a Python library that provides a simple interface for interacting with WeChat, a popular Chinese messaging app. It allows users to automate WeChat operations, such as sending messages, managing contacts, and handling group chats, through a Python script.

Pros

  • Easy to use and implement for WeChat automation
  • Supports both personal and official accounts
  • Provides a wide range of functionalities, including text, image, and file messaging
  • Active community and regular updates

Cons

  • Limited to WeChat platform, not applicable for other messaging apps
  • May be affected by WeChat's policy changes or security updates
  • Documentation is primarily in Chinese, which may be challenging for non-Chinese speakers
  • Potential for misuse in spamming or unauthorized automation

Code Examples

  1. Logging in and sending a text message:
import itchat

itchat.auto_login()
itchat.send('Hello, WeChat!', toUserName='filehelper')
  1. Handling incoming messages:
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    return f'You said: {msg.text}'

itchat.auto_login(hotReload=True)
itchat.run()
  1. Sending an image:
@itchat.msg_register(itchat.content.TEXT)
def send_image(msg):
    if msg.text == 'image':
        itchat.send_image('path/to/image.jpg', toUserName=msg.fromUserName)

itchat.auto_login(hotReload=True)
itchat.run()

Getting Started

To get started with ItChat, follow these steps:

  1. Install ItChat using pip:

    pip install itchat
    
  2. Import the library and log in:

    import itchat
    itchat.auto_login(hotReload=True)
    
  3. Send a message:

    itchat.send('Hello, World!', toUserName='filehelper')
    
  4. Run the script:

    itchat.run()
    

Note: You'll need to scan a QR code with your WeChat app to log in when running the script for the first time.

Competitor Comparisons

13,948

微信机器人 / 可能是最优雅的微信个人号 API ✨✨

Pros of wxpy

  • More actively maintained with recent updates
  • Cleaner and more Pythonic API design
  • Better documentation and examples

Cons of wxpy

  • Smaller community and fewer contributors
  • Less comprehensive feature set compared to ItChat
  • May have compatibility issues with some WeChat versions

Code Comparison

ItChat:

import itchat

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

itchat.auto_login()
itchat.run()

wxpy:

from wxpy import *

bot = Bot()

@bot.register()
def reply_message(msg):
    return msg.text

bot.join()

Both libraries provide similar functionality for interacting with WeChat, but wxpy offers a more streamlined and intuitive API. ItChat uses decorators for message handling, while wxpy uses a more object-oriented approach with the Bot class.

wxpy's code is generally more concise and easier to read, making it a good choice for developers who prioritize clean code and simplicity. However, ItChat's larger community and more extensive feature set may be beneficial for complex projects or those requiring specific functionalities.

Ultimately, the choice between wxpy and ItChat depends on the project requirements, developer preferences, and the need for specific features or community support.

19,998

Conversational RPA SDK for Chatbot Makers. Join our Discord: https://discord.gg/7q8NBZbQzt

Pros of Wechaty

  • Multi-platform support (WeChat, WhatsApp, Gitter, etc.)
  • Supports multiple programming languages (TypeScript, JavaScript, Python, Go, Java, PHP, C#)
  • More active development and larger community

Cons of Wechaty

  • Steeper learning curve due to more complex architecture
  • Requires more setup and configuration
  • Potentially higher resource usage due to its broader scope

Code Comparison

ItChat:

import itchat

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

itchat.auto_login()
itchat.run()

Wechaty:

import { Wechaty } from 'wechaty'

const bot = new Wechaty()
bot.on('message', async msg => {
  console.log(`Message: ${msg}`)
})
await bot.start()

Both libraries provide simple ways to create chatbots, but Wechaty's multi-platform nature is evident in its more generic approach. ItChat is more focused on WeChat-specific functionality, making it easier to use for WeChat-only applications. Wechaty's code is more verbose but offers greater flexibility for cross-platform development.

Python Wechaty is a Conversational RPA SDK for Chatbot Makers written in Python

Pros of python-wechaty

  • Cross-platform support (Windows, macOS, Linux)
  • More active development and community support
  • Supports multiple messaging protocols beyond WeChat

Cons of python-wechaty

  • Steeper learning curve due to more complex architecture
  • Requires more setup and configuration
  • Larger codebase and dependencies

Code Comparison

ItChat:

import itchat

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

itchat.auto_login()
itchat.run()

python-wechaty:

from wechaty import Wechaty, Contact
from wechaty_puppet import MessageType

class MyBot(Wechaty):
    async def on_message(self, msg: MessageType):
        if msg.text() == 'ding':
            await msg.say('dong')

bot = MyBot()
bot.start()

Summary

ItChat is simpler and easier to use for basic WeChat automation tasks, while python-wechaty offers more flexibility and features for advanced users. ItChat has a more straightforward API, but python-wechaty provides better cross-platform support and is actively maintained. The choice between the two depends on the specific requirements of your project and your familiarity with more complex bot frameworks.

Mac微信功能拓展/微信插件/微信小助手(A plugin for Mac WeChat)

Pros of WeChatExtension-ForMac

  • Specifically designed for macOS, offering a native experience
  • Includes additional features like message recall prevention and auto-reply
  • Actively maintained with frequent updates

Cons of WeChatExtension-ForMac

  • Limited to macOS platform, not cross-platform like ItChat
  • Requires installation and modification of the official WeChat client
  • May be less suitable for automated bot development compared to ItChat

Code Comparison

WeChatExtension-ForMac (Objective-C):

- (void)hook_methodSignatureForSelector:(SEL)aSelector {
    if ([NSStringFromSelector(aSelector) isEqualToString:@"sendLogoutCGIWithCompletion:"]) {
        return;
    }
    [self hook_methodSignatureForSelector:aSelector];
}

ItChat (Python):

def send(self, msg, toUserName=None):
    if toUserName is None:
        toUserName = self.storageClass.userName
    url = '%s/webwxsendmsg' % self.loginInfo['url']
    payloads = {
        'BaseRequest': self.loginInfo['BaseRequest'],
        'Msg': msg.get('Msg', {
            'Type': 1,
            'Content': msg['Text'],
            'FromUserName': self.storageClass.userName,
            'ToUserName': toUserName,
            'LocalID': int(time.time() * 1e4),
            'ClientMsgId': int(time.time() * 1e4),
        }),
    }
    headers = {'ContentType': 'application/json; charset=UTF-8'}
    r = self.s.post(url, data=json.dumps(payloads, ensure_ascii=False).encode('utf8'), headers=headers)
    return r.json()['BaseResponse']['Ret'] == 0

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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