def push_to_iOS(title, body, pb_key_filename):
    with open(pb_key_filename) as pb_key_file:
        pb_key = pb_key_file.read()

    pb = PushBullet(pb_key)

    pb.push_note(title, body)
예제 #2
0
    def send_push(title, body):
        pushbullet = PushBullet(api_key)
        if not devices:
            pushbullet.push_note(title=title, body=body)
        else:
            # load devices
            d = pushbullet.devices

            for i in devices:
                d[i].push_note(title=title, body=body)
예제 #3
0
class PushBulletLogger(Logger):
    def __init__(self, level: int, api_key: str) -> None:
        super().__init__(level)
        self._pb = PushBullet(api_key)

    def alert(self, level: int, alert_title: str, alert_msg: str) -> None:
        super().alert(level, alert_title, alert_msg)
        try:
            self._pb.push_note("Cryptrade Alert: ", alert_title)
        except Exception:
            self.log(level, "PushBullet notification failed!")
예제 #4
0
def test_push_note_no_recipents(pb_push, pb_refresh):

    pb = PushBullet("apikey")

    pb.push_note("test_note title", "test_note body")

    pb_push.assert_called_with({
        "type": "note",
        "title": "test_note title",
        "body": "test_note body",
    })
예제 #5
0
class PushBulletSender(Sender):
    def __init__(self, setting):
        super(PushBulletSender, self).__init__(setting)

        self.pushbullet = PushBullet(self.config_api)
        if hasattr(self, 'config_channel'):
            self.pushbullet = self.pushbullet.get_channel(self.config_channel)

    def post(self, title, message, url):
        if url:
            message = '{}\n{}'.format(message, url)
        self.pushbullet.push_note(title, message)
예제 #6
0
    def push_note(self, event):
        """
        Pushes a note to the configured pushbullet accounts
        """

        host = event.host
        title = event.title + ": " + host
        message = host + ": " + event.message + " at " + \
                event.timestamp.strftime("%H:%M:%S %m/%d/%y")

        for key in self.api_keys:
            pb = PushBullet(key)
            pb.push_note(title, message)
예제 #7
0
class PushBulletNotificationService(BaseNotificationService):
    """ Implements notification service for Pushbullet. """
    def __init__(self, api_key):
        from pushbullet import PushBullet

        self.pushbullet = PushBullet(api_key)

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

        title = kwargs.get(ATTR_TITLE)

        self.pushbullet.push_note(title, message)
예제 #8
0
class PushBulletNotificationService(BaseNotificationService):
    """ Implements notification service for Pushbullet. """

    def __init__(self, api_key):
        from pushbullet import PushBullet

        self.pushbullet = PushBullet(api_key)

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

        title = kwargs.get(ATTR_TITLE)

        self.pushbullet.push_note(title, message)
예제 #9
0
 def monitor(self):
     current_model_list = os.listdir(self.model_path)
     from pushbullet import PushBullet
     pb = PushBullet(api_key=self.api_key)
     res1 = self.get_model_status(self.model_path, time.ctime())
     res2, status = self.get_process_status(self.pid)
     pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body=res1 + res2)
     while True:
         now_model_list = os.listdir(self.model_path)
         if now_model_list == current_model_list:
             res2, status = self.get_process_status(self.pid)
             if status == 'fail':
                 pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body='运行结束或者异常,请检查电脑运行情况!!!!!!!')
                 break
             else:
                 pass
         else:
             res1 = self.get_model_status(self.model_path, time.ctime())
             res2, status = self.get_process_status(self.pid)
             current_model_list = now_model_list
             if status == 'fail':
                 pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body='运行结束或者异常,请检查电脑运行情况!!!!!!!')
                 break
             else:
                 pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body=res1 + res2)
예제 #10
0
def test_push_note(pb_push, pb_refresh):
    device = Mock()
    device.device_iden = "123"

    pb = PushBullet("apikey")

    pb.push_note("test_note title", "test_note body", device=device)

    pb_push.assert_called_with({
        "type": "note",
        "title": "test_note title",
        "body": "test_note body",
        "device_iden": "123",
    })
예제 #11
0
class Flow:
    def __init__(self, googleapi, api_key, email, **_):
        if api_key == 'YOUR_API_KEY_HERE':
            raise ValueError('Missing api key in settings')

        self.email = email
        self.pb = PushBullet(api_key)

        self.credentials_storage_path = googleapi.credentials_storage_path
        self.flow = flow_from_clientsecrets(
            filename=googleapi.client_secrets_path,
            scope='https://www.googleapis.com/auth/calendar.readonly',
            redirect_uri='urn:ietf:wg:oauth:2.0:oob')

        self.last_check = None
        self.callback = lambda: None

    def run(self, callback):
        self.callback = callback

        authorize_url = self.flow.step1_get_authorize_url()
        self.pb.push_link('Google Auth Request', authorize_url, email=self.email)
        self.last_check = datetime.now()

    def iter_received_codes(self):
        pushes = self.pb.get_pushes(modified_after=self.last_check.timestamp())
        self.last_check = datetime.now()
        for push in pushes:
            if push['type'] == 'note' and push['sender_email'] == self.email:
                self.pb.dismiss_push(push['iden'])
                yield push['body'].strip()

    def check_response(self):
        if self.last_check is None:
            return

        for code in self.iter_received_codes():
            try:
                credential = self.flow.step2_exchange(code)
                Storage(self.credentials_storage_path).put(credential)
                break
            except (ValueError, FlowExchangeError) as error:
                self.pb.push_note('', 'Error: ' + str(error), email=self.email)
        else:
            return

        self.last_check = None
        self.callback()
        self.pb.push_note('', 'Authentication complete', email=self.email)
예제 #12
0
class PushbulletLogHandler(logging.Handler):
    def __init__(self, api_key, stack_trace=False):
        logging.Handler.__init__(self)
        self.api_key = api_key
        self.stack_trace = stack_trace
        self.pb_session = PushBullet(self.api_key)

    def emit(self, record):
        message = '{}'.format(record.getMessage())

        if self.stack_trace and record.exc_info:
            message += '\n'
            message += '\n'.join(traceback.format_exception(*record.exc_info))

        self.pb_session.push_note('' + str(self.level), message)
예제 #13
0
 def add_alert(self, module, message):
     """ajoute une alerte"""
     if (not module in self.alertes) or self.alertes[module] != message:
         self.alertes[module] = message
         self.write_config()
         pb = PushBullet(self.api_key)
         note = pb.push_note(self.title + " - " + module, message)
예제 #14
0
    class PushbulletNotifier(AbstractNotifier):
        def __init__(self, api_key):
            self.pb = PushBullet(api_key)

        def notify(self, title, message):
            self.pb.push_note(title, message)

        @staticmethod
        def is_enabled():
            if Config.pushbullet_token:
                return True
            return False

        @classmethod
        def from_config(cls):
            return cls(Config.pushbullet_token)
예제 #15
0
def pb_message(pbmsg):
    """Send message using pushbullet module."""
    if args.notify is not None and args.quiet is not True:
        from pushbullet import PushBullet, InvalidKeyError, PushbulletError
        try:
            pb = PushBullet(args.notify)
        except InvalidKeyError:
            log('Notification'.ljust(17) + ' | ' + color('token'.ljust(8)) +
                ' | ')
        except PushbulletError:
            log('Notification'.ljust(17) + ' | ' + color('error'.ljust(8)) +
                ' | ')
        else:
            pb.push_note('Gigaset Elements', pbmsg)
            log('Notification'.ljust(17) + ' | ' + color('pushed'.ljust(8)) +
                ' | ')
    return
예제 #16
0
    class PushbulletNotifier(AbstractNotifier):

        def __init__(self, api_key):
            self.pb = PushBullet(api_key)

        def notify(self, title, message):
            self.pb.push_note(title, message)

        @staticmethod
        def is_enabled():
            if Config.pushbullet_token:
                return True
            return False

        @classmethod
        def from_config(cls):
            return cls(Config.pushbullet_token)
예제 #17
0
def push(title: str, body: str = None) -> None:
    """
    Push a message to iPhone
    :param title: Title of the message to push
    :param body: Body of the message to push

    """
    try:
        with open(
                '/Users/Alex/Documents/Python3/driveuploader/pushbullet_token.txt'
        ) as files:
            token = files.read().strip()
        pb = PushBullet(token)
        pb.push_note('{}'.format(title),
                     '{}'.format(body),
                     device=pb.get_device('iPhone'))
    except:
        pass
예제 #18
0
class PushbulletNotifier(NotifierABC):
    name = 'pushbullet'

    def __init__(self):
        self.pb = PushBullet(NotifiersConfig.get().pushbullet.token)

    def notify(self, title, message):
        self.pb.push_note(title, message)

    @staticmethod
    def is_enabled():
        return bool(NotifiersConfig.get().pushbullet.enabled)

    @staticmethod
    def get_config_template():
        return {
            'enabled': confuse.TypeTemplate(bool),
            'token': confuse.String()
        }
예제 #19
0
def send_pushbullet(followers, ng_group, ng_news):
    msg = build_notif_msg(ng_news)

    for follower in followers:
        if follower.send_pushbullets:
            try:
                pb = PushBullet(follower.pushbullet_api_key)
                if not pb:
                    continue
                pb.push_note(ng_news.subject, msg)
            except Exception:
                pass
            log = Log()
            log.type = 'N'
            log.group = ng_group
            log.user = follower
            log.description = "Pushbullet notification (api_key=%s) (subject=%s)"\
                              % (follower.pushbullet_api_key, ng_news.subject)
            log.save()
예제 #20
0
    def pushbullet_post(self, issue):
        """ Posts to Pushbullet API.
        For future reference, the push_note() function returns two
        values. One bool that specificies whether the push was a success
        or not, and a dict with additional info.
        """

        pb = PushBullet('YOUR-API-KEY')
        worked, push = pb.push_note(u"Förseningar", issue)
        if not worked:
            print(push)
예제 #21
0
class PB_Alarm(Alarm):
    def __init__(self, api_key):
        self.client = PushBullet(api_key)
        log.info("PB_Alarm intialized.")
        push = self.client.push_note("PokeAlarm activated!", "We will alert you about pokemon.")

    def pokemon_alert(self, pokemon):
        notification_text = "A wild " + pokemon['name'].title() + " has appeared!"
        google_maps_link = gmaps_link(pokemon["lat"], pokemon["lng"])
        time_text = pkmn_time_text(pokemon['disappear_time'])
        push = self.client.push_link(notification_text, google_maps_link, body=time_text)
