Ejemplo n.º 1
0
    def received_command(self, command, data, reply_message, sender, *args, **kwargs):
        if re.search(self.command_pattern, command, re.IGNORECASE):
            # Probability of the grade being between second and third items
            probs = [
                (0.1, 20, 20),
                (0.4, 15, 19.9),
                (0.25, 12, 14.9),
                (0.10, 10, 11.9),
                (0.13, 7, 9.9),
                (0.02, 0, 6.9)
            ]

            rand = random.random()
            log("rand: %s" % rand)

            _x = 0.0
            grade = 0

            for i in range(len(probs)):
                _x += probs[i][0]
                if rand <= _x:
                    grade = random.random() * (probs[i][2] - probs[i][1]) + probs[i][1]
                    break

            log("Guessed grade: %s" % grade)

            reply_message("{0:.1f}/20".format(grade))
            EventDispatcherSingleton().terminate_scripts()
Ejemplo n.º 2
0
    def received_command(self, command, data, reply_function, sender, *args, **kwargs):
        match = re.search(self.command_pattern, command, re.IGNORECASE)

        if match:
            log("Asked for a mustache, by {0}".format(sender['screen_name']))

            if not self.st_memory.is_person_marked('mustache', sender['screen_name']):
                # Mark them
                self.st_memory.mark_person('mustache', sender['screen_name'])

                avatar_url = sender['profile_image_url']
                avatar_url = avatar_url.replace('_normal', '')

                raw_url = 'http://mustachify.me/?src={0}'
                img_url = raw_url.format(urllib.request.quote(avatar_url))
                log("Image url: {0}".format(img_url))
                img = BytesIO(requests.get(url=img_url).content)

                self.twitter.update_status_with_media(
                    status='@' + sender['screen_name'],
                    media=img,
                    in_reply_to_status_id=data['id_str']
                )

                EventDispatcherSingleton().terminate_scripts()

            else:
                self.twitter.reply_to(data, ':)')
Ejemplo n.º 3
0
    def received_command(self, command, data, reply_function, sender, *args,
                         **kwargs):
        match = re.search(self.command_pattern, command, re.IGNORECASE)

        if match:
            log("Asked for how old, by {0}".format(sender['screen_name']))

            if not self.st_memory.is_person_marked('how-old',
                                                   sender['screen_name']):
                # Mark them
                self.st_memory.mark_person('how-old', sender['screen_name'])

                avatar_url = sender['profile_image_url']
                avatar_url = avatar_url.replace('_normal', '')
                avatar_img = requests.get(url=avatar_url).content

                self.twitter.update_status_with_media(
                    status='@' + sender['screen_name'],
                    media=BytesIO(img),
                    in_reply_to_status_id=data['id_str'])

                EventDispatcherSingleton().terminate_scripts()

            else:
                self.twitter.reply_to(data, ':)')
Ejemplo n.º 4
0
    def received_command(self, command, data, reply_function, sender, *args, **kwargs):
        match = re.search(self.command_pattern, command)
        if match:
            x = match.group('x')
            y = match.group('y')

            error_msg = None
            if len(x) < self.MINIMUM_LENGTH:
                error_msg = '{0} از {1} حرف کمتره'.format(x, self.MINIMUM_LENGTH)
            elif '@' in x:
                error_msg = 'به منشن‌ها جواب نمی‌دم. :)'

            if error_msg:
                self.twitter.send_direct_message(text=error_msg, user_id=self.teacher_id)
                return

            self.st_memory.memory.setdefault('learned_replies', {}).setdefault(x, []).append({
                'text': y,
                'teacher_id': self.teacher_id,
                'teacher_screen_name': self.teacher_screen_name,
                'times_used': 0,
            })

            log("learned_replies size: {0}".format(
                len(self.st_memory.memory['learned_replies'])))
            reply_message = 'اوکی اگر کسی گفت {0} می‌گم {1}.'.format(x, y)

            # reply_function is not used because we send a direct message regardless of message type
            self.twitter.send_direct_message(text=reply_message, user_id=self.teacher_id)
            EventDispatcherSingleton().terminate_scripts()
