Esempio n. 1
0
#!/usr/bin/env python3

import paho.mqtt.client as mqtt
import requests
import sys
from pushbullet import Pushbullet

pb = Pushbullet(sys.argv[1])
channel_name = sys.argv[2]
mqtt_channel = sys.argv[3]

channel = pb.get_channel(channel_name)


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe(mqtt_channel)


def on_message(client, userdata, msg):
    file = msg.payload.decode()
    result = channel.push_note('Torrent complete',
                               '{} has finished downlaoding'.format(file))
    print('{} has finished downloading'.format(file))


client = mqtt.Client()
client.connect("localhost", 1883, 60)

client.on_connect = on_connect
client.on_message = on_message
Esempio n. 2
0
			url = "https://studentdetails-99fa7.firebaseio.com/"
			firebase = FirebaseApplication(url, None)
			result = firebase.get("/IT01", None)


			if name == "Yong Teng":
				for i in tempResult: #Check for entries captured by NFC
					if i == '0xcb28549225L':
						name = "Yong Teng"
						studentid = "S10198102"
						classdetails = "IT01"
						push = firebase.put("/IT01", "0xcb28549225L", {"Name": name, "StudentID": studentid, "Class": classdetails, "Time": timestampStr})
						
						if counter == 0:
							pb = Pushbullet("o.nXnlSCCZsxJVypY8kDYmkpDdwDh52RsE")
							push = pb.push_note("Attendance have been taken", "At {}" .format(timestampStr))
							counter += 1
							print("{}'s Entry Pushed!" .format(name))

						elif counter != 0:
							print("{}'s Notification Already Pushed!" .format(name))

					
					else:
						print("[INFO] Checking for RFID Entry.....")


			if name == "Wei Jie":
				for i in tempResult: #Check for entries captured by NFC		
					if i == '0xdb10109249L':
Esempio n. 3
0
from picamera import PiCamera
from time import sleep
from datetime import datetime
from grovepi import *
import grovepi
import time
import sys
from pushbullet import Pushbullet
#from pushbullet2 import PushBullet

#connecting to pusb bullet api
pb = Pushbullet("o.xWndImaQeTc7WvQC6tK3yyTAJVdBKxrU")
pushes = pb.get_pushes()
print(pushes)

print(pb.devices)
samsung = pb.get_device('Samsung SM-G950F')

button = 7
ultrasonic_ranger = 2
grovepi.pinMode(button, "INPUT")
camera = PiCamera()
now = datetime.now()
filename = ''

print grovepi.ultrasonicRead(ultrasonic_ranger)


def take_photo():
    global filename
    #change this naming convention as it is not working
from pushbullet import Pushbullet
import time

api_key = 'API'
temperatura = int(input('Digite a temperatura da maquina  '))
umidade = int(input('Digite a Umidade da maquina  '))
ca = int(input('Digite a Corrente elétrica da maquina  '))
rpm = int(input('Digite a RPM da maquina  '))

if temperatura > 95:
    pb = Pushbullet(api_key)
    push = pb.push_note("ALERTA", "Temperatura esta acima do normal")
    time.sleep(3)
elif temperatura < 30:
    pb = Pushbullet(api_key)
    push = pb.push_note("ALERTA", "Temperatura esta abaixo do normal")
    time.sleep(3)
if temperatura >= 30 and temperatura <= 95:
    print('Temperatura Normal')
if umidade > 80:
    pb = Pushbullet(api_key)
    push = pb.push_note("ALERTA", "Umidade esta acima do normal")
    time.sleep(3)
elif umidade < 40:
    pb = Pushbullet(api_key)
    push = pb.push_note("ALERTA", "Umidade esta abaixo do normal")
    time.sleep(3)
if umidade >= 40 and umidade <= 85:
    print('Umidade Normal')
if ca > 300:
    pb = Pushbullet(api_key)
