Skip to content

Instantly share code, notes, and snippets.

@eliask
Created February 17, 2022 17:17
Show Gist options
  • Save eliask/a981a9ef938c1825b0d5a9c2a38f280e to your computer and use it in GitHub Desktop.
Save eliask/a981a9ef938c1825b0d5a9c2a38f280e to your computer and use it in GitHub Desktop.
Windows toast notification with Python
import sys
from xml.sax.saxutils import escape
import winrt.windows.ui.notifications as notifications
import winrt.windows.data.xml.dom as dom
from winrt.windows.ui.notifications import ToastNotificationManager, ToastNotification, ToastTemplateType
if not sys.argv[2:]:
print(f'Usage: {sys.argv[0]} <title> <message ...>')
sys.exit(1)
title = sys.argv[1]
message = '\n'.join(sys.argv[2:])
nManager = notifications.ToastNotificationManager
notifier = nManager.create_toast_notifier(title)
tString = f"""
<toast launch="app-defined-string">
<visual>
<binding template="ToastImageAndText01">
<!-- NB: The test image here doesn't work in Win10+? -->
<image id="1" placement="hero" src="https://picsum.photos/364/180?image=1043" alt="hero"/>
<text id="1">{escape(message)}</text>
</binding>
</visual>
<audio src="ms-winsoundevent:Notification.Reminder"/>
</toast>
"""
xDoc = dom.XmlDocument()
xDoc.load_xml(tString)
notification = notifications.ToastNotification(xDoc)
notifier.show(notification)
def toast_notification(AppID, title, text):
XML = ToastNotificationManager.get_template_content(ToastTemplateType.TOAST_TEXT02)
t = XML.get_elements_by_tag_name("text")
t[0].append_child(XML.create_text_node(title))
t[1].append_child(XML.create_text_node(text))
notifier = ToastNotificationManager.create_toast_notifier(AppID)
notifier.show(ToastNotification(XML))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment