Python使用itchat模块实现群聊转发,自动回复功能示例

yipeiwu_com6年前Python基础

本文实例讲述了Python使用itchat模块实现群聊转发,自动回复功能。分享给大家供大家参考,具体如下:

1.itchat自动把好友发来的消息,回复给他

仅能实现自动回复 原文给 好友发来的文本消息、图片表情消息。

#!/usr/bin/python
#coding=utf-8
import itchat
from itchat.content import *
@itchat.msg_register([PICTURE,TEXT])
def simple_reply(msg):
  if msg['Type'] == TEXT:
    ReplyContent = 'I received message: '+msg['Content']
  if msg['Type'] == PICTURE:
    ReplyContent = 'I received picture: '+msg['FileName']
  itchat.send_msg(ReplyContent,msg['FromUserName'])
itchat.auto_login()
itchat.run()

这里注册了两个消息类型,文本和图片(表情),当微信接收到这两个消息时就会进入注册的函数simple_reply,msg是一个字典类型里面包含了消息数据包,有发送者、接收者、消息类型、消息内容等超多的信息

itchat要注册消息类型,比如注册了TEXT(itchat.content.text),就会接收文本消息,其他消息不会触发函数。消息类型见库中的content.py文件

消息类型判断,msg['Type']
消息发起者,msg['FromUserName']
消息接收者,msg['ToUserName']
文本消息,msg['Content']
文件名字,msg['FileName'],注:如果是自带的表情就会显示表情

2.自动转发指定的群聊消息给指定的好友。

应用场景:每天会在微信群内收集订餐的小伙伴名单,订餐的回复+1,

由于时间跨度,群消息太多,手工上下翻 +1 的消息难免遗漏,所以这段脚本正好满足此需求。

转发的内容是:群内昵称:+1

#!/usr/bin/python
#coding=UTF-8
import itchat
from itchat.content import *
@itchat.msg_register([PICTURE,TEXT],isGroupChat=True)
def simple_reply(msg):
  users = itchat.search_friends(name=u'测试23')#通讯录中好友备注名
  userName = users[0]['UserName']
  if msg['Content'] == "+1":
    itchat.send(u'%s\u2005: %s '%(msg['ActualNickName'],msg['Content']),toUserName=userName)
itchat.auto_login()#enableCmdQR=True 可以在命令行显示二维码
itchat.run()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python中的map、reduce和filter浅析

1、先看看什么是 iterable 对象 以内置的max函数为例子,查看其doc:复制代码 代码如下:>>> print max.__doc__max(iterable...

Python 循环终止语句的三种方法小结

在Python循环终止语句有三种: 1、break break用于退出本层循环 示例如下: while True: print "123" break print "45...

Linux下使用python自动修改本机网关代码分享

#!/usr/bin/python #auto change gateway Created By mickelfeng import os import random,re g='...

pytorch实现mnist数据集的图像可视化及保存

pytorch实现mnist数据集的图像可视化及保存

如何将pytorch中mnist数据集的图像可视化及保存 导出一些库 import torch import torchvision import torch.utils.data...

在Python中使用pngquant压缩png图片的教程

说到png图片压缩,可能很多人知道TinyPNG这个网站。但PS插件要钱(虽然有破解的),Developer API要连到他服务器去,不提网络传输速度,Key也是有每月限制的。 &nbs...