Пример #1
0
def FanAlert(curtemp, status):
    config = ConfigParser.RawConfigParser()
    config.read('../fishtank.conf')

    # send push notification
    app = App(appid=config.get('push', 'app_id'), secret=config.get('push', 'app_secret'))
    app.notify(event_name='FanAlert', trackers={ 'curtemp': curtemp, 'status': status})
Пример #2
0
def ControlAlert(channel, status):
    config = ConfigParser.RawConfigParser()
    config.read('../fishtank.conf')

    # send push notification
    app = App(appid=config.get('push', 'app_id'), secret=config.get('push', 'app_secret'))
    app.notify(event_name='ControlAlert', trackers={ 'channel': channel, 'status': status})
Пример #3
0
def pushMessage(event_name, message):
    
    '''
    Args:
        event_name: 发送到instapush对应的App名称
        message: 要推送的信息, dict类型,{key1:value1, key2:value2},对应于instapush相应的trackers
    '''
    
    app = App(appid=App_ID, secret=App_secret)
    app.notify(event_name=event_name, trackers=message)    
Пример #4
0
def send_via_insta(msg):
    '''
    need correct appid and secret, or this script could not work
    '''
    global appid
    global secret
    app = App(appid=appid, secret=secret)
    # event_name is pre-configured at https://instapush.im
    # 'message' is also pre-configured
    app.notify(event_name='rpi3b', trackers={'message': msg})
Пример #5
0
def send_via_insta(msg):
    '''
    need correct appid and secret, or this script could not work
    '''
    global appid
    global secret
    app = App(appid=appid, secret=secret)
    # event_name is pre-configured at https://instapush.im
    # 'message' is also pre-configured
    app.notify(event_name='rpi3b', trackers={'message': msg})
Пример #6
0
 def notify(title, check_num=0, type_info=1):
     app = App(appid=os.getenv('instapush_id'), secret=os.getenv('instapush_secret'))
     try:
         if type_info == 1:
             res = app.notify(event_name='get_list', trackers={'title': title, 'check_num':check_num})
         else:
             date_info = time.strftime('%Y-%m-%d %H:%M:%S')
             res = app.notify(event_name='zhihufav', trackers={'title': title, 'date':date_info})
         print(res)
     except Exception, e:
         print(Exception)
         print(e)
Пример #7
0
def TempAlert(sensor, curtemp, maxtemp, mintemp):
    config = ConfigParser.RawConfigParser()
    config.read('../fishtank.conf')

    # send push notification
    app = App(appid=config.get('push', 'app_id'), secret=config.get('push', 'app_secret'))
    app.notify(event_name='TempsAlert', trackers={ 'sensor': sensor, 'curtemp': curtemp, 'maxtemp': maxtemp, 'mintemp': mintemp})

    # send email notification
    sender = config.get('email', 'sender')
    receiver = [ config.get('email', 'receiver') ]
    smtpObj = smtplib.SMTP(config.get('email', 'smtp'))
    smtpObj.sendmail(sender, receiver, message % (sender, receiver, sensor, sensor, datetime.now(), curtemp, maxtemp, mintemp)) 
    smtpObj.quit()