예제 #22
0
 def push(self):
     """ Push a task """
     p = PushBullet(self.api)
     if self.type == 'text':
         success, push = p.push_note(self.title, self.message)
     elif self.type == 'list':
         self.message = self.message.split(',')
         success, push = p.push_list(self.title, self.message)
     elif self.type == 'link':
         success, push = p.push_link(self.title, self.message)
     else:
         success, push = p.push_file(file_url=self.message, file_name="cat.jpg", file_type="image/jpeg")
예제 #23
0
class PushbulletClient(PushNotificationClient):

    _client = None

    def get_name(self):
        return "Pushbullet"

    def set_api_key(self, api):
        try:
            self._client = PushBullet(api)
        except Exception as e:
            self._logger.exception(str(e))

    def send_message(self, title, msg):
        try:
            self._client.push_note(title=title, body=msg)
        except Exception as e:
            self._logger.exception(str(e))

    def set_logger(self, logger):
        pass
예제 #24
0
class PBNotification:
    def __init__(self, title='PyFi Alert', msg=''):
        self.pb = PushBullet(API_KEY)
        self.connected_list = []
        self.disconnected_list = []
        self.title = title
        self.msg = msg

    def add_connected_device(self, device):
        self.connected_list.append(device)

    def add_disconnected_device(self, device):
        self.disconnected_list.append(device)

    def construct_msg(self):
        con_device_list_len = len(self.connected_list)
        if con_device_list_len == 1:
            self.msg += f'{self.connected_list[0]} is connected.'
        elif con_device_list_len == 2:
            self.msg += f'{self.connected_list[0]} and {self.connected_list[1]} are connected.'
        elif con_device_list_len >= 3:
            self.msg += f'{", ".join(self.connected_list[:-1])}, and {self.connected_list[-1]} are connected.'

        if self.msg != '':
            self.msg += ' '

        discon_device_list_len = len(self.disconnected_list)
        if discon_device_list_len == 1:
            self.msg += f'{self.disconnected_list[0]} is disconnected.'
        elif discon_device_list_len == 2:
            self.msg += f'{self.disconnected_list[0]} and {self.disconnected_list[1]} are disconnected.'
        elif discon_device_list_len >= 3:
            self.msg += f'{", ".join(self.disconnected_list[:-1])}, and {self.disconnected_list[-1]} are disconnected.'

    def send_notification(self):
        self.construct_msg()
        if self.msg != '':
            self.pb.push_note(self.title, self.msg)
def notification(product_name, product_price
                 ):  #Function which is used to send notification on our phone

    text = product_name
    text += ' is now available for your desired price.'
    text += '\n You can get it now at '
    text += product_price
    text += '\n'
    text += URL  #Text contains the message which will be displayed as notification

    pb = PushBullet(API_KEY)  #Class Variable of API_KEY

    push = pb.push_note('Price Drop', text)  #Sending Notification
    #Title of Notification followed by text inside the parenthesis

    print('Notification Sent!')  #Prints 'Notification Sent' on your terminal
예제 #26
0
class Pushbullet_Alarm(Alarm):
	
	def __init__(self, settings):
		self.client = PushBullet(settings['api_key']) 
		log_msg = "Pushbullet Alarm intialized"
		if 'name' in settings:
			self.name = settings['name']
			log_mst = log_msg + ": " + self.name
		log.info(log_msg)
		push = self.client.push_note("PokeAlarm activated!", "We will alert you about pokemon.")
		
	def pokemon_alert(self, pkinfo):
		notification_text = pkinfo['alert']
		if hasattr(self, 'name') :
			notification_text = self.name + ": " + notification_text
		gmaps_link = pkinfo['gmaps_link']
		time_text =  pkinfo['time_text']
		push = self.client.push_link(notification_text, gmaps_link, body=time_text)
예제 #27
0
class PB_Alarm(Alarm):
	
	def __init__(self, api_key):
		self.client = PushBullet(api_key) 
		log.info("PB_Alarm intialized.")
		push = self.client.push_note("PokeAlarm activated!", "We will alert you about pokemon.")
		
	def pokemon_alert(self, pokemon):
		#notification_text = "A wild " + pokemon['name'].title() + " has appeared!"
		# Or retrieve a channel by its channel_tag. Note that an InvalidKeyError is raised if the channel_tag does not exist
		#your pushbullet channelname
		my_channel = self.client.get_channel('YOURCHANNELNAME') 
		
		google_maps_link = gmaps_link(pokemon["lat"], pokemon["lng"])
		time_text =  pkmn_time_text(pokemon['disappear_time'])
		notification_text = "("+ pokemon['name'].title() + " found" +"! "+" "  + time_text + "."
		push = self.client.push_link(notification_text, google_maps_link, body=time_text)
		#send to channel
		push = self.client.push_link(notification_text, google_maps_link, body=time_text, channel=my_channel)
def start(api_key,root):
    # flag used to count number of attempt left
    flag = 10
    while 1:
        if is_connected():
            try:
                pb =PushBullet(api_key)
            except:
                tkinter.messagebox.showinfo('Invalid Key','Entered key is invalid!')
                break
            pushMsg =pb.push_note("PYTHON : ","Found Internet Connectivity, is this you? if not message 'No' otherwise message 'Yes' ")
            time.sleep(30)
            val = pb.get_pushes()
            action = val[0]['body']
            print(action)
            if action.lower() == 'no':
               intruder_pic()
               Image_send(pb)
               time.sleep(10)
               logOff()
               root.destroy()
               break
            elif action.lower() == 'yes':
                flag = 10
                time.sleep(3600)
            else:
                flag -= 1
                if flag == 0:
                    intruder_pic()
                    Image_send(pb)
                    time.sleep(10)
                    logOff()
                    root.destroy()
                    break
                time.sleep(60)    
        else:
            time.sleep(600)
예제 #29
0
 def pushbullet_msg_to_device(self,title,body,device=None):
     log.info("Sending notification to Pushbullet service")
     pushb = PushBullet(self.config_get("pushbullet_api_key"))
     pushb.push_note(title,body)
예제 #30
0
from pushbullet import PushBullet

api_key = "<API KEY>"

pb = PushBullet(api_key)
push = pb.push_note("Hello", "World")

#pushes = pb.get_pushes()
#print pushes
예제 #31
0
def pb_alert(title, msg):
    """Makes a Pushbullet push using the configured API key and provided title and message"""
    pb = PushBullet(pb_api)
    pb.push_note(title, msg)
예제 #32
0
def send_push(message, body, pushbullet_token=environ.get('PUSHBULLET_TOKEN')):
    """ Sends a foo location to Pushbullet """
    print pushbullet_token
    pb = PushBullet(pushbullet_token)
    success, push = pb.push_note(message, body)
    return success
