版权声明:本文为徐代龙原创文章,未经徐代龙允许不得转载。网络资源网站:xudailong.cc 福利网站:www.00reso.com 公众号:蛇崽网盘教程资源 https://blog.csdn.net/xudailong_blog/article/details/83750018
突然来了下兴致,又弄了个前几个月弄的微信群机器人,功能有好友之间的回复,群艾特后的回复。下面是源码,有更多的请看其他博文
# -*- coding: utf-8 -*-
# @Time : 2018/11/5 12:17
# @Author : 蛇崽
# @Email : [email protected]
# @Site : https://blog.csdn.net/xudailong_blog
# @File : test_wx.py
# @Software: PyCharm (微信机器人)
from itchat.content import *
import requests
import json
import itchat
itchat.auto_login(hotReload=True)
# 调用图灵机器人的api,采用爬虫的原理,根据聊天消息返回回复内容
def tuling(info):
appkey = "51aab7fddc564e5c848279eda92be4b2"
url = "http://www.tuling123.com/openapi/api?key=%s&info=%s" % (appkey, info)
req = requests.get(url)
content = req.text
data = json.loads(content)
answer = data['text']
return answer
# 对于群聊信息,定义获取想要针对某个群进行机器人回复的群ID函数
def group_id():
groups = itchat.get_chatrooms(update=True)
for i in range(len(groups)):
group_name = groups[i]['NickName']
if 'xxxx' in group_name:
return group_name
# 注册文本消息,绑定到text_reply处理函数
# text_reply msg_files可以处理好友之间的聊天回复
@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
itchat.send('%s' % tuling(msg['Text']), msg['FromUserName'])
@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
msg['Text'](msg['FileName'])
return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName'])
# 现在微信加了好多群,并不想对所有的群都进行设置微信机器人,只针对想要设置的群进行微信机器人,可进行如下设置
@itchat.msg_register(TEXT, isGroupChat=True)
def group_text_reply(msg):
group_name = group_id()
if msg['isAt']:
msg_text = msg['Text']
info = msg_text
if '我的群昵称' in msg_text:
info = str(msg_text).replace('我的群昵称','')
msg.user.send(u'%s' % tuling(info),group_name)
itchat.run()
上面的源码中需要注意的几点:
1 xxxx是指的是目标群名称, 有些群昵称有的有符号表情,你可以进行简单的中文包含即可。
2 我的群昵称是指的是你在群里面的昵称,而不是你的账号的昵称。这块地方你可以多进行测试一下
3 微信web端多次登录后会出现禁止登录web端的情况,测试的时候请注意你的使用频率。
--------------------------------------- 下面是个人信息 ------------------------------------------------
个人微信:hll643435675(备注:博客)
更多资源请访问:
https://blog.csdn.net/xudailong_blog/article/details/78762262
慕课视频教程:https://blog.csdn.net/xudailong_blog/article/details/82909611
https://xudailong.cc/2018/09/30/muke-courses/
更多资源请关注公众号(蛇崽网盘教程资源 ):
--------------------------------------- 上面是个人信息 ------------------------------