Esempio n. 5
0
def watch_tgtg():
    if tgtg_email is not None and tgtg_password is not None:
        tgtg_client = TgtgClient(email=tgtg_email, password=tgtg_password)
    elif tgtg_user_id is not None and tgtg_access_token is not None:
        tgtg_client = TgtgClient(user_id=tgtg_user_id,
                                 access_token=tgtg_access_token)
    else:
        print(
            "Neither email and password nor user id and access token for TGTG were specified. Aborting..."
        )

    pb_client = None
    if pb_api_key is not None:
        pb_client = Pushbullet(pb_api_key)

    pb_notification_channel = pb_client.get_channel(
        pb_notification_channel_tag
    ) if pb_notification_channel_tag is not None else None

    if bool(environ.get('PB_CLEAR_CHANNEL',
                        False)) and pb_notification_channel is not None:
        for push in pb_client.get_pushes():
            if 'channel_iden' in push and push[
                    'channel_iden'] == pb_notification_channel.iden:
                pb_client.delete_push(push['iden'])

    available_items = {}
    while True:
        for available_item in available_items.values():
            available_item['still_available'] = False

        items = tgtg_client.get_items(favorites_only=True,
                                      latitude=tgtg_search_lat,
                                      longitude=tgtg_search_lon,
                                      radius=tgtg_search_range)

        print(
            f"Found {len(items)} favourited stores of which {len([_ for _ in items if _['items_available'] > 0])} have available items..."
        )
        for item in items:
            if item['items_available'] > 0:
                if item['item']['item_id'] in available_items:
                    available_items[item['item']
                                    ['item_id']]['still_available'] = True
                else:
                    print(
                        f"Found newly available product: {item['display_name']} since {datetime.now().strftime('%H:%M:%S (%d.%m.%Y)')}"
                    )
                    if pb_client is not None:
                        push_guid = uuid4().hex
                        pb_client.push_link(
                            f"New TGTG product available",
                            f"https://share.toogoodtogo.com/item/{item['item']['item_id']}",
                            f"{item['display_name']} since {datetime.now().strftime('%H:%M:%S (%d.%m.%Y)')}",
                            channel=pb_notification_channel,
                            guid=push_guid)
                    available_items[item['item']['item_id']] = {
                        'item': item,
                        'still_available': True,
                        'push_guid': push_guid
                    }

        keys_to_delete = []
        for available_item_id, available_item in available_items.items():
            if not available_item['still_available']:
                print(
                    f"Product is no longer available: {available_item['item']['display_name']} since {datetime.now().strftime('%H:%M:%S (%d.%m.%Y)')}"
                )
                if pb_client is not None:
                    push_to_delete = next(
                        (push
                         for push in pb_client.get_pushes() if 'guid' in push
                         and push['guid'] == available_item['push_guid']),
                        None)
                    if push_to_delete is not None:
                        pb_client.delete_push(push_to_delete['iden'])

                keys_to_delete.append(available_item_id)

        for key_to_delete in keys_to_delete:
            del available_items[key_to_delete]

        print(
            f"All favourited stores were processed. Sleeping {environ.get('SLEEP_INTERVAL', '60')} seconds..."
        )
        time.sleep(int(environ.get('SLEEP_INTERVAL', '60')))
Esempio n. 6
0
from datetime import timedelta
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

import logging
import os
import cloudstorage as gcs
from gcloud import storage
from google.cloud import storage

from pushbullet import Pushbullet

import speech_recognition as sr

pb = Pushbullet('o.V6LChFjuMwBnctjCgBDCPQaSm67dJxTc')

app = Flask(__name__)
app.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'
basedir = os.path.abspath(os.path.dirname(__file__))

HOST = "34.87.232.0"
USER = "******"
PASSWORD = "******"
DATABASE = "People"

app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://{}:{}@{}/{}".format(
    USER, PASSWORD, HOST, DATABASE)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

db.init_app(app)
Esempio n. 7
0
 def __init__(self, api_key):
     ''' Initialize pushbullet '''
     self.pushbullet = Pushbullet(api_key)
     self.logging = logging.getLogger('Notificator')
     self.logging.setLevel(level=logging.DEBUG)
Esempio n. 8
0
for yt in range(1, 100):
    new_look = 'rf_code_%s' % (yt)
    for new_lines in content:
        if new_look in new_lines:
            # Only select the name of the sensor
            rf_list.append(new_lines.split(" ")[1:][0].split(":")[1])
            to_stop = False
    if to_stop == True:
        break

# Import push notification library
if use_pushbullet == True:
    from pushbullet import Pushbullet
    try:
        for access_token in token_list:
            pushbullet_list.append(Pushbullet(access_token))
    except:
        use_pushbullet = 'RETEST'