예제 #33
0
def mention(bot, event, *args):
    """alert a @mentioned user"""
    """minimum length check for @mention"""
    username = args[0].strip()
    if len(username) <= 2:
        logging.warning("@mention from {} ({}) too short (== '{}')".format(
            event.user.full_name, event.user.id_.chat_id, username))
        return

    users_in_chat = event.conv.users
    mention_chat_ids = []
    """check if synced room, if so, append on the users"""
    sync_room_list = bot.get_config_suboption(event.conv_id, 'sync_rooms')
    if sync_room_list:
        if event.conv_id in sync_room_list:
            for syncedroom in sync_room_list:
                if event.conv_id not in syncedroom:
                    users_in_chat += bot.get_users_in_conversation(syncedroom)
    """
    /bot mention <fragment> test
    """
    noisy_mention_test = False
    if len(args) == 2 and args[1] == "test":
        noisy_mention_test = True
    """
    quidproquo: users can only @mention if they themselves are @mentionable (i.e. have a 1-on-1 with the bot)
    """
    conv_1on1_initiator = bot.get_1on1_conversation(event.user.id_.chat_id)
    if bot.get_config_option("mentionquidproquo"):
        if conv_1on1_initiator:
            logging.info("quidproquo: user {} ({}) has 1-on-1".format(
                event.user.full_name, event.user.id_.chat_id))
        else:
            logging.warning("quidproquo: user {} ({}) has no 1-on-1".format(
                event.user.full_name, event.user.id_.chat_id))
            if noisy_mention_test or bot.get_config_suboption(
                    event.conv_id, 'mentionerrors'):
                bot.send_message_parsed(
                    event.conv,
                    "<b>{}</b> cannot @mention anyone until they say something to me first."
                    .format(event.user.full_name))
            return
    """track mention statistics"""
    user_tracking = {
        "mentioned": [],
        "ignored": [],
        "failed": {
            "pushbullet": [],
            "one2one": [],
        }
    }
    """
    begin mentioning users as long as they exist in the current conversation...
    """

    conversation_name = get_conv_name(event.conv, truncate=True)
    logging.info("@mention '{}' in '{}' ({})".format(username,
                                                     conversation_name,
                                                     event.conv.id_))
    username_lower = username.lower()
    """is @all available globally/per-conversation/initiator?"""
    if username_lower == "all":
        if not bot.get_config_suboption(event.conv.id_, 'mentionall'):
            """global toggle is off/not set, check admins"""
            logging.info(
                "@all in {}: disabled/unset global/per-conversation".format(
                    event.conv.id_))
            admins_list = bot.get_config_suboption(event.conv_id, 'admins')
            if event.user_id.chat_id not in admins_list:
                """initiator is not an admin, check whitelist"""
                logging.info("@all in {}: user {} ({}) is not admin".format(
                    event.conv.id_, event.user.full_name,
                    event.user.id_.chat_id))
                all_whitelist = bot.get_config_suboption(
                    event.conv_id, 'allwhitelist')
                if all_whitelist is None or event.user_id.chat_id not in all_whitelist:

                    logging.warning("@all in {}: user {} ({}) blocked".format(
                        event.conv.id_, event.user.full_name,
                        event.user.id_.chat_id))
                    if conv_1on1_initiator:
                        bot.send_message_parsed(
                            conv_1on1_initiator,
                            "You are not allowed to use @all in <b>{}</b>".
                            format(conversation_name))
                    if noisy_mention_test or bot.get_config_suboption(
                            event.conv_id, 'mentionerrors'):
                        bot.send_message_parsed(
                            event.conv,
                            "<b>{}</b> blocked from using <i>@all</i>".format(
                                event.user.full_name))
                    return
                else:
                    logging.info(
                        "@all in {}: allowed, {} ({}) is whitelisted".format(
                            event.conv.id_, event.user.full_name,
                            event.user.id_.chat_id))
            else:
                logging.info("@all in {}: allowed, {} ({}) is an admin".format(
                    event.conv.id_, event.user.full_name,
                    event.user.id_.chat_id))
        else:
            logging.info("@all in {}: enabled global/per-conversation".format(
                event.conv.id_))
    """generate a list of users to be @mentioned"""
    mention_list = []
    for u in users_in_chat:

        # mentions also checks nicknames if one is configured
        #  exact matches only! see following IF block
        nickname = ""
        nickname_lower = ""
        if bot.memory.exists(['user_data', u.id_.chat_id, "nickname"]):
            nickname = bot.memory.get_by_path(
                ['user_data', u.id_.chat_id, "nickname"])
            nickname_lower = nickname.lower()

        if username_lower == "all" or \
                username_lower in u.full_name.replace(" ", "").lower() or \
                username_lower in u.full_name.replace(" ", "_").lower() or \
                username_lower == nickname_lower:

            logging.info("user {} ({}) is present".format(
                u.full_name, u.id_.chat_id))

            if u.is_self:
                """bot cannot be @mentioned"""
                logging.info("suppressing bot mention by {} ({})".format(
                    event.user.full_name, event.user.id_.chat_id))
                continue

            if u.id_.chat_id == event.user.id_.chat_id and username_lower == "all":
                """prevent initiating user from receiving duplicate @all"""
                logging.info("suppressing @all for {} ({})".format(
                    event.user.full_name, event.user.id_.chat_id))
                continue

            if u.id_.chat_id in mention_chat_ids:
                """prevent most duplicate mentions (in the case of syncouts)"""
                logging.info(
                    "suppressing duplicate mention for {} ({})".format(
                        event.user.full_name, event.user.id_.chat_id))
                continue

            donotdisturb = bot.config.get('donotdisturb')
            if donotdisturb:
                """user-configured DND"""
                if u.id_.chat_id in donotdisturb:
                    logging.info("suppressing @mention for {} ({})".format(
                        u.full_name, u.id_.chat_id))
                    user_tracking["ignored"].append(u.full_name)
                    continue

            mention_list.append(u)

    if len(mention_list) > 1 and username_lower != "all":
        if conv_1on1_initiator:
            html = '{} users would be mentioned with "@{}"! Be more specific. List of matching users:<br />'.format(
                len(mention_list), username, conversation_name)

            for u in mention_list:
                html += u.full_name
                if bot.memory.exists(['user_data', u.id_.chat_id, "nickname"]):
                    html += ' (' + bot.memory.get_by_path(
                        ['user_data', u.id_.chat_id, "nickname"]) + ')'
                html += '<br />'

            bot.send_message_parsed(conv_1on1_initiator, html)

        logging.info(
            "@{} not sent due to multiple recipients".format(username_lower))
        return  #SHORT-CIRCUIT
    """send @mention alerts"""
    for u in mention_list:
        alert_via_1on1 = True
        """pushbullet integration"""
        pushbullet_integration = bot.get_config_suboption(
            event.conv.id_, 'pushbullet')
        if pushbullet_integration is not None:
            if u.id_.chat_id in pushbullet_integration.keys():
                pushbullet_config = pushbullet_integration[u.id_.chat_id]
                if pushbullet_config["api"] is not None:
                    pb = PushBullet(pushbullet_config["api"])
                    success, push = pb.push_note(
                        "{} mentioned you in {}".format(
                            event.user.full_name, conversation_name,
                            event.text))
                    if success:
                        user_tracking["mentioned"].append(u.full_name)
                        logging.info("{} ({}) alerted via pushbullet".format(
                            u.full_name, u.id_.chat_id))
                        alert_via_1on1 = False  # disable 1on1 alert
                    else:
                        user_tracking["failed"]["pushbullet"].append(
                            u.full_name)
                        logging.warning(
                            "pushbullet alert failed for {} ({})".format(
                                u.full_name, u.id_.chat_id))

        if alert_via_1on1:
            """send alert with 1on1 conversation"""
            conv_1on1 = bot.get_1on1_conversation(u.id_.chat_id)
            if conv_1on1:
                bot.send_message_parsed(
                    conv_1on1,
                    "<b>{}</b> @mentioned you in <i>{}</i>:<br />{}".format(
                        event.user.full_name, conversation_name, event.text))
                mention_chat_ids.append(u.id_.chat_id)
                user_tracking["mentioned"].append(u.full_name)
                logging.info("{} ({}) alerted via 1on1 ({})".format(
                    u.full_name, u.id_.chat_id, conv_1on1.id_))
            else:
                user_tracking["failed"]["one2one"].append(u.full_name)
                if bot.get_config_suboption(event.conv_id, 'mentionerrors'):
                    bot.send_message_parsed(
                        event.conv,
                        "@mention didn't work for <b>{}</b>. User must say something to me first."
                        .format(u.full_name))
                logging.warning(
                    "user {} ({}) could not be alerted via 1on1".format(
                        u.full_name, u.id_.chat_id))

    if noisy_mention_test:
        html = "<b>@mentions:</b><br />"
        if len(user_tracking["failed"]["one2one"]) > 0:
            html = html + "1-to-1 fail: <i>{}</i><br />".format(", ".join(
                user_tracking["failed"]["one2one"]))
        if len(user_tracking["failed"]["pushbullet"]) > 0:
            html = html + "PushBullet fail: <i>{}</i><br />".format(", ".join(
                user_tracking["failed"]["pushbullet"]))
        if len(user_tracking["ignored"]) > 0:
            html = html + "Ignored (DND): <i>{}</i><br />".format(", ".join(
                user_tracking["ignored"]))
        if len(user_tracking["mentioned"]) > 0:
            html = html + "Alerted: <i>{}</i><br />".format(", ".join(
                user_tracking["mentioned"]))
        else:
            html = html + "Nobody was successfully @mentioned ;-(<br />"

        if len(user_tracking["failed"]["one2one"]) > 0:
            html = html + "Users failing 1-to-1 need to say something to me privately first.<br />"

        bot.send_message_parsed(event.conv, html)
