用pynotify獲得Google日曆提醒

veldts發表於2012-01-20

原文:Google Calendar notifications using pynotify

我使用Google日曆(Google Calendar)管理日程表,不過,我還急需一項功能,即在設定過提醒的約會到期時通知自己。

本文給出了一個完成這項功能的Python程式示例。該程式利用Google Data API的Python客戶端庫和pynotify。

下面會詳細給出程式碼,以便各位根據自己的需要加以修改。

首先,匯入GTK+和pynotify,並初始化pynotify。

import gtk
import pynotify
pynotify.init(sys.argv[0])

其次,匯入gdata Calendar API,連線到指定日曆。這裡使用簡單的email/密碼組合進行登入,這不是最佳做法,但卻是最簡單的。隨意使用OAuth 2.0。:-)

calendar_service = gdata.calendar.service.CalendarService()
calendar_service.email = 'mygooglelogin'
calendar_service.password = 'mygooglepassword'
calendar_service.ProgrammaticLogin()

接下來,準備請求日曆資訊並進行通知!首先,從預設日曆請求提取事件。

feed = calendar_service.GetCalendarEventFeed()

隨後,遍歷feed中的所有條目,執行各種檢查。

for event in feed.entry:
    # If the event status is not confirmed, go to the next event.
    if event.event_status.value != "CONFIRMED":
        continue
    # Now iterate over all the event dates (usually it has one)
    for when in event.when:
        # Parse start and end time
        try:
            start_time = datetime.datetime.strptime(when.start_time.split(".")[0], "%Y-%m-%dT%H:%M:%S")
            end_time = datetime.datetime.strptime(when.end_time.split(".")[0], "%Y-%m-%dT%H:%M:%S")
        except ValueError:
            # ValueError happens on parsing error. Parsing errors
            # usually happen for "all day" events since they have
            # not time, but we do not care about this events.
            continue
        now = datetime.datetime.now()
        # Check that the event hasn't already ended
        if end_time > now:
            # Check each alert
            for reminder in when.reminder:
                # We handle only reminders with method "alert"
                # and whose start time minus the reminder delay has passed
                if reminder.method == "alert" \
                        and start_time - datetime.timedelta(0, 60 * int(reminder.minutes)) < now:
                    # Build the notification
                    notification = pynotify.Notification(summary=event.title.text,
                                                         message=event.content.text)
                    # Set an icon from the GTK+ stock icons
                    notification.set_icon_from_pixbuf(gtk.Label().render_icon(gtk.STOCK_DIALOG_INFO,
                                                                              gtk.ICON_SIZE_LARGE_TOOLBAR))
                    notification.set_timeout(0)
                    # Show the notification
                    notification.show()

執行這個程式,如果這時恰好有個約會發出提醒,你就會看到一個通知。

利用上述程式碼,足以做出點東西來。

不樂意用Python程式設計的話,不妨試試gcalcli

特別說明:感謝大家積極參與【iTran樂譯】第3期

相關文章