Ejemplo n.º 5
0
    def received_command(self, command, data, reply_function, sender, *args, **kwargs):
        match = re.search(self.command_pattern, command, re.IGNORECASE)

        if match:
            log("Asked for a mustache, by {0}".format(sender['screen_name']))

            if not self.st_memory.is_person_marked('mustache', sender['screen_name']):
                # Mark them
                self.st_memory.mark_person('mustache', sender['screen_name'])

                avatar_url = sender['profile_image_url']
                avatar_url = avatar_url.replace('_normal', '')

                raw_url = 'http://mustachify.me/?src={0}'
                img_url = raw_url.format(urllib.request.quote(avatar_url))
                log("Image url: {0}".format(img_url))

                img = requests.get(url=img_url).content

                self.twitter.update_status_with_media(
                    status='@' + sender['screen_name'],
                    media=BytesIO(img),
                    in_reply_to_status_id=data['id_str']
                )

                EventDispatcherSingleton().terminate_scripts()

            else:
                self.twitter.reply_to(data, ':)')
def run():
    if not settings.DEBUG:
        log("Starting streamer...")
        stream = EventDispatcherSingleton()
        stream.user(replies="all")
    else:
        stream = Testing()
        stream.user(replies="all")
Ejemplo n.º 7
0
def run():
    if not settings.DEBUG:
        log("Starting streamer...")
        stream = EventDispatcherSingleton()
        stream.user(replies="all")
    else:
        stream = Testing()
        stream.user(replies="all")
 def user(self, *args, **kwargs):
     while True:
         try:
             super(EventDispatcherSingleton, self).user(self, *args, **kwargs)
         except TwythonRateLimitError as e:
             log("Rate limit error, asks to retry after {0}".format(e.retry_after))
             time.sleep(min(int(e.retry_after), 5))
         except TwythonError as e:
             log("Twython error {0}".format(e))
Ejemplo n.º 9
0
 def dedicate_to(self):
     if not settings.DEBUG:
         # Correct way is to retrieve id's then show_user but doesn't work on heroku
         friends = self.get_all_friends()
         dedicated_to = random.choice(friends)['screen_name']
     else:
         dedicated_to = 'tester'
     log("Dedicate tweet to: " + dedicated_to)
     return dedicated_to
Ejemplo n.º 10
0
 def reply(self, data, keyword, reply):
     img_url = get_random_google_image(random.choice(self.search_phrases))
     img = requests.get(url=img_url).content
     log('Sending image: %s' % img_url)
     self.twitter.update_status_with_media(
         status='@' + data['user']['screen_name'],
         media=BytesIO(img),
         in_reply_to_status_id=data['id_str'])
     EventDispatcherSingleton().terminate_scripts()
Ejemplo n.º 11
0
    def update(self):
        # TODO: get json from http://api.adviceslip.com/advice/{i} 0<i<188, for non-repetitive results
        url = 'http://api.adviceslip.com/advice'
        obj = json.loads(urllib.request.urlopen(url).readall().decode('utf-8'))
        log('Loaded json object for random advice')
        slip = obj['slip']

        tags = "#advice #اندرز"
        status = "{0} {1}".format(slip['advice'], tags)
        self.twitter.tweet(status=status)
Ejemplo n.º 12
0
    def update(self):
        # TODO: get json from http://api.adviceslip.com/advice/{i} 0<i<188, for non-repetitive results
        url = "http://api.adviceslip.com/advice"
        obj = json.loads(urllib.request.urlopen(url).readall().decode("utf-8"))
        log("Loaded json object for random advice")
        slip = obj["slip"]

        tags = "#advice #اندرز"
        status = "{0} {1}".format(slip["advice"], tags)
        self.twitter.tweet(status=status)
