Skip to content

Commit

Permalink
私聊定制群定时任务功能(同时支持itchat、ntchat)
Browse files Browse the repository at this point in the history
  • Loading branch information
haikerwang committed Sep 17, 2023
1 parent 1f0a420 commit 698cd66
Show file tree
Hide file tree
Showing 2 changed files with 115 additions and 10 deletions.
80 changes: 80 additions & 0 deletions Tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
from channel.chat_message import ChatMessage
from croniter import croniter
import threading
try:
from channel.wechatnt.ntchat_channel import wechatnt
except Exception as e:
print(f"未安装ntchat: {e}")

class ExcelTool(object):
__file_name = "timeTask.xlsx"
Expand Down Expand Up @@ -812,3 +816,79 @@ def get_cron_expression(self):
tempValue = tempValue.replace("Cron[", "")
tempValue = tempValue.replace("]", "")
return tempValue

#是否 私聊制定群任务
def isPerson_makeGrop(self):
tempValue = self.eventStr.endswith("]")
tempValue1 = "group[" in self.eventStr or "Group[" in self.eventStr
return tempValue and tempValue1

#获取私聊制定群任务的群Title、事件
def get_Persion_makeGropTitle_eventStr(self):
index = -1
targetStr = self.eventStr
if "group[" in targetStr:
index = targetStr.index("group[")
elif "Group[" in targetStr:
index = targetStr.index("Group[")
if index < 0:
return "", targetStr

substring_event = targetStr[:index]
substring_groupTitle = targetStr[index + 1:]
substring_groupTitle = substring_groupTitle.replace("]", "").strip()
return substring_event, substring_groupTitle

#通过 群Title 获取群ID
def get_gropID_withGroupTitle(self, groupTitle, channel_name):
if len(groupTitle) <= 0:
return ""
#itchat
if channel_name == "wx":
tempRoomId = ""
#群聊处理
try:
#群聊
chatrooms = itchat.get_chatrooms(update=True)[1:]
#获取群聊
for chatroom in chatrooms:
#id
userName = chatroom["UserName"]
NickName = chatroom["NickName"]
if NickName == groupTitle:
tempRoomId = userName
break

return tempRoomId
except Exception as e:
print(f"通过 群Title 获取群ID发生错误,错误信息为:{e}")
return tempRoomId


elif channel_name == "nt":
tempRoomId = ""
try:
#数据结构为字典数组
rooms = wechatnt.get_rooms()
if len(rooms) > 0:
#遍历
for item in rooms:
roomId = item.get("wxid")
nickname = item.get("nickname")
if nickname == groupTitle:
tempRoomId = roomId
break

return tempRoomId

except Exception as e:
print(f"通过 群Title 获取群ID发生错误,错误信息为:{e}")
return tempRoomId
else:
print(f"通过 群Title 获取群ID 不支持的channel,channel为:{channel_name}")






45 changes: 35 additions & 10 deletions timetask.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from channel.chat_message import ChatMessage
import logging
from plugins import *
import logging
from plugins.timetask.TimeTaskTool import TaskManager
from plugins.timetask.config import conf, load_config
from plugins.timetask.Tool import TimeTaskModel
Expand Down Expand Up @@ -36,7 +35,7 @@ class TimeTaskRemindType(Enum):
desire_priority=500,
hidden=True,
desc="定时任务系统,可定时处理事件",
version="2.4",
version="2.5",
author="haikerwang",
)

Expand Down Expand Up @@ -196,6 +195,13 @@ def add_timeTask(self, content, e_context: EventContext):
if not taskModel.isValid_Cron_time():
self.replay_use_default(defaultErrorMsg, e_context)
return

#私人为群聊任务
if taskModel.isPerson_makeGrop():
newEvent, groupTitle = taskModel.get_Persion_makeGropTitle_eventStr()
if len(groupTitle) <= 0 or len(newEvent) <= 0 :
self.replay_use_default(defaultErrorMsg, e_context)
return

#task入库
taskId = self.taskManager.addTask(taskModel)
Expand Down Expand Up @@ -295,7 +301,26 @@ def replay_use_custom(self, model: TimeTaskModel, reply_text: str, replyType: Re
#执行定时task
def runTimeTask(self, model: TimeTaskModel):

print("触发了定时任务:{} , 任务详情:{}".format(model.taskId, model.eventStr))
#事件内容
eventStr = model.eventStr
#发送的用户ID
other_user_id = model.other_user_id
#是否群聊
isGroup = model.isGroup

#是否个人为群聊制定的任务
if model.isPerson_makeGrop():
newEvent, groupTitle = model.get_Persion_makeGropTitle_eventStr()
eventStr = newEvent
channel_name = RobotConfig.conf().get("channel_type", "wx")
groupId = model.get_gropID_withGroupTitle(groupTitle , channel_name)
other_user_id = groupId
isGroup = True
if len(groupId) <= 0:
logging.error(f"通过群标题【{groupTitle}】,未查到对应的群ID, 跳过本次消息")
return

print("触发了定时任务:{} , 任务详情:{}".format(model.taskId, eventStr))

#去除多余字符串
orgin_string = model.originMsg.replace("ChatMessage:", "")
Expand All @@ -305,21 +330,21 @@ def runTimeTask(self, model: TimeTaskModel):
# 创建字典
content_dict = {match[0]: match[1] for match in matches}
#替换源消息中的指令
content_dict["content"] = model.eventStr
content_dict["content"] = eventStr
#添加必要key
content_dict["receiver"] = model.other_user_id
content_dict["session_id"] = model.other_user_id
content_dict["isgroup"] = model.isGroup
content_dict["receiver"] = other_user_id
content_dict["session_id"] = other_user_id
content_dict["isgroup"] = isGroup
msg : ChatMessage = ChatMessage(content_dict)
content_dict["msg"] = msg
context = Context(ContextType.TEXT, model.eventStr, content_dict)
context = Context(ContextType.TEXT, eventStr, content_dict)

#查看配置中是否开启拓展功能
is_open_extension_function = self.conf.get("is_open_extension_function", True)
#需要拓展功能
if is_open_extension_function:
#事件字符串
event_content = model.eventStr
event_content = eventStr
#支持的功能
funcArray = self.conf.get("extension_function", [])
#是否是GPT消息
Expand Down Expand Up @@ -392,7 +417,7 @@ def runTimeTask(self, model: TimeTaskModel):
current_time_without_seconds = current_time.floor('minute')
# 转换为指定格式的字符串
formatted_time = current_time_without_seconds.format("YYYY-MM-DD HH:mm:ss")
reply_text = f"⏰叮铃铃,定时任务时间已到啦~\n【当前时间】:{formatted_time}\n【任务编号】:{model.taskId}\n【任务详情】:{model.eventStr}"
reply_text = f"⏰叮铃铃,定时任务时间已到啦~\n【当前时间】:{formatted_time}\n【任务编号】:{model.taskId}\n【任务详情】:{eventStr}"
replyType = ReplyType.TEXT

#消息回复
Expand Down

0 comments on commit 698cd66

Please sign in to comment.