# To kill a process manually -> type 'top' to obtain pid then 'sudo kill pid'
# Kill all the current RF Sniffer instances!
p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
    if 'RFSniffer' in line:
        pid = int(line.split(None, 1)[0])
        to_kill = "sudo kill %s" % (pid)
        os.system(to_kill)

# Path to executables
send_script = "/home/pi/433Utils/RPi_utils/codesend"
Esempio n. 9
0
def push_text(Title, Message):
    global apiKey
    pb = Pushbullet(apiKey)
    push = pb.push_note(Title, Message)
Esempio n. 10
0
 def push_bullet(self, body=None, title=None):
     pb = Pushbullet(Keys.PUSHBULLET)
     pb.push_note(title, body)
Esempio n. 11
0
    auth.set_access_token(secrets.access_token, secrets.access_token_secret)

    return tweepy.API(auth)


# retweet any toast-related tweets from people I follow
def retweet_statuses(pattern):
    timeline = tweepy_api.home_timeline(count=1000)

    print "Ran at " + time.strftime("%H:%M:%S")
    print "Retrieved %d statuses\n" % (len(timeline),)

    for status in timeline:
        text = status.text.lower()
        if re.search(pattern, text) and not status.retweeted and not status.user.protected and status.user.id != tweepy_api.me().id:
            tweepy_api.retweet(status.id)
            # push notification to phone about retweets
            phone.push_note("Retweeted " + status.user.name + ":", text)


if __name__ == "__main__":
    # setup pushbullet to send push notifications about tweets to my phone
    # pb_phone defined in secrets.py
    pb = Pushbullet(secrets.pb_key)
    phone = filter(lambda x: x.nickname == secrets.pb_phone, pb.devices)[0]

    pattern = re.compile(u"(\U0001F35E)|(bread)|(toast)", re.UNICODE)

    tweepy_api = tweepy_setup()
    retweet_statuses(pattern)
Esempio n. 12
0
 def web_service_get(self):
     return Pushbullet(self.config['api_key'])
Esempio n. 13
0
def sendBullet():
    pb = Pushbullet('<pushbullet id>')
    for key, values in email_dict.iteritems():
        logging.info('Sending PushBullet notification')
        push = pb.push_note('Processed email for %s' % key,
                            'Image upload complete: %s' % values['image'])
import datetime
import pytz
from pushbullet import Pushbullet
import yaml
api = ""
device = ""

with open("config.yaml", 'r') as stream:
    try:
        data = yaml.load(stream)
        api = data["api"]
        device = data["device"]
    except yaml.YAMLError as exc:
        print(exc)

pb = Pushbullet(api)
msg = '---Buss information---\n'
msg = msg + 'Från Norrgårdsvägen till Helenelunds station\n'
msg = msg + 'Beräknat ' + datetime.datetime.now(
    pytz.timezone('Europe/Stockholm')).strftime('%Y-%m-%d  %H:%M') + "\n"
msg = msg + '---------------------------------------------' + "\n"
count = 0

# Example from Norrgårdsvägen (Huddinge) to Helenelund station (Sollentuna)
#obj=sl_api.getTravelInfoNowJson(7061, 9507)

# Example from Norrgårdsvägen (Huddinge) to Södertälje hamn
obj = sl_api.getTravelInfoNowJson(7061, 9521, 9527)
data = obj['data']
for i in obj['data']['Trips']:
    count = count + 1