예제 #34
0
def mention(bot, event, *args):
    """alert a @mentioned user"""

    """minimum length check for @mention"""
    username = args[0].strip()
    if len(username) < 2:
        logging.warning(_("@mention from {} ({}) too short (== '{}')").format(event.user.full_name, event.user.id_.chat_id, username))
        return

    users_in_chat = event.conv.users
    mention_chat_ids = []

    """sync room support"""
    if bot.get_config_option('syncing_enabled'):
        sync_room_list = bot.get_config_option('sync_rooms')
        if sync_room_list:
            """scan through each room group"""
            for rooms_group in sync_room_list:
                if event.conv_id in rooms_group:
                    """current conversation is part of a syncroom group, add "external" users"""
                    for syncedroom in rooms_group:
                        if event.conv_id is not syncedroom:
                            users_in_chat += bot.get_users_in_conversation(syncedroom)
                    users_in_chat = list(set(users_in_chat)) # make unique
                    logging.info(_("@mention in a syncroom: {} user(s) present").format(len(users_in_chat)))
                    break

    """
    /bot mention <fragment> test
    """
    noisy_mention_test = False
    if len(args) == 2 and args[1] == "test":
        noisy_mention_test = True

    initiator_has_dnd = _user_has_dnd(bot, event.user.id_.chat_id)

    """
    quidproquo: users can only @mention if they themselves are @mentionable (i.e. have a 1-on-1 with the bot)
    """
    conv_1on1_initiator = bot.get_1on1_conversation(event.user.id_.chat_id)
    if bot.get_config_option("mentionquidproquo"):
        if conv_1on1_initiator:
            if initiator_has_dnd:
                logging.info(_("quidproquo: user {} ({}) has DND active").format(event.user.full_name, event.user.id_.chat_id))
                if noisy_mention_test or bot.get_config_suboption(event.conv_id, 'mentionerrors'):
                    bot.send_message_parsed(
                        event.conv,
                        _("<b>{}</b>, you cannot @mention anyone until your DND status is toggled off.").format(
                            event.user.full_name))
                return
            else:
                logging.info(_("quidproquo: user {} ({}) has 1-on-1").format(event.user.full_name, event.user.id_.chat_id))
        else:
            logging.warning(_("quidproquo: user {} ({}) has no 1-on-1").format(event.user.full_name, event.user.id_.chat_id))
            if noisy_mention_test or bot.get_config_suboption(event.conv_id, 'mentionerrors'):
                bot.send_message_parsed(
                    event.conv,
                    _("<b>{}</b> cannot @mention anyone until they say something to me first.").format(
                        event.user.full_name))
            return

    """track mention statistics"""
    user_tracking = {
      "mentioned":[],
      "ignored":[],
      "failed": {
        "pushbullet": [],
        "one2one": [],
      }
    }

    """
    begin mentioning users as long as they exist in the current conversation...
    """

    conversation_name = get_conv_name(event.conv, truncate=True);
    logging.info(_("@mention '{}' in '{}' ({})").format(username, conversation_name, event.conv.id_))
    username_lower = username.lower()

    """is @all available globally/per-conversation/initiator?"""
    if username_lower == "all":
        if not bot.get_config_suboption(event.conv.id_, 'mentionall'):

            """global toggle is off/not set, check admins"""
            logging.info(_("@all in {}: disabled/unset global/per-conversation").format(event.conv.id_))
            admins_list = bot.get_config_suboption(event.conv_id, 'admins')
            if event.user_id.chat_id not in admins_list:

                """initiator is not an admin, check whitelist"""
                logging.info(_("@all in {}: user {} ({}) is not admin").format(event.conv.id_, event.user.full_name, event.user.id_.chat_id))
                all_whitelist = bot.get_config_suboption(event.conv_id, 'mentionallwhitelist')
                if all_whitelist is None or event.user_id.chat_id not in all_whitelist:

                    logging.warning(_("@all in {}: user {} ({}) blocked").format(event.conv.id_, event.user.full_name, event.user.id_.chat_id))
                    if conv_1on1_initiator:
                        bot.send_message_parsed(
                            conv_1on1_initiator,
                            _("You are not allowed to use @all in <b>{}</b>").format(
                                conversation_name))
                    if noisy_mention_test or bot.get_config_suboption(event.conv_id, 'mentionerrors'):
                        bot.send_message_parsed(
                            event.conv,
                            _("<b>{}</b> blocked from using <i>@all</i>").format(
                                event.user.full_name))
                    return
                else:
                    logging.info(_("@all in {}: allowed, {} ({}) is whitelisted").format(event.conv.id_, event.user.full_name, event.user.id_.chat_id))
            else:
                logging.info(_("@all in {}: allowed, {} ({}) is an admin").format(event.conv.id_, event.user.full_name, event.user.id_.chat_id))
        else:
            logging.info(_("@all in {}: enabled global/per-conversation").format(event.conv.id_))

    """generate a list of users to be @mentioned"""
    exact_nickname_matches = []
    mention_list = []
    for u in users_in_chat:

        # mentions also checks nicknames if one is configured
        #  exact matches only! see following IF block
        nickname = ""
        nickname_lower = ""
        if bot.memory.exists(['user_data', u.id_.chat_id, "nickname"]):
            nickname = bot.memory.get_by_path(['user_data', u.id_.chat_id, "nickname"])
            nickname_lower = nickname.lower()

        if username_lower == "all" or \
                username_lower in u.full_name.replace(" ", "").lower() or \
                username_lower in u.full_name.replace(" ", "_").lower() or \
                username_lower == nickname_lower:

            logging.info(_("user {} ({}) is present").format(u.full_name, u.id_.chat_id))

            if u.is_self:
                """bot cannot be @mentioned"""
                logging.info(_("suppressing bot mention by {} ({})").format(event.user.full_name, event.user.id_.chat_id))
                continue

            if u.id_.chat_id == event.user.id_.chat_id and username_lower == "all":
                """prevent initiating user from receiving duplicate @all"""
                logging.info(_("suppressing @all for {} ({})").format(event.user.full_name, event.user.id_.chat_id))
                continue

            if u.id_.chat_id in mention_chat_ids:
                """prevent most duplicate mentions (in the case of syncouts)"""
                logging.info(_("suppressing duplicate mention for {} ({})").format(event.user.full_name, event.user.id_.chat_id))
                continue

            if bot.memory.exists(["donotdisturb"]):
                if _user_has_dnd(bot, u.id_.chat_id):
                    logging.info(_("suppressing @mention for {} ({})").format(u.full_name, u.id_.chat_id))
                    user_tracking["ignored"].append(u.full_name)
                    continue

            if username_lower == nickname_lower:
                if u not in exact_nickname_matches:
                    exact_nickname_matches.append(u)

            if u not in mention_list:
                mention_list.append(u)

    """prioritise exact nickname matches"""
    if len(exact_nickname_matches) == 1:
        logging.info(_("prioritising nickname match for {}").format(exact_nickname_matches[0].full_name))
        mention_list = exact_nickname_matches

    if len(mention_list) > 1 and username_lower != "all":
        if conv_1on1_initiator:
            text_html = _('{} users would be mentioned with "@{}"! Be more specific. List of matching users:<br />').format(
                len(mention_list), username, conversation_name)

            for u in mention_list:
                text_html += u.full_name
                if bot.memory.exists(['user_data', u.id_.chat_id, "nickname"]):
                    text_html += ' (' + bot.memory.get_by_path(['user_data', u.id_.chat_id, "nickname"]) + ')'
                text_html += '<br />'

            bot.send_message_parsed(conv_1on1_initiator, text_html)

        logging.info(_("@{} not sent due to multiple recipients").format(username_lower))
        return #SHORT-CIRCUIT

    """send @mention alerts"""
    for u in mention_list:
            alert_via_1on1 = True

            """pushbullet integration"""
            if bot.memory.exists(['user_data', u.id_.chat_id, "pushbullet"]):
                pushbullet_config = bot.memory.get_by_path(['user_data', u.id_.chat_id, "pushbullet"])
                if pushbullet_config is not None:
                    if pushbullet_config["api"] is not None:
                        pb = PushBullet(pushbullet_config["api"])
                        success, push = pb.push_note(
                            _("{} mentioned you in {}").format(
                                    event.user.full_name,
                                    conversation_name),
                                event.text)
                        if success:
                            user_tracking["mentioned"].append(u.full_name)
                            logging.info(_("{} ({}) alerted via pushbullet").format(u.full_name, u.id_.chat_id))
                            alert_via_1on1 = False # disable 1on1 alert
                        else:
                            user_tracking["failed"]["pushbullet"].append(u.full_name)
                            logging.warning(_("pushbullet alert failed for {} ({})").format(u.full_name, u.id_.chat_id))

            if alert_via_1on1:
                """send alert with 1on1 conversation"""
                conv_1on1 = bot.get_1on1_conversation(u.id_.chat_id)
                if conv_1on1:
                    bot.send_message_parsed(
                        conv_1on1,
                        _("<b>{}</b> @mentioned you in <i>{}</i>:<br />{}").format(
                            event.user.full_name,
                            conversation_name,
                            event.text)) # prevent internal parser from removing <tags>
                    mention_chat_ids.append(u.id_.chat_id)
                    user_tracking["mentioned"].append(u.full_name)
                    logging.info(_("{} ({}) alerted via 1on1 ({})").format(u.full_name, u.id_.chat_id, conv_1on1.id_))
                else:
                    user_tracking["failed"]["one2one"].append(u.full_name)
                    if bot.get_config_suboption(event.conv_id, 'mentionerrors'):
                        bot.send_message_parsed(
                            event.conv,
                            _("@mention didn't work for <b>{}</b>. User must say something to me first.").format(
                                u.full_name))
                    logging.warning(_("user {} ({}) could not be alerted via 1on1").format(u.full_name, u.id_.chat_id))

    if noisy_mention_test:
        text_html = _("<b>@mentions:</b><br />")
        if len(user_tracking["failed"]["one2one"]) > 0:
            text_html = text_html + _("1-to-1 fail: <i>{}</i><br />").format(", ".join(user_tracking["failed"]["one2one"]))
        if len(user_tracking["failed"]["pushbullet"]) > 0:
            text_html = text_html + _("PushBullet fail: <i>{}</i><br />").format(", ".join(user_tracking["failed"]["pushbullet"]))
        if len(user_tracking["ignored"]) > 0:
            text_html = text_html + _("Ignored (DND): <i>{}</i><br />").format(", ".join(user_tracking["ignored"]))
        if len(user_tracking["mentioned"]) > 0:
            text_html = text_html + _("Alerted: <i>{}</i><br />").format(", ".join(user_tracking["mentioned"]))
        else:
            text_html = text_html + _("Nobody was successfully @mentioned ;-(<br />")

        if len(user_tracking["failed"]["one2one"]) > 0:
            text_html = text_html + _("Users failing 1-to-1 need to say something to me privately first.<br />")

        bot.send_message_parsed(event.conv, text_html)
