Пример #1
0
    def _stringifyTweet(self, tweet):
        """
        turn a tweet object into a nice string for us to send to IRC
        @type tweet: dict[str, T/str]
        """
        retweet = None
        # get the original tweet if this is a retweet
        if 'retweeted_status' in tweet:
            retweet = tweet
            tweet = retweet['retweeted_status']

        tweetText = StringUtils.unescapeXHTML(tweet['text'])
        tweetText = re.sub('[\r\n]+', StringUtils.graySplitter, tweetText)
        for url in tweet['entities']['urls']:
            tweetText = tweetText.replace(url['url'], url['expanded_url'])

        timestamp = parser.parse(tweet['created_at'])
        timeString = timestamp.strftime('%A, %Y-%m-%d %H:%M:%S %Z')
        delta = datetime.datetime.utcnow() - timestamp.replace(tzinfo=None)
        deltaString = StringUtils.deltaTimeToString(delta)
        tweetText = u'{} (tweeted {}, {} ago)'.format(tweetText, timeString, deltaString)

        if retweet is None:
            user = tweet['user']['screen_name']
        else:
            user = retweet['user']['screen_name']
            tweetText = 'RT {}: {}'.format(tweet['user']['screen_name'], tweetText)
            
        link = u'https://twitter.com/{}/status/{}'.format(tweet['user']['screen_name'], tweet['id_str'])
        link = WebUtils.shortenGoogl(link)

        formatString = unicode(assembleFormattedText(A.normal[A.bold['@{0}>'], ' {1} {2}']))
        newTweet = formatString.format(user, tweetText, link)
        return newTweet
Пример #2
0
    def execute(self, message):
        """
        @type message: IRCMessage
        """
        match = re.search('^hango+?u?t$', message.Command, re.IGNORECASE)
        if match or ((message.Type == 'JOIN') and
                     (message.User.Name == 'Emily[iOS]')):
            if message.ReplyTo not in self.hangoutDict:
                self.hangoutDict[message.ReplyTo] = None
                self._syncHangoutDict()
            if self.hangoutDict[message.ReplyTo] is None:
                return IRCResponse(ResponseType.Say,
                                   'No hangouts posted here yet',
                                   message.ReplyTo)

            hangout = self.hangoutDict[message.ReplyTo]

            timeDiff = datetime.datetime.utcnow() - hangout.lastDate
            url = 'https://talkgadget.google.com/hangouts/_/{0}'.format(
                hangout.lastCode)
            byLine = 'first linked {0} ago'.format(
                StringUtils.deltaTimeToString(timeDiff))

            if ((message.Type == 'JOIN')
                    and (message.User.Name == 'Emily[iOS]')):
                response = 'Welcome Back, Lady Emily.  Here\'s the hangout for your streaming pleasure: http://bit.ly/DBHangoutReloaded'
            else:
                response = 'Last hangout linked: {0} ({1})'.format(url, byLine)

            return IRCResponse(ResponseType.Say, response, message.ReplyTo)

        match = re.search(r'google\.com/hangouts/_/(?P<code>[^\?\s]+)',
                          message.MessageString, re.IGNORECASE)

        if not match:
            return

        if message.ReplyTo not in self.hangoutDict or self.hangoutDict[
                message.ReplyTo] is None:
            self.hangoutDict[message.ReplyTo] = Data()
        elif match.group('code') == self.hangoutDict[message.ReplyTo].lastCode:
            return

        self.hangoutDict[message.ReplyTo].lastCode = match.group('code')
        self.hangoutDict[message.ReplyTo].lastUser = message.User.Name
        self.hangoutDict[message.ReplyTo].lastDate = datetime.datetime.utcnow()

        self._syncHangoutDict()

        return
Пример #3
0
    def execute(self, message):
        """
        @type message: IRCMessage
        """
        match = re.search('^hango+?u?t$', message.Command, re.IGNORECASE)
        if match or ((message.Type == 'JOIN') and (message.User.Name == 'Emily[iOS]')):
            if message.ReplyTo not in self.hangoutDict:
                self.hangoutDict[message.ReplyTo] = None
                self._syncHangoutDict()
            if self.hangoutDict[message.ReplyTo] is None:
                return IRCResponse(ResponseType.Say,
                                   'No hangouts posted here yet',
                                   message.ReplyTo)

            hangout = self.hangoutDict[message.ReplyTo]

            timeDiff = datetime.datetime.utcnow() - hangout.lastDate
            url = 'https://talkgadget.google.com/hangouts/_/{0}'.format(hangout.lastCode)
            byLine = 'first linked {0} ago'.format(StringUtils.deltaTimeToString(timeDiff))

            if ((message.Type == 'JOIN') and (message.User.Name == 'Emily[iOS]')):
                response = 'Welcome Back, Lady Emily.  Here\'s the hangout for your streaming pleasure: http://bit.ly/DBHangoutReloaded'
            else:
                response = 'Last hangout linked: {0} ({1})'.format(url, byLine)

            return IRCResponse(ResponseType.Say, response, message.ReplyTo)

        match = re.search(r'google\.com/hangouts/_/(?P<code>[^\?\s]+)',
                          message.MessageString,
                          re.IGNORECASE)

        if not match:
            return

        if message.ReplyTo not in self.hangoutDict or self.hangoutDict[message.ReplyTo] is None:
            self.hangoutDict[message.ReplyTo] = Data()
        elif match.group('code') == self.hangoutDict[message.ReplyTo].lastCode:
            return

        self.hangoutDict[message.ReplyTo].lastCode = match.group('code')
        self.hangoutDict[message.ReplyTo].lastUser = message.User.Name
        self.hangoutDict[message.ReplyTo].lastDate = datetime.datetime.utcnow()

        self._syncHangoutDict()

        return