Ejemplo n.º 13
0
 def user(self, *args, **kwargs):
     while True:
         try:
             super(EventDispatcherSingleton,
                   self).user(self, *args, **kwargs)
         except TwythonRateLimitError as e:
             log("Rate limit error, asks to retry after {0}".format(
                 e.retry_after))
             time.sleep(min(int(e.retry_after), 5))
         except TwythonError as e:
             log("Twython error {0}".format(e))
 def load_scripts(self):
     """
     Loads scripts to self.scripts
     """
     script_classes = script_loader.load_scripts('scripts.twitter_related',
                                                 settings.INSTALLED_TWITTER_RELATED_SCRIPTS)
     log("Loading twitter related scripts")
     for script in script_classes:
         listen_to = script.listen_to if isinstance(script.listen_to, list) else [script.listen_to]
         for event in listen_to:
             self.scripts.setdefault(event, []).append(script())
             log("Loaded {0} for type {1}".format(script.__name__, event))
Ejemplo n.º 15
0
 def load_scripts(self):
     """
     Loads scripts to self.scripts
     """
     script_classes = script_loader.load_scripts(
         'scripts.twitter_related',
         settings.INSTALLED_TWITTER_RELATED_SCRIPTS)
     log("Loading twitter related scripts")
     for script in script_classes:
         listen_to = script.listen_to if isinstance(
             script.listen_to, list) else [script.listen_to]
         for event in listen_to:
             self.scripts.setdefault(event, []).append(script())
             log("Loaded {0} for type {1}".format(script.__name__, event))
Ejemplo n.º 16
0
    def on_timeline_update(self, data):
        marked = self.st_memory.is_person_marked(self.__class__.__name__, data['user']['screen_name'], self.max_answers)

        if not marked:
            for i in range(len(self.replies)):
                reply = self.replies[i]
                for keyword in reply['keywords']:
                    if re.findall(keyword, data['text']):
                        log('matched')
                        try:
                            self.st_memory.mark_person(self.__class__.__name__, data['user']['screen_name'])
                            self.reply(data, keyword, reply)

                        except TwythonError as e:
                            print(e)
Ejemplo n.º 17
0
    def on_timeline_update(self, data):
        marked = self.st_memory.is_person_marked(self.__class__.__name__,
                                                 data['user']['screen_name'],
                                                 self.max_answers)

        if not marked:
            for i in range(len(self.replies)):
                reply = self.replies[i]
                for keyword in reply['keywords']:
                    if re.findall(keyword, data['text']):
                        log('matched')
                        try:
                            self.st_memory.mark_person(
                                self.__class__.__name__,
                                data['user']['screen_name'])
                            self.reply(data, keyword, reply)

                        except TwythonError as e:
                            print(e)
Ejemplo n.º 18
0
    def on_self_status_update(self, data):
        tweets = data['user']['statuses_count']
        log("Number of tweets: " + str(tweets))

        if is_round(tweets + 1):
            log("Next tweet is round")
            try:
                status = 'توییت {0} تقدیم به {1}.'.format(str(tweets + 1), '@' + self.dedicate_to())
            except TwythonError as e:
                log("Twython error: " + str(e))
                log("Last call headers:\n + " + str(self.twitter.twitter._last_call))
                status = 'توییت {0} رو هم تقدیم نمی‌کنیم...'.format(str(tweets + 1))
            self.twitter.tweet(status=status)
Ejemplo n.º 19
0
    def received_command(self, command, data, reply_message, sender, *args, **kwargs):
        match = re.search(self.command_pattern, command, re.IGNORECASE)

        if match:
            if not self.st_memory.is_person_marked('hungry', sender['screen_name'], 3):
                # Mark them
                self.st_memory.mark_person('hungry', sender['screen_name'])

                log("{0} is hungry".format(sender['screen_name']))

                url = 'http://chibepazam.com/'
                page = BeautifulSoup(urllib.request.urlopen(url).readall().decode('utf-8'))
                food_name = page.select('div.title')[0].string.replace('\r|\n', '')
                recipe_url = page.select('img[src$=ok.gif]')[0].parent['href']

                response = '{0} {1}'.format(food_name, recipe_url)
                reply_message(response)
                EventDispatcherSingleton().terminate_scripts()
            else:
                reply_message(':)')