예제 #35
0
def mention(bot, event, *args):
    """alert a @mentioned user"""

    """allow mentions to be disabled via global or per-conversation config"""
    config_mentions_enabled = False if bot.get_config_suboption(event.conv.id_, "mentions.enabled") is False else True
    if not config_mentions_enabled:
        logger.info("mentions explicitly disabled by config for {}".format(event.conv_id))
        return

    """minimum length check for @mention"""
    minimum_length = bot.get_config_suboption(event.conv_id, "mentionminlength")
    if not minimum_length:
        minimum_length = 2
    username = args[0].strip()
    if len(username) < minimum_length:
        logger.debug(
            "@mention from {} ({}) too short (== '{}')".format(event.user.full_name, event.user.id_.chat_id, username)
        )
        return

    users_in_chat = event.conv.users
    mention_chat_ids = []

    """sync room support"""
    if bot.get_config_option("syncing_enabled"):
        sync_room_list = bot.get_config_option("sync_rooms")
        if sync_room_list:
            """scan through each room group"""
            for rooms_group in sync_room_list:
                if event.conv_id in rooms_group:
                    """current conversation is part of a syncroom group, add "external" users"""
                    for syncedroom in rooms_group:
                        if event.conv_id is not syncedroom:
                            users_in_chat += bot.get_users_in_conversation(syncedroom)
                    users_in_chat = list(set(users_in_chat))  # make unique
                    logger.debug("@mention in a syncroom: {} user(s) present".format(len(users_in_chat)))
                    break

    """
    /bot mention <fragment> test
    """
    noisy_mention_test = False
    if len(args) == 2 and args[1] == "test":
        noisy_mention_test = True

    initiator_has_dnd = _user_has_dnd(bot, event.user.id_.chat_id)

    """
    quidproquo: users can only @mention if they themselves are @mentionable (i.e. have a 1-on-1 with the bot)
    """
    conv_1on1_initiator = yield from bot.get_1to1(event.user.id_.chat_id)
    if bot.get_config_option("mentionquidproquo"):
        if conv_1on1_initiator:
            if initiator_has_dnd:
                logger.info(
                    "quidproquo: user {} ({}) has DND active".format(event.user.full_name, event.user.id_.chat_id)
                )
                if noisy_mention_test or bot.get_config_suboption(event.conv_id, "mentionerrors"):
                    yield from bot.coro_send_message(
                        event.conv,
                        _("<b>{}</b>, you cannot @mention anyone until your DND status is toggled off.").format(
                            event.user.full_name
                        ),
                    )
                return
            else:
                logger.debug("quidproquo: user {} ({}) has 1-on-1".format(event.user.full_name, event.user.id_.chat_id))
        else:
            logger.info("quidproquo: user {} ({}) has no 1-on-1".format(event.user.full_name, event.user.id_.chat_id))
            if noisy_mention_test or bot.get_config_suboption(event.conv_id, "mentionerrors"):
                yield from bot.coro_send_message(
                    event.conv,
                    _("<b>{}</b> cannot @mention anyone until they say something to me first.").format(
                        event.user.full_name
                    ),
                )
            return

    """track mention statistics"""
    user_tracking = {"mentioned": [], "ignored": [], "failed": {"pushbullet": [], "one2one": []}}

    """
    begin mentioning users as long as they exist in the current conversation...
    """

    conversation_name = bot.conversations.get_name(event.conv)
    logger.info("@mention '{}' in '{}' ({})".format(username, conversation_name, event.conv.id_))
    username_lower = username.lower()
    username_upper = username.upper()

    """is @all available globally/per-conversation/initiator?"""
    if username_lower == "all":
        if not bot.get_config_suboption(event.conv.id_, "mentionall"):

            """global toggle is off/not set, check admins"""
            logger.debug("@all in {}: disabled/unset global/per-conversation".format(event.conv.id_))
            admins_list = bot.get_config_suboption(event.conv_id, "admins")
            if event.user_id.chat_id not in admins_list:

                """initiator is not an admin, check whitelist"""
                logger.debug(
                    "@all in {}: user {} ({}) is not admin".format(
                        event.conv.id_, event.user.full_name, event.user.id_.chat_id
                    )
                )
                all_whitelist = bot.get_config_suboption(event.conv_id, "mentionallwhitelist")
                if all_whitelist is None or event.user_id.chat_id not in all_whitelist:

                    logger.warning(
                        "@all in {}: user {} ({}) blocked".format(
                            event.conv.id_, event.user.full_name, event.user.id_.chat_id
                        )
                    )
                    if conv_1on1_initiator:
                        yield from bot.coro_send_message(
                            conv_1on1_initiator,
                            _("You are not allowed to mention all users in <b>{}</b>").format(conversation_name),
                        )
                    if noisy_mention_test or bot.get_config_suboption(event.conv_id, "mentionerrors"):
                        yield from bot.coro_send_message(
                            event.conv, _("<b>{}</b> blocked from mentioning all users").format(event.user.full_name)
                        )
                    return
                else:
                    logger.info(
                        "@all in {}: allowed, {} ({}) is whitelisted".format(
                            event.conv.id_, event.user.full_name, event.user.id_.chat_id
                        )
                    )
            else:
                logger.info(
                    "@all in {}: allowed, {} ({}) is an admin".format(
                        event.conv.id_, event.user.full_name, event.user.id_.chat_id
                    )
                )
        else:
            logger.info("@all in {}: enabled global/per-conversation".format(event.conv.id_))

    """generate a list of users to be @mentioned"""
    exact_nickname_matches = []
    exact_fragment_matches = []
    mention_list = []
    for u in users_in_chat:

        # mentions also checks nicknames if one is configured
        #  exact matches only! see following IF block
        nickname = ""
        nickname_lower = ""
        if bot.memory.exists(["user_data", u.id_.chat_id, "nickname"]):
            nickname = bot.memory.get_by_path(["user_data", u.id_.chat_id, "nickname"])
            nickname_lower = nickname.lower()

        _normalised_full_name_upper = remove_accents(u.full_name.upper())

        if (
            username_lower == "all"
            or username_lower in u.full_name.replace(" ", "").lower()
            or username_upper in _normalised_full_name_upper.replace(" ", "")
            or username_lower in u.full_name.replace(" ", "_").lower()
            or username_upper in _normalised_full_name_upper.replace(" ", "_")
            or username_lower == nickname_lower
            or username in u.full_name.split(" ")
        ):

            logger.info("user {} ({}) is present".format(u.full_name, u.id_.chat_id))

            if u.is_self:
                """bot cannot be @mentioned"""
                logger.debug("suppressing bot mention by {} ({})".format(event.user.full_name, event.user.id_.chat_id))
                continue

            if u.id_.chat_id == event.user.id_.chat_id and username_lower == "all":
                """prevent initiating user from receiving duplicate @all"""
                logger.debug("suppressing @all for {} ({})".format(event.user.full_name, event.user.id_.chat_id))
                continue

            if u.id_.chat_id == event.user.id_.chat_id and not noisy_mention_test:
                """prevent initiating user from mentioning themselves"""
                logger.debug("suppressing @self for {} ({})".format(event.user.full_name, event.user.id_.chat_id))
                continue

            if u.id_.chat_id in mention_chat_ids:
                """prevent most duplicate mentions (in the case of syncouts)"""
                logger.debug(
                    "suppressing duplicate mention for {} ({})".format(event.user.full_name, event.user.id_.chat_id)
                )
                continue

            if bot.memory.exists(["donotdisturb"]):
                if _user_has_dnd(bot, u.id_.chat_id):
                    logger.info("suppressing @mention for {} ({})".format(u.full_name, u.id_.chat_id))
                    user_tracking["ignored"].append(u.full_name)
                    continue

            if username_lower == nickname_lower:
                if u not in exact_nickname_matches:
                    exact_nickname_matches.append(u)

            if username in u.full_name.split(" ") or username_upper in _normalised_full_name_upper.split(" "):

                if u not in exact_fragment_matches:
                    exact_fragment_matches.append(u)

            if u not in mention_list:
                mention_list.append(u)

    if len(exact_nickname_matches) == 1:
        """prioritise exact nickname matches"""
        logger.info("prioritising nickname match for {}".format(exact_nickname_matches[0].full_name))
        mention_list = exact_nickname_matches
    elif len(exact_fragment_matches) == 1:
        """prioritise case-sensitive fragment matches"""
        logger.info(
            "prioritising single case-sensitive fragment match for {}".format(exact_fragment_matches[0].full_name)
        )
        mention_list = exact_fragment_matches
    elif len(exact_fragment_matches) > 1 and len(exact_fragment_matches) < len(mention_list):
        logger.info(
            "prioritising multiple case-sensitive fragment match for {}".format(exact_fragment_matches[0].full_name)
        )
        mention_list = exact_fragment_matches

    if len(mention_list) > 1 and username_lower != "all":

        send_multiple_user_message = True

        if bot.memory.exists(["user_data", event.user.id_.chat_id, "mentionmultipleusermessage"]):
            send_multiple_user_message = bot.memory.get_by_path(
                ["user_data", event.user.id_.chat_id, "mentionmultipleusermessage"]
            )

        if send_multiple_user_message or noisy_mention_test:
            if conv_1on1_initiator:
                text_html = _(
                    '{} users would be mentioned with "@{}"! Be more specific. List of matching users:<br />'
                ).format(len(mention_list), username, conversation_name)

                for u in mention_list:
                    text_html += u.full_name
                    if bot.memory.exists(["user_data", u.id_.chat_id, "nickname"]):
                        text_html += " (" + bot.memory.get_by_path(["user_data", u.id_.chat_id, "nickname"]) + ")"
                    text_html += "<br />"

                text_html += "<br /><em>To toggle this message on/off, use <b>/bot bemorespecific</b></em>"

                yield from bot.coro_send_message(conv_1on1_initiator, text_html)

        logger.warning("@{} not sent due to multiple recipients".format(username_lower))
        return  # SHORT-CIRCUIT

    """support for reprocessor
    override the source name by defining event._external_source"""
    source_name = event.user.full_name
    if hasattr(event, "_external_source"):
        source_name = event._external_source

    """send @mention alerts"""
    for u in mention_list:
        alert_via_1on1 = True

        """pushbullet integration"""
        if bot.memory.exists(["user_data", u.id_.chat_id, "pushbullet"]):
            pushbullet_config = bot.memory.get_by_path(["user_data", u.id_.chat_id, "pushbullet"])
            if pushbullet_config is not None:
                if pushbullet_config["api"] is not None:
                    success = False
                    try:
                        pb = PushBullet(pushbullet_config["api"])
                        push = pb.push_note(
                            _("{} mentioned you in {}").format(source_name, conversation_name), event.text
                        )
                        if isinstance(push, tuple):
                            # backward-compatibility for pushbullet library < 0.8.0
                            success = push[0]
                        elif isinstance(push, dict):
                            success = True
                        else:
                            raise TypeError("unknown return from pushbullet library: {}".format(push))
                    except Exception as e:
                        logger.exception("pushbullet error")

                    if success:
                        user_tracking["mentioned"].append(u.full_name)
                        logger.info("{} ({}) alerted via pushbullet".format(u.full_name, u.id_.chat_id))
                        alert_via_1on1 = False  # disable 1on1 alert
                    else:
                        user_tracking["failed"]["pushbullet"].append(u.full_name)
                        logger.warning("pushbullet alert failed for {} ({})".format(u.full_name, u.id_.chat_id))

        if alert_via_1on1:
            """send alert with 1on1 conversation"""
            conv_1on1 = yield from bot.get_1to1(u.id_.chat_id)
            if conv_1on1:
                yield from bot.coro_send_message(
                    conv_1on1,
                    _("<b>{}</b> @mentioned you in <i>{}</i>:<br />{}").format(
                        source_name, conversation_name, event.text
                    ),
                )  # prevent internal parser from removing <tags>
                mention_chat_ids.append(u.id_.chat_id)
                user_tracking["mentioned"].append(u.full_name)
                logger.info("{} ({}) alerted via 1on1 ({})".format(u.full_name, u.id_.chat_id, conv_1on1.id_))
            else:
                user_tracking["failed"]["one2one"].append(u.full_name)
                if bot.get_config_suboption(event.conv_id, "mentionerrors"):
                    yield from bot.coro_send_message(
                        event.conv,
                        _("@mention didn't work for <b>{}</b>. User must say something to me first.").format(
                            u.full_name
                        ),
                    )
                logger.warning("user {} ({}) could not be alerted via 1on1".format(u.full_name, u.id_.chat_id))

    if noisy_mention_test:
        text_html = _("<b>@mentions:</b><br />")
        if len(user_tracking["failed"]["one2one"]) > 0:
            text_html = text_html + _("1-to-1 fail: <i>{}</i><br />").format(
                ", ".join(user_tracking["failed"]["one2one"])
            )
        if len(user_tracking["failed"]["pushbullet"]) > 0:
            text_html = text_html + _("PushBullet fail: <i>{}</i><br />").format(
                ", ".join(user_tracking["failed"]["pushbullet"])
            )
        if len(user_tracking["ignored"]) > 0:
            text_html = text_html + _("Ignored (DND): <i>{}</i><br />").format(", ".join(user_tracking["ignored"]))
        if len(user_tracking["mentioned"]) > 0:
            text_html = text_html + _("Alerted: <i>{}</i><br />").format(", ".join(user_tracking["mentioned"]))
        else:
            text_html = text_html + _("Nobody was successfully @mentioned ;-(<br />")

        if len(user_tracking["failed"]["one2one"]) > 0:
            text_html = text_html + _("Users failing 1-to-1 need to say something to me privately first.<br />")

        yield from bot.coro_send_message(event.conv, text_html)
            try:
                if settings.pushbullet_use_channel:
                    channels = p.channels
                    for channel in channels:
                        #print dev.device_iden + ' ' + dev.nickname
                        if channel.channel_tag == settings.pushbullet_channel_tag:
                            sendto_channel = channel
                    if not sendto_channel:
                        logger.error('PushBullet channel configured, but tag "' + settings.pushbullet_channel_tag + '" not found')
                        print('PushBullet channel configured, but tag "' + settings.pushbullet_channel_tag + '" not found')
            except AttributeError, e:
                logger.error('PushBullet channel settings not found - ' + str(e))
                print('PushBullet channel settings not found, see settings_example.py - ' + str(e))

            for disruption in changed_disruptions:
                message = format_disruption(disruption)
                logger.debug(message)
                #print message
                if sendto_channel:
                    sendto_channel.push_note(message['header'], message['message'])
                else:
                    p.push_note(message['header'], message['message'], sendto_device)
        if trips:
            for trip in trips:
                if trip.has_delay:
                    message = format_trip(trip)
                    #print message
                    logger.debug(message)
                    #p.push_note('title', 'body', sendto_device)
                    p.push_note(message['header'], message['message'], sendto_device)