Пример #4
0
 def _fetch(self, j, short, mode, label):
     r = j['modes'][mode]
     data = []
     t = A.normal[A.bold['{} {}: '.format(label, r[0]['rule']['name'])],
                  '/'.join(r[0]['maps'])]
     data.append(assembleFormattedText(t))
     if not short:
         # include next maps
         now = int(time.time())
         startTime = r[1]['startTime']
         delta = startTime - now
         d = datetime.timedelta(seconds=delta)
         deltaStr = StringUtils.deltaTimeToString(d, resolution='m')
         t = A.normal[A.bold['{} {} in {}: '.
                             format(label, r[1]['rule']['name'], deltaStr)],
                      '/'.join(r[1]['maps'])]
         data.append(assembleFormattedText(t))
     return ' | '.join(data)
Пример #5
0
    def execute(self, message):
        """
        @type message: IRCMessage
        """
        if len(message.ParameterList) < 2:
            return IRCResponse(ResponseType.Say, self.help, message.ReplyTo)

        command = message.ParameterList[1].lower()
        delay = timeparse(message.ParameterList[0])
        delayDelta = datetime.timedelta(seconds=delay)
        delayString = StringUtils.deltaTimeToString(delayDelta, 's')
        params = message.ParameterList[2:]
        commandString = u'{}{} {}'.format(self.bot.commandChar, command, u' '.join(params))
        commandString = commandString.replace('$delayString', delayString)
        commandString = commandString.replace('$delay', str(delay))

        newMessage = IRCMessage(message.Type, message.User.String, message.Channel, commandString, self.bot)

        moduleHandler = self.bot.moduleHandler
        if command in moduleHandler.mappedTriggers:
            d = task.deferLater(reactor, delay, moduleHandler.mappedTriggers[command].execute, newMessage)
            d.addCallback(self.bot.sendResponse)
            return IRCResponse(ResponseType.Say,
                               "OK, I'll execute that in {}".format(delayString),
                               message.ReplyTo,
                               {'delay': delay, 'delayString': delayString})
        else:
            if 'Alias' not in moduleHandler.commands:
                return IRCResponse(ResponseType.Say,
                                   "'{}' is not a recognized command".format(command),
                                   message.ReplyTo)

            if command not in moduleHandler.commands['Alias'].aliases:
                return IRCResponse(ResponseType.Say,
                                   "'{}' is not a recognized command or alias".format(command),
                                   message.ReplyTo)

            d = task.deferLater(reactor, delay, moduleHandler.commands['Alias'].execute, newMessage)
            d.addCallback(self.bot.sendResponse)
            return IRCResponse(ResponseType.Say,
                               "OK, I'll execute that in {}".format(delayString),
                               message.ReplyTo)
Пример #6
0
    def execute(self, message):
        """
        @type message: IRCMessage
        """
        match = re.search('^hango+?u?t$', message.Command, re.IGNORECASE)
        if match:
            if message.ReplyTo not in self.hangoutDict:
                self.hangoutDict[message.ReplyTo] = None
            if self.hangoutDict[message.ReplyTo] is None:
                return IRCResponse(ResponseType.Say,
                                   'No hangouts posted here yet',
                                   message.ReplyTo)

            hangout = self.hangoutDict[message.ReplyTo]

            timeDiff = datetime.datetime.utcnow() - hangout.lastDate
            url = 'https://talkgadget.google.com/hangouts/_/{0}'.format(hangout.lastCode)
            byLine = 'first linked {0} ago by {1}'.format(StringUtils.deltaTimeToString(timeDiff), hangout.lastUser)

            response = 'Last hangout linked: {0} ({1})'.format(url, byLine)

            return IRCResponse(ResponseType.Say, response, message.ReplyTo)

        match = re.search(r'google\.com/hangouts/_/(?P<code>[^\?\s]+)',
                          message.MessageString,
                          re.IGNORECASE)

        if not match:
            return

        if message.ReplyTo not in self.hangoutDict or self.hangoutDict[message.ReplyTo] is None:
            self.hangoutDict[message.ReplyTo] = Data()
        elif match.group('code') == self.hangoutDict[message.ReplyTo].lastCode:
            return

        self.hangoutDict[message.ReplyTo].lastCode = match.group('code')
        self.hangoutDict[message.ReplyTo].lastUser = message.User.Name
        self.hangoutDict[message.ReplyTo].lastDate = datetime.datetime.utcnow()
        return