Ejemplo n.º 20
0
    def on_timeline_update(self, data):
        do_reply = (random.randint(0, 400) == 0)
        if not do_reply or data.get('in_reply_to_status_id_str', None) or data['entities']['user_mentions'] or len(
                data['text']) == 0:
            return

        log('Ok...sending nobody cares')

        img_url = get_random_google_image(random.choice(self.search_phrases))
        img = requests.get(url=img_url).content
        log('image: %s' % img_url)

        try:
            self.twitter.update_status_with_media(
                status='@' + data['user']['screen_name'],
                media=BytesIO(img),
                in_reply_to_status_id=data['id_str']
            )
            EventDispatcherSingleton().terminate_scripts()
        except TwythonError as e:
            print(e)
Ejemplo n.º 21
0
    def received_command(self, command, data, reply_message, sender, *args, **kwargs):
        if re.search(self.command_pattern, command, re.IGNORECASE):
            while True:
                r = request.Request('http://9gag.com/random')
                opened = request.urlopen(r)
                parsed = BeautifulSoup(opened)

                log("Found 9gag link: %s" % (opened.geturl()))

                if parsed.select('.gif-post'):
                    # Ignore gif posts
                    log("Ignoring... was a gif post")
                    continue

                try:
                    log("Trying to send %s" % opened.geturl())
                    img_url = parsed.select('.badge-item-img')[0].get('src')
                    title = parsed.select('.badge-item-title')[0].getText()

                    img = requests.get(url=img_url).content

                    status = '@%s %s - %s' % (sender['screen_name'], title, opened.geturl())
                    if len(status) > settings.TWEET_LENGTH:
                        status = '@%s %s' % (sender['screen_name'], title)

                    self.twitter.update_status_with_media(
                        status=status,
                        media=BytesIO(img),
                        in_reply_to_status_id=data['id_str']
                    )
                    break
                except Exception:
                    pass
            EventDispatcherSingleton().terminate_scripts()
Ejemplo n.º 22
0
    def received_command(self, command, data, reply_message, sender, *args,
                         **kwargs):
        if re.search(self.command_pattern, command, re.IGNORECASE):
            while True:
                r = request.Request('http://9gag.com/random')
                opened = request.urlopen(r)
                parsed = BeautifulSoup(opened)

                log("Found 9gag link: %s" % (opened.geturl()))

                if parsed.select('.gif-post'):
                    # Ignore gif posts
                    log("Ignoring... was a gif post")
                    continue

                try:
                    log("Trying to send %s" % opened.geturl())
                    img_url = parsed.select('.badge-item-img')[0].get('src')
                    title = parsed.select('.badge-item-title')[0].getText()

                    img = requests.get(url=img_url).content

                    status = '@%s %s - %s' % (sender['screen_name'], title,
                                              opened.geturl())
                    if len(status) > settings.TWEET_LENGTH:
                        status = '@%s %s' % (sender['screen_name'], title)

                    self.twitter.update_status_with_media(
                        status=status,
                        media=BytesIO(img),
                        in_reply_to_status_id=data['id_str'])
                    break
                except Exception:
                    pass
            EventDispatcherSingleton().terminate_scripts()
Ejemplo n.º 23
0
    def received_command(self, command, data, reply_function, sender, *args,
                         **kwargs):
        match = re.search(self.command_pattern, command)
        if match:
            x = match.group('x')
            y = match.group('y')

            error_msg = None
            if len(x) < self.MINIMUM_LENGTH:
                error_msg = '{0} از {1} حرف کمتره'.format(
                    x, self.MINIMUM_LENGTH)
            elif '@' in x:
                error_msg = 'به منشن‌ها جواب نمی‌دم. :)'

            if error_msg:
                self.twitter.send_direct_message(text=error_msg,
                                                 user_id=self.teacher_id)
                return

            self.st_memory.memory.setdefault('learned_replies',
                                             {}).setdefault(x, []).append({
                                                 'text':
                                                 y,
                                                 'teacher_id':
                                                 self.teacher_id,
                                                 'teacher_screen_name':
                                                 self.teacher_screen_name,
                                                 'times_used':
                                                 0,
                                             })

            log("learned_replies size: {0}".format(
                len(self.st_memory.memory['learned_replies'])))
            reply_message = 'اوکی اگر کسی گفت {0} می‌گم {1}.'.format(x, y)

            # reply_function is not used because we send a direct message regardless of message type
            self.twitter.send_direct_message(text=reply_message,
                                             user_id=self.teacher_id)
            EventDispatcherSingleton().terminate_scripts()
