91 lines
2.4 KiB
Go
91 lines
2.4 KiB
Go
|
|
package main
|
||
|
|
|
||
|
|
import (
|
||
|
|
"flag"
|
||
|
|
"fmt"
|
||
|
|
"os"
|
||
|
|
"os/exec"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
func main() {
|
||
|
|
// 定义命令行参数
|
||
|
|
var message string
|
||
|
|
var title string
|
||
|
|
|
||
|
|
flag.StringVar(&message, "message", "", "通知消息内容")
|
||
|
|
flag.StringVar(&title, "title", "提醒", "通知标题")
|
||
|
|
flag.Parse()
|
||
|
|
|
||
|
|
// 检查是否提供了消息参数
|
||
|
|
if message == "" {
|
||
|
|
fmt.Println("请提供消息内容,使用 -message 参数")
|
||
|
|
fmt.Println("用法: go run main.go -message \"你的消息\" [-title \"标题\"]")
|
||
|
|
os.Exit(1)
|
||
|
|
}
|
||
|
|
|
||
|
|
// 发送系统通知
|
||
|
|
err := sendNotification(title, message)
|
||
|
|
if err != nil {
|
||
|
|
fmt.Printf("发送通知失败: %v\n", err)
|
||
|
|
os.Exit(1)
|
||
|
|
}
|
||
|
|
|
||
|
|
fmt.Println("通知已发送")
|
||
|
|
}
|
||
|
|
|
||
|
|
// sendNotification 发送系统通知
|
||
|
|
func sendNotification(title, message string) error {
|
||
|
|
// 检测操作系统并使用相应的通知命令
|
||
|
|
switch os := strings.ToLower(os.Getenv("OS")); os {
|
||
|
|
case "windows_nt", "windows":
|
||
|
|
return sendWindowsNotification(title, message)
|
||
|
|
case "darwin":
|
||
|
|
return sendMacNotification(title, message)
|
||
|
|
default:
|
||
|
|
// 假设是Linux系统
|
||
|
|
return sendLinuxNotification(title, message)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// sendWindowsNotification 发送Windows系统通知
|
||
|
|
func sendWindowsNotification(title, message string) error {
|
||
|
|
// 使用PowerShell的Toast通知
|
||
|
|
powershellCmd := fmt.Sprintf(
|
||
|
|
"Add-Type -AssemblyName System.Windows.Forms; "+
|
||
|
|
"$notify = New-Object System.Windows.Forms.NotifyIcon; "+
|
||
|
|
"$notify.Icon = [System.Drawing.SystemIcons]::Information; "+
|
||
|
|
"$notify.BalloonTipTitle = '%s'; "+
|
||
|
|
"$notify.BalloonTipText = '%s'; "+
|
||
|
|
"$notify.Visible = $true; "+
|
||
|
|
"$notify.ShowBalloonTip(3000); "+
|
||
|
|
"Start-Sleep -Seconds 3",
|
||
|
|
escapePowerShellString(title),
|
||
|
|
escapePowerShellString(message),
|
||
|
|
)
|
||
|
|
|
||
|
|
cmd := exec.Command("powershell.exe", "-Command", powershellCmd)
|
||
|
|
return cmd.Run()
|
||
|
|
}
|
||
|
|
|
||
|
|
// sendMacNotification 发送macOS系统通知
|
||
|
|
func sendMacNotification(title, message string) error {
|
||
|
|
cmd := exec.Command("osascript", "-e",
|
||
|
|
fmt.Sprintf(`display notification "%s" with title "%s"`, message, title))
|
||
|
|
return cmd.Run()
|
||
|
|
}
|
||
|
|
|
||
|
|
// sendLinuxNotification 发送Linux系统通知
|
||
|
|
func sendLinuxNotification(title, message string) error {
|
||
|
|
cmd := exec.Command("notify-send", title, message)
|
||
|
|
return cmd.Run()
|
||
|
|
}
|
||
|
|
|
||
|
|
// escapePowerShellString 转义PowerShell字符串中的特殊字符
|
||
|
|
func escapePowerShellString(s string) string {
|
||
|
|
s = strings.ReplaceAll(s, "'", "''")
|
||
|
|
s = strings.ReplaceAll(s, "`", "``")
|
||
|
|
s = strings.ReplaceAll(s, "\"", "`\"")
|
||
|
|
return s
|
||
|
|
}
|