Пример #7
0
    def _stringifyTweet(self, tweet):
        """
        turn a tweet object into a nice string for us to send to IRC
        @type tweet: dict[str, T/str]
        """
        retweet = None
        # get the original tweet if this is a retweet
        if 'retweeted_status' in tweet:
            retweet = tweet
            tweet = retweet['retweeted_status']

        tweetText = StringUtils.unescapeXHTML(tweet['text'])
        tweetText = re.sub('[\r\n]+', StringUtils.graySplitter, tweetText)
        for url in tweet['entities']['urls']:
            tweetText = tweetText.replace(url['url'], url['expanded_url'])

        timestamp = parser.parse(tweet['created_at'])
        timeString = timestamp.strftime('%A, %Y-%m-%d %H:%M:%S %Z')
        delta = datetime.datetime.utcnow() - timestamp.replace(tzinfo=None)
        deltaString = StringUtils.deltaTimeToString(delta)
        tweetText = u'{} (tweeted {}, {} ago)'.format(tweetText, timeString,
                                                      deltaString)

        if retweet is None:
            user = tweet['user']['screen_name']
        else:
            user = retweet['user']['screen_name']
            tweetText = 'RT {}: {}'.format(tweet['user']['screen_name'],
                                           tweetText)

        link = u'https://twitter.com/{}/status/{}'.format(
            tweet['user']['screen_name'], tweet['id_str'])
        link = WebUtils.shortenGoogl(link)

        formatString = unicode(
            assembleFormattedText(A.normal[A.bold['@{0}>'], ' {1} {2}']))
        newTweet = formatString.format(user, tweetText, link)
        return newTweet
Пример #8
0
    def FollowYouTube(self, videoID, message):
        if self.youtubeKey is None:
            return IRCResponse(ResponseType.Say, '[YouTube API key not found]',
                               message.ReplyTo)

        fields = 'items(id,snippet(title,description,channelTitle,liveBroadcastContent),contentDetails(duration),statistics(viewCount),liveStreamingDetails(scheduledStartTime))'
        parts = 'snippet,contentDetails,statistics,liveStreamingDetails'
        url = 'https://www.googleapis.com/youtube/v3/videos?id={}&fields={}&part={}&key={}'.format(
            videoID, fields, parts, self.youtubeKey)

        webPage = WebUtils.fetchURL(url)
        webPage.body = webPage.body.decode('utf-8')
        j = json.loads(webPage.body)

        if 'items' not in j:
            return None

        data = []

        vid = j['items'][0]

        title = vid['snippet']['title']
        data.append(title)
        channel = vid['snippet']['channelTitle']
        data.append(channel)
        if vid['snippet']['liveBroadcastContent'] == 'none':
            length = parse_duration(
                vid['contentDetails']['duration']).total_seconds()
            m, s = divmod(int(length), 60)
            h, m = divmod(m, 60)
            if h > 0:
                length = u'{0:02d}:{1:02d}:{2:02d}'.format(h, m, s)
            else:
                length = u'{0:02d}:{1:02d}'.format(m, s)

            data.append(length)
        elif vid['snippet']['liveBroadcastContent'] == 'upcoming':
            startTime = vid['liveStreamingDetails']['scheduledStartTime']
            startDateTime = dateutil.parser.parse(startTime)
            now = datetime.datetime.now(dateutil.tz.tzutc())
            delta = startDateTime - now
            timespan = StringUtils.deltaTimeToString(delta, 'm')
            timeString = assembleFormattedText(
                A.normal['Live in ', A.fg.cyan[A.bold[timespan]]])
            data.append(timeString)
            pass  # time till stream starts, indicate it's upcoming
        elif vid['snippet']['liveBroadcastContent'] == 'live':
            status = unicode(
                assembleFormattedText(A.normal[A.fg.red[A.bold['{} Live']]]))
            status = status.format(u'●')
            data.append(status)
        else:
            pass  # if we're here, wat

        views = int(vid['statistics']['viewCount'])
        data.append('{:,}'.format(views))

        description = vid['snippet']['description']
        if not description:
            description = u'<no description available>'
        description = re.sub('(\n|\s)+', ' ', description)
        limit = 150
        if len(description) > limit:
            description = u'{} ...'.format(description[:limit].rsplit(' ',
                                                                      1)[0])
        data.append(description)

        return IRCResponse(
            ResponseType.Say, self.graySplitter.join(data), message.ReplyTo,
            {'urlfollowURL': 'http://youtu.be/{}'.format(videoID)})