Пример #8
0
async def main():
    init()
    app = App(appid='5972ed6da4c48a4118de80b2',
              secret='3acda6333f7422e45f24ecbc5aa971d5')
    print("loading webdriver...")
    drv = webdriver.PhantomJS()
    while True:
        print("fetching danawa...")
        l = drv.get("http://prod.danawa.com/info/?pcode=1795206&cate=1131401")
        result = drv.find_element_by_xpath('//*[@class="big_price"]')
        date = drv.find_element_by_xpath('//span[@class="product_date"]')
        t = result.text
        t = re.sub(',', '', t)
        date = date.text

        print(t)

        with db.get_conn():
            o = Price.select().order_by(Price.id.desc()).limit(3)
        p = []
        for i in o:
            with db.get_conn():
                p.append(i.price)

        if len(p) == 0:
            p.append('0')

        v = int(t) - int(p[-1])

        now = datetime.datetime.now().strftime('%Y%m%d-%H%M')
        d = {'date': date, 'localdate': now, 'title': 'Toshiba 3T', 'price': t}
        #with db.get_conn():
        with db.atomic():
            Price.insert_many([d]).execute()

        msg = "toshiba 3T: {} ( {})\n(<--{}won<---{}won)".format(
            t, v, p[-1], p[-2])

        # 가격변동이 있을 때만 InstaPushing 합니다
        if v != 0 or int(t) < 90000:
            print('price is different. instapushing!!!')
            app.notify(event_name='alarm', trackers={'msg': msg})
        #app.notify(event_name = 'alarm', trackers={'msg': msg})

        print('sleep {} secs'.format(INTERVAL))
        # cpu load를 없애기 위함입니다. danawa 페이지 왜저리 자원을 많이 먹죠? ㄷㄷㄷ
        drv.get('192.168.0.1:8888')
        await asyncio.sleep(INTERVAL)
Пример #9
0
def notify(title, message, event_name, appid, secret, trackers, retcode=None):
    """
    Required parameter:
        * ``event_name`` - Instapush event (the notification template)
        * ``appid`` - The appid found on the dashboard
        * ``secret`` - The secret found on the dashboard
        * ``traskers`` - List of the placeholders for the selected event
    """

    logger = logging.getLogger(__name__)
    _msgs = re.split(r'(?<!\\):', message)
    msgs = []

    for msg in _msgs:
        msg = msg.replace("\\:", ":")
        msgs.append(msg)

    if len(msgs) != len(trackers):
        logger.error(('Wrong number of messages! There are {} trackers so you '
                      'have to provide {} messages. Remember to separate each '
                      'message with \':\' (example: send "msg1:msg2")').format(
                          len(trackers), len(trackers)))
        raise WrongMessageCountException()

    to_send = {}

    for tracker, msg in zip(trackers, msgs):
        to_send[tracker] = msg

    app = App(appid=appid, secret=secret)
    res = app.notify(event_name=event_name, trackers=to_send)

    if res["status"] != 200:
        logger.error(res["msg"])
        raise ApiException()
    def send_push_notification(self, alarmMesssage):  # pip install instapush

        #insta = Instapush(user_token='57c5f710a4c48a6d45ee19ce')

        #insta.list_app()             #List all apps

        #insta.add_app(title='Home Surveillance') #Create a app named title

        app = App(appid='57c5f92aa4c48adc4dee19ce',
                  secret='2ed5c7b8941214510a94cfe4789ddb9f')

        #app.list_event()             #List all event

        #app.add_event(event_name='FaceDetected', trackers=['message'],
        #              message='{message} face detected.')

        app.notify(event_name='FaceDetected',
                   trackers={
                       'message':
                       "NOTIFICATION ALERT\n================\n" + alarmMesssage
                   })
Пример #11
0
class MongoPipeline(object):
    collection_name = "recipe_item"

    def __init__(self, mongo_uri, mongo_db, instapush_appid, instapush_secret):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db
        self.instapush_app = None
        if instapush_appid and instapush_secret:
            from instapush import App
            self.instapush_app = App(appid=instapush_appid,
                                     secret=instapush_secret)

    @classmethod
    def from_crawler(cls, crawler):
        return cls(mongo_uri=crawler.settings.get("MONGO_URI"),
                   mongo_db=crawler.settings.get("MONGO_DATABASE"),
                   instapush_appid=crawler.settings.get("INSTAPUSH_APPID", ""),
                   instapush_secret=crawler.settings.get(
                       "INSTAPUSH_SECRET", ""))

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]
        if self.instapush_app:
            self.instapush_app.notify(event_name='spider_events',
                                      trackers={'event': 'starts'})

    def close_spider(self, spider):
        self.client.close()
        if self.instapush_app:
            self.instapush_app.notify(event_name='spider_events',
                                      trackers={'event': 'stops'})

    def process_item(self, item, spider):
        self.db[self.collection_name].insert_one(dict(item))
        return item
