python使用 itchat結合圖靈微信群機器人回覆原始碼
阿新 • • 發佈:2018-11-16
突然來了下興致,又弄了個前幾個月弄的微信群機器人,功能有好友之間的回覆,群艾特後的回覆。下面是原始碼,有更多的請看其他博文
# -*- 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 '@%[email protected]%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/
更多資源請關注公眾號(蛇崽網盤教程資源 ):
--------------------------------------- 上面是個人資訊 ------------------------------