Ejemplo n.º 24
0
    def received_command(self, command, data, reply_message, sender, *args,
                         **kwargs):
        if re.search(self.command_pattern, command, re.IGNORECASE):
            # Probability of the grade being between second and third items
            probs = [(0.1, 20, 20), (0.4, 15, 19.9), (0.25, 12, 14.9),
                     (0.10, 10, 11.9), (0.13, 7, 9.9), (0.02, 0, 6.9)]

            rand = random.random()
            log("rand: %s" % rand)

            _x = 0.0
            grade = 0

            for i in range(len(probs)):
                _x += probs[i][0]
                if rand <= _x:
                    grade = random.random() * (probs[i][2] -
                                               probs[i][1]) + probs[i][1]
                    break

            log("Guessed grade: %s" % grade)

            reply_message("{0:.1f}/20".format(grade))
            EventDispatcherSingleton().terminate_scripts()
Ejemplo n.º 25
0
    def received_command(self, command, data, reply_message, sender, *args,
                         **kwargs):
        match = re.search(self.command_pattern, command, re.IGNORECASE)

        if match:
            if not self.st_memory.is_person_marked('hungry',
                                                   sender['screen_name'], 3):
                # Mark them
                self.st_memory.mark_person('hungry', sender['screen_name'])

                log("{0} is hungry".format(sender['screen_name']))

                url = 'http://chibepazam.com/'
                page = BeautifulSoup(
                    urllib.request.urlopen(url).readall().decode('utf-8'))
                food_name = page.select('div.title')[0].string.replace(
                    '\r|\n', '')
                recipe_url = page.select('img[src$=ok.gif]')[0].parent['href']

                response = '{0} {1}'.format(food_name, recipe_url)
                reply_message(response)
                EventDispatcherSingleton().terminate_scripts()
            else:
                reply_message(':)')
Ejemplo n.º 26
0
    def on_timeline_update(self, data):
        do_reply = (random.randint(0, 1000) == 0)
        if not do_reply or data.get('in_reply_to_status_id_str', None) or data['entities']['user_mentions'] or len(
                data['text']) == 0:
            return

        log('Ok...sending nobody cares')

        script_dir = os.path.dirname(__file__)
        photo_rel_address = 'assets/nobody_cares.jpg'
        photo_path = os.path.join(script_dir, photo_rel_address)
        photo = open(photo_path, 'rb')

        log('Photo found')

        try:
            self.twitter.update_status_with_media(
                status='@' + data['user']['screen_name'],
                media=photo,
                in_reply_to_status_id=data['id_str']
            )
            EventDispatcherSingleton().terminate_scripts()
        except TwythonError as e:
            print(e)
Ejemplo n.º 27
0
    def update_status_with_media(self, status, media, in_reply_to_status_id):
        '''

        :param status:
        :param media: is simply the un-uploaded media
        :param in_reply_to:
        :return:
        '''

        try:
            log('blah blaaeouaoeuh')
            response = self.twitter.upload_media(media=media)
            log('blah blah')
            self.twitter.update_status(status=status, media_ids=[response['media_id']],
                                       in_reply_to_status_id=in_reply_to_status_id)
            self.status_update_hooks()
        except TwythonError as e:
            log("Twython error, updating status with media: {0}".format(e))
Ejemplo n.º 28
0
    def update_status_with_media(self, status, media, in_reply_to_status_id):
        '''

        :param status:
        :param media: is simply the un-uploaded media
        :param in_reply_to:
        :return:
        '''

        try:
            log('blah blaaeouaoeuh')
            response = self.twitter.upload_media(media=media)
            log('blah blah')
            self.twitter.update_status(
                status=status,
                media_ids=[response['media_id']],
                in_reply_to_status_id=in_reply_to_status_id)
            self.status_update_hooks()
        except TwythonError as e:
            log("Twython error, updating status with media: {0}".format(e))
