예제 #1
0
    def _send_with_pushover(self):
        """Send Notification with Pushover API

        Returns:
            dict -- Response from service
        """
        kwargs = Notification._clean_up_kwargs(self.kwargs.copy(), self.service)
        image_url = kwargs.pop("image_url", None)
        if image_url:
            kwargs["image"] = requests.get(image_url, stream=True).content
        pusher = PushoverAPI(current_app.config["PUSHOVER_TOKEN"])
        return pusher.send_message(self.user.pushover, self.message, **kwargs)
예제 #2
0
def send_notification(initiator, *args, **kwargs):
    """Send Notification via Pushover"""
    if "image" in kwargs and kwargs["image"]:
        img_url = kwargs["image"]
        kwargs["image"] = requests.get(img_url, stream=True).content
    pusher = PushoverAPI(os.environ.get("PUSHOVER_TOKEN"))
    response = pusher.send_message(os.environ.get("PUSHOVER_USER"), *args,
                                   **kwargs)
    kwargs["message"] = args[0]
    if "image" in kwargs:
        kwargs["image"] = img_url
    new = Notification(initiator, args[0][:2000], kwargs, response)
    db.session.add(new)
    db.session.commit()
    return response
예제 #3
0
파일: __init__.py 프로젝트: jbouwh/core
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up pushover from a config entry."""

    pushover_api = PushoverAPI(entry.data[CONF_API_KEY])
    try:
        await hass.async_add_executor_job(pushover_api.validate,
                                          entry.data[CONF_USER_KEY])

    except BadAPIRequestError as err:
        if "application token is invalid" in str(err):
            raise ConfigEntryAuthFailed(err) from err
        raise ConfigEntryNotReady(err) from err

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = pushover_api

    hass.async_create_task(
        discovery.async_load_platform(
            hass,
            Platform.NOTIFY,
            DOMAIN,
            {
                CONF_NAME: entry.data[CONF_NAME],
                CONF_USER_KEY: entry.data[CONF_USER_KEY],
                "entry_id": entry.entry_id,
            },
            hass.data[DATA_HASS_CONFIG],
        ))

    return True
예제 #4
0
def push_note(script):
    p = PushoverAPI('a4u1afrfsocorp6r1cdes1ydn5g2m6')

    def inner_push(func):
        '''
        separate function from Grabloid, used to notify Alec Burtner-Abt (primary dev)
        of script failure or success while running bots for CMA team.  Leverages Pushover App
        '''
        def func_wrapper(*args, **kwargs):
            try:
                func(*args, **kwargs)
                p.send_message('ukdn5gtjkaejnd6qmwy42ej2yofmsz',
                               f'{script} has successfully run.')
            except:

                tb = sys.exc_info()[2]
                tb = traceback.print_tb(tb)
                err = sys.exc_info()[0]
                print(err)
                print(tb)
                p.send_message(
                    'ukdn5gtjkaejnd6qmwy42ej2yofmsz',
                    f'{script} did not terminate properly.\n {traceback.print_tb(sys.exc_info()[2])}'
                )

        return func_wrapper

    return inner_push
예제 #5
0
class PushoverNotificationservice(NotificationService):
    def __init__(self, api_key, device_identifier):
        super().__init__(device_identifier)
        self._api_key = api_key
        self._notification_service = PushoverAPI(self._api_key)

    def send_test_notification(self):
        self._notification_service.send_message(self.device_identifier,
                                                'Test',
                                                title='Test')

    def send_notification(self, title, message):
        self._notification_service.send_message(self.device_identifier,
                                                message,
                                                title=title)

    @staticmethod
    def get_service_name():
        return 'Pushover'
예제 #6
0
파일: user.py 프로젝트: deeptube/Tubee
    def pushover(self, key):
        """Pushover Setter

        Validating Key and save iff valid

        Decorators:
            pushover.setter

        Arguments:
            key {str} -- User's pushover key obtain from https://pushover.net

        Raises:
            InvalidAction -- Raised when user gave an invalid user key
        """
        pusher = PushoverAPI(current_app.config["PUSHOVER_TOKEN"])
        response = pusher.validate(key)
        if response["status"] != 1:
            raise InvalidAction("Invalid Pushover User Key")
        self._pushover_key = key
        db.session.commit()
예제 #7
0
async def validate_input(hass: HomeAssistant,
                         data: dict[str, Any]) -> dict[str, str]:
    """Validate user input."""
    errors = {}
    pushover_api = PushoverAPI(data[CONF_API_KEY])
    try:
        await hass.async_add_executor_job(pushover_api.validate,
                                          data[CONF_USER_KEY])
    except BadAPIRequestError as err:
        if "application token is invalid" in str(err):
            errors[CONF_API_KEY] = "invalid_api_key"
        elif "user key is invalid" in str(err):
            errors[CONF_USER_KEY] = "invalid_user_key"
        else:
            errors["base"] = "cannot_connect"
    return errors
예제 #8
0
def send_pushover_notifications(latest: dict):
    users = env('PUSHOVER_USER_TOKENS').split(',')
    p = PushoverAPI(env('PUSHOVER_API_TOKEN'))
    for user in users:
        p.send_message(user, latest['quote'], url=latest['url'])
예제 #9
0
#!/home/cabox/.pyenv/versions/3.7.0/bin/python

from pushover_complete import PushoverAPI
from iperfspeed_config import *

p = PushoverAPI(
    p_apptoken)  # an instance of the PushoverAPI representing your application
p.send_message(p_userkey, 'PushoverAPI test')  # send a message to a user
예제 #10
0
        params['title'] = get_l0ip(msg['SOURCEIP'])
    else:
        params['title'] = title
    if message is None
        params['message'] = msg['MESSAGE']
    else:
        params['message'] = message
    params['timestamp'] = int(msg['R_UNIXTIME'])
    pushover.send_message(**params)

def update_defaults(ip):
    result = copy.deepcopy(defaults)
    new = database.get_pushover(ip)
    if new is not None:
        for key, value in new.iteritems():
            if key is not None:
                result[key] = value
    return result

pushover = PushoverAPI(os.getenv('PUSHOVER_TOKEN'))
defaults = dict()

if os.getenv('PUSHOVER_USER') != '':
    defaults['user'] = os.getenv('PUSHOVER_USER')
if os.getenv('PUSHOVER_DEVICE') != '':
    defaults['device'] = os.getenv('PUSHOVER_DEVICE')
if os.getenv('PUSHOVER_SOUND') != '':
    defaults['sound'] = os.getenv('PUSHOVER_SOUND')
if  os.getenv('PUSHOVER_PRIORITY') != '':
    defaults['priority'] = int(os.getenv('PUSHOVER_PRIORITY'))
예제 #11
0
    sys.exit(1)
if not args.prefix:
    sys.exit(2)
if not args.directories:
    sys.exit(3)

config = ConfigParser.ConfigParser()
config.read(args.config)

push_app_key = config.get('Pushover', 'app_key')
push_user_key = config.get('Pushover', 'user_key')
flickr_key = config.get('Flickr', 'key')
flickr_secret = config.get('Flickr', 'secret')
flickr_token_cache = config.get('Flickr', 'token-cache')

p = PushoverAPI(push_app_key)
flickr = flickrapi.FlickrAPI(flickr_key,
                             flickr_secret,
                             token_cache_location=flickr_token_cache)


def upload(file_path, location, time_stamp, event_name, info):
    tags = ['zoneminder', location, info]
    tag_text = ' '.join(map(lambda s: '"' + s + '"', tags))
    response = flickr.upload(
        filename=file_path,
        title=location + ' ' + time_stamp + ' ' + event_name,
        description=location + ' ' + time_stamp + ' ' + event_name,
        tags=tag_text,
        is_public=0,
        is_family=0,
예제 #12
0
 def __init__(self, hass, user_key, api_token):
     """Initialize the service."""
     self._hass = hass
     self._user_key = user_key
     self._api_token = api_token
     self.pushover = PushoverAPI(self._api_token)
예제 #13
0
class PushoverNotificationService(BaseNotificationService):
    """Implement the notification service for Pushover."""

    def __init__(self, hass, user_key, api_token):
        """Initialize the service."""
        self._hass = hass
        self._user_key = user_key
        self._api_token = api_token
        self.pushover = PushoverAPI(self._api_token)

    def send_message(self, message="", **kwargs):
        """Send a message to a user."""

        # Extract params from data dict
        title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
        data = dict(kwargs.get(ATTR_DATA) or {})
        url = data.get(ATTR_URL)
        url_title = data.get(ATTR_URL_TITLE)
        priority = data.get(ATTR_PRIORITY)
        retry = data.get(ATTR_RETRY)
        expire = data.get(ATTR_EXPIRE)
        callback_url = data.get(ATTR_CALLBACK_URL)
        timestamp = data.get(ATTR_TIMESTAMP)
        sound = data.get(ATTR_SOUND)
        html = 1 if data.get(ATTR_HTML, False) else 0

        image = data.get(ATTR_ATTACHMENT)
        # Check for attachment
        if image is not None:
            # Only allow attachments from whitelisted paths, check valid path
            if self._hass.config.is_allowed_path(data[ATTR_ATTACHMENT]):
                # try to open it as a normal file.
                try:
                    file_handle = open(data[ATTR_ATTACHMENT], "rb")
                    # Replace the attachment identifier with file object.
                    image = file_handle
                except OSError as ex_val:
                    _LOGGER.error(ex_val)
                    # Remove attachment key to send without attachment.
                    image = None
            else:
                _LOGGER.error("Path is not whitelisted")
                # Remove attachment key to send without attachment.
                image = None

        targets = kwargs.get(ATTR_TARGET)

        if not isinstance(targets, list):
            targets = [targets]

        for target in targets:
            try:
                self.pushover.send_message(
                    self._user_key,
                    message,
                    target,
                    title,
                    url,
                    url_title,
                    image,
                    priority,
                    retry,
                    expire,
                    callback_url,
                    timestamp,
                    sound,
                    html,
                )
            except ValueError as val_err:
                _LOGGER.error(val_err)
예제 #14
0
 def __init__(self, opp, user_key, api_token):
     """Initialize the service."""
     self._opp = opp
     self._user_key = user_key
     self._api_token = api_token
     self.pushover = PushoverAPI(self._api_token)
예제 #15
0
 def __init__(self, api_key, device_identifier):
     super().__init__(device_identifier)
     self._api_key = api_key
     self._notification_service = PushoverAPI(self._api_key)
예제 #16
0
        print('Average transmitted data in various formats:')
        print('  bits per second      (bps)   {0:,.2f}'.format(
            result.sent_bps))
        print('  Kilobits per second  (kbps)  {0:,.2f}'.format(
            result.sent_kbps))
        print('  Megabits per second  (Mbps)  {0:,.2f}'.format(
            result.sent_Mbps))
        print('  KiloBytes per second (kB/s)  {0:,.2f}'.format(
            result.sent_kB_s))
        print('  MegaBytes per second (MB/s)  {0:,.2f}'.format(
            result.sent_MB_s))

        if result.sent_MB_s < transfer_min or test_run:
            # send alert to pushover
            p = PushoverAPI(
                p_apptoken
            )  # an instance of the PushoverAPI representing your application
            # send a message to a user
            p.send_message(
                p_userkey, 'iPerf Speed Warning\n' +
                'date:\t\t{:%Y-%m-%d}\n'.format(datetime.datetime.now()) +
                'time:\t\t{:%H-%M}\n'.format(datetime.datetime.now()) +
                'CPU utilization :\t\t%d%%\n' % (result.local_cpu_total) +
                'transmitted:\t\t%d MB/s\n' % (result.sent_bytes / 1000000) +
                'throughput:\t\t%d Mb/s\n' % (result.sent_MB_s))

    # log stats to local csv file
    with open('stats.csv', 'a') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow([
            result.time, '{0:,.2f}'.format(result.sent_bytes / 1000000),