def open_connections(verbose=False): # Read from config file config = ConfigParser.ConfigParser() #config.read('config.ini') config.read([os.path.expanduser('~/.chumbpush')]) # Connect to IMAP server imap_server = config.get('imap', 'server') if verbose: print 'Connecting to', imap_server imap_connection = imaplib2.IMAP4_SSL(imap_server) # Login to our account imap_username = config.get('imap', 'username') imap_password = config.get('imap', 'password') if verbose: print 'Logging in as', imap_username imap_connection.login(imap_username, imap_password) # Set up Twitter API twitter_consumer_key = config.get('twitter', 'consumer_key') twitter_consumer_secret = config.get('twitter', 'consumer_secret') twitter_access_token_key = config.get('twitter', 'access_token_key') twitter_access_token_secret = config.get('twitter', 'access_token_secret') twitter_api = twitter.Api(consumer_key=twitter_consumer_key, consumer_secret=twitter_consumer_secret, access_token_key=twitter_access_token_key, access_token_secret=twitter_access_token_secret) # Set up Bitify API bitly_login = config.get('bitly', 'login') bitly_apikey = config.get('bitly', 'apikey') bitify = bitly.Api(login=bitly_login, apikey=bitly_apikey) return imap_connection, twitter_api, bitify
def random_blog(): data = browser.open("http://gulzarmanzil.wordpress.com/?random").read() soup = BeautifulSoup(data) title = soup.find('title').findAll(text=True)[0].split('|')[0].strip() link = browser.geturl() rep_with = { "‘": "'", "’": "'", "’": "'", "–": "-", "…": "...", "…": "...", } for rem in rep_with.keys(): while rem in title: title.replace(rem, rep_with[rem]) if len(title + ' ' + link) > 130: try: # Fill your BITLY api credentials here bittifier = bitly.Api(login=CREDENTIALS['bitly']['login'], apikey=CREDENTIALS['bitly']['key']) link = str(bittifier.shorten(link)) except: pass return title + ' ' + link
def livetweet(title, liveurl): CK = 'XXXXXXXXXXXXXXXXXX' # Consumer Key CS = 'XXXXXXXXXXXXXXXXXX' # Consumer Secret AT = 'XXXXXXXXXXXXXXXXXX' # Access Token AS = 'XXXXXXXXXXXXXXXXXX' # Accesss Token Secert bitlylogin = '******' apikey = 'XXXXXXXXXXXXXXXXXX' #bitly認証 bitly_api = bitly.Api(login=bitlylogin, apikey=apikey) # ツイート投稿用のURL url_media = "https://upload.twitter.com/1.1/media/upload.json" url_text = "https://api.twitter.com/1.1/statuses/update.json" # OAuth認証で POST method で投稿 twitter = OAuth1Session(CK, CS, AT, AS) short_url = bitly_api.shorten(liveurl) req = twitter.post(url_text, params={"status": "【配信開始】" + title + "\n" + short_url}) # レスポンスを確認 if req.status_code == 200: print("OK") else: print("Error: %d" % req.status_code)
def run(): conn = sqlite3.connect('tweets.db') # if table not exists, create table cur = conn.cursor() query = cur.execute( "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='tweet_table'" ) if query.fetchone()[0] <= 0: cur.execute( "CREATE TABLE tweet_table(Id INTEGER PRIMARY KEY, reddit_id TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)" ) consumer_key = TwitterKey['consumer_key'] consumer_secret = TwitterKey['consumer_secret'] access_token = TwitterKey['access_token'] access_token_secret = TwitterKey['access_token_secret'] auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) bot = tweepy.API(auth) shortapi = bitly.Api(login=BitlyKey['login'], apikey=BitlyKey['apikey']) url = 'http://www.reddit.com/r/programming/.json' jsondata = json.loads(urllib2.urlopen(url).read()) if 'data' in jsondata and 'children' in jsondata['data']: posts = jsondata['data']['children'] posts.reverse() for ind, post in enumerate(posts): entry = post['data'] # logging.debug(entry['permalink'] + ' ' +entry['url']) postid = entry['id'] num_comments = entry['num_comments'] query = cur.execute( "SELECT * FROM tweet_table WHERE reddit_id = '%s'" % postid) if len(query.fetchall()) == 0 and num_comments > 5: title = entry['title'] score = entry['score'] downs = entry['downs'] ups = entry['ups'] permalink = shortapi.shorten('http://www.reddit.com' + entry['permalink']) url = shortapi.shorten(entry['url']) author = entry['author'] status = ' %s [%s by:%s comments:%d score:%d]' % ( url, permalink, author, num_comments, score) status = title[:(135 - len(status))] + status status = status.encode('utf-8') logging.debug(status) bot.update_status(status) cur.execute("INSERT INTO tweet_table VALUES (?, ?, ?)", [None, postid, None]) conn.commit() conn.close()
def shorten_url(url): """ shorten url via bit.ly services """ bitly_l = site_info.get_by(name=u'bitly_login_user').value.encode('utf8') bitly_key = site_info.get_by(name=u'bitly_api_key').value.encode('utf8') api = bitly.Api(login=bitly_l, apikey=bitly_key) short_url = api.shorten(url) return short_url
def shorten_url(url, credentials): """ Shorten a url using bit.ly. """ api = bitly.Api(**credentials) short = api.shorten(url) return short
def _get_bitly_api(): """Get an instance of the bit.ly API class""" global bitly_api if bitly_api is None: import bitly login = getattr(settings, 'BITLY_USERNAME', '') apikey = getattr(settings, 'BITLY_API_KEY', '') bitly_api = bitly.Api(login, apikey) return bitly_api
def bitly_url(context): api = bitly.Api(login=settings.BITLY_LOGIN, apikey=settings.BITLY_APIKEY) url_original = 'http://' + context['request'].META['HTTP_HOST'] + context[ 'request'].META['PATH_INFO'] try: url_shorten = api.shorten(url_original) except TypeError: url_shorten = "#" context.update({'url': url_shorten}) return context
def bitify_urls(text): pat_url = re.compile( r'''http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+''' ) bitify = bitly.Api(login='******', apikey='bitley_apikey') for url in re.findall(pat_url, text): short_url = bitify.shorten(url) text = text.replace(url, short_url) return text
def _shorten_answers_urls(self, domain, answers): urls = {} for answer in answers: urls[answer['answer_id']] = ScanNewAnswers._answer_url( domain, answer) if len(urls) > 0: a = bitly.Api(login=guru_globals.bitly_login, apikey=guru_globals.bitly_api_key) short_urls = a.shorten(urls.values()) return dict(zip(urls.keys(), short_urls)) return {}
def get(self): consumer_key = TwitterKey['consumer_key'] consumer_secret = TwitterKey['consumer_secret'] access_token = TwitterKey['access_token'] access_token_secret = TwitterKey['access_token_secret'] auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) bot = tweepy.API(auth) shortapi = bitly.Api(login=BitlyKey['login'], apikey=BitlyKey['apikey']) url = 'http://www.reddit.com/r/programming/.json' jsondata = json.loads(urllib2.urlopen(url).read()) tweets = '' if 'data' in jsondata and 'children' in jsondata['data']: posts = jsondata['data']['children'] posts.reverse() for ind, post in enumerate(posts): entry = post['data'] logging.debug(entry['permalink'] + ' ' + entry['url']) postid = entry['id'] query = TwitterDB.all() num_comments = entry['num_comments'] query.filter('reddit_id =', postid) res = query.fetch(1) if len(res) == 0 and num_comments > 5: title = entry['title'] score = entry['score'] downs = entry['downs'] ups = entry['ups'] permalink = shortapi.shorten('http://www.reddit.com' + entry['permalink']) url = shortapi.shorten(entry['url']) author = entry['author'] status = ' %s [%s by:%s comments:%d score:%d]' % ( url, permalink, author, num_comments, score) status = title[:(140 - len(status))] + status status = status.encode('utf-8') logging.debug(status) tweets += '<p>' + status + '</p>' bot.update_status(status) item = TwitterDB() item.reddit_id = postid item.put() self.response.out.write("Done!\n" + tweets)
def _shorten_comments(self, domain, comments): urls = {} for question in comments: for comment in comments[question]: url = ScanNewComments._comment_url(domain, comment) urls[comment['comment_id']] = url if len(urls.values()) > 0: a = bitly.Api(login=guru_globals.bitly_login, apikey=guru_globals.bitly_api_key) short_urls = a.shorten(urls.values()) return dict(zip(urls.keys(), short_urls)) return {}
def send_to_twitter(self, song): twitter_message = "Now Playing: %s - %s" % (song.artist(), song.title) if self.bitly_username and self.bitly_key: url = self.base_url + song.get_absolute_url() self.log.debug("Bitly : Full URL To Song URL: %s" % url) try: api = bitly.Api(login=self.bitly_username, apikey=self.bitly_key) short_url = api.shorten(url) twitter_message += ' - %s' % short_url except: self.log.warning("Bit.ly failed to shorten url!") if self.twitter_username and self.twitter_password: self.log.debug("Tweeting: %s" % twitter_message) self.tweet(self.twitter_username, self.twitter_password, twitter_message)
def test(): consumer_key = "Y58SeSAKiseoXalPqbYhIQ" consumer_secret = "q51SOmJhT8eVRORKtx6AiqJ1YfsDnRAqbmWmtdjklo" access_token = "178269422-SNexeTB56lZ9wQ3VXL1nRJg0WeYdWoHUfqlEwjO2" access_token_secret = "WrGaBCHtGbZLttIQKVmrqhTp9wOYM9KSs6HSOHLf3k" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) bot = tweepy.API(auth) shortapi = bitly.Api(login='******', apikey='R_39fbf3e0a40688bfe792dd90bd41b4e8') feed = 'http://www.reddit.com/r/programming/.rss' atomxml = feedparser.parse(feed) entries = atomxml['entries'] tweets = '' if len(entries) != 0: entries.reverse() for x in range(len(entries)): entry = entries[x] title = str(unicode(entry['title']).encode("utf-8")) link = str(unicode(entry['link']).encode("utf-8")) myid = str(unicode(entry['id']).encode("utf-8")) summary = str(unicode(entry['summary']).encode("utf-8")) num_comments = 0 status = '' soup = BeautifulSoup(summary) links = soup.findAll('a') #print entry try: for link in links: if link['href'].find('/user/') < 0: #urllink = str(unicode(link['href']).encode("utf-8")) status += ' ' + shortapi.shorten(link['href']) if link.string.find('comments') > 0: status += ' ' + link.string num_comments = int(link.string[1:-1].split()[0]) try: status = title[:(140 - len(status))] + status except: status = repr(title[:(140 - len(status))]) + status print status print num_comments except: pass
def get_shortened_url(url): shortener = weechat.config_get_plugin('shortener') if shortener == 'bitly': import bitly api = bitly.Api(login=weechat.config_get_plugin('bitly_login'), apikey=weechat.config_get_plugin('bitly_key')) history = 1 if weechat.config_get_plugin( 'bitly_add_to_history') == 'true' else 0 return api.shorten(url, {'history': history}) if shortener == 'isgd': url = ISGD % urlencode({'url': url}) if shortener == 'tinyurl': url = TINYURL % urlencode({'url': url}) try: return urlopen(url).read() except: return url
def get_shortened_url(url): shortener = weechat.config_get_plugin('shortener') if shortener == 'bitly': import bitly api = bitly.Api(login=weechat.config_get_plugin('bitly_login'), apikey=weechat.config_get_plugin('bitly_key')) history = 1 if weechat.config_get_plugin('bitly_add_to_history') == 'true' else 0 return api.shorten(url, {'history':history}) if shortener == 'isgd': url = ISGD % urlencode({'url': url}) if shortener == 'tinyurl': url = TINYURL % urlencode({'url': url}) try: opener = urllib2.build_opener() opener.addheaders = [('User-Agent', 'weechat')] return opener.open(url).read() except: return url
def ices_get_next(): global meta global timestamp global twitter_username global twitter_password if timestamp: delta = datetime.datetime.now() - timestamp if delta < timedelta(seconds=3): time.sleep(3) Log.warning("Song '%s' borked for some reason!" % meta) timestamp = datetime.datetime.now() Log.debug("Finding a new song for ices") song = findQueued() meta = "%s - %s" % (song.artist(), song.title) Log.debug("Now playing \"%s\" [ID %s]" % (song.title, song.id)) # Now to add the song portion of the link to the end of it # Generate simplified Twitter message twitter_message = "Now Playing: %s - %s" % (song.artist(), song.title) # Append the Bit.Ly shortened URL, only if it's active if bitly_username and bitly_key: url = base_url + song.get_absolute_url() Log.debug("Bitly : Full URL To Song URL: %s" % url) try: api = bitly.Api(login=bitly_username, apikey=bitly_key) short_url = api.shorten(url) twitter_message += ' - %s' % short_url except: Log.warning("Bit.ly failed to shorten url!") if twitter_username and twitter_password: Log.debug("Tweeting: %s" % twitter_message) tweet(twitter_username, twitter_password, twitter_message) try: filepath = song.file.path.encode(enc) except: filepath = song.file.path.encode(fsenc, 'ignore') Log.debug("Giving ices path %s" % filepath) return filepath
def __init__(self): self.name = "*****@*****.**" self.password = "******" self.skip_n163 = False self.skip_sina = False self.skip_twitter = False self.login_to_sina_microblog() self.login_to_net163_microblog() self.twitter_api = twitter.Api(username='******', password='******') self.bitly_api = bitly.Api(login='******', apikey='R_a4fb86c8c3e20ea6d9d83ef36ff023d7') result = 5 if (self.skip_n163): result -= 2 if (self.skip_sina): result -= 2 if (self.skip_twitter): result -= 2 self.quota = result
def bitly(login, apikey, url): import bitly api = bitly.Api(login=login, apikey=apikey) return api.shorten(url)
import bitly import re import time import os from invenio.search_engine import perform_request_search bitly_key = 'R_4165e9efdb444469a6dd475b52f16b87' bitly_account = 'hoc3426' api = bitly.Api(login=bitly_account, apikey=bitly_key) category = { 'a': [ '1. Cosmic Frontier', 50, 'exp fnal-e-0990 or fnal-t-0969 or fnal-e-0987 or auger or cdms or fnal-e-0961 or fnal-e-1000 or lsst or sdss or snap or des' ], 'b': ['2a. Energy Frontier (TeV)', 50, 'exp fnal-e-0823 or fnal-e-0830'], 'c': ['2b. Energy Frontier (CMS)', 50, 'exp cern-lhc-cms'], 'd': [ '3. Intensity Frontier', 50, 'exp fnal-e-0831 or fnal-e-0875 or fnal-e-0898 or fnal-e-0906 or fnal-e-0929 or fnal-e-0938 or fnal-e-0954 or fnal-e-0973 or fnal-e-0974 or fnal-e-0989 or fnal-t-0962 or lbne' ], 'e': [ '4. Theory', 50, 'r fermilab pub and tc p not tc c not tc r and (r ae and fc p or r t or r a)' ], 'f': [ '5a. Science and Technology (S&T) conference', 10, 'Major accelerator conferences from http://www.jacow.org/index.php?n=Main.Proceedings' ], 'g': [ '5b. Science and Technology (S&T) published', 10,
from util import hook, http import bitly import uuid from random import randint api = bitly.Api(login='******', apikey='R_fdf99e81477ce574c386c26560112865') def removeNonAscii(s): return "".join(i for i in s if ord(i) < 128) def random_digits(n): range_start = 10**(n - 1) range_end = (10**n) - 1 return randint(range_start, range_end) @hook.command('gh') @hook.command def grouphug(inp, nick='', chan='', say=None): if inp == '': #h = http.get_html("http://grouphug.us/%s" % str(uuid.uuid1())) return "http://grouphug.us/confessions/%s" % str(random_digits(10)) else: h = http.get_html("http://grouphug.us/confessions/%s" % inp) hugID = h.xpath('//h2[@class="title"]/a/text()')[1] hugContent = removeNonAscii(h.xpath('//div[@class="content"]/p/text()')[1]) if len(hugContent) > 350: hugContent = hugContent[:350] + "..." hugURL = "http://grouphug.us/confessions/%s" % (hugID)
def make_verified(self, request, queryset, send_twitter=True): item_count = 0 import twitter, bitly import tweepy twitter_api = None if send_twitter: twitter_auth = tweepy.OAuthHandler( settings.TWITTER_OAUTH_CONSUMER_KEY, settings.TWITTER_OAUTH_CONSUMER_SECRET) twitter_auth.set_access_token(settings.TWITTER_OAUTH_ACCESS_KEY, settings.TWITTER_OAUTH_ACCESS_SECRET) twitter_api = tweepy.API(twitter_auth) for item in queryset: item_count += 1 item.verified = True posted_twitter = False if send_twitter and not item.twitter_notified: url_api = bitly.Api(login=settings.BITLY_USERNAME, apikey=settings.BITLY_APYKEY) short_url = url_api.shorten("http://www.djangosites.org%s" % item.get_absolute_url()) total_length_left = 140 - len(short_url) - len( item.owner.username) - len("Just listed '' by ; ") - 1 truncated_title = item.title[:total_length_left] #try: status = twitter_api.update_status( "Just listed '%s' by %s; %s" % (truncated_title, item.owner, short_url)) #status = api.PostUpdate("Just listed '%s' by %s; %s" % (truncated_title, item.owner, short_url)) #except: #pass # dodgy to prevent this completely dying on us item.twitter_notified = True posted_twitter = True item.save() if posted_twitter: twitter_text = "- a tweet linking to this listing was also posted over at https://twitter.com/djangosites." else: twitter_text = "" message = """Hi! I've just checked the listing you submitted to www.djangosites.org and it checks out OK - it looks like you really do use Django. As such, I've published your listing which can now be seen at http://www.djangosites.org%s %s Let me know if I can help at all - just respond to this e-mail. Cheers, Ross Poulton Curator, Djangosites.org """ % (item.get_absolute_url(), twitter_text) send_mail('Your djangosites.org listing is live', message, 'DjangoSites <*****@*****.**>', [item.owner.email]) if item_count == 1: count_bit = "1 website was" else: count_bit = "%s websites were" % item_count msg = '%s successfully marked as verified' % count_bit if send_twitter: msg = msg + ' and Twitter updated' self.message_user(request, msg)
MONTH = YEAR + '-02' MONTH_1 = YEAR + '-01' MONTH_2 = YEAR_1 + '-12' else: fmonth = lambda x: '-0' + str(x) if x < 10 else '-' + str(x) MONTH = YEAR + fmonth(MONTH) MONTH_1 = YEAR + fmonth(MONTH_1) MONTH_2 = YEAR + fmonth(MONTH_2) os.environ['TZ'] = 'CEST+5' DATE_TIME_STAMP = time.strftime('%Y-%m-%d %H:%M:%S') DATE_STAMP = time.strftime('%Y-%m-%d') BITLY_KEY = 'R_4165e9efdb444469a6dd475b52f16b87' BITLY_ACCOUNT = 'hoc3426' API = bitly.Api(login=BITLY_ACCOUNT, apikey=BITLY_KEY) def main(): groups = ['All', 'E', 'CMS', 'T', 'A', 'AE', 'PPD', 'AD/APC'] groups += ['TD', 'CD', 'Other'] docs = ['All', 'PUB', 'THESIS', 'CONF', 'TM', 'FN'] dates = [YEAR_2, YEAR_1, YEAR, MONTH_2, MONTH_1, MONTH] filename = 'fermilab_research_glance.html' filename_w = 'www/' + filename output = open(filename_w, 'w') output.write('<!doctype html>\n') output.write('<html lang="en">\n') output.write('<head>\n') output.write(' <meta charset="utf-8">\n')
month = "Jul" return re.sub("^0", "", date[2]) + " de " + month + " " + date[0] tuits = [] # process data for line in data_file: line = line.split("|") # date as mm-dd date = re.sub("^[0-9]{4}-", "", line[0].strip()) if date == today: event = line[1].strip() link = line[2].strip() shortUrl = bitly.Api(login=API_USERNAME, apikey=API_KEY).shorten(link) formatted_date = format_date(line[0]) f.write(formatted_date + "\n") tuit = formatted_date + ": " + event + " " + shortUrl cmd = '/usr/local/bin/t update "' + tuit + '"' tuits.append(cmd) # count number of tuits for today n_tuits = len(tuits) if n_tuits > 0: timeToSleep = 6.0 * 60 * 60 / n_tuits else: timeToSleep = 1
###!/usr/bin/env python ## /RelVal(ZMM|WM|TTbar|JpsiMM|SingleMu.*)/CMSSW_(4_1_2|3_11_1) from optparse import OptionParser import bitly shortener=bitly.Api('jklukas', 'R_478578d1bd76cea3a334bd56425de23f') link_template="https://cmsweb.cern.ch/dqm/relval/start?runnr=%(runNum)s;dataset=%(dataset1)s;sampletype=offline_data;filter=all;referencepos=overlay;referenceshow=all;referenceobj1=other::%(dataset2)s:;striptype=object;stripruns=;stripaxis=run;stripomit=none;workspace=Everything;size=M;root=%(root)s;zoom=no;" def main(): parser = OptionParser() options, args = parser.parse_args() kind, hltpath, runNum, dataset1, dataset2 = args if(kind == "mc"): root = 'HLT/Muon/Efficiency_Layouts/' + hltpath else: root = 'HLT/Muon/DistributionsGlobal/' + hltpath link = link_template % locals() short = shortener.shorten(link) print "#############################################################################################################" print "Validation of: " + dataset1 print "Reference sample: " + dataset2 print "Type of Sample: " + kind print "HLT Path: " + hltpath print "Run Number: " + runNum print "Link: " + link print "#############################################################################################################"
def what(phenny, input): """.what - interface for what.cd""" db_conn = sqlite3.connect('modules/what.db') db_cur = db_conn.cursor() db_cur.execute('SELECT id FROM users WHERE name = "%s"' % input.nick) user = db_cur.fetchone() if user is None: phenny.say('%s: sorry, you\'re not an authorised user' % input.nick) return else: userID = user[0] f = open("modules/whatData.json") s = "" for line in f: s = s + line import simplejson decoder = simplejson.JSONDecoder() bLogin = decoder.decode(s)['bitly']['login'] bApiKey = decoder.decode(s)['bitly']['apikey'] import bitly api = bitly.Api(login=bLogin, apikey=bApiKey) try: args = input.group(2).rsplit(' ') except: if '.what' in input: phenny.say( '%s: please specify find, add, genres, search, list or users' % input.nick) return else: args = (' ', ' ') if args[0] == 'search': if len(args) > 2: try: (url, searchRatio) = findTorrentPage(phenny, input) (artist, album, genre) = getTorrentDetails(url) phenny.say('%s: first result is "%s" (match: %.1f%%) | %s' % (input.nick, artist + u' - ' + album, searchRatio * 100, api.shorten(url))) except SyntaxError: phenny.say('%s: found no results' % (input.nick)) return except: phenny.say('%s: could not contact what.cd or malformed input' % input.nick) return else: phenny.say('%s: usage is .what search artist - album' % input.nick) return elif args[0] == 'add': if len(args) > 2: try: (url, searchRatio) = findTorrentPage(phenny, input) (artist, album, genre) = getTorrentDetails(url) if searchRatio < 0.9: phenny.say( '%s: first result is "%s" [%s] (match %.1f%% too low, not adding)' % (input.nick, artist + u' - ' + album, api.shorten(url), searchRatio * 100)) return else: phenny.say('%s: found "%s" (match: %.1f%%)' % (input.nick, artist + u' - ' + album, searchRatio * 100)) except: return else: try: url = args[1] if 'what.cd' not in url: phenny.say('%s: url must point to what.cd' % input.nick) return if 'torrents.php' not in url: phenny.say('%s: url must point to a torrent' % input.nick) return except: phenny.say( '%s: usage is .what add <url> or .what add artist - album' % input.nick) return try: shortUrl = api.shorten(url) except: phenny.say('%s: url appears malformed' % input.nick) return try: (artist, album, genre) = getTorrentDetails(url) except: phenny.say('%s: there was a problem parsing the given page' % input.nick) return try: db_cur.execute('SELECT id FROM genres WHERE name="%s"' % genre) genreID = db_cur.fetchone() if genreID is None: db_cur.execute('INSERT INTO genres VALUES(null, "%s")' % genre) genreID = db_cur.lastrowid else: genreID = genreID[0] db_cur.execute( 'INSERT INTO recommendations VALUES(null, "%s", "%s", "%s", "%d", "%d")' % (artist, album, shortUrl, genreID, userID)) db_conn.commit() phenny.say('%s: [%s - %s | %s | %s] added!' % (input.nick, artist, album, genre, shortUrl)) except: phenny.say( '%s: there was a problem communicating with the database' % input.nick) return elif args[0] == 'users': db_cur.execute('SELECT * FROM users') users = db_cur.fetchall() for user in users: db_cur.execute( 'SELECT id FROM recommendations WHERE user_id = %d' % user[0]) entries = db_cur.fetchall() if entries is not None: numEntries = len(entries) else: numEntries = 0 if numEntries == 1: strEnd = 'entry' else: strEnd = 'entries' phenny.say('%s: %d %s' % (user[1], numEntries, strEnd)) elif args[0] == 'find': try: genre = args[1] except: phenny.say('%s: usage is .what find <genre> or .what find recent' % input.nick) return if args[1] == 'recent': try: db_cur.execute( 'SELECT r.id,artist,album,g.name,url,u.name FROM recommendations AS r LEFT JOIN users AS u ON r.user_id = u.id LEFT JOIN genres AS g ON r.genre_id = g.id ORDER BY r.id DESC LIMIT 3' ) except: phenny.say('%s: no recent recommendations!' % input.nick) else: try: db_cur.execute( 'SELECT r.id,artist,album,g.name,url,u.name FROM recommendations AS r LEFT JOIN users AS u ON r.user_id = u.id LEFT JOIN genres AS g ON r.genre_id = g.id WHERE g.name = "%s" ORDER BY r.id DESC LIMIT 3' % args[1]) except: phenny.say('%s: no recommendations in database!' % input.nick) recs = db_cur.fetchall() if len(recs) == 0: phenny.say('%s: no entries for genre "%s"' % (input.nick, genre)) return for rec in recs: phenny.say('%d: %s - %s | %s | %s | %s' % (rec[0], rec[1], rec[2], rec[3], rec[4], rec[5])) elif args[0] == 'genres': db_cur.execute('SELECT name FROM genres ORDER BY name ASC') genres = db_cur.fetchall() if genres is None: phenny.say('%s: no genres in database!' % input.nick) return line = '' for genre in genres: line += genre[0] + ', ' phenny.say('%s: %s' % (input.nick, line[:-2])) return else: args = input.split(' ') for arg in args: if 'what.cd/torrents.php?id=' in arg: try: (artist, album, genre) = getTorrentDetails(arg) phenny.say( '%s: [%s - %s | %s | %s]' % (input.nick, artist, album, genre, api.shorten(arg))) return except: phenny.say( '%s: there was a problem retrieving the torrent information' % input.nick) return phenny.say('%s: did not understand command' % input.nick)
def shorten_url(url): bitly_api = bitly.Api(login=BITLY_LOGIN, apikey=BITLY_KEY) return bitly_api.shorten(url)