예제 #37
0
파일: quora.py 프로젝트: AlbertBGeorge/py4e
import time
import os
#takes intruder pic
def intruder_pic():
 cam=cv2.VideoCapture(0)
 s,im=cam.read()
 #cv2.imshow("Test Picture",im)
 cv2.imwrite("Intruder.bmp",im)
#intruder suspected message
def suspected_message():
 speak = wincl.Dispatch("SAPI.SpVoice")
 speak.Speak("Intruder Suspected")
#Your PushBullet API key
api_key ="YourPushBulletAPIKeyHere"
pb =PushBullet(api_key)
pushMsg =pb.push_note("PYTHON : ","Found Internet Connectivity, is this you? if not message 'No' ")
#pushes captured image to Mobile
def Image_send():
 with open("Intruder.bmp", "rb") as pic:
 file_data = pb.upload_file(pic, "Intruder.bmp")
 push = pb.push_file(**file_data)
#log off PC if Intruder Suspected
def logOff():
 os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
#Controller
def Control():
 while True:
 val =pb.get_pushes()
 action =val[0]['body']
 print(action)
 if action=='No' or 'no':
예제 #38
0
def main(output_mode, test_mode, funds_info_file, output_file, pushbullet_key):
    funds_info = pd.read_csv(os.path.join(os.getcwd(), funds_info_file),
                             float_precision='high')
    nfunds = len(funds_info['fund number'])

    user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
    headers = {
        'User-Agent': user_agent,
    }
    url_base = "https://www.funder.co.il/fund/"
    messages = []
    for inx in range(nfunds):
        fund_number = funds_info['fund number'][inx]
        request = Request(url_base + str(fund_number), None,
                          headers)  #The assembled request
        response = urlopen(request)
        # page source:
        data = response.read()  # The data u need
        nihol = re.findall(r'"nihol":(.*?),', data.decode('utf-8'))
        nemanut = re.findall(r'"nemanut":(.*?),', data.decode('utf-8'))
        if len(nihol) > 1 or len(nihol) == 0:
            msg = f'More than 1 value or no values for nihol for fund {str(fund_number)} was found, skipping fund'
            messages.append(msg)
            warnings.warn(msg)
            continue
        if len(nemanut) > 1 or len(nemanut) == 0:
            msg = f'More than 1 value or no values for nemanut for fund {str(fund_number)} was found, skipping fund'
            messages.append(msg)
            warnings.warn(msg)
            continue

        nihol = round(float(nihol[0]), 3)
        nemanut = round(float(nemanut[0]), 3)

        # compare with current value:
        if nihol != funds_info['nihol (%)'][inx]:
            msg = f"For fund number {str(fund_number)} the nihol fee changed! It was {funds_info['nihol (%)'][inx]} and now {nihol}"
            messages.append(msg)
        if nemanut != funds_info['nemanut (%)'][inx]:
            msg = f"For fund number {str(fund_number)} the nemanut fee changed! It was {funds_info['nemanut (%)'][inx]} and now {nemanut}"
            messages.append(msg)

    if test_mode == 'on' or len(messages) > 0:
        if test_mode == 'on':
            title = "test"
            text = 'This is a test'
        else:
            title = "Funds update"
            messages.append('#########')
            messages.append('Note:')
            messages.append(
                '* If any of your fees changed, update them in the csv to avoid getting repeated messages'
            )
            messages.append(
                '* If you recieved a warning regarding one of the funds maybe something is FISHY. Either correct it or remove it from the list'
            )
            text = '\n'.join(messages)
        if output_mode == 'push' or output_mode == 'both':
            pb = PushBullet(pushbullet_key)
            push = pb.push_note(title, text)
        if output_mode == 'file' or output_mode == 'both':
            with open(output_file, "a") as f:
                today = date.today()
                f.write(f"Date: {today}\n")
                f.write(text)
                f.write(f'\n\n')
예제 #39
0
파일: main.py 프로젝트: Tchekda/IVAO-Utils

def get_time():
    return datetime.datetime.now().strftime("%H:%M:%S", )


def get_short_client(client: Client):
    return client.callsign + "(" + str(client.vid) + ")"


if __name__ == "__main__":
    if 'API_KEY' in os.environ:
        pb = PushBullet(os.environ['API_KEY'])
        pb.delete_pushes()
        pb.push_note(
            PB_TITLE, "Connected at " +
            datetime.datetime.now().strftime("%H:%M:%S %b %d %Y", ))
    try:
        print("Starting at " +
              datetime.datetime.now().strftime("%H:%M:%S %b %d %Y", ))
        delay = None  # Random delay between 3 - 5 minutes
        if os.getenv("UPDATE_DELAY") is not None:
            delay = float(os.getenv("UPDATE_DELAY"))
        server.run_update_stream(delay=delay)
    except Exception as e:
        print("Error : " + str(e))
        if pb:
            pb.push_note(PB_TITLE, "Error : " + str(e))
    finally:
        print("Closing at " +
              datetime.datetime.now().strftime("%H:%M:%S %b %d %Y", ))
        day = re.findall(dayPat, htmlPage[hour.end():change.start()])
        parts[-1].append(len(day))
        parts[-1].append(re.match(lastChangedPat, htmlPage).group(1))
    else:
        stage += 1
        if stage == 1:
            parts.append([change.group(2)])
        else:
            parts[-1].append(change.group(2))
        if stage == 3:
            stage = 0
            for tempHour in re.finditer(hourPat, htmlPage[:change.start()]):
                hour = tempHour
            parts[-1].append(hour.group(1))
            day = re.findall(dayPat, htmlPage[hour.end():change.start()])
            parts[-1].append(len(day))
            parts[-1].append(re.match(lastChangedPat, htmlPage).group(1))

days = ["Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag"]
text = ""
parts = sorted(parts, key=itemgetter(-1))
for part in parts:
    text += str(days[part[-2]-1]) + " " + part[-3] + "e uur "
    if len(part) == 5:
        text += part[0] + " " + part[1] + " " + part[2] + "\n"
    else:
        text += part[0] + "\n"

# print text
success, push = pb.push_note("Rooster wijzigingen", text)
예제 #41
0
def push_to_iOS(title, body, pb_key):
    pb = PushBullet(pb_key)

    pb.push_note(title, body)
예제 #42
0
#!/usr/bin/env python
#Obtain your API_KEY from: https://www.pushbullet.com/account

from pushbullet import PushBullet
import sys

API_KEY = "YOUR API KEY HERE"

pb = PushBullet(API_KEY)

if __name__ == "__main__":

	if len(sys.argv) > 3:#If the message being passed is not encapsulated in quotes, it will be broken at each whitespace into separate arguments
		sys.argv[2] = ' '.join(sys.argv[1:])

	success, push = pb.push_note(sys.argv[1], sys.argv[2])
	print success
