Skip to content

Commit

Permalink
增加 ntfy 通知 (#2537)
Browse files Browse the repository at this point in the history
Co-authored-by: qiaoyun680 <qiaoyun680>
  • Loading branch information
qiaoyun680 authored Oct 22, 2024
1 parent 3822c37 commit 185fd2f
Show file tree
Hide file tree
Showing 9 changed files with 1,142 additions and 4 deletions.
9 changes: 8 additions & 1 deletion back/data/notify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export enum NotificationMode {
'feishu' = 'feishu',
'webhook' = 'webhook',
'chronocat' = 'Chronocat',
'ntfy' = 'ntfy',
}

abstract class NotificationBaseInfo {
Expand Down Expand Up @@ -139,6 +140,11 @@ export class LarkNotification extends NotificationBaseInfo {
public larkKey = '';
}

export class NtfyNotification extends NotificationBaseInfo {
public ntfyUrl = '';
public ntfyTopic = '';
public ntfyPriority = '';
}
export interface NotificationInfo
extends GoCqHttpBotNotification,
GotifyNotification,
Expand All @@ -158,5 +164,6 @@ export interface NotificationInfo
PushMeNotification,
WebhookNotification,
ChronocatNotification,
LarkNotification {}
LarkNotification,
NtfyNotification {}

23 changes: 22 additions & 1 deletion back/services/notify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export default class NotificationService {
['webhook', this.webhook],
['lark', this.lark],
['chronocat', this.chronocat],
['ntfy', this.ntfy],
]);

private title = '';
Expand Down Expand Up @@ -516,7 +517,7 @@ export default class NotificationService {
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
}
}

private async pushPlus() {
const { pushPlusToken, pushPlusUser } = this.params;
Expand Down Expand Up @@ -661,6 +662,26 @@ export default class NotificationService {
}
}

private async ntfy() {
const { ntfyUrl, ntfyTopic, ntfyPriority } = this.params;
try {
const res: any = await got
.post(`${ntfyUrl || 'https://ntfy.sh'}/${ntfyTopic}`, {
...this.gotOption,
body: `${this.title}\n${this.content}`,
headers: { 'Title': 'qinglong', 'Priority': `${ntfyPriority || '3'}` },
});
if (res.statusCode === 200) {
return true;
} else {
throw new Error(JSON.stringify(res));
}
} catch (error: any) {
throw new Error(error.response ? error.response.body : error);
}
}


private async chronocat() {
const { chronocatURL, chronocatQQ, chronocatToken } = this.params;
try {
Expand Down
12 changes: 11 additions & 1 deletion sample/config.sample.sh
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,17 @@ export FSKEY=""
export QMSG_KEY=""
export QMSG_TYPE=""

## 20. 自定义通知
## 20.Ntfy
## 官方文档: https://docs.ntfy.sh
## ntfy_url 填写ntfy地址,如https://ntfy.sh
## ntfy_topic 填写ntfy的消息应用topic
## ntfy_priority 填写推送消息优先级,默认为3
export NTFY_URL=""
export NTFY_TOPIC=""
export NTFY_PRIORITY="3"


## 21. 自定义通知
## 自定义通知 接收回调的URL
export WEBHOOK_URL=""
## WEBHOOK_BODY 和 WEBHOOK_HEADERS 多个参数时,直接换行或者使用 $'\n' 连接多行字符串,比如 export dd="line 1"$'\n'"line 2"
Expand Down
41 changes: 41 additions & 0 deletions sample/notify.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ const push_config = {
WEBHOOK_HEADERS: '', // 自定义通知 请求头
WEBHOOK_METHOD: '', // 自定义通知 请求方法
WEBHOOK_CONTENT_TYPE: '', // 自定义通知 content-type

NTFY_URL: '', // ntfy地址,如https://ntfy.sh,默认为https://ntfy.sh
NTFY_TOPIC: '', // ntfy的消息应用topic
NTFY_PRIORITY: '3', // 推送消息优先级,默认为3
};

for (const key in push_config) {
Expand Down Expand Up @@ -1188,6 +1192,42 @@ function webhookNotify(text, desp) {
});
}

function ntfyNotify(text, desp) {
return new Promise((resolve) => {
const { NTFY_URL, NTFY_TOPIC, NTFY_PRIORITY } = push_config;
if (NTFY_TOPIC) {
const options = {
url: NTFY_URL || `https://ntfy.sh`,
body: `${desp}\n${text}`,
headers: {
'Title': 'qinglong',
'Priority': NTFY_PRIORITY || '3'
},
timeout,
};
$.post(options, (err, resp, data) => {
try {
if (err) {
console.log('Ntfy 通知调用API失败😞\n', err);
} else {
if (data.success) {
console.log('Ntfy 发送通知消息成功🎉\n');
} else {
console.log(`Ntfy 发送通知消息异常 ${JSON.stringify(data)}`);
}
}
} catch (e) {
$.logErr(e, resp);
} finally {
resolve(data);
}
});
} else {
resolve();
}
});
}

function parseString(input, valueFormatFn) {
const regex = /(\w+):\s*((?:(?!\n\w+:).)*)/g;
const matches = {};
Expand Down Expand Up @@ -1316,6 +1356,7 @@ async function sendNotify(text, desp, params = {}) {
chronocatNotify(text, desp), // Chronocat
webhookNotify(text, desp), // 自定义通知
qmsgNotify(text, desp), // 自定义通知
ntfyNotify(text, desp), // Ntfy
]);
}

Expand Down
33 changes: 32 additions & 1 deletion sample/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ def print(text, *args, **kw):
'WEBHOOK_HEADERS': '', # 自定义通知 请求头
'WEBHOOK_METHOD': '', # 自定义通知 请求方法
'WEBHOOK_CONTENT_TYPE': '' # 自定义通知 content-type

'NTFY_URL': '', # ntfy地址,如https://ntfy.sh
'NTFY_TOPIC': '', # ntfy的消息应用topic
'NTFY_PRIORITY':'3', # 推送消息优先级,默认为3
}
# fmt: on

Expand Down Expand Up @@ -777,6 +781,32 @@ def chronocat(title: str, content: str) -> None:
print(f"QQ群消息:{ids}推送失败!")


def ntfy(title: str, content: str) -> None:
"""
通过 Ntfy 推送消息
"""
if not push_config.get("NTFY_TOPIC"):
print("ntfy 服务的 NTFY_TOPIC 未设置!!\n取消推送")
return
print("ntfy 服务启动")
priority = '3'
if not push_config.get("NTFY_PRIORITY"):
print("ntfy 服务的NTFY_PRIORITY 未设置!!默认设置为3")
else:
priority = push_config.get("NTFY_PRIORITY")
data = (title + "\n" +content).encode(encoding='utf-8')
headers = {
"Title": "qinglong",
"Priority": priority
}
url = push_config.get("NTFY_URL") + "/" + push_config.get("NTFY_TOPIC")
response = requests.post(url, data=data, headers=headers)

if response["code"] == 200:
print("Ntfy 推送成功!")
else:
print("Ntfy 推送失败!错误信息:", response)

def parse_headers(headers):
if not headers:
return {}
Expand Down Expand Up @@ -937,7 +967,8 @@ def add_notify_function():
notify_function.append(chronocat)
if push_config.get("WEBHOOK_URL") and push_config.get("WEBHOOK_METHOD"):
notify_function.append(custom_notify)

if push_config.get("NTFY_TOPIC"):
notify_function.append(ntfy)
if not notify_function:
print(f"无推送渠道,请检查通知变量是否正确")
return notify_function
Expand Down
Loading

0 comments on commit 185fd2f

Please sign in to comment.