Example #1
0
	def retrieveTwitterTitle(url, timeout=5.0):
		tweetMatches = re.search('twitter.com/(?P<name>[^/]+)(?:/status/(?P<id>[^/]+).*)?', url)
		if not tweetMatches:
			CommandTemplate.logWarning("[url] No twitter matches found in '{}'".format(url))
			return None
		apikeys = GlobalStore.commandhandler.apikeys
		if 'twitter' not in apikeys or 'tokentype' not in apikeys['twitter'] or 'token' not in apikeys['twitter']:
			CommandTemplate.logError("[url] Twitter API token info not found!")
			return None
		headers = {"Authorization": "{} {}".format(apikeys['twitter']['tokentype'], apikeys['twitter']['token'])}
		if 'id' in tweetMatches.groupdict() and tweetMatches.group('id') is not None:
			#Specific tweet
			twitterUrl = "https://api.twitter.com/1.1/statuses/show.json?id={id}".format(id=tweetMatches.group('id'))
			twitterDataPage = requests.get(twitterUrl, headers=headers, timeout=timeout)
			twitterdata = json.loads(twitterDataPage.text.encode('utf-8'))

			return u"@{username} ({name}): {text} [{timestamp}]".format(username=twitterdata['user']['screen_name'], name=twitterdata['user']['name'],
													text=twitterdata['text'], timestamp=twitterdata['created_at'])
		else:
			#User page
			twitterUrl = u"https://api.twitter.com/1.1/users/show.json?screen_name={name}".format(name=tweetMatches.group('name'))
			twitterDataPage = requests.get(twitterUrl, headers=headers, timeout=timeout)
			twitterdata = json.loads(twitterDataPage.text.encode('utf-8'))

			title = u"{name} (@{screen_name}): {description} ({statuses_count:,} tweets posted, {followers_count:,} followers, following {friends_count:,})"
			if 'verified' in twitterdata and twitterdata['verified'] is True:
				title += u". Verified account"
			return title.format(**twitterdata)
Example #2
0
	def retrieveYoutubetitle(url, timeout=5.0):
		if 'google' not in GlobalStore.commandhandler.apikeys:
			CommandTemplate.logError("[url] Google API key not found!")
			return None
		#First we need to determine the video ID from something like this: http://www.youtube.com/watch?v=jmAKXADLcxY or http://youtu.be/jmAKXADLcxY
		videoId = u""
		if url.count('youtu.be') > 0:
			videoId = url[url.rfind('/')+1:]
		else:
			videoIdMatch = re.search('.+v=([^&#]+)', url)
			if videoIdMatch:
				videoId = videoIdMatch.group(1)

		if videoId == u"":
			CommandTemplate.logError(u"[url] No Youtube videoId found in '{}'".format(url))
			return None
		googleUrl = "https://www.googleapis.com/youtube/v3/videos"
		params = {'part': 'statistics,snippet,contentDetails', 'id': videoId, 'key': GlobalStore.commandhandler.apikeys['google'],
				  'fields': 'items/snippet(title,description),items/contentDetails/duration,items/statistics(viewCount,likeCount,dislikeCount)'}
		googleJson = json.loads(requests.get(googleUrl, params=params, timeout=timeout).text.encode('utf-8'))

		if 'error' in googleJson:
			CommandTemplate.logError(u"[url] ERROR with Google requests. {}: {}. [{}]".format(googleJson['error']['code'],
																				   googleJson['error']['message'],
																				   json.dumps(googleJson).replace('\n',' ')))
			return None
		if 'items' not in googleJson or len(googleJson['items']) != 1:
			CommandTemplate.logError(u"[url] Unexpected reply from Google API: {}".format(json.dumps(googleJson).replace('\n', ' ')))
			return None
		videoData = googleJson['items'][0]
		durationtimes = DateTimeUtil.parseIsoDate(videoData['contentDetails']['duration'])
		durationstring = u""
		if durationtimes['day'] > 0:
			durationstring += u"{day} d, "
		if durationtimes['hour'] > 0:
			durationstring += u"{hour:02}:"
		durationstring += u"{minute:02}:{second:02}"
		durationstring = durationstring.format(**durationtimes)
		#Check if there's a description
		description = videoData['snippet']['description'].strip()
		if description == u"":
			description = u"<No description>"

		return u"{title} [{duration}, {viewcount:,} views]: {description}".format(title=videoData['snippet']['title'].strip(),
																				  duration=durationstring,
																				  viewcount=int(videoData['statistics']['viewCount']),
																				  description=description)