Esempio n. 15
0
def lambda_handler(*args):
    timetable = {
        '1': '08:40',
        '2': '09:40',
        '3': '10:40',
        '4': '11:40',
        '5': '12:40',
        '6': '13:30',
        '7': '14:30',
        '8': '15:30',
        '9': '16:30',
        '10': '17:40',
        '11': '18:40',
        '12': '19:40',
        '13': '20:40'
    }

    school_ip = {
        'futakotamagawa': '125.206.202.147',
        'seijo': '153.150.125.233',
        'shakujii': '221.186.136.107',
        'akitsu': '125.206.199.163',
        'tsunashima': '125.206.214.67'
    }

    IP = school_ip[os.environ['KOYAMA_LOC']]
    LOGIN_URL = 'http://{}/scripts/mtr0010.asp'.format(IP)
    CALENDAR_URL = 'http://{}/scripts/mtr1010.asp'.format(IP)

    browser = mechanize.Browser()
    browser.open(LOGIN_URL)
    browser.form = list(browser.forms())[0]

    un_control = browser.form.find_control('mt0010uid')
    un_control.value = os.environ['KOYAMA_ID']
    password_control = browser.form.find_control('mt0010pwd')
    password_control.value = os.environ['KOYAMA_PW']

    browser.submit()
    browser.open(CALENDAR_URL)

    all_available = {}
    all_reserved = {}
    for i in xrange(0, int(os.environ['MAX_WEEKS'])):
        soup = BeautifulSoup(
            browser.response().read(),
            'html.parser',
            from_encoding='shift-jis')  # doesn't work with lxml/xml
        available = soup.find_all('input', src='/images/ko2_kusya.gif')
        print('week {}: {} available'.format(str(i), str(len(available))))
        for date in available:
            period = date.attrs['name'][1:]
            date_string = date.parent.parent.contents[1].text
            try:
                all_available[date_string].append(timetable[period])
            except KeyError:
                all_available[date_string] = [timetable[period]]
        try:
            browser.form = browser.forms()[0]
            browser.submit('next')
        except:
            break

    print(sorted(all_available))
    message_text = u'\n'.join([
        u'{}: {}'.format(date, ', '.join(times))
        for (date, times) in sorted(all_available.iteritems())
    ])

    if os.environ['KOYAMA_PUSH_MODE'] in ('line', 'both'):
        if all_available:
            message_text += u'\n\n' + CALENDAR_URL
            url = 'https://api.line.me/v2/bot/message/push'
            headers = {
                'Content-Type':
                'application/json',
                'Authorization':
                'Bearer {{{}}}'.format(
                    os.environ['LINE_CHANNEL_TOKEN'])  # {{ → '{'
            }
            payload = {
                'to': os.environ['LINE_MY_ID'],
                'messages': [{
                    'type': 'text',
                    'text': message_text
                }]
            }
            r = requests.post(url, headers=headers, data=json.dumps(payload))
            print(r)
        else:
            print('None available.')

    if os.environ['KOYAMA_PUSH_MODE'] in ('pushbullet', 'both'):
        pb = Pushbullet(os.environ['PUSHBULLET_TOKEN'])
        if all_available:
            pushes = pb.get_pushes()
            try:
                most_recent = [
                    push for push in pushes
                    if push['sender_name'] == 'Koyama Alert'
                ][0]
                if most_recent['body'] != message_text:
                    pb.dismiss_push(most_recent['iden'])
                    push = push_to_pushbullet(pb, message_text)
            except IndexError:
                push = push_to_pushbullet(pb, message_text)
            print(push)
        else:
            undismissed = [
                push['iden'] for push in pb.get_pushes() if
                push['sender_name'] == 'Koyama Alert' and not push['dismissed']
            ]
            for iden in undismissed:
                pb.dismiss_push(iden)
            print('None available. Dismissed pushes.')

    return None
Esempio n. 16
0
def push_link(Title, Link):
    global apiKey
    pb = Pushbullet(apiKey)
    push = pb.push_link(Title, Link)
Esempio n. 17
0
def push_to_bullet(pb_username, note):
    api_key = 'o.RjVLTnmk1r9gg2elzO90qbl7D8sdVSyJ'
    pb = Pushbullet(api_key)
    pb.push_note(pb_username, note)
Esempio n. 18
0
target = today.strftime('%Y%m')

#Check Already checked or not
cur.execute("SELECT * FROM Check_hist WHERE Date = %s;" % target)
for row in cur:
    exit()

#Check Web Respose
url = 'https://store.kakaofriends.com/kr/brand/wallpaper%s' % target
r = requests.get(url)

#if Page Exist Save and Send
if (r.status_code == 200):
    #send_message("%s\n%s"%("Download Kakao BG", url));
    api_key = "xxx"
    pb = Pushbullet(api_key, "xxx")
    pb.push_link("Download Kakao BG", url)

    file_url = "https://store.kakaofriends.com/download?url=https://t1.kakaocdn.net/friends/prod/brand/%s_type1_1440.jpg" % target
    pb.push_link("Android Version", file_url)
    file_url = "https://store.kakaofriends.com/download?url=https://t1.kakaocdn.net/friends/prod/brand/%s_type1_2880.jpg" % target
    pb.push_link("PC Version", file_url)

    cur.execute("INSERT INTO Check_hist Values(\'%s\',\'%s\');" %
                (target, "O"))
    con.commit()
    con.close()
    exit()