예제 #43
0
def mention(bot, event, *args):
    """alert a @mentioned user"""
    """allow mentions to be disabled via global or per-conversation config"""
    config_mentions_enabled = False if bot.get_config_suboption(
        event.conv.id_, 'mentions.enabled') is False else True
    if not config_mentions_enabled:
        logger.info("mentions explicitly disabled by config for {}".format(
            event.conv_id))
        return
    """minimum length check for @mention"""
    minimum_length = bot.get_config_suboption(event.conv_id,
                                              'mentionminlength')
    if not minimum_length:
        minimum_length = 2
    username = args[0].strip()
    if len(username) < minimum_length:
        logger.debug("@mention from {} ({}) too short (== '{}')".format(
            event.user.full_name, event.user.id_.chat_id, username))
        return

    users_in_chat = event.conv.users
    mention_chat_ids = []
    """sync room support"""
    if bot.get_config_option('syncing_enabled'):
        sync_room_list = bot.get_config_option('sync_rooms')
        if sync_room_list:
            """scan through each room group"""
            for rooms_group in sync_room_list:
                if event.conv_id in rooms_group:
                    """current conversation is part of a syncroom group, add "external" users"""
                    for syncedroom in rooms_group:
                        if event.conv_id is not syncedroom:
                            users_in_chat += bot.get_users_in_conversation(
                                syncedroom)
                    users_in_chat = list(set(users_in_chat))  # make unique
                    logger.debug(
                        "@mention in a syncroom: {} user(s) present".format(
                            len(users_in_chat)))
                    break
    """
    /bot mention <fragment> test
    """
    noisy_mention_test = False
    if len(args) == 2 and args[1] == "test":
        noisy_mention_test = True

    initiator_has_dnd = _user_has_dnd(bot, event.user.id_.chat_id)
    """
    quidproquo: users can only @mention if they themselves are @mentionable (i.e. have a 1-on-1 with the bot)
    """
    conv_1on1_initiator = yield from bot.get_1to1(event.user.id_.chat_id)
    if bot.get_config_option("mentionquidproquo"):
        if conv_1on1_initiator:
            if initiator_has_dnd:
                logger.info("quidproquo: user {} ({}) has DND active".format(
                    event.user.full_name, event.user.id_.chat_id))
                if noisy_mention_test or bot.get_config_suboption(
                        event.conv_id, 'mentionerrors'):
                    yield from bot.coro_send_message(
                        event.conv,
                        _("<b>{}</b>, you cannot @mention anyone until your DND status is toggled off."
                          ).format(event.user.full_name))
                return
            else:
                logger.debug("quidproquo: user {} ({}) has 1-on-1".format(
                    event.user.full_name, event.user.id_.chat_id))
        else:
            logger.info("quidproquo: user {} ({}) has no 1-on-1".format(
                event.user.full_name, event.user.id_.chat_id))
            if noisy_mention_test or bot.get_config_suboption(
                    event.conv_id, 'mentionerrors'):
                yield from bot.coro_send_message(
                    event.conv,
                    _("<b>{}</b> cannot @mention anyone until they say something to me first."
                      ).format(event.user.full_name))
            return
    """track mention statistics"""
    user_tracking = {
        "mentioned": [],
        "ignored": [],
        "failed": {
            "pushbullet": [],
            "one2one": [],
        }
    }
    """
    begin mentioning users as long as they exist in the current conversation...
    """

    conversation_name = bot.conversations.get_name(event.conv)
    logger.info("@mention '{}' in '{}' ({})".format(username,
                                                    conversation_name,
                                                    event.conv.id_))
    username_lower = username.lower()
    username_upper = username.upper()
    """is @all available globally/per-conversation/initiator?"""
    if username_lower == "all":
        if not bot.get_config_suboption(event.conv.id_, 'mentionall'):
            """global toggle is off/not set, check admins"""
            logger.debug(
                "@all in {}: disabled/unset global/per-conversation".format(
                    event.conv.id_))
            admins_list = bot.get_config_suboption(event.conv_id, 'admins')
            if event.user_id.chat_id not in admins_list:
                """initiator is not an admin, check whitelist"""
                logger.debug("@all in {}: user {} ({}) is not admin".format(
                    event.conv.id_, event.user.full_name,
                    event.user.id_.chat_id))
                all_whitelist = bot.get_config_suboption(
                    event.conv_id, 'mentionallwhitelist')
                if all_whitelist is None or event.user_id.chat_id not in all_whitelist:

                    logger.warning("@all in {}: user {} ({}) blocked".format(
                        event.conv.id_, event.user.full_name,
                        event.user.id_.chat_id))
                    if conv_1on1_initiator:
                        yield from bot.coro_send_message(
                            conv_1on1_initiator,
                            _("You are not allowed to mention all users in <b>{}</b>"
                              ).format(conversation_name))
                    if noisy_mention_test or bot.get_config_suboption(
                            event.conv_id, 'mentionerrors'):
                        yield from bot.coro_send_message(
                            event.conv,
                            _("<b>{}</b> blocked from mentioning all users").
                            format(event.user.full_name))
                    return
                else:
                    logger.info(
                        "@all in {}: allowed, {} ({}) is whitelisted".format(
                            event.conv.id_, event.user.full_name,
                            event.user.id_.chat_id))
            else:
                logger.info("@all in {}: allowed, {} ({}) is an admin".format(
                    event.conv.id_, event.user.full_name,
                    event.user.id_.chat_id))
        else:
            logger.info("@all in {}: enabled global/per-conversation".format(
                event.conv.id_))
    """generate a list of users to be @mentioned"""
    exact_nickname_matches = []
    exact_fragment_matches = []
    mention_list = []
    for u in users_in_chat:

        # mentions also checks nicknames if one is configured
        #  exact matches only! see following IF block
        nickname = ""
        nickname_lower = ""
        if bot.memory.exists(['user_data', u.id_.chat_id, "nickname"]):
            nickname = bot.memory.get_by_path(
                ['user_data', u.id_.chat_id, "nickname"])
            nickname_lower = nickname.lower()

        _normalised_full_name_upper = remove_accents(u.full_name.upper())

        if (username_lower == "all"
                or username_lower in u.full_name.replace(" ", "").lower()
                or username_upper in _normalised_full_name_upper.replace(
                    " ", "")
                or username_lower in u.full_name.replace(" ", "_").lower()
                or username_upper in _normalised_full_name_upper.replace(
                    " ", "_") or username_lower == nickname_lower
                or username in u.full_name.split(" ")):

            logger.info("user {} ({}) is present".format(
                u.full_name, u.id_.chat_id))

            if u.is_self:
                """bot cannot be @mentioned"""
                logger.debug("suppressing bot mention by {} ({})".format(
                    event.user.full_name, event.user.id_.chat_id))
                continue

            if u.id_.chat_id == event.user.id_.chat_id and username_lower == "all":
                """prevent initiating user from receiving duplicate @all"""
                logger.debug("suppressing @all for {} ({})".format(
                    event.user.full_name, event.user.id_.chat_id))
                continue

            if u.id_.chat_id == event.user.id_.chat_id and not noisy_mention_test:
                """prevent initiating user from mentioning themselves"""
                logger.debug("suppressing @self for {} ({})".format(
                    event.user.full_name, event.user.id_.chat_id))
                continue

            if u.id_.chat_id in mention_chat_ids:
                """prevent most duplicate mentions (in the case of syncouts)"""
                logger.debug(
                    "suppressing duplicate mention for {} ({})".format(
                        event.user.full_name, event.user.id_.chat_id))
                continue

            if bot.memory.exists(["donotdisturb"]):
                if _user_has_dnd(bot, u.id_.chat_id):
                    logger.info("suppressing @mention for {} ({})".format(
                        u.full_name, u.id_.chat_id))
                    user_tracking["ignored"].append(u.full_name)
                    continue

            if username_lower == nickname_lower:
                if u not in exact_nickname_matches:
                    exact_nickname_matches.append(u)

            if (username in u.full_name.split(" ") or username_upper
                    in _normalised_full_name_upper.split(" ")):

                if u not in exact_fragment_matches:
                    exact_fragment_matches.append(u)

            if u not in mention_list:
                mention_list.append(u)

    if len(exact_nickname_matches) == 1:
        """prioritise exact nickname matches"""
        logger.info("prioritising nickname match for {}".format(
            exact_nickname_matches[0].full_name))
        mention_list = exact_nickname_matches
    elif len(exact_fragment_matches) == 1:
        """prioritise case-sensitive fragment matches"""
        logger.info(
            "prioritising single case-sensitive fragment match for {}".format(
                exact_fragment_matches[0].full_name))
        mention_list = exact_fragment_matches
    elif len(exact_fragment_matches) > 1 and len(exact_fragment_matches) < len(
            mention_list):
        logger.info(
            "prioritising multiple case-sensitive fragment match for {}".
            format(exact_fragment_matches[0].full_name))
        mention_list = exact_fragment_matches

    if len(mention_list) > 1 and username_lower != "all":

        send_multiple_user_message = True

        if bot.memory.exists([
                'user_data', event.user.id_.chat_id,
                "mentionmultipleusermessage"
        ]):
            send_multiple_user_message = bot.memory.get_by_path([
                'user_data', event.user.id_.chat_id,
                "mentionmultipleusermessage"
            ])

        if send_multiple_user_message or noisy_mention_test:
            if conv_1on1_initiator:
                text_html = _(
                    '{} users would be mentioned with "@{}"! Be more specific. List of matching users:<br />'
                ).format(len(mention_list), username, conversation_name)

                for u in mention_list:
                    text_html += u.full_name
                    if bot.memory.exists(
                        ['user_data', u.id_.chat_id, "nickname"]):
                        text_html += ' (' + bot.memory.get_by_path(
                            ['user_data', u.id_.chat_id, "nickname"]) + ')'
                    text_html += '<br />'

                text_html += "<br /><em>To toggle this message on/off, use <b>/bot bemorespecific</b></em>"

                yield from bot.coro_send_message(conv_1on1_initiator,
                                                 text_html)

        logger.warning(
            "@{} not sent due to multiple recipients".format(username_lower))
        return  #SHORT-CIRCUIT
    """support for reprocessor
    override the source name by defining event._external_source"""
    source_name = event.user.full_name
    if hasattr(event, '_external_source'):
        source_name = event._external_source
    """send @mention alerts"""
    for u in mention_list:
        alert_via_1on1 = True
        """pushbullet integration"""
        if bot.memory.exists(['user_data', u.id_.chat_id, "pushbullet"]):
            pushbullet_config = bot.memory.get_by_path(
                ['user_data', u.id_.chat_id, "pushbullet"])
            if pushbullet_config is not None:
                if pushbullet_config["api"] is not None:
                    success = False
                    try:
                        pb = PushBullet(pushbullet_config["api"])
                        push = pb.push_note(
                            _("{} mentioned you in {}").format(
                                source_name, conversation_name), event.text)
                        if isinstance(push, tuple):
                            # backward-compatibility for pushbullet library < 0.8.0
                            success = push[0]
                        elif isinstance(push, dict):
                            success = True
                        else:
                            raise TypeError(
                                "unknown return from pushbullet library: {}".
                                format(push))
                    except Exception as e:
                        logger.exception("pushbullet error")

                    if success:
                        user_tracking["mentioned"].append(u.full_name)
                        logger.info("{} ({}) alerted via pushbullet".format(
                            u.full_name, u.id_.chat_id))
                        alert_via_1on1 = False  # disable 1on1 alert
                    else:
                        user_tracking["failed"]["pushbullet"].append(
                            u.full_name)
                        logger.warning(
                            "pushbullet alert failed for {} ({})".format(
                                u.full_name, u.id_.chat_id))

        if alert_via_1on1:
            """send alert with 1on1 conversation"""
            conv_1on1 = yield from bot.get_1to1(u.id_.chat_id)
            if conv_1on1:
                yield from bot.coro_send_message(
                    conv_1on1,
                    _("<b>{}</b> @mentioned you in <i>{}</i>:<br />{}").format(
                        source_name, conversation_name, event.text
                    ))  # prevent internal parser from removing <tags>
                mention_chat_ids.append(u.id_.chat_id)
                user_tracking["mentioned"].append(u.full_name)
                logger.info("{} ({}) alerted via 1on1 ({})".format(
                    u.full_name, u.id_.chat_id, conv_1on1.id_))
            else:
                user_tracking["failed"]["one2one"].append(u.full_name)
                if bot.get_config_suboption(event.conv_id, 'mentionerrors'):
                    yield from bot.coro_send_message(
                        event.conv,
                        _("@mention didn't work for <b>{}</b>. User must say something to me first."
                          ).format(u.full_name))
                logger.warning(
                    "user {} ({}) could not be alerted via 1on1".format(
                        u.full_name, u.id_.chat_id))

    if noisy_mention_test:
        text_html = _("<b>@mentions:</b><br />")
        if len(user_tracking["failed"]["one2one"]) > 0:
            text_html = text_html + _("1-to-1 fail: <i>{}</i><br />").format(
                ", ".join(user_tracking["failed"]["one2one"]))
        if len(user_tracking["failed"]["pushbullet"]) > 0:
            text_html = text_html + _(
                "PushBullet fail: <i>{}</i><br />").format(", ".join(
                    user_tracking["failed"]["pushbullet"]))
        if len(user_tracking["ignored"]) > 0:
            text_html = text_html + _("Ignored (DND): <i>{}</i><br />").format(
                ", ".join(user_tracking["ignored"]))
        if len(user_tracking["mentioned"]) > 0:
            text_html = text_html + _("Alerted: <i>{}</i><br />").format(
                ", ".join(user_tracking["mentioned"]))
        else:
            text_html = text_html + _(
                "Nobody was successfully @mentioned ;-(<br />")

        if len(user_tracking["failed"]["one2one"]) > 0:
            text_html = text_html + _(
                "Users failing 1-to-1 need to say something to me privately first.<br />"
            )

        yield from bot.coro_send_message(event.conv, text_html)
