def share(provider_id, debate_id): if provider_id not in ['facebook', 'twitter']: abort(404) try: thread = cdw.threads.with_id(debate_id) except: abort(404) record = ShareRecord(provider=provider_id, debateId=debate_id) record.save() config = current_app.config lr = config['LOCAL_REQUEST'] question_id = str(thread.question.id) url = "%s/questions/%s/debates/%s" % (lr, question_id, debate_id) username = config['CDW']['bitly']['username'] api_key = config['CDW']['bitly']['api_key'] b = bitlyapi.BitLy(username, api_key) res = b.shorten(longUrl=url) short_url = res['url'] if provider_id == 'facebook': msg = "I just debated at CDW" # TODO: Ugly, make nicer app_id = config['SOCIAL_PROVIDERS']['facebook']['oauth'][ 'consumer_key'] fb_url = "http://www.facebook.com/dialog/feed?" \ "app_id=%s" \ "&link=%s" \ "&name=%s" \ "&description=%s" \ "&message=%s" \ "&redirect_uri=%s" \ "&display=page" redirect_url = urllib.quote_plus('%s/share/close' % lr) fb_url = fb_url % (app_id, urllib.quote_plus(url), urllib.quote_plus('ILSTU Views'), urllib.quote_plus('A place for civil debate'), urllib.quote_plus(msg), redirect_url) current_app.logger.debug(fb_url) return redirect(fb_url) if provider_id == 'twitter': msg = "I just debated on ILSTU Views. %s" % short_url msg = urllib.quote_plus(msg) return redirect('http://twitter.com/home?status=%s' % msg)
def shorten(url): if app.config['BITLY_KEY']: b = bitlyapi.BitLy(app.config['BITLY_USER'], app.config['BITLY_KEY']) res = b.shorten(longUrl=url) return res['url'] else: req = urllib2.Request("https://www.googleapis.com/urlshortener/v1/url", headers={"Content-Type": "application/json"}, data=json.dumps({'longUrl': url})) request_result = urllib2.urlopen(req) result = request_result.read() result_json = json.loads(result) return result_json['id']
def acortarUrl(self, url): const = clavesConstantes.clavesConstantes() resultado = "" try: #Me conecto con mi usuario y clave a bit.ly b = bitlyapi.BitLy(const.BIT_LY_USERNAME, const.BIT_LY_API_KEY) #Acorto la url de google res = b.shorten(longUrl=url) #Devuelvo la url acortada. resultado = res['url'] except: resultado = url return resultado
def __init__(self, hub): self.hub = hub self.DBSession = None # The consumer should pick up *all* messages. self.topic = self.hub.config.get('topic_prefix', 'org.fedoraproject') if not self.topic.endswith('*'): self.topic += '*' super(TweetBotConsumer, self).__init__(hub) self.config = hub.config # Set up fedmsg.meta fedmsg.meta.make_processors(**self.config) # Set up twitter and statusnet.. multiple accounts if configured settings = self.config.get('tweet_endpoints', []) self.apis = [twitter_api.Api(**endpoint) for endpoint in settings] # Set up bitly settings = self.config['bitly_settings'] self.bitly = bitlyapi.BitLy( settings['api_user'], settings['api_key'], ) # How long to sleep if we spew too fast. hibernate_duration = self.config['tweet_hibernate_duration'] # Sleep a second or two inbetween messages to try and avoid # the hibernate self.intermessage_pause = self.config['tweet_intermessage_pause'] def _post_to_api(api, message): try: api.PostUpdate(message) except Exception as e: if 'Too many notices too fast;' in str(e): # Cool our heels then try again. self.log.info("Sleeping for %i" % hibernate_duration) time.sleep(hibernate_duration) _post_to_api(api, message) elif 'json decoding' in str(e): # Let it slide ... no idea what this one is. pass elif 'duplicate' in str(e): # Let it slide ... pass else: raise self._post_to_api = _post_to_api
def generate(): try: url = 'https://api.whatsapp.com/send?phone=' num = raw_input(bb + '\n[]' + aa + 'Your number(ex:628): ') user = '******' api = 'R_bdfa2f0ef8384a39b659b3927cee619f' b = bitlyapi.BitLy(user, api) longurl = url + num response = b.shorten(longUrl=longurl) time.sleep(2) print(bb + '[]' + aa + 'Link: ' + cc + response['url']) print(bb + '[]' + aa + 'Generate your live chat successfully') print(bb + '[]' + aa + 'Follow my instagram @khazulyusseryy') except KeyboardInterrupt: print(bb + '[]' + aa + 'Goodbyee')
def aggregate_issues(conf): """ Return all issues from every target. Takes a config object and a callable which returns a shortened url. """ # Setup bitly shortening callback get_opt = lambda option: conf.get('general', option) bitly = bitlyapi.BitLy(get_opt('bitly.api_user'), get_opt('bitly.api_key')) shorten = lambda url: bitly.shorten(longUrl=url)['url'] # Create and call service objects for every target in the config targets = [t.strip() for t in conf.get('general', 'targets').split(',')] return sum([ SERVICES[conf.get(t, 'service')](conf, t, shorten).issues() for t in targets ], [])
def generateTwitter(author, revision, comment, domain='', reponame=''): tweet = '' tracurl = '' comment = comment.rstrip(' ') trimLength = 140 - (len(author)) - len(str(revision)) # if there's a trac domain, count that as well if domain: trimLength -= 13 #additional chars in the tweet if reponame: trimLength -= len(reponame) tracurl = '/'.join([domain, 'changeset', str(revision), reponame]) else: tracurl = '/'.join([domain, 'changeset', str(revision)]) #Get short url from bit.ly if BITLY_USERNAME and BITLY_KEY: #import bitly only if fields are not empty import bitlyapi try: bitly = bitlyapi.BitLy(BITLY_USERNAME, BITLY_KEY) resUrl = bitly.shorten(longUrl=tracurl) shortUrl = resUrl['url'] except: shortUrl = '' if shortUrl: tracurl = shortUrl trimLength -= len(tracurl) else: trimLength -= 8 #additional chars in the tweet if len(comment) > trimLength: comment = comment[0:trimLength - 3] comment = comment.rstrip(' ') comment += '..' if comment.endswith('.') else '...' if domain: if reponame: tweet = '%s: rev %s on %s: %s %s' % (author, str(revision), reponame, comment, tracurl) else: tweet = '%s: rev %s: %s %s' % (author, str(revision), comment, tracurl) else: tweet = '%s: rev %s: %s' % (author, str(revision), comment) return tweet
def main(url): opts, args = parse_args() config = ConfigParser() config.read(os.path.expanduser(opts.config)) if not config.has_section('bitly'): msg = 'Failed to read bit.ly API configuration ' \ 'from %s.' % opts.config notify("%s failed.\n%s" % (__file__, msg), 'dialog-warning') sys.exit(1) api = bitlyapi.BitLy( config.get('bitly', 'api_user'), config.get('bitly', 'api_key'), ) return api.shorten(longUrl=url)['url']
def privmsg(dumbot, user, channel, msg): # TODO more thorough admin checking than just nick - maybe hostmask? usernick = getUsernick(user) if usernick in dumbot.config['admins']: commandmode = True if channel == dumbot.config['nick']: ### query replylocation = usernick command = msg elif msg.startswith(dumbot.config['nick'] + ': '): ### hilight in channel replylocation = channel command = msg[len(dumbot.config['nick'] + ': '):] else: commandmode = False if commandmode: if command.startswith('join ') and command.count(' ') == 1: joinChannel(dumbot, command[len('join '):]) elif command.startswith('part ') and command.count(' ') == 1: partChannel(dumbot, command[len('part '):]) elif command == "list admins": listAdmins(dumbot, replylocation) elif command.startswith('add admin ') and command.count(' ') == 2: addAdmin(dumbot, command[len('add admin '):], replylocation) elif command.startswith('remove admin ') and command.count( ' ') == 2: removeAdmin(dumbot, command[len('remove admin '):], usernick, replylocation) b = bitlyapi.BitLy(dumbot.config['bitly_user'], dumbot.config['bitly_key']) urls = getURLs(msg) if urls: print(urls) for url in urls: res = b.shorten(longUrl=url) soup = BeautifulSoup(urllib2.urlopen(url)) dumbot.msg( channel, soup.title.string.encode() + ' - ' + res['url'].encode())
def _tweet(job): # get short url for the job long_url = "http://jobs.code4lib.org/job/%s/" % job.id bitly = bitlyapi.BitLy(settings.BITLY_USERNAME, settings.BITLY_PASSWORD) response = bitly.shorten(longUrl=long_url) url = response['url'] # construct tweet message msg = job.title if job.employer: msg = msg + " at " + job.employer.name msg += ' ' + url # tweet it auth = tweepy.OAuthHandler(settings.CODE4LIB_TWITTER_OAUTH_CONSUMER_KEY, settings.CODE4LIB_TWITTER_OAUTH_CONSUMER_SECRET) auth.set_access_token(settings.CODE4LIB_TWITTER_OAUTH_ACCESS_TOKEN_KEY, settings.CODE4LIB_TWITTER_OAUTH_ACCESS_TOKEN_SECRET) twitter = tweepy.API(auth) twitter.update_status(msg)
def _aggregate_issues(args): """ This worker function is separated out from the main :func:`aggregate_issues` func only so that we can use multiprocessing on it for speed reasons. """ # Unpack arguments conf, target = args try: # By default, we don't shorten URLs shorten = lambda url: url # Setup bitly shortening callback if creds are specified bitly_opts = ['bitly.api_user', 'bitly.api_key'] if all([conf.has_option('general', opt) for opt in bitly_opts]): get_opt = lambda option: conf.get('general', option) bitly = bitlyapi.BitLy(get_opt('bitly.api_user'), get_opt('bitly.api_key')) shorten = lambda url: bitly.shorten(longUrl=url)['url'] cachefile = os.path.expanduser("~/.cache/bitly.dbm") if not os.path.isdir(os.path.expanduser("~/.cache/")): os.makedirs(os.path.expanduser("~/.cache/")) # Cache in order to avoid hitting the bitly api over and over. # bitly links never expire or change, so why not cache on disk? region = dogpile.cache.make_region().configure( "dogpile.cache.dbm", arguments=dict(filename=cachefile), ) shorten = region.cache_on_arguments()(shorten) service = SERVICES[conf.get(target, 'service')](conf, target, shorten) return service.issues() except Exception as e: log.name(target).trace('error').critical("worker failure") return WORKER_FAILURE finally: log.name(target).info("Done with [%s]" % target)
def short_url(self): long_url = "http://jobs.code4lib.org/job/%s/" % self.id bitly = bitlyapi.BitLy(settings.BITLY_USERNAME, settings.BITLY_PASSWORD) response = bitly.shorten(longUrl=long_url) return response['url']
def shortener(url): bit = bitlyapi.BitLy(settings.BITLY_USER, settings.BITLY_KEY) return bit.shorten(longUrl = url)['url']
def tweet(**kw): """ Rebroadcast messages to twitter and statusnet New values in the fedmsg configuration are needed for this to work. Lists and dicts of authentication credentials such as: - :term:`tweet_endpoints` - :term:`bitly_settings` And scalars to help with rate limiting such as: - :term:`tweet_hibernate_duration` - :term:`tweet_intermessage_pause` """ # First, sanity checking. if not kw.get('tweet_endpoints', None): raise ValueError("Not configured to tweet.") # Boilerplate.. kw['publish_endpoint'] = None kw['name'] = 'relay_inbound' kw['mute'] = True # Set up fedmsg fedmsg.init(**kw) fedmsg.text.make_processors(**kw) # Set up twitter and statusnet.. multiple accounts if configured settings = kw.get('tweet_endpoints', []) apis = [twitter_api.Api(**endpoint) for endpoint in settings] # Set up bitly settings = kw['bitly_settings'] bitly = bitlyapi.BitLy( settings['api_user'], settings['api_key'], ) # How long to sleep if we spew too fast. hibernate_duration = kw['tweet_hibernate_duration'] # Sleep a second or two inbetween messages to try and avoid the hibernate intermessage_pause = kw['tweet_intermessage_pause'] def _post_to_api(api, message): try: api.PostUpdate(message) except Exception as e: if 'Too many notices too fast;' in str(e): # Cool our heels then try again. print "Sleeping for", hibernate_duration time.sleep(hibernate_duration) _post_to_api(api, message) elif 'json decoding' in str(e): # Let it slide ... no idea what this one is. pass elif 'duplicate' in str(e): # Let it slide ... pass else: raise for name, ep, topic, msg in fedmsg.tail_messages(**kw): message = fedmsg.text.msg2subtitle(msg, **kw) link = fedmsg.text.msg2link(msg, **kw) if link: link = bitly.shorten(longUrl=link)['url'] message = (message[:138] + " ")[:139 - len(link)] + link else: message = message[:140] print("Tweeting %r" % message) for api in apis: _post_to_api(api, message) time.sleep(intermessage_pause)
#pprint(bills) print "Found all bill summaries and sponsors" pprint(bills) # now that we have all of our bills and data, we'll tweet 'em out from requests_oauthlib import OAuth1 import bitlyapi import sys auth = OAuth1(twitter_client_key, twitter_client_secret, twitter_access_token, twitter_access_token_secret) bit = bitlyapi.BitLy(bitly_user, bitly_api_key) for bill, burr in bills.iteritems(): # shorten summary to 140 chars summarysummary = (burr['summary'][:180] + '..') if len(burr['summary']) > 180 else burr['summary'] text_link = bit.shorten(longUrl=burr['billLink']).get('url') votes_link = bit.shorten(longUrl=burr['votesLink']).get('url') yayNum = burr.get('yays') nayNum = burr.get('nays') status = '(Yea: ' + str(yayNum) + ' / Nay: ' + str(nayNum) passed = 'PASSED' if burr.get('passed') else 'REPEALED' status += ' ' + passed tweet = bill + ' ' + burr.get(
def makeBit(url): b = bitlyapi.BitLy("mauerbac", local_settings.BITLY_API_KEY) #Add bitly API key res = b.shorten(longUrl=url) return res['url']
#!/usr/bin/env python # Import the modules import bitlyapi import sys # Define your API information API_USER = "******" API_KEY = "your_api_key" b = bitlyapi.BitLy(API_USER, API_KEY) # Define how to use the program usage = """Usage: python shortener.py [url] e.g python shortener.py http://www.google.com""" if len(sys.argv) != 2: print(usage) sys.exit(0) longurl = sys.argv[1] response = b.shorten(longUrl=longurl) print(response['url'])
with open(featured_filename, 'rb') as img: featured_data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(featured_data)) attachment_id = response['id'] if attachment_id: post.thumbnail = attachment_id post.post_status = 'publish' wp.call(posts.EditPost(post.id, post)) post_link = wp.call(posts.GetPost(post.id)) if tw_enabled == "true": print "Posting to twitter .." auth = tweepy.OAuthHandler(tw_consumer, tw_secret) auth.set_access_token(tw_token, tw_token_secret) api = tweepy.API(auth) b = bitlyapi.BitLy(tw_bitlyuser, tw_bitlykey) tweet = 'New Listing : ', addressfix, ' , ', listpricefix, ' , ', bedrooms, ' beds ', bathrooms, ' baths ' hashtag_list = tw_hashtags.split(',') for hash in hashtag_list: tweet += '#', hash, ' ' tweet_fixed = ''.join(str(e) for e in tweet) try: bitly_url = b.shorten(longUrl=post_link.link) except Exception, e: print 'Bitly error : ' + str(e) bitly_url = '' tweet_fixed += ' ' + str(bitly_url['url']) #pprint.pprint(bitly_url['url']) try: api.update_status(tweet_fixed[:140]) # pprint.pprint(tweet_fixed[:140])