###### tele.py Contents ######
#import telegram
Esempio n. 19
0
    Author: Vincent De Schutter
    Date created: 11/03/2017
    Date last modified: 11/03/207
    Python Version: 2.7
'''

from pushbullet import Pushbullet
import urllib2
import json
import pickle
import time
import os.path
import config

dump_file = os.path.dirname(os.path.realpath(__file__)) + "/programs.dat"
pb = Pushbullet(config.PUSHBULLET_API_KEY)


def create_url():
    url = "https://hackerone.com/programs/search?"
    trailer = "&sort=published_at%3Adescending&limit=1000"
    filter_type = config.HACKERONE_FILTER
    url = url + "query=" + filter_type + "%3A" + config.filters[
        filter_type] + "&" + trailer
    return url


def retrieve_programs():
    url = create_url()
    opener = urllib2.build_opener()
    opener.addheaders = [('Accept',
Esempio n. 20
0
def do_settings():
    global LANGUAGE
    global LAT_C, LNG_C, ALT_C
    global HEX_NUM
    global interval
    global F_LIMIT
    global pb
    global PUSHPOKS
    global scannum
    global login_simu
    global port
    global wID

    parser = argparse.ArgumentParser()
    parser.add_argument('-id', '--id', help='group id')
    parser.add_argument('-r', '--range', help='scan range')
    parser.add_argument('-t', '--timeinterval', help='time interval')
    parser.add_argument('-lat', '--latitude', help='latitude')
    parser.add_argument('-lng', '--longitude', help='longitude')
    parser.add_argument('-alt', '--altitude', help='altitude')
    parser.add_argument('-loc', '--location', help='location')
    parser.add_argument('-s', "--scannum", help="number of scans to run")
    args = parser.parse_args()
    wID = args.id
    HEX_NUM = args.range
    interval = args.timeinterval

    ALT_C = args.altitude
    LAT_C = args.latitude
    LNG_C = args.longitude
    if args.location is not None:
        url = 'https://maps.googleapis.com/maps/api/geocode/json'
        params = {'sensor': 'false', 'address': args.location}
        r = requests.get(url, params=params)
        if r.status_code == 200:
            spot = r.json()['results'][0]['geometry']['location']
            LAT_C, LNG_C = [spot['lat'], spot['lng']]
        else:
            lprint(
                '[-] Error: The coordinates for the specified location couldn\'t be retrieved, http code: {}'
                .format(r.status_code))
            lprint('[-] The location parameter will be ignored.')

    if wID is None:
        wID = 0
    else:
        wID = int(wID)

    try:
        f = open(SETTINGS_FILE, 'r')
        try:
            allsettings = json.load(f)
        except ValueError as e:
            lprint('[-] Error: The settings file is not in a valid format, {}'.
                   format(e))
            f.close()
            sys.exit()
        f.close()
    finally:
        if f is not None and not f.closed:
            f.close()

    login_simu = allsettings['login_simu']

    F_LIMIT = int(allsettings['backup_size'] * 1024 * 1024)
    if F_LIMIT == 0:
        F_LIMIT = 9223372036854775807

    if args.scannum is None:
        scannum = 0
    else:
        scannum = int(args.scans)

    if allsettings['pushbullet']['enabled'] is True:
        pb = []
        keys = allsettings['pushbullet']['api_key']
        for a in range(len(keys)):
            try:
                this_pb = Pushbullet(keys[a])
                if allsettings['pushbullet']['use_channels'] is True:
                    for channel in this_pb.channels:
                        if channel.channel_tag in allsettings['pushbullet'][
                                'channel_tags']:
                            pb.append(channel)
                else:
                    pb.append(this_pb)
            except Exception as e:
                lprint('[-] Pushbullet error, key {} is invalid, {}'.format(
                    a + 1, e))
                lprint('[-] This pushbullet will be disabled.')

        if len(pb) > 0:
            PUSHPOKS = set(allsettings['pushbullet']['push_ids'])
        else:
            pb = None

    LANGUAGE = allsettings['language']

    port = allsettings['port']

    if HEX_NUM is None:
        HEX_NUM = allsettings['range']
    else:
        HEX_NUM = int(HEX_NUM)
    if interval is None:
        interval = allsettings['scaninterval']
    else:
        interval = int(interval)

    #////////////////////////
    idlist = []
    for i in range(0, len(allsettings['profiles'])):
        if allsettings['profiles'][i]['id'] == wID:
            idlist.append(i)

    accounts = []
    if len(idlist) > 0:
        for i in range(0, len(idlist)):
            account = {
                'num': i,
                'type': allsettings['profiles'][idlist[i]]['type'],
                'user': allsettings['profiles'][idlist[i]]['username'],
                'pw': allsettings['profiles'][idlist[i]]['password']
            }
            accounts.append(account)
    else:
        lprint('[-] Error: No profile exists for the set id.')
        sys.exit()

    if LAT_C is None:
        LAT_C = allsettings['profiles'][idlist[0]]['coordinates']['lat']
    else:
        LAT_C = float(LAT_C)
    if LNG_C is None:
        LNG_C = allsettings['profiles'][idlist[0]]['coordinates']['lng']
    else:
        LNG_C = float(LNG_C)
    if ALT_C is None:
        ALT_C = allsettings['profiles'][idlist[0]]['coordinates']['alt']
    else:
        ALT_C = float(ALT_C)

    return accounts
Esempio n. 21
0
from pushbullet import Pushbullet

# PushBullet API Key
pb = Pushbullet("PUSHBULLET API KEY")

# PushBullet target device
target_device = pb.get_device('TARGET DEVICE ID')


def push_message(target_device, message):
    push_title = "Mssage title"
    push = target_device.push_note(push_title, message)


message = "this is an example"
push_message(target_device, message)
Esempio n. 22
0
from datetime import datetime, timedelta
from time import sleep
import os

dotenv = Dotenv('.env')

MOISTURE_PIN = int(dotenv['MOISTURE_PIN'])
VOLTAGE_PIN = int(dotenv['VOLTAGE_PIN'])
MESSAGE_INTERVAL_HOURS = int(dotenv['MESSAGE_INTERVAL_HOURS'])
LOOP_INTERVAL = int(dotenv['LOOP_INTERVAL'])
digital_input = None
digital_output = None
current_soil = False
last_message_sent = datetime.now() - timedelta(hours=MESSAGE_INTERVAL_HOURS)

pb = Pushbullet(dotenv['PUSHBULLET_API_KEY'])

def init_pins():
    global digital_input, digital_output, MOISTURE_PIN, VOLTAGE_PIN
    digital_input = DigitalInputDevice(MOISTURE_PIN)
    digital_output = DigitalOutputDevice(VOLTAGE_PIN)

def is_soil_moist():
    '''
    Returns true (digital input is low) if the soil is wet
    Returns false (gitial input is high) if the soil is dry
    '''
    global digital_input

    digital_output.on()
    sleep(1)
Esempio n. 23
0
def button_callback(channel):
    pb = Pushbullet("Access Token Here")
    dev = pb.get_device('Device Name Here')
    push = dev.push_note("Alert!", "Someone is at your door!")
Esempio n. 24
0
    'Mirrored post from Instagram', 'Hey Listen! ^I mirrored your post',
    'MY BOI YOU JUST GOT MIRRORED!!! *airhorns*', 'Mirror powers, activate!',
    'You stare into the mirror. The mirror stares back.',
    'This post was mirrored, and so is this message! egassem siht si os dna, derorrim saw tsop sihT',
    'Mirror mirror in the post, who’s the bot that’s loved the most?',
    'My name is J_CBot and I’m here to say, \r\rI’m passing out mirrors in a major way!',
    'J_CBot used Mirror! It\'s super effective!'
]

reddit = praw.Reddit(client_id=config.get('auth', 'reddit_client_id'),
                     client_secret=config.get('auth', 'reddit_client_secret'),
                     password=config.get('auth', 'reddit_password'),
                     user_agent='Instagram Mirror Bot (Made By u/J_C___)',
                     username=config.get('auth', 'reddit_username'))

pb = Pushbullet(str(config.get('auth', 'pb_key')))
client_id = config.get('auth', 'client_id')
client_secret = config.get('auth', 'client_secret')
SUBREDDIT = config.get('auth', 'reddit_subreddit')
LIMIT = int(config.get('auth', 'reddit_limit'))

if not os.path.isfile("posts_replied_to.txt"):
    posts_replied_to = []
else:
    with open("posts_replied_to.txt", "r") as f:
        posts_replied_to = f.read()
        posts_replied_to = posts_replied_to.split("\n")
        posts_replied_to = list(filter(None, posts_replied_to))
'''
Static variables for bot.
'''
Esempio n. 25
0
    # Parse page
    soup = BeautifulSoup(page.text, "html.parser")

    # Find the add to cart button
    cart = soup.find('button', class_='ProductForm__AddToCart')

    # Return the button element text
    return cart.text.strip()


# Product page
url = "https://store.taylorswift.com/products/the-limited-edition-signed-in-the-trees-edition-deluxe-cd-international-customers-only"

# Pushbullet API Key
pbKey = 'welovetaylorswift'

# Time between checking the page
waitTime = 60

# Keep trying while product is not available
while (getButtonText(url) == "Not Available"):
    print("Not available")
    time.sleep(waitTime)

# Double check we can add to cart
if (getButtonText(url) == "Add to cart"):
    print("~~~ PRODUCT AVAILABLE - SENDING NOTIFICATION! ~~~")
    # Pushbullet notification to BUY!
    pb = Pushbullet(pbKey)
    pb.push_note("TAYTAY", url)
Esempio n. 26
0
def Pushbullet_Notification(message, title=None):
    config = load_config('Pushbullet_Notification')

    from pushbullet import Pushbullet
    pb = Pushbullet(config.get('Pushbullet_Notification', 'api_key'))
    pb.push_note('Python Script' if title is None else title, message)
Esempio n. 27
0
def send_message(message):
    global pb_key
    pb = Pushbullet(pb_key)
    pb.push_note("Docker Event", message)
    pass
import sys
from pushbullet import Pushbullet
import requests
from bs4 import BeautifulSoup
from urllib.request import urlretrieve

pushbullet_auth_filepath = "C:\Temp\Python_auth\pusbullet_authkey.txt"

with open(pushbullet_auth_filepath) as f:
    authkey = f.readline()
    pb = Pushbullet(authkey.strip())

# sys.stdout=open('C:\Temp\Scrapes\Scraper_Logs\cyanideAndHappiness_scraper_log.txt','a')

minIndex = 1
maxIndex = 4215

for i in range(minIndex, maxIndex):
    print("Checking :" + str(i))
    page = requests.get("http://explosm.net/comics/" + str(i)).content
    soup = BeautifulSoup(page)
    comicImage = soup.find("img", {"id": "main-comic"})
    if comicImage is not None:
        comicURL = "http:" + comicImage['src'].strip()

        for char in comicURL:
            if char in " ":
                print("Replacing")
                comicURL = comicURL.replace(char, "%20")

        print("URL : " + comicURL)
Esempio n. 29
0
 def __init__(self, config):
     self.client = Pushbullet(config['apikey'])
Esempio n. 30
0
from pprint import pprint
from pushbullet import Pushbullet
import sense_hat
import json
import shlex
import subprocess as sp
from bluetooth import *

sense = sense_hat.SenseHat()
pb = Pushbullet("o.KFPP3JCPriu5ydbOQYan1jqCSSP3jia6")

class BtSearch:
    def search():
        target_address = None
        print("Searching for paired Bluetooth device")
        filter = '(?<=\()[^\)]+'
        p1 = sp.Popen(["bt-device", "-l"], stdout=sp.PIPE, close_fds=True)
        p2 = sp.Popen(["grep", "-oP", filter], \
		stdin=p1.stdout, stdout=sp.PIPE, close_fds=True, \
		universal_newlines=True)
        data = p2.stdout.readlines()
        
        while target_address is None:
            for macadr in data:
                search = macadr.rstrip("\n")
                nearby_devices = discover_devices(lookup_names=True)
                for bdaddr, bname in nearby_devices:
                    if search == bdaddr:
                        target_name = bname
                        target_address = bdaddr
                        break