前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >微信模拟个人号itchat库使用教程

微信模拟个人号itchat库使用教程

原创
作者头像
手撕代码八百里
修改2023-11-17 01:39:08
8950
修改2023-11-17 01:39:08
举报
文章被收录于专栏:猿计划猿计划

前言

chatgpt的这把火也把QQ机器人,WX机器人,WEB机器人各种智能问答类的应用带火了。

发现了一个itchat的开源项目,也有比较详细的资料,本文着手来玩一下itchat,下文是在把玩itchat时做的记录整理下来的结晶。

参考资料

1、itchat 官方文档

https://itchat.readthedocs.io/zh/latest/

2、itchat开源项目仓库地址

https://github.com/littlecodersh/itchat

安装itchat开发&运行环境

首先你的电脑环境安装了最新的python环境和pip.下文就默认为你已经安装好了。

1、通过pip 安装itchat

代码语言:shell
复制
pip install itchat

开发案例

1、创建一个chat.py

代码语言:shell
复制
touch chat.py

2、引入itchat库

代码语言:python
代码运行次数:0
复制
import itchat

3、测试是否成功

代码语言:python
代码运行次数:0
复制
(base) zhenghui@zh-pc:/media/zhenghui/软件/project/pyProject/qianfan/itchat$ 
(base) zhenghui@zh-pc:/media/zhenghui/软件/project/pyProject/qianfan/itchat$ 
(base) zhenghui@zh-pc:/media/zhenghui/软件/project/pyProject/qianfan/itchat$ python3 chat.py 
(base) zhenghui@zh-pc:/media/zhenghui/软件/project/pyProject/qianfan/itchat$ 

如果什么都没打印,就成功了。

例如出现如下所示的提示就说明没安装成功:

代码语言:shell
复制
(base) zhenghui@zh-pc:/media/zhenghui/软件/project/pyProject/qianfan/itchat$ python3 chat.py 
Traceback (most recent call last):
  File "/media/zhenghui/软件/project/pyProject/qianfan/itchat/chat.py", line 1, in <module>
    import itchat1
ModuleNotFoundError: No module named 'itchat1'
(base) zhenghui@zh-pc:/media/zhenghui/软件/project/pyProject/qianfan/itchat$ 

如果没安装成功,可以先尝试把pip升级