Example #3
0
    def retrieveImgurTitle(url, timeout=5.0):
        if 'imgur' not in GlobalStore.commandhandler.apikeys or 'clientid' not in GlobalStore.commandhandler.apikeys[
                'imgur']:
            CommandTemplate.logError("[url] Imgur API key not found!")
            return None
        imageIdMatches = re.search('imgur\.com/([^.]+)', url, re.IGNORECASE)
        if imageIdMatches is None:
            CommandTemplate.logError(
                "[url] No Imgur ID found in '{}'".format(url))
            return None
        imageId = imageIdMatches.group(1)
        isGallery = False
        imageType = 'image'
        if '/' in imageId:
            if 'gallery' in imageId:
                imageType = 'gallery/album'
                isGallery = True
            imageId = imageId[imageId.rfind('/') + 1:]
        headers = {
            "Authorization":
            "Client-ID " +
            GlobalStore.commandhandler.apikeys['imgur']['clientid']
        }
        imgurUrl = "https://api.imgur.com/3/{type}/{id}".format(type=imageType,
                                                                id=imageId)
        imgurDataPage = requests.get(imgurUrl,
                                     headers=headers,
                                     timeout=timeout)
        imgdata = json.loads(imgurDataPage.text.encode('utf-8'))
        if imgdata['success'] is not True or imgdata['status'] != 200:
            CommandTemplate.logError(
                "[url] Error while retrieving ImgUr image data: {}".format(
                    imgurDataPage.text.encode('utf-8')))
            return None
        imgdata = imgdata['data']
        if imgdata['title'] is None:
            imgdata['title'] = u"No Title"
        title = u"{imgdata[title]} ("
        if isGallery:
            title += u"{imgdata[images_count]} images"
        else:
            imgFilesize = imgdata['size'] / 1024.0
            #Split into two lines because we're only formatting imgFilesize here, and otherwise it errors out on imgdata
            title += u"{imgdata[width]:,}x{imgdata[height]:,}"
            title += u"  {imgFilesize:,.0f} kb".format(imgFilesize=imgFilesize)
        title += u"  {imgdata[views]:,} views"
        title += u")"

        if 'animated' in imgdata and imgdata['animated'] is True:
            title += u" (Animated)"
        if 'nsfw' in imgdata and imgdata['nsfw'] is True:
            title += u" (NSFW!)"
        return title.format(imgdata=imgdata)
Example #4
0
 def getHelp(self, message):
     #If there's no parameters provided, just show the generic module help text
     if message.messagePartsLength <= 1:
         return CommandTemplate.getHelp(self, message)
     #Check if the parameter matches one of our generator triggers
     requestedTrigger = message.messageParts[1].lower()
     for generator, triggers in self.generators.iteritems():
         #If the triggers is a single string check if it's identical, otherwise check if it's in the list
         if (isinstance(triggers, basestring) and requestedTrigger
                 == triggers) or requestedTrigger in triggers:
             #Trigger match! If the match is a grammar file, retrieve its description
             if isinstance(generator, basestring):
                 with open(os.path.join(self.filesLocation, generator),
                           'r') as grammarFile:
                     grammarDict = json.load(grammarFile)
                     if '_description' in grammarDict:
                         return u"{}{} {}: {}".format(
                             message.bot.commandPrefix,
                             message.messageParts[0], requestedTrigger,
                             grammarDict['_description'])
                     else:
                         return "The '{}' generator file didn't specify a help text, sorry!".format(
                             requestedTrigger)
             #Match is one of the built-in functions
             else:
                 helptext = "No helptext was set for this generator, sorry"
                 if requestedTrigger == 'name':
                     helptext = "Generates a random first and last name. You can provide a parameter to specify the gender"
                 elif requestedTrigger == 'game' or requestedTrigger == 'videogame':
                     helptext = "Generates random video game names. You can provide a number to make it generate that many game names, " \
                        "and replacement words that will get inserted into the generated name"
                 elif requestedTrigger == 'word' or requestedTrigger == 'word2':
                     helptext = "Generates a random word, or tries to. Add a number to make it generate that many words, increasing the chance one of them is pronounceable"
                 return "{}{} {}: {}".format(message.bot.commandPrefix,
                                             message.messageParts[0],
                                             requestedTrigger, helptext)
     #No matching generator trigger was found
     return "I'm not familiar with the '{}' generator, though if you think it would make a good one, feel free to inform my owner(s), maybe they'll create it!".format(
         requestedTrigger)
Example #5
0
	def retrieveImgurTitle(url, timeout=5.0):
		if 'imgur' not in GlobalStore.commandhandler.apikeys or 'clientid' not in GlobalStore.commandhandler.apikeys['imgur']:
			CommandTemplate.logError("[url] Imgur API key not found!")
			return None
		imageIdMatches = re.search('imgur\.com/([^.]+)', url, re.IGNORECASE)
		if imageIdMatches is None:
			CommandTemplate.logError("[url] No Imgur ID found in '{}'".format(url))
			return None
		imageId = imageIdMatches.group(1)
		isGallery = False
		imageType = 'image'
		if '/' in imageId:
			if 'gallery' in imageId:
				imageType = 'gallery/album'
				isGallery = True
			imageId = imageId[imageId.rfind('/')+1:]
		headers = {"Authorization": "Client-ID " + GlobalStore.commandhandler.apikeys['imgur']['clientid']}
		imgurUrl = "https://api.imgur.com/3/{type}/{id}".format(type=imageType, id=imageId)
		imgurDataPage = requests.get(imgurUrl, headers=headers, timeout=timeout)
		imgdata = json.loads(imgurDataPage.text.encode('utf-8'))
		if imgdata['success'] is not True or imgdata['status'] != 200:
			CommandTemplate.logError("[url] Error while retrieving ImgUr image data: {}".format(imgurDataPage.text.encode('utf-8')))
			return None
		imgdata = imgdata['data']
		if imgdata['title'] is None:
			imgdata['title'] = u"No Title"
		title = u"{imgdata[title]} ("
		if isGallery:
			title += u"{imgdata[images_count]} images"
		else:
			imgFilesize = imgdata['size'] / 1024.0
			#Split into two lines because we're only formatting imgFilesize here, and otherwise it errors out on imgdata
			title += u"{imgdata[width]:,}x{imgdata[height]:,}"
			title += u"  {imgFilesize:,.0f} kb".format(imgFilesize=imgFilesize)
		title += u"  {imgdata[views]:,} views"
		title += u")"

		if 'animated' in imgdata and imgdata['animated'] is True:
			title += u" (Animated)"
		if 'nsfw' in imgdata and imgdata['nsfw'] is True:
			title += u" (NSFW!)"
		return title.format(imgdata=imgdata)