Пример #12
0
    def save_data(self, trigger_id, **data):
        """
            let's save the data

            :param trigger_id: trigger ID from which to save data
            :param data: the data to check to be used and save
            :type trigger_id: int
            :type data:  dict
            :return: the status of the save statement
            :rtype: boolean
        """
        title, content = super(ServiceInstapush, self).save_data(trigger_id, **data)
        instance = InstapushModel.objects.get(trigger_id=trigger_id)
        Instapush(user_token=self.token)
        app = App(appid=instance.app_id, secret=instance.app_secret)
        trackers = {instance.tracker_name: content}
        status = app.notify(event_name=instance.event_name, trackers=trackers)
        return status
def Pushinformation(Ip_address_Eth0,Ip_address_wlan0,Ip_address_internet,Exist_Eth,Exist_wlan,Exist_Internet) :
    # This function can push information to mobile phone.
    # Note the app tag, It need to be changed to your own tag before you use it, or I will receive your Ip address...

    app = App(appid = '561bac12a4c48a31793792b5', secret = '5b3446093d50511955f95b589988c541')

    local_time = time.localtime()
    string_time = 'Now Time is : ' + str(local_time[3]) + ' : ' + str(local_time[4])
    app.notify(event_name = 'Report_IP_address_of_raspberry_pi', trackers ={'Message': string_time})

    if Exist_Eth:
        string_Eth0 = 'Eth Ip address : ' + Ip_address_Eth0
        app.notify(event_name = 'Report_IP_address_of_raspberry_pi', trackers ={'Message': string_Eth0})

    if Exist_wlan:
        string_wlan0 = 'Wlan Ip address : ' + Ip_address_wlan0
        app.notify(event_name = 'Report_IP_address_of_raspberry_pi', trackers ={'Message': string_wlan0})

    if Exist_Internet:
        string_internet = 'Internet Ip address : ' + Ip_address_internet
        app.notify(event_name = 'Report_IP_address_of_raspberry_pi', trackers ={'Message': string_internet})
Пример #14
0
    def save_data(self, trigger_id, **data):
        """
            let's save the data

            :param trigger_id: trigger ID from which to save data
            :param data: the data to check to be used and save
            :type trigger_id: int
            :type data:  dict
            :return: the status of the save statement
            :rtype: boolean
        """
        title, content = super(ServiceInstapush,
                               self).save_data(trigger_id, **data)
        instance = InstapushModel.objects.get(trigger_id=trigger_id)
        Instapush(user_token=self.token)
        app = App(appid=instance.app_id, secret=instance.app_secret)
        trackers = {instance.tracker_name: content}
        status = app.notify(event_name=instance.event_name, trackers=trackers)
        return status
Пример #15
0
class Pusher:
    def __init__(self, config):
        self.config = config
        self.app = App(appid=self.config['APPID'],
                       secret=self.config['SECRET'])

    def push(self, msg):
        try:
            ret = self.app.notify(event_name=self.config['EVENT_NAME'],
                                  trackers={self.config['TRACKERS']: str(msg)})
        except Exception:
            Log.log_error(traceback.format_exc())
            return False
        if ret == None:
            Log.log_error('Unknown error.')
            return False
        if ret['error']:
            Log.log_error('Push error, msg: {}'.format(ret['msg']))
            return False
        return True
Пример #16
0
def notify(title, message, event_name, appid, secret, trackers, retcode=None):
    """
    Required parameter:
        * ``event_name`` - Instapush event (the notification template)
        * ``appid`` - The appid found on the dashboard
        * ``secret`` - The secret found on the dashboard
        * ``traskers`` - List of the placeholders for the selected event
    """

    logger = logging.getLogger(__name__)
    _msgs = re.split(r"(?<!\\):", message)
    msgs = []

    for msg in _msgs:
        msg = msg.replace("\\:", ":")
        msgs.append(msg)

    if len(msgs) != len(trackers):
        logger.error(
            (
                "Wrong number of messages! There are {} trackers so you "
                "have to provide {} messages. Remember to separate each "
                "message with ':' (example: send \"msg1:msg2\")"
            ).format(len(trackers), len(trackers))
        )
        raise WrongMessageCountException()

    to_send = {}

    for tracker, msg in zip(trackers, msgs):
        to_send[tracker] = msg

    app = App(appid=appid, secret=secret)
    res = app.notify(event_name=event_name, trackers=to_send)

    if res["status"] != 200:
        logger.error(res["msg"])
        raise ApiException()