예제 #44
0
    # Check if all uuids in orders_present are present in orders
    for uuid in orders_present.keys():
        if uuid in order_uuids:
            continue
        else:
            # Order is gone!
            orders_to_notify.append(orders_present[uuid])

    if len(orders_to_notify) > 0:
        # Push to pushbullet here
        print('Order disappeared! Canceled or sold!')
        note_to_push = ''
        for to_notify in orders_to_notify:
            ex = to_notify['Exchange']
            order_type = to_notify['OrderType']
            limit = to_notify['Limit']
            note_to_push += '%s : %s : %s' % (ex, order_type, limit)
            note_to_push += '\n'
        print(note_to_push)
        pb.push_note('Order moved!', note_to_push)

    # Reset orders_present to the current list
    orders_present = {order['OrderUuid']: order for order in orders_current}
    print('Orders present: %s' % orders_present)

    # Sleep for remaining time
    loop_end_time = time()
    remaining_time = LOOP_SLEEP_TIME - (loop_end_time - loop_start_time)
    sleep(max(0, remaining_time))
예제 #45
0
# -*- coding: utf-8 -*-
from pushbullet import PushBullet

pb = PushBullet('F8WuT1U8GMYCSRXxyJSQewC84j4SoD8X')

success, push = pb.push_note("NDM CP장애 발생!", "호수 대량 삭제 발생함!!")
#LDR,Arduino light jaane pr pushbullet ---> led on krni h ya nhi
from pushbullet import PushBullet
from urllib3 import request
import requests
import serial

api_key = 'YourPushBulletAPIKeyHere'
pb = PushBullet(api_key)
push = pb.push_note("Arduino", "Bhai Light Chali gyi..LED ON kru?")

#print(pushes)


def check_val():

    global val
    pushes = pb.get_pushes()
    val = pushes[0]['body']
    #print(val)


arduino = serial.Serial('COM3', 9600)

while True:
    check_val()
    if (val == '1' or val == 'ON' or val == 'ha'):
        arduino.write(b'1')

    if (val == '0' or val == 'nhi' or val == 'OFF'):
        arduino.write(b'0')
예제 #47
0
#!/usr/bin/python3
import sys
from pushbullet import PushBullet

pb = PushBullet("key")
if len(sys.argv) > 1:
    s = ""
    for i in range(1, len(sys.argv)):
        if i > 1:
            s += " "
        s += str(sys.argv[i])
    pb.push_note("OpenHAB", s)
예제 #48
0
#!/usr/bin/python3
import sys
from pushbullet import PushBullet

pb = PushBullet("key")
if len(sys.argv) > 1:
	s = ""
	for i in range(1, len(sys.argv)):
		if i>1:
			s += " "
		s += str(sys.argv[i])
	pb.push_note("OpenHAB", s)
예제 #49
0
class PomodoroTimer:
    '''
    PomodoroTimer

    Args:
        **s_time: Sprint time in minutes.
        **b_time: Break time in minutes.
        **iterations: Iterations count.
        **push_bullet: PushBullet API key.

    Attributes:
        break_time_sound: PyGame sound to play at start of break time.
        sprint_time_sound: PyGame sound to play at start of sprint time.

        clock: PyGame clock.
        tick_speed: Ticks per second to run.
        counter: Timer (ms) that tracks current progress through sprint or break.
        run_time: Overall (ms) run time of the Pomodoro Timer.

        in_sprint: Are we currently in a sprint.
        sprint_time: Sprint length (ms)
        break_time: Break length (ms)

        max_iterations: How many iterations to run.
        iterations: Current iteration

        pb: PushBullet object.
    '''
    def __init__(self, s_time=20, b_time=5, iterations=5, push_bullet=None):

        self.break_time_sound = pygame.mixer.Sound('breaktime.wav')
        self.sprint_time_sound = pygame.mixer.Sound('sprinttime.wav')

        self.clock = pygame.time.Clock()
        self.tick_speed = 1.5
        self.counter = 0  # Tracks progress of current sprint or break
        self.run_time = 0  # Tracks progress of entire process

        # In minutes
        self.in_sprint = True
        self.sprint_time = s_time * 60 * 1000
        self.break_time = b_time * 60 * 1000

        # Amount of times to iterate process
        self.max_iterations = iterations
        self.iterations = 0

        self.pb = None
        self.set_pushbullet(push_bullet)

        self.print_welcome()

    def set_pushbullet(self, pb_key):

        if pb_key:
            self.pb = PushBullet(pb_key)
        else:
            self.pb = None

    def print_welcome(self):
        '''Print welcome message and display some variables'''

        # Get a boolean var on whether Push Bullet has been initted
        push_bullet = self.pb is not None

        print(' Welcome to Pomodoro!\n----------------------')
        # Display variables
        print(
            'Sprint time:\t{} minute(s)\nBreak time:\t{} minute(s)\nIterations:\t{}\nPushBullet?\t{}\nTick Speed:\t{}\n'
            .format(int(self.sprint_time / 60 / 1000),
                    int(self.break_time / 60 / 1000), self.max_iterations,
                    push_bullet, self.tick_speed))
        print('Press enter to start your first {} minute sprint...'.format(
            int(self.sprint_time / 60 / 1000)))
        input()
        print('Let\'s Go!')

    def tick(self):
        '''Update counter and check if sprint or break time has been finished'''

        dt = self.clock.tick(self.tick_speed)
        self.run_time += dt
        self.counter += dt

        if self.in_sprint:
            if self.counter > self.sprint_time:
                self.start_break()
        else:
            if self.counter > self.break_time:
                self.start_sprint()

    def start_break(self, wait=True):
        '''Starts break and resets variables for next sprint'''

        flash_terminal_on()
        send_notifcation('Time to start your break, confirm in terminal...')
        if type(self.pb) is PushBullet:
            self.pb.push_note(
                'Break Time!',
                'It is time for your break, come back to start the timer.')
        self.break_time_sound.play()
        extend_time = input('Start Break? (or extend your sprint by?)')
        flash_terminal_off()
        if extend_time:
            self.extend(int(extend_time))
            return
        print('Starting Break for {} minute(s).'.format(
            int(self.break_time / 1000 / 60)))
        self.in_sprint = False
        self.counter = 0

    def start_sprint(self, wait=True):
        '''Starts a new sprint and sets up for next break'''

        flash_terminal_on()
        send_notifcation('Time to start your sprint, confirm in terminal...')
        if type(self.pb) is PushBullet:
            self.pb.push_note(
                'Sprint Time!',
                'It is time for your sprint, come back to start the timer.')
        self.sprint_time_sound.play()
        extend_time = input('Start Sprint? (or extend your break by?) ')
        flash_terminal_off()
        if extend_time:
            self.extend(int(extend_time))
            return
        print('Starting Sprint for {} minute(s).'.format(
            int(self.sprint_time / 1000 / 60)))
        self.in_sprint = True
        self.counter = 0
        self.iterations += 1

    def extend(self, time):
        '''Extends sprint or break by a given time'''

        if self.in_sprint:
            self.counter = self.sprint_time - (time * 60 * 1000)
            print('Your sprint has been extended by {} minutes.'.format(time))
        else:
            self.counter = self.break_time - (time * 60 * 1000)
            print('Your break has been extended by {} minutes.'.format(time))

    def run(self):
        '''Main run function'''

        while self.iterations <= self.max_iterations:
            self.tick()
        print('You have finished all iterations of your sprint. Goodbye :)')
        pygame.quit()
        exit()
예제 #50
0
 def push(self, subject, body):
     pb = PushBullet('stuffhere')
     success, push = pb.push_note(subject, body)
     print success
예제 #51
0
import requests
from datetime import datetime
from pushbullet import PushBullet

count = 0
API = 'o.WfYU9eM5o7fXoBq5PxburlwjXEpfCw0Q'
pb = PushBullet(API)
#SHAHDARA
b = datetime.today()
headers = {
    "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0"
}
url = 'https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?'
para = {"district_id": 148, "date": b.strftime("%d-%m-%Y")}
a = requests.get(url, params=para, headers=headers)
file = a.json()

for i in range(0, len(file['centers'])):
    if (file['centers'][i]['sessions'][0]['min_age_limit'] == 18 and
        (file['centers'][i]['sessions'][0]['available_capacity'] >= 1)):
        count = count + 1

if count >= 1:
    pb.push_note("Vaccine Slots Available", "Slots Available for 18+ Hurry up")
예제 #52
0
from pushbullet import PushBullet

pb = PushBullet('YOUR API_TOKEN')
import datetime


def take_picture(path_):
    import pygame.camera

    pygame.camera.init()
    cam = pygame.camera.Camera(pygame.camera.list_cameras()[0])
    cam.start()
    img = cam.get_image()
    pygame.image.save(img, path_)
    pygame.camera.quit()


time = datetime.datetime.now()
import os
acc = os.getlogin()

phone = pb.devices[0]
take_picture('C:\\Users\\' + acc + '\\Desktop\\photo.bmp')

with open('C:\\Users\\' + acc + '\\Desktop\\photo.bmp', "rb") as pic:
    file_data = pb.upload_file(pic, "picture.jpg")

pb.push_note("Log in to account " + acc + " at " + str(time), "", device=phone)

push = pb.push_file(**file_data)
예제 #53
0
def pushbullet_init(pb_key="dis_u:aint_getting:)"):
	#init pushbullet with pb_key
	#and alias for sending notes/alarms
	pb = PushBullet(pb_key)
	note = pb.push_note("PUSH EXT IP DETAILS",  getting.info[''])