たれながし.info

とあるITエンジニアの備忘録

Windowsのトースト通知を表示する方法

PowerShell/Pythonを使ってWindowsの「トースト通知」を表示する方法

目的

Windowsにはトースト通知という機能があります。
この記事では、PowerShellPythonでトースト通知を表示する方法を紹介します。

(Defenderがマルウェアを検知した時にモニター右下にピコーン!!て出るやつです。)

  ↓これ

PowerShellの場合

トースト通知はWindows Runtime API(WinRT API)として実装されているので、PowerShellから該当APIを呼び出す形になります。

トースト通知のひな型はXMLで定義します。XMLのサンプルはMicrosoftのサイトに記載があります。
ちなみに、XMLで画像を指定する時、絶対パスじゃないとダメっぽいです。(src='c:\test.png'の様に指定)

docs.microsoft.com

コード

シンプルな通知の例です。XML部分は別ファイルにすることも可能です。

$title = "タイトル"
$message = "メッセージ"
$detail = "詳細"

[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
[Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null

$app_id = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe'

$content = @"
<?xml version="1.0" encoding="utf-8"?>
<toast>
    <visual>
        <binding template="ToastGeneric">
            <text>$($title)</text>
            <text>$($message)</text>
            <text>$($detail)</text>
        </binding>
    </visual>
</toast>
"@

$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
$xml.LoadXml($content)
$toast = New-Object Windows.UI.Notifications.ToastNotification $xml
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($app_id).Show($toast)

実行結果


Pythonの場合

Pythonを使ってトースト通知を表示するには、「Plyer」の「notification.notify」メソッドを使うのが簡単です。
「Plyer」も内部的には「WinRT API」を呼び出していると思います。

「Plyer」のソースコードGitHubで公開されています。
github.com

「notify」メソッドの仕様は、以下に記載があります。
(私のWindows10環境では、title, message以外の引数が動作することを確認できませんでした。)

plyer.readthedocs.io

コード

まず、pipで該当パッケージをインストールします。

pip install plyer


シンプルな通知の例です。

from plyer import notification
notification.notify(title = "タイトル", message="メッセージ")

実行結果