Пример #17
0
while True:
	if ( gpio.input(door_pin) and door == 1 ):
		logging.debug("Checking Opened")
		result = bluetooth.lookup_name('', timeout=5)
		
		if (result != None):
			logging.debug("Tim opened door")
			doorChange('tim', 1, 0)
			process = subprocess.Popen(welcomeHomeBash.split(), stdout=subprocess.PIPE)
			output = process.communicate()[0]
		else:
			logging.debug("Unknown opened door")
			process = subprocess.Popen(intruderOpenBash.split(), stdout=subprocess.PIPE)
			output = process.communicate()[0]
			appPush.notify(event_name='Test', trackers={ 'event': 'Door Opened'})
			doorChange('unknown', 1,3)
		
		door = 0
		time.sleep(1)
	
	if ( gpio.input(door_pin) == False and door!= 1):
		logging.debug("Checking Closed")
		result = bluetooth.lookup_name('', timeout=5)
		
		if (result != None):
			logging.debug("Tim closed the door")
			doorChange('tim', 0, 0)
			process = subprocess.Popen(goodbyeHomeBash.split(), stdout=subprocess.PIPE)
			output = process.communicate()[0]
		else:
Пример #18
0
output_file = open(".added_history", "r+")
added_history = output_file.read()
output_file_human = open("added_history", "r+")
added_history_human = output_file_human.read()

turl = Config.get('Transmission', 'url')
tusr = Config.get('Transmission', 'usr')
tpwd = Config.get('Transmission', 'pwd')
SESSID = subprocess.check_output("curl --silent --anyauth --user " + tusr +
                                 ":" + tpwd + " " + turl +
                                 " | sed 's/.*<code>//g;s/<\/code>.*//g'",
                                 shell=True)
loG(1, SESSID)
if "X-Transmission-Session-Id:" not in SESSID:
    loG(1, "ERROR - SESSID non valido!!")
    app.notify(event_name='error', trackers={'message': 'SESSID non valido!!'})
    quit()
emailsub = '[pyTorrent] Torrent aggiunto!'
emailmsg = '<h1>pyTorrent</h1>'
#loG(1,d.entries)
for ee in d.entries:
    loG(2, '__Valutando__ ' + ee.title)
    for serie in utili:
        path = Series.get(serie, 'path')
        ignorez = Series.get(serie, 'ignore')
        nyd = Series.get(serie, 'needed')
        if dim(ee.title, serie, ignorez.split(','), nyd):
            a += 1
            loG(1, '    Published: ' + ee.published)
            loG(1, '    Title:     ' + ee.title)
            loG(1, '    Filename:  ' + ee.torrent_filename)
Пример #19
0
    if (gpio.input(door_pin) and door == 1):
        logging.debug("Checking Opened")
        result = bluetooth.lookup_name('', timeout=5)

        if (result != None):
            logging.debug("Tim opened door")
            doorChange('tim', 1, 0)
            process = subprocess.Popen(welcomeHomeBash.split(),
                                       stdout=subprocess.PIPE)
            output = process.communicate()[0]
        else:
            logging.debug("Unknown opened door")
            process = subprocess.Popen(intruderOpenBash.split(),
                                       stdout=subprocess.PIPE)
            output = process.communicate()[0]
            appPush.notify(event_name='Test',
                           trackers={'event': 'Door Opened'})
            doorChange('unknown', 1, 3)

        door = 0
        time.sleep(1)

    if (gpio.input(door_pin) == False and door != 1):
        logging.debug("Checking Closed")
        result = bluetooth.lookup_name('', timeout=5)

        if (result != None):
            logging.debug("Tim closed the door")
            doorChange('tim', 0, 0)
            process = subprocess.Popen(goodbyeHomeBash.split(),
                                       stdout=subprocess.PIPE)
            output = process.communicate()[0]
