File: notify.py

package info (click to toggle)
python-bumps 1.0.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,200 kB
  • sloc: python: 24,517; xml: 493; ansic: 373; makefile: 211; javascript: 99; sh: 94
file content (70 lines) | stat: -rw-r--r-- 1,983 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import os
import logging

TWITTER_KEYS = "~/.ssh/twitter"
EMAIL_SERVER = "localhost"
EMAIL_SENDER = "bumps@reflectometry.org"


def notify(user, msg, body="No body", level=1):
    """
    Send a notfication message to the user regarding the job status.
    """

    if not user:
        pass
    elif user.startswith("@"):
        tweet(user, msg)
    elif "@" in user:
        email(EMAIL_SENDER, [user], body, subject=msg, server=EMAIL_SERVER)
    else:
        logging.debug("%s : %s" % (user, msg))


twitter = None


def tweet(user, msg):
    global twitter
    if twitter is None:
        twitter = open_twitter(TWITTER_KEYS)
    twitter.direct_messages.new(user=user, text=msg)


def open_twitter(authfile):
    from twitter import Twitter, OAuth  # @UnresolvedImport twitter is optional

    # Load credentials from authfile
    for line in open(os.path.expanduser(authfile)).readlines():
        exec(line)
    auth = OAuth(access_token, access_secret, consumer_key, consumer_secret)  # @UndefinedVariable comes from authfile
    return Twitter(auth=auth)


def email(sender, receivers, message, subject="no subject", server="localhost"):
    """
    Send an email message to a group of receivers
    """
    import smtplib

    if ":" in server:
        host, port = server.split(":")
        port = int(port)
    else:
        host, port = server, 25
    header = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
    header %= sender, ", ".join(receivers), subject
    # print "Sending the following mail message:\n"+header+message
    # print "Trying to connect to",host,port
    smtp = smtplib.SMTP(host, port)
    # print "Connection established"
    smtp.sendmail(sender, receivers, header + message)
    # print "Mail sent from",sender,"to",", ".join(receivers)
    smtp.quit()


if __name__ == "__main__":
    msg = "test notification"
    body = "See http://reflectometry.org for details."
    # notify('@pkienzle', msg, body)
    notify("paknist@gmail.com", msg, body)