Ejemplo n.º 29
0
def run():
    log("Standalone run")
    script_classes = load_scripts('scripts.standalone', INSTALLED_STANDALONE_SCRIPTS)
    scripts = [script() for script in script_classes]
    remaining_chunks = {}
    for script in scripts:
        remaining_chunks[script.__class__.__name__] = script.repeat_time

    while True:
        sleep(STAND_ALONE_REPEAT_TIME_CHUNKS)
        try:
            for script in scripts:
                remaining_chunks[script.__class__.__name__] -= 1
                if remaining_chunks[script.__class__.__name__] == 0:
                    remaining_chunks[script.__class__.__name__] = script.repeat_time
                    script.on_called()

        except TwythonRateLimitError as e:
            log("Rate limit error, asks to retry after {0}".format(e.retry_after))
            time.sleep(min(int(e.retry_after), 5*60*60))
        except TwythonError as e:
            log("Twython error: {0}".format(e))
    def on_success(self, data):
        data_type = DataParser.get_type_of_data(data)
        data = normalize_data(data)

        if not data_type:
            log("Type of data unknown \n {0}".format(data))
            return

        log("Data received, with type: " + data_type)
        log("Data: {0}".format(data))

        for script in self.scripts.setdefault(data_type, []):
            script_name = script.__class__.__name__

            log("Data type: {1} script found: {0}".format(script_name, data_type))
            try:
                getattr(script, 'on_' + data_type)(data)
            except DoNotCallOtherScripts:
                break
            except TwythonError as e:
                log("Twython error when occurred when running script {0}\nError is:{1}".format(script_name, e))
            except Exception as e:
                log("Some exception occurred during execution of %s \n %s" % (script_name, e))
Ejemplo n.º 31
0
 def mark_person(self, key, username):
     log('Mark {0} for {1}'.format(username, key))
     mark = self.memory.setdefault('mark', {})
     mark[key].setdefault(username, 0)
     mark[key][username] += 1
 def on_error(self, status_code, data):
     log("Error streaming [{0}]: {1}".format(status_code, data))
Ejemplo n.º 33
0
    def on_success(self, data):
        data_type = DataParser.get_type_of_data(data)
        data = normalize_data(data)

        if not data_type:
            log("Type of data unknown \n {0}".format(data))
            return

        log("Data received, with type: " + data_type)
        log("Data: {0}".format(data))

        for script in self.scripts.setdefault(data_type, []):
            script_name = script.__class__.__name__

            log("Data type: {1} script found: {0}".format(
                script_name, data_type))
            try:
                getattr(script, 'on_' + data_type)(data)
            except DoNotCallOtherScripts:
                break
            except TwythonError as e:
                log("Twython error when occurred when running script {0}\nError is:{1}"
                    .format(script_name, e))
            except Exception as e:
                log("Some exception occurred during execution of %s \n %s" %
                    (script_name, e))
Ejemplo n.º 34
0
 def tweet(self, status, *args, **kwargs):
     try:
         self.twitter.update_status(status=status, *args, **kwargs)
         self.status_update_hooks()
     except TwythonError as e:
         log("Twython error, tweeting: {0}".format(e))
Ejemplo n.º 35
0
 def tweet(self, status, *args, **kwargs):
     try:
         self.twitter.update_status(status=status, *args, **kwargs)
         self.status_update_hooks()
     except TwythonError as e:
         log("Twython error, tweeting: {0}".format(e))
Ejemplo n.º 36
0
 def update_status_with_media(self, *args, **kwargs):
     try:
         self.twitter.update_status_with_media(*args, **kwargs)
         self.status_update_hooks()
     except TwythonError as e:
         log("Twython error, updating status with media: {0}".format(e))
Ejemplo n.º 37
0
 def on_error(self, status_code, data):
     log("Error streaming [{0}]: {1}".format(status_code, data))