Пример #20
0
# -*- coding:utf8 -*-
import sys
reload(sys)
from instapush import Instapush,App
app=App(appid='5716c8375659e3a956080a46',secret='ae9a83ef6a5ffbc976309d9cc3f911f6')
#app.notify('Gec',{'isim':'Namık ERDOĞAN','tarih':'2016-04-20','gir':'giriş','saat':'9:51'})
a1="Namık ERDOĞAN"
a2="22:12:00"
a3="2014/04/20"

appnot={'plu':a1}




app.notify(event_name='sat',trackers=appnot)
Пример #21
0
def call_me(message):
    app = App(appid='566572b8a4c48a7953d79bf8', secret='de395badf71ff5ebb6bc8275ba7184e7')
    app.notify(event_name='message', trackers={ 'message': message})
Пример #22
0
#!/usr/bin/env python
# -*- coding:utf-8 -*- 
# @Author   : ATIME
# @License  : GNU General Public License
# @Contact  : [email protected]   
# @Time     : 2017/12/19 10:33
# @File     : push.py
# @Version  : Python2.7.14

from instapush import Instapush, App

# insta = Instapush(user_token='xxxxxxx')
#
# insta.list_app()             #List all apps
#
# insta.add_app(title='title') #Create a app named title

app = App(appid='5a387736a4c48a6e16fc3061', secret='a3aad896c2f71175cb64b6f515bd7624')

print(app.list_event())

app.add_event(event_name='signups', trackers=['email'], message='{email} hia hia hia')

app.notify(event_name='signups', trackers={'email': '*****@*****.**'})
Пример #23
0
def instapush(username,time,content):
    app = App(appid='appid',secret='app secret')
    app.notify(event_name='Weibo',trackers={"username":username,"time":time,"weibo":content})
    return
Пример #24
0
import RPi.GPIO as GPIO
import time
import os.path
from instapush import Instapush, App
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP)

input_state = GPIO.input(4)
if input_state == False and os.path.isfile('active') == False:
    open('active', 'a')
    app = App(appid='xxxxxxxx', secret='xxxxxxxx')
    app.notify(event_name='Baby_Monitor', trackers={'Baby': 'Louis'})
    time.sleep(600)
    os.remove('active')
Пример #25
0
subreddit = r.get_subreddit('bapcsalescanada')

def get_titles( subreddit ):
    try:
        submissions = subreddit.get_new(limit=5)
    except:
        print "Error getting submissions."
        return []
    titles = []
    try:
        for post in submissions:
            titles.append(post.title.encode('ascii', errors='ignore'))
    except:
        print "Error parsing titles"
    return titles

previous = []
while not previous:
    previous = get_titles(subreddit)
    sleep(10)

while True:
    current = get_titles(subreddit)
    if not current:
        continue
    for title in list(set(current) - set(previous)):
        print title
        app.notify(event_name='newpost', trackers={'title': title})
    previous = current
    sleep(10)
Пример #26
0
def push():
    app = App(appid='595713a2a4c48ae3b8b70aa0',
              secret='78fbc7d58e750b37773b3dbd13c967c5')
    app.notify(event_name='alarm', trackers={'msg': '하핫'})
Пример #27
0
 def notify():
     babyname, appid, secret = Notify.readcfg()
     app = App(appid=appid, secret=secret)
     app.notify(event_name='BabyCam', trackers={'Baby': babyname})
     time.sleep(600)
Пример #28
0
 def instapush(self,username,time,status):
     action = {'W_chat_stat_online':'上线了','W_chat_stat_offline':'下线了'}
     app = App(appid='appid',secret='secret')
     app.notify(event_name='WeiboStat',trackers={"username":username,"time":time,"status":action[status]})
Пример #29
0
def push_notification(message):
	app = App(appid=INSTAPUSH_ID, secret=INSTAPUSH_SECRET)
	app.notify(event_name='ThermAlert', trackers={ 'message': message})