Skip to content

Instantly share code, notes, and snippets.

@fanlushuai
Created December 4, 2023 09:16
Show Gist options
  • Save fanlushuai/e9fa72e6e94b644b88dfdf90b0d5fcd5 to your computer and use it in GitHub Desktop.
Save fanlushuai/e9fa72e6e94b644b88dfdf90b0d5fcd5 to your computer and use it in GitHub Desktop.
分析微信消息情感,对某一个用户消极情感,进行关爱提醒。
# -*- coding: utf-8 -*-
import cntext
from itchat.content import *
import itchat, time
import requests
# {'a': {'lastTime': 1701659203, 'banScore': 0}, 'b': {'lastTime': 1701659203, 'banScore': 0}, 'c': {'lastTime': 1701659201, 'banScore': 2}}
banStatistics = {}
cnDiction = cntext.load_pkl_dict("DUTIR.pkl")["DUTIR"]
def genScore(text):
r = cntext.sentiment(
text=text,
diction=cnDiction,
lang="chinese",
)
# {'乐_num': 0, '好_num': 0, '怒_num': 0, '哀_num': 0, '惧_num': 0, '恶_num': 0, '惊_num': 0, 'stopword_num': 0, 'word_num': 1, 'sentence_num': 1}
print(r)
return r["恶_num"]
def FBI(memberName, text):
accumulateTimeRangeSec = 30 * 60 # 30分钟
currentTimeSec = int(time.time())
if banStatistics.get(memberName) == None:
banStatistics.setdefault(memberName, {})["lastTime"] = currentTimeSec
banStatistics.setdefault(memberName, {})["banScore"] = 0
lastAddBanCountTimeSec = banStatistics[memberName]["lastTime"]
if currentTimeSec - lastAddBanCountTimeSec > accumulateTimeRangeSec:
banStatistics[memberName] = {}
else:
textBanScore = genScore(text)
newScore = banStatistics[memberName]["banScore"] + textBanScore
banStatistics[memberName] = {"lastTime": currentTimeSec, "banScore": newScore}
scoreLimit = 5
print(banStatistics[memberName]["banScore"])
if banStatistics[memberName]["banScore"] > scoreLimit:
banStatistics[memberName]["banScore"] = 3
return True
return False
def getSayLove():
try:
return requests.post("https://api.qqsuu.cn/api/dm-saylove").json()["data"][
"content"
]
except:
return "从前车马很慢,书信很远,一生只够爱一个人。"
def SendChatRoomsMsg(gname, context):
# 获取群组所有的相关信息(注意最好群聊保存到通讯录)
myroom = itchat.get_chatrooms(update=True)
# myroom = itchat.get_chatrooms()
# 定义全局变量(也可以不定义)
global username
# 传入指定群名进行搜索,之所以搜索,是因为群员的名称信息也在里面
myroom = itchat.search_chatrooms(name=gname)
for room in myroom:
# print(room)
# 遍历所有NickName为键值的信息进行匹配群名
if room["NickName"] == gname:
username = room["UserName"]
# 得到群名的唯一标识,进行信息发送
itchat.send_msg(context, username)
else:
print("No groups found")
@itchat.msg_register(TEXT, isGroupChat=True)
def text_reply(msg):
content = msg["Content"]
nickName = msg["ActualNickName"]
fromUserName = msg["FromUserName"]
print(fromUserName)
if FBI(nickName, content):
lovelyContent = getSayLove()
backMsg = "@%s %s [小笔记已经记你 %s 次]" % (
nickName,
lovelyContent,
banStatistics[nickName]["banScore"],
)
print(backMsg)
# todo 此处修改为自己的群聊。
SendChatRoomsMsg("a", backMsg)
itchat.auto_login()
itchat.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment