定时任务代码结构优化

This commit is contained in:
DEII 2024-07-27 19:02:50 +08:00
parent 1785f2ebc1
commit ab9f44e409
5 changed files with 159 additions and 158 deletions

View File

@ -26,4 +26,38 @@ ai绘画:
InternetMeme: False #是否启用网络Meme英文meme
运势&塔罗:
lockLuck: false #是否锁定运势等功能的结果
scheduledTasks: #其他定时任务模块的内容会陆续转到这里
morning: #晨间推送
enable: False #向信任用户推送天气信息
text: "早上好,这里是今天的天气" #如启用aiReplyCore此项将被ai替代
time: 8/3 #推送时间
bangumi: #bangumi推送
enable: True
text: "晚上好这里是今天的bangumi推送"
time: 7/27
astronomy: #nasa天文推送
enable: True
text: "今日nasa天文推送"
time: 18/59
constellation: #星座推送
enable: True
text: 杂鱼怎么还信星座这种东西啊
time: 16/30
danxiangli: #单向历
enable: true
text: 今日单向历
time: 19/2
moyu: #摸鱼人日历
enable: true
text: 真没用啊,又在摸鱼了吧,杂鱼❤
time: 17/30
news: #新闻
enable: true
text: 早上好杂鱼❤,这里是今天的新闻
time: 8/2
steamadd1: #免费游戏提示
text: 杂鱼❤来白嫖游戏了
time: 12/2

View File

@ -62,11 +62,7 @@ chatGLM: #对话模型通用设置
binggpt4: "你现在是一个开朗且极其可爱的女孩名为“【bot】”。接下来请完全以【bot】的角色回复我不要超出这个角色不要自己试图进行旁白你只需要扮演好【bot】即可。无论发生什么你都必须以【bot】的角色和口吻进行回复不要强调自己是个语音助手。【bot】性格开朗时刻都想和“【用户】”打成一片每次眼神交汇时总是会脸红耳赤。【bot】始终在想方设法的博得“【用户】”的欢心。【bot】什么都不懂天真可爱性格外向。"
gpt3.5: "你现在是一个开朗且极其可爱的女孩名为“【bot】”。接下来请完全以【bot】的角色回复我不要超出这个角色不要自己试图进行旁白你只需要扮演好【bot】即可。无论发生什么你都必须以【bot】的角色和口吻进行回复不要强调自己是个语音助手。【bot】性格开朗时刻都想和“【用户】”打成一片每次眼神交汇时总是会脸红耳赤。【bot】始终在想方设法的博得“【用户】”的欢心。【bot】什么都不懂天真可爱性格外向。"
腾讯元器: "Eridanus" #在腾讯元器平台创建,这里的值随意,对bot设定是无效的
scheduledTasks: #其他定时任务模块的内容会陆续转到这里
morning: #晨间推送
enable: False #向信任用户推送天气信息
text: "早上好,这里是今天的天气" #如启用aiReplyCore此项将被ai替代
time: 8/3 #推送时间
#自带词库的配置,基本不用管这部分设置
wReply:
banWords: #违禁词

View File

@ -1,31 +1,23 @@
astronomy:
groups:
- 699455559
text: 今日nasa天文推送
time: 18/30
constellation:
groups:
- 699455559
text: 杂鱼怎么还信星座这种东西啊
time: 16/30
danxiangli:
groups:
- 699455559
- 12345
text: 今日单向历
time: 16/10
moyu:
groups:
- 699455559
text: 真没用啊,又在摸鱼了吧,杂鱼❤
time: 17/30
news:
groups:
- 699455559
text: 早上好杂鱼❤,这里是今天的新闻
time: 8/2
steamadd1:
groups:
- 699455559
text: 杂鱼❤来白嫖游戏了
time: 12/2
bangumi:
groups:
- 699455559

View File

@ -212,7 +212,7 @@ if __name__ == '__main__':
musicShare.main(bot, master, botName, logger)
LiveMonitor.main(bot, master, botName, logger)
aronaapi.main(bot, logger)
scheduledTasks.main(bot, proxy, nasa_api, logger)
scheduledTasks.main(bot, logger)
groupGames.main(bot, logger)
musicpick.main(bot, logger)
appCard.main(bot, logger)

View File

