tools

- collection of tools for supernets sysadmins
git clone git://git.acid.vegas/tools.git
Log | Files | Refs | Archive

api.py (5395B)

      1 #!/usr/bin/env python
      2 # hateserv irc bot - developed by acidvegas in python (https://git.acid.vegas/hateserv)
      3 
      4 import http.client
      5 import json
      6 import re
      7 
      8 def between(source, start, stop):
      9 	data = re.compile(start + '(.*?)' + stop, re.IGNORECASE|re.MULTILINE).search(source)
     10 	return data.group(1) if data else False
     11 
     12 def geoip(ip: str):
     13 	api = geturl('api.ipapi.is', '?q='+ip)
     14 	data = json.loads(api)
     15 	LOCATION = '{0}, {1}, {2}'.format(data['location']['city'], data['location']['state'], data['location']['country_code'])
     16 	ASN = 'AS{0} {1}'.format(data['asn']['asn'], data['asn']['descr'])
     17 	RIR = data['rir']
     18 	return {'location': LOCATION, 'asn': ASN, 'rir': RIR}
     19 
     20 def geturl(url, endpoint, headers={}):
     21 	conn = http.client.HTTPSConnection(url, timeout=15)
     22 	conn.request('GET', endpoint, headers=headers)
     23 	response = conn.getresponse().read()
     24 	conn.close()
     25 	return response
     26 
     27 def google(query):
     28 	service = build('customsearch', 'v1', developerKey=google_api_key, cache_discovery=False).cse()
     29 	results = service.list(q=query, cx=google_cse_id, num=10).execute()
     30 	return results['items'] if results else False
     31 
     32 def github(option, query):
     33 	if option == 'search':
     34 		data = json.loads(geturl('api.github.com', '/search/repositories?q='+query, headers={'Accept':'application/vnd.github.v3+json','User-Agent':'HateServ/1.0'}))
     35 		return data['items'] if data['items'] else False
     36 	elif option == 'repo':
     37 		return json.loads(geturl('api.github.com', '/repos/'+query, headers={'Accept':'application/vnd.github.v3+json','User-Agent':'HateServ/1.0'}))
     38 	elif option == 'user':
     39 		return json.loads(geturl('api.github.com', '/users/'+query, headers={'Accept':'application/vnd.github.v3+json','User-Agent':'HateServ/1.0'}))
     40 
     41 def imdb(query):
     42 	''' https://www.omdbapi.com '''
     43 	year = query.split()[-1]
     44 	query = query.replace(' ','%20')
     45 	search = 'i' if query.startswith('tt') else 't'
     46 	if search == 't' and len(year) == 4 and year.isdigit():
     47 		endpoint = f'/?{search}={query[:-5]}&y={year}&apikey={api_key}'
     48 	else:
     49 		endpoint = f'/?{search}={query}&apikey={api_key}'
     50 	conn = http.client.HTTPSConnection('omdbapi.com', timeout=15)
     51 	conn.request('GET', endpoint, headers={'Accept':'application/json'})
     52 	response = json.loads(conn.getresponse().read())
     53 	conn.close()
     54 	return response if response['Response'] == 'True' else False
     55 
     56 def reddit(option, subreddit, id=None):
     57 	if option == 'post':
     58 		data = json.loads(geturl('reddit.com', f'/r/{subreddit}/comments/{id}.json', headers={'Accept':'application/json','User-Agent':'HateServ/1.0'}))
     59 		return data[0]['data']['children'][0]['data'] if 'error' not in data else False
     60 	elif option == 'subreddit':
     61 		data = json.loads(geturl('reddit.com', f'/r/{subreddit}.json?limit=20', headers={'Accept':'application/json','User-Agent':'HateServ/1.0'}))
     62 		posts = [item['data'] for item in data['data']['children'] if not item['data']['stickied']]
     63 		return posts if posts else None
     64 
     65 def youtube(option, query, api_key):
     66 	if option == 'video':
     67 		api = httplib.get_json(f'https://www.googleapis.com/youtube/v3/videos?key={config.api.google_api_key}&part=snippet,statistics&id={id}')
     68 		if api['items']:
     69 			api                 = api['items'][0]
     70 			data                = {}
     71 			data['channel']     = api['snippet']['channelTitle']
     72 			data['description'] = ' '.join(api['snippet']['description'].split())
     73 			data['dislikes']    = api['statistics']['dislikeCount']
     74 			data['likes']       = api['statistics']['likeCount']
     75 			data['title']       = api['snippet']['title']
     76 			data['views']       = api['statistics']['viewCount']
     77 			return data
     78 		else:
     79 			return False
     80 	elif option == 'search':
     81 		service = build('youtube', 'v3', developerKey=api_key).search()
     82 		results = service.list(part='id', type='video', q=query, maxResults=10).execute()
     83 		return results['items'] if results else False
     84 
     85 def twitter(data):
     86 #	auth = tweepy.OAuthHandler(twitter_consumer_key, twitter_consumer_secret)
     87 #	auth.set_access_token(twitter_access_token, twitter_access_secret)
     88 #	api = tweepy.API(auth)
     89 #	api.update_status(data)
     90 	pass
     91 
     92 def unreal():
     93 	pass
     94 
     95 def anope():
     96 	pass
     97 
     98 
     99 '''
    100 elif args[0] == '.imdb' and len(args) >= 2:
    101                         query = ' '.join(args[1:])
    102                         api   = imdb.search(query, config.api.omdbapi_key)
    103                         if api:
    104                             Commands.sendmsg(chan, '{0} {1} {2} {3}'.format(color('Title  :', white), api['Title'], api['Year'], color(api['Rated'], grey)))
    105                             Commands.sendmsg(chan, '{0} {1}{2}'.format(color('Link   :', white), underline, color('https://imdb.com/title/' +  api['imdbID'], light_blue)))
    106                             Commands.sendmsg(chan, '{0} {1}'.format(color('Genre  :', white), api['Genre']))
    107                             if api['imdbRating'] == 'N/A':
    108                                 Commands.sendmsg(chan, '{0} {1} N/A'.format(color('Rating :', white), color('★★★★★★★★★★', grey)))
    109                             else:
    110                                 Commands.sendmsg(chan, '{0} {1}{2} {3}'.format(color('Rating :', white), color('★'*round(float(api['imdbRating'])), yellow), color('★'*(10-round(float(api['imdbRating']))), grey), a
    111 pi['imdbRating']))
    112                             Commands.sendmsg(chan, '{0} {1}'.format(color('Plot   :', white), api['Plot']))
    113                         else:
    114                             Commands.error(chan, 'no results found')
    115 '''