代码语言:shell
复制
(base) zhenghui@zh-pc:/media/zhenghui/软件/project/pyProject/qianfan/itchat$ pip install --upgrade pip
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: pip in /media/zhenghui/软件/anaconda3/lib/python3.10/site-packages (23.2.1)
Collecting pip
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/47/6a/453160888fab7c6a432a6e25f8afe6256d0d9f2cbd25971021da6491d899/pip-23.3.1-py3-none-any.whl (2.1 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 2.0 MB/s eta 0:00:00
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 23.2.1
    Uninstalling pip-23.2.1:
      Successfully uninstalled pip-23.2.1
Successfully installed pip-23.3.1
(base) zhenghui@zh-pc:/media/zhenghui/软件/project/pyProject/qianfan/itchat$

然后再安装itchat

对了,我还遇到了版本过低的问题,可以升级一下itchat:

代码语言:shell
复制
(base) zhenghui@zh-pc:/media/zhenghui/软件/project/pyProject/qianfan/itchat$ pip install --upgrade itchat
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: itchat in /media/zhenghui/软件/anaconda3/lib/python3.10/site-packages (1.3.10)
Requirement already satisfied: requests in /media/zhenghui/软件/anaconda3/lib/python3.10/site-packages (from itchat) (2.30.0)
Requirement already satisfied: pyqrcode in /media/zhenghui/软件/anaconda3/lib/python3.10/site-packages (from itchat) (1.2.1)
Requirement already satisfied: pypng in /media/zhenghui/软件/anaconda3/lib/python3.10/site-packages (from itchat) (0.20220715.0)
Requirement already satisfied: charset-normalizer<4,>=2 in /media/zhenghui/软件/anaconda3/lib/python3.10/site-packages (from requests->itchat) (2.0.4)
Requirement already satisfied: idna<4,>=2.5 in /media/zhenghui/软件/anaconda3/lib/python3.10/site-packages (from requests->itchat) (3.4)
Requirement already satisfied: urllib3<3,>=1.21.1 in /media/zhenghui/软件/anaconda3/lib/python3.10/site-packages (from requests->itchat) (2.0.3)
Requirement already satisfied: certifi>=2017.4.17 in /media/zhenghui/软件/anaconda3/lib/python3.10/site-packages (from requests->itchat) (2022.12.7)
(base) zhenghui@zh-pc:/media/zhenghui/软件/project/pyProject/qianfan/itchat$ 

4、创建登陆代码

代码语言:python
代码运行次数:0
复制
import itchat

itchat.auto_login()

短短两行代码就能成功,并且可以微信扫码,惊讶到我了。

手机微信扫码后,就会出现如下界面:

5、给自己的文件助手发消息

代码只需要一行:

代码语言:python
代码运行次数:0
复制
itchat.send('Hello, filehelper', toUserName='filehelper')

一行代码就可以给文件助手发送消息

6、发送文本消息:

代码语言:python
代码运行次数:0
复制
# 发送文本消息给指定好友(通过备注名或昵称)
friend = itchat.search_friends(name="好友的昵称")[0]
itchat.send("Hello, friend!", toUserName=friend['UserName'])

7、接收消息

代码语言:python
代码运行次数:0
复制
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    # 收到文本消息时的回复
    itchat.send("I received: {}".format(msg['Text']), toUserName=msg['FromUserName'])

# 运行itchat
itchat.run()

上述代码中,@itchat.msg_register(itchat.content.TEXT) 装饰器用于注册消息处理函数。在这个例子中,当收到文本消息时,会调用 text_reply 函数发送回复消息。

8、获取好友列表

代码语言:python
代码运行次数:0
复制
friends = itchat.get_friends()
for friend in friends:
    print("昵称: {}, 备注: {}".format(friend['NickName'], friend['RemarkName']))

9、获取群聊消息

代码语言:python
代码运行次数:0
复制
chatrooms = itchat.get_chatrooms()
for chatroom in chatrooms:
    print("群聊名称: {}, 群聊ID: {}".format(chatroom['NickName'], chatroom['UserName']))

10、监听其他的消息

代码语言:python
代码运行次数:0
复制
@itchat.msg_register(itchat.content.FRIENDS)
def add_friend(msg):
    # 自动接受好友请求
    itchat.add_friend(**msg['Text'])
    itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName'])

@itchat.msg_register(itchat.content.TEXT, isGroupChat=True)
def text_reply(msg):
    # 在群聊中接收文本消息
    print(msg['ActualNickName'], ":", msg['Text'])

11、登出和完成后调用特定的方法

代码语言:python
代码运行次数:0
复制
def lc():
    print('finish login')
def ec():
    print('exit')

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

完整实例代码如下:

代码语言:python
代码运行次数:0
复制
#coding=utf8
import itchat
# tuling plugin can be get here:
# https://github.com/littlecodersh/EasierLife/tree/master/Plugins/Tuling
from tuling import get_response

@itchat.msg_register('Text')
def text_reply(msg):
    if u'作者' in msg['Text'] or u'主人' in msg['Text']:
        return u'你可以在这里了解他:https://github.com/littlecodersh'
    elif u'源代码' in msg['Text'] or u'获取文件' in msg['Text']:
        itchat.send('@fil@main.py', msg['FromUserName'])
        return u'这就是现在机器人后台的代码,是不是很简单呢?'
    elif u'获取图片' in msg['Text']:
        itchat.send('@img@applaud.gif', msg['FromUserName']) # there should be a picture
    else:
        return get_response(msg['Text']) or u'收到:' + msg['Text']

@itchat.msg_register(['Picture', 'Recording', 'Attachment', 'Video'])
def atta_reply(msg):
    return ({ 'Picture': u'图片', 'Recording': u'录音',
        'Attachment': u'附件', 'Video': u'视频', }.get(msg['Type']) +
        u'已下载到本地') # download function is: msg['Text'](msg['FileName'])

@itchat.msg_register(['Map', 'Card', 'Note', 'Sharing'])
def mm_reply(msg):
    if msg['Type'] == 'Map':
        return u'收到位置分享'
    elif msg['Type'] == 'Sharing':
        return u'收到分享' + msg['Text']
    elif msg['Type'] == 'Note':
        return u'收到:' + msg['Text']
    elif msg['Type'] == 'Card':
        return u'收到好友信息:' + msg['Text']['Alias']

@itchat.msg_register('Text', isGroupChat = True)
def group_reply(msg):
    if msg['isAt']:
        return u'@%s\u2005%s' % (msg['ActualNickName'],
            get_response(msg['Text']) or u'收到:' + msg['Text'])

@itchat.msg_register('Friends')
def add_friend(msg):
    itchat.add_friend(**msg['Text'])
    itchat.send_msg(u'项目主页:github.com/littlecodersh/ItChat\n'
        + u'源代码  :回复源代码\n' + u'图片获取:回复获取图片\n'
        + u'欢迎Star我的项目关注更新!', msg['RecommendInfo']['UserName'])

itchat.auto_login(True, enableCmdQR=True)
itchat.run()

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 参考资料
  • 安装itchat开发&运行环境
  • 开发案例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档