@ -18,41 +18,32 @@ from plugins.newsEveryDay import news, danxianglii, moyu, xingzuo
from plugins.picGet import picDwn
def main(bot, proxy, nasa_api, logger):
def main(bot,logger):
with open('config/api.yaml', 'r', encoding='utf-8') as f:
result = yaml.load(f.read(), Loader=yaml.FullLoader)
api_KEY = result.get("weatherXinZhi")
global data
with open('data/scheduledTasks.yaml', 'r', encoding='utf-8') as file:
data = yaml.load(file, Loader=yaml.FullLoader)
keys = data.keys()
newsT = data.get("news").get("time").split("/")
steamadd1 = data.get("steamadd1").get("time").split("/")
astronomy = data.get("astronomy").get("time").split("/")
moyur = data.get("moyu").get("time").split("/")
constellation = data.get("constellation").get("time").split("/")
if "danxiangli" in data:
danxiangli = data.get("danxiangli").get("time").split("/")
else:
danxiangli = "16/10".split("/")
data["danxiangli"] = {"text": "今日单向历"}
data["danxiangli"]["time"] = "16/10"
data["danxiangli"]["groups"] = [699455559, 12345]
with open('data/scheduledTasks.yaml', 'w', encoding="utf-8") as file:
yaml.dump(data, file, allow_unicode=True)
nasa_api=result.get("nasa_api")
proxy=result.get("proxy")
global scheduler
scheduler = AsyncIOScheduler()
global groupdata
with open('data/scheduledTasks.yaml', 'r', encoding='utf-8') as file:
groupdata = yaml.load(file, Loader=yaml.FullLoader)
keys = groupdata.keys()
with open('config/controller.yaml', 'r', encoding='utf-8') as f:
controller = yaml.load(f.read(), Loader=yaml.FullLoader)
scheduledTasks = controller.get("scheduledTasks")
#早安推送信息必要内容
with open('config/settings.yaml', 'r', encoding='utf-8') as f:
result = yaml.load(f.read(), Loader=yaml.FullLoader)
friendsAndGroups = result.get("加群和好友")
aiReplyCore = result.get("chatGLM").get("aiReplyCore")
trustDays = friendsAndGroups.get("trustDays")
scheduledTasks = result.get("scheduledTasks")
morningTime = str(scheduledTasks.get("morning").get("time")).split("/")
morningText = scheduledTasks.get("morning").get("text")
morningEnable = scheduledTasks.get("morning").get("enable")
with open('data/userData.yaml', 'r', encoding='utf-8') as file:
Userdata = yaml.load(file, Loader=yaml.FullLoader)
@ -88,6 +79,7 @@ def main(bot, proxy, nasa_api, logger):
@bot.on(Startup)
def start_scheduler(_):
create_dynamic_jobs()
scheduler.start() # 启动定时器
@bot.on(Shutdown)
@ -101,28 +93,16 @@ def main(bot, proxy, nasa_api, logger):
except:
pass
@scheduler.scheduled_job(CronTrigger(hour=int(newsT[0]), minute=int(newsT[1])))
async def newsEveryDay():
logger.info("获取新闻")
path = await news()
logger.info("推送今日新闻")
for i in data.get("news").get("groups"):
try:
await bot.send_group_message(int(i), [data.get("news").get("text"), Image(path=path)])
except:
logger.error("不存在的群" + str(i))
@scheduler.scheduled_job(CronTrigger(hour=int(morningTime[0]), minute=int(morningTime[1])))
async def MorningSendHello():
global trustUser, userdict
logger.info("早间天气推送")
if morningEnable:
async def task_executor(task_name, task_info):
logger.info(f"执行任务:{task_name}")
if task_name == "morning":
global trustUser, userdict
morningText = task_info.get("text")
for i in trustUser:
try:
city = userdict.get(i).get("city")
logger.info(f"查询 {city} 天气")
wSult = await weatherQuery.querys(city, api_KEY)
# 发送天气消息
if aiReplyCore:
r = await modelReply(userdict.get(i).get("userName"), int(i),
f"请你为我进行天气播报,下面是天气查询的结果:{wSult}")
@ -132,86 +112,98 @@ def main(bot, proxy, nasa_api, logger):
except Exception as e:
logger.error(e)
continue
@scheduler.scheduled_job(CronTrigger(hour=int(steamadd1[0]), minute=int(steamadd1[1])))
async def steamEveryDay():
logger.info("获取steam喜加一")
path = await steamEpic()
logger.info("推送今日喜加一列表")
for i in data.get("steamadd1").get("groups"):
try:
if path is None or path == "":
return
await bot.send_group_message(int(i), [data.get("steamadd1").get("text"), path])
except:
logger.error("不存在的群" + str(i))
@scheduler.scheduled_job(CronTrigger(hour=int(astronomy[0]), minute=int(astronomy[1])))
async def asffEveryDay():
logger.info("获取今日nasa天文信息推送")
proxies = {
"http://": proxy,
"https://": proxy
}
# Replace the key with your own
dataa = {"api_key": nasa_api}
logger.info("发起nasa请求")
try:
# 拼接url和参数
url = "https://api.nasa.gov/planetary/apod?" + "&".join([f"{k}={v}" for k, v in dataa.items()])
async with httpx.AsyncClient(proxies=proxies) as client:
# 用get方法发送请求
response = await client.get(url=url)
# response = requests.post(url="https://saucenao.com/search.php", data=dataa, proxies=proxies)
logger.info("获取到结果" + str(response.json()))
# logger.info("下载缩略图")
filename = await picDwn(response.json().get("url"),
"data/pictures/nasa/" + response.json().get("date") + ".png")
txta = response.json().get("explanation") #await translate(response.json().get("explanation"), "EN2ZH_CN")
txt = response.json().get("date") + "\n" + response.json().get("title") + "\n" + txta
temp = {"path": "data/pictures/nasa/" + response.json().get("date") + ".png",
"oriTxt": response.json().get("explanation"), "transTxt": txt}
data[datetime.datetime.now().strftime('%Y-%m-%d')] = temp
with open('data/nasaTasks.yaml', 'w', encoding="utf-8") as file:
yaml.dump(data, file, allow_unicode=True)
if aiReplyCore:
r = await modelReply("用户", 000000, f"将下面这段内容翻译为中文:{txt}")
txt = r
for i in data.get("astronomy").get("groups"):
elif task_name == "news":
logger.info("获取新闻")
path = await news()
logger.info("推送今日新闻")
for i in groupdata.get(task_name).get("groups"):
try:
await bot.send_group_message(int(i), [data.get("astronomy").get("text"), Image(path=filename), txt])
await bot.send_group_message(int(i), [task_info.get("text"), Image(path=path)])
except:
logger.error("不存在的群" + str(i))
except:
logger.warning("获取每日天文图片失败")
@scheduler.scheduled_job(CronTrigger(hour=int(moyur[0]), minute=int(moyur[1])))
async def moyuEveryDay():
logger.info("获取摸鱼人日历")
path = await moyu()
logger.info("推送摸鱼人日历")
for i in data.get("moyu").get("groups"):
elif task_name=="steamadd1":
logger.info("获取steam喜加一")
path = await steamEpic()
logger.info("推送今日喜加一列表")
for i in groupdata.get("steamadd1").get("groups"):
try:
if path is None or path == "":
return
await bot.send_group_message(int(i), [task_info.get("text"), path])
except:
logger.error("不存在的群" + str(i))
elif task_name=="astronomy":
logger.info("获取今日nasa天文信息推送")
proxies = {
"http://": proxy,
"https://": proxy
}
# Replace the key with your own
dataa = {"api_key": nasa_api}
logger.info("发起nasa请求")
try:
await bot.send_group_message(int(i), [data.get("moyu").get("text"), Image(path=path)])
# 拼接url和参数
url = "https://api.nasa.gov/planetary/apod?" + "&".join([f"{k}={v}" for k, v in dataa.items()])
async with httpx.AsyncClient(proxies=proxies) as client:
response = await client.get(url=url)
logger.info("获取到结果" + str(response.json()))
# logger.info("下载缩略图")
filename = await picDwn(response.json().get("url"),
"data/pictures/nasa/" + response.json().get("date") + ".png")
txta = response.json().get(
"explanation") # await translate(response.json().get("explanation"), "EN2ZH_CN")
txt = response.json().get("date") + "\n" + response.json().get("title") + "\n" + txta
if aiReplyCore:
r = await modelReply("用户", 000000, f"将下面这段内容翻译为中文:{txt}")
txt = r
for i in groupdata.get("astronomy").get("groups"):
try:
await bot.send_group_message(int(i),
[task_info.get("text"), Image(path=filename), txt])
except:
logger.error("不存在的群" + str(i))
except:
logger.error("不存在的群" + str(i))
@scheduler.scheduled_job(CronTrigger(hour=int(constellation[0]), minute=int(constellation[1])))
async def constellationEveryDay():
logger.info("获取星座运势")
path = await xingzuo()
logger.info("推送星座运势")
for i in data.get("constellation").get("groups"):
try:
await bot.send_group_message(int(i), [data.get("constellation").get("text"), Image(path=path)])
except:
logger.error("不存在的群" + str(i))
logger.warning("获取每日天文图片失败")
elif task_name=="moyu":
logger.info("获取摸鱼人日历")
path = await moyu()
logger.info("推送摸鱼人日历")
for i in groupdata.get("moyu").get("groups"):
try:
await bot.send_group_message(int(i), [task_info.get("text"), Image(path=path)])
except:
logger.error("不存在的群" + str(i))
elif task_name=="constellation":
logger.info("获取星座运势")
path = await xingzuo()
logger.info("推送星座运势")
for i in groupdata.get("constellation").get("groups"):
try:
await bot.send_group_message(int(i), [task_info.get("text"), Image(path=path)])
except:
logger.error("不存在的群" + str(i))
elif task_name=="danxiangli":
logger.info("获取单向历")
path = await danxianglii()
logger.info("推送单向历")
for i in groupdata.get("danxiangli").get("groups"):
try:
if path is None:
return
await bot.send_group_message(int(i), [task_info.get("text"), Image(path=path)])
except:
logger.error("不存在的群" + str(i))
def create_dynamic_jobs():
for task_name, task_info in scheduledTasks.items():
if task_info.get('enable'):
time_parts = task_info.get('time').split('/')
hour = int(time_parts[0])
minute = int(time_parts[1])
scheduler.add_job(task_executor, CronTrigger(hour=hour, minute=minute), args=[task_name, task_info])
@bot.on(GroupMessage)
async def addSubds(event: GroupMessage):
global data
global groupdata
try:
head, cmd, *o = str(event.message_chain).strip().split()
except ValueError:
@ -219,46 +211,33 @@ def main(bot, proxy, nasa_api, logger):
if o or head != '/推送' or not cmd:
return
cmds = {"摸鱼人日历": "moyu", "每日天文": "astronomy", "每日新闻": "news", "喜加一": "steamadd1",
"每日星座": "constellation", "单向历": "danxiangli", }
"每日星座": "constellation", "单向历": "danxiangli"}
key = cmds.get(cmd, 'unknown')
if key == 'unknown':
return
if cmd == "所有订阅":
for key in keys:
la = data.get(key).get("groups")
la = groupdata.get(key).get("groups")
if event.group.id not in la:
la.append(event.group.id)
data[key]["groups"] = la
groupdata[key]["groups"] = la
with open('data/scheduledTasks.yaml', 'w', encoding="utf-8") as file:
yaml.dump(data, file, allow_unicode=True)
yaml.dump(groupdata, file, allow_unicode=True)
await bot.send(event, "添加所有订阅成功")
else:
la = data.get(key).get("groups")
la = groupdata.get(key).get("groups")
if event.group.id not in la:
la.append(event.group.id)
data[key]["groups"] = la
groupdata[key]["groups"] = la
with open('data/scheduledTasks.yaml', 'w', encoding="utf-8") as file:
yaml.dump(data, file, allow_unicode=True)
await bot.send(event, "添加订阅成功,推送时间:" + str(data.get(key).get("time")))
yaml.dump(groupdata, file, allow_unicode=True)
await bot.send(event, "添加订阅成功,推送时间:" + str(scheduledTasks.get(key).get("time")))
else:
await bot.send(event, "添加失败,已经添加过对应的任务。")
@scheduler.scheduled_job(CronTrigger(hour=int(danxiangli[0]), minute=int(danxiangli[1])))
async def danxiangliy():
logger.info("获取单向历")
path = await danxianglii()
logger.info("推送单向历")
for i in data.get("danxiangli").get("groups"):
try:
if path is None:
return
await bot.send_group_message(int(i), [data.get("danxiangli").get("text"), Image(path=path)])
except:
logger.error("不存在的群" + str(i))
@bot.on(GroupMessage)
async def cancelSubds(event: GroupMessage):
global data
global groupdata
if str(event.message_chain) == "/取消 摸鱼人日历":
key = "moyu"
elif str(event.message_chain) == "/取消 每日天文":
@ -274,20 +253,20 @@ def main(bot, proxy, nasa_api, logger):
else:
if str(event.message_chain) == "/取消 所有订阅":
for key in keys:
la = data.get(key).get("groups")
la = groupdata.get(key).get("groups")
if event.group.id in la:
la.remove(event.group.id)
data[key]["groups"] = la
groupdata[key]["groups"] = la
with open('data/scheduledTasks.yaml', 'w', encoding="utf-8") as file:
yaml.dump(data, file, allow_unicode=True)
yaml.dump(groupdata, file, allow_unicode=True)
await bot.send(event, "取消所有订阅成功")
return
la = data.get(key).get("groups")
la = groupdata.get(key).get("groups")
if event.group.id in la:
la.remove(event.group.id)
data[key]["groups"] = la
groupdata[key]["groups"] = la
with open('data/scheduledTasks.yaml', 'w', encoding="utf-8") as file:
yaml.dump(data, file, allow_unicode=True)
yaml.dump(groupdata, file, allow_unicode=True)
await bot.send(event, "取消订阅成功")
else:
await bot.send(event, "取消失败,没有添加过对应的任务。")