示例#1
0
def item_create(form):
    record = db(db.geo_item.f_name == request.vars.f_name).select().first()
    if record.f_qrcode == None:
        arg = str(record.id)
        path = 'http://siri.pythonanywhere.com/byui_art/default/item_details?itemId=' + arg + '&qr=True'
        tiny = ""
        shortSuccess = False
        try:
            shortener = Shortener('Tinyurl')
            tiny = "{}".format(shortener.short(path))
            session.tinyCreateException = tiny
            shortSuccess = True
        except:
            session.tinyCreateException = "There was a problem with the url shortener. Please try again."

        if shortSuccess:
            code = qrcode.make(tiny)
        else:
            code = qrcode.make(path)
        qrName='geo_item.f_qrcode.%s.jpg' % (uuid.uuid4())
        code.save(request.folder + 'uploads/qrcodes/' + qrName, 'JPEG')
        record.update_record(f_qrcode=qrName)
        qr_text(qrName, record.f_name, record.f_alt5, tiny)
    try:
        imgPath = request.folder + 'uploads/' + record.f_image
        thumbName = 'geo_item.f_thumb.%s.%s.jpg' % (uuid.uuid4(), record.id)
        thumb = Image.open(request.folder + 'uploads/' + record.f_image)
        thumb.thumbnail((350, 10000), Image.ANTIALIAS)
        thumb.save(request.folder + 'uploads/thumbs/' + thumbName, 'JPEG')
        record.update_record(f_thumb=thumbName)
    except:
        session.itemCreateException = "there was a problem updating the image in item_create: " + record.f_name
    return dict()
示例#2
0
def maybe_market_to_twitter(bounty, event_name):
    """Tweet the specified Bounty event."""
    if not settings.TWITTER_CONSUMER_KEY:
        return False
    if event_name not in ['new_bounty', 'remarket_bounty']:
        return False
    if bounty.get_natural_value() < 0.0001:
        return False
    if bounty.network != settings.ENABLE_NOTIFICATIONS_ON_NETWORK:
        return False
    return False  # per 2018/01/22 convo with vivek / kevin, these tweets have low engagement
    # we are going to test manually promoting these tweets for a week and come back to revisit this

    api = twitter.Api(
        consumer_key=settings.TWITTER_CONSUMER_KEY,
        consumer_secret=settings.TWITTER_CONSUMER_SECRET,
        access_token_key=settings.TWITTER_ACCESS_TOKEN,
        access_token_secret=settings.TWITTER_ACCESS_SECRET,
    )
    tweet_txts = [
        "Earn {} {} {} now by completing this task: \n\n{}",
        "Oppy to earn {} {} {} for completing this task: \n\n{}",
        "Is today the day you (a) boost your OSS rep (b) make some extra cash? 🤔 {} {} {} \n\n{}",
    ]
    if event_name == 'remarket_bounty':
        tweet_txts = tweet_txts + [
            "Gitcoin open task of the day is worth {} {} {} ⚡️ \n\n{}",
            "Task of the day 💰 {} {} {} ⚡️ \n\n{}",
        ]
    if event_name == 'new_bounty':
        tweet_txts = tweet_txts + [
            "Extra! Extra 🗞🗞 New Funded Issue, Read all about it 👇  {} {} {} \n\n{}",
            "Hot off the blockchain! 🔥🔥🔥 There's a new task worth {} {} {} \n\n{}",
            "💰 New Task Alert.. 💰 Earn {} {} {} for working on this 👇 \n\n{}",
        ]

    random.shuffle(tweet_txts)
    tweet_txt = tweet_txts[0]

    shortener = Shortener('Tinyurl')

    new_tweet = tweet_txt.format(
        round(bounty.get_natural_value(), 4), bounty.token_name,
        ("(${})".format(bounty.value_in_usdt) if bounty.value_in_usdt else ""),
        shortener.short(bounty.get_absolute_url()))
    new_tweet = new_tweet + " " + github_org_to_twitter_tags(
        bounty.org_name)  # twitter tags
    if bounty.keywords:  # hashtags
        for keyword in bounty.keywords.split(','):
            _new_tweet = new_tweet + " #" + str(keyword).lower().strip()
            if len(_new_tweet) < 140:
                new_tweet = _new_tweet

    try:
        api.PostUpdate(new_tweet)
    except Exception as e:
        print(e)
        return False

    return True
示例#3
0
def coll_create(form):
    record = db(db.geo_collection.f_name == request.vars.f_name).select().first()
    arg = str(record.id)
    path = 'http://siri.pythonanywhere.com/byui_art/default/collection_details?collectionId=' + arg + '&qr=True'
    tiny = ""
    #######################################################################
    ################## TESTING PYSHORTENERS : TINYURL #####################
    #######################################################################
    
    try:
        shortener = Shortener('TinyurlShortener')
        tiny = "{}".format(shortener.short(path))
    except:
        session.tinyCreateException = "There was a problem with the url shortener. Please try again."
    
    #######################################################################
    ###################### END PYSHORTENERS : TINYURL #####################
    #######################################################################
    

    
    code = qrcode.make(tiny)
    qrName='geo_collection.f_qrcode.%s.jpg' % (uuid.uuid4())
    code.save(request.folder + 'uploads/qrcodes/' + qrName, 'JPEG')
    qr_text(qrName, record.f_name, record.f_location, tiny)
    record.update_record(f_qrcode=qrName)
    return dict()
示例#4
0
def get_text_message(url):
    shortener = Shortener('Google', api_key=API_KEY)
    url = shortener.short(url)
    try:
        return "Your shorten url is \n {}".format(url)
    except Exception as e:
        return "Ahh... Snap :O"
示例#5
0
def get_qr_code(url):
    shortener = Shortener('Google', api_key=API_KEY)
    shortener.short(url)
    try:
        return "Share your QR Code as \n {}".format(shortener.qrcode())
    except Exception as e:
        return "Ahh... Snap :O"
 def __init__(self):
     self.pages = self.num_user_input('\nEnter number of pages to search:\n'
                                      )  # Number of indeed pages to search.
     self.num_jobs = self.num_user_input(
         '\nEnter max job listings to receive:\n'
     ) * 2  # Buffer for duplicates.
     self.resume = self.load_resume()
     self.email = self.user_input('\nEnter email:\n')
     print(
         '\nYou may leave any of the following prompts blank to broaden your search.'
     )
     self.city = self.user_input('\nEnter desired city:\n').strip().title()
     self.state = self.user_input(
         '\nEnter state abbreviation:\n').strip().upper()
     self.terms = self.user_input(
         '\nEnter desired job title:\n').strip().lower()
     print('\nLoading NLP packages...')
     self.nlp = spacy.load('en_core_web_lg')
     self.nn = NearestNeighbors(n_neighbors=self.num_jobs,
                                algorithm='ball_tree')
     self.shortener = Shortener('Bitly', bitly_token=API_KEY)
     self.jobs = []
     self.base_email = EMAIL_ADDRESS
     self.vectors = None
     self.main()
示例#7
0
def tweet_post(title, url, subid):

    #post found scores to twitter
    CONSUMERKEY = keys[0]
    CONSUMERSECRET = keys[1]
    ACCESSKEY = keys[2]
    ACCESSSECRET = keys[3]

    nonDuplicateFlag = True

    auth = tweepy.OAuthHandler(CONSUMERKEY, CONSUMERSECRET)
    auth.set_access_token(ACCESSKEY, ACCESSSECRET)
    api = tweepy.API(auth)

    #Clean link to prepare for tweeting
    title = tweet_cleanup(title)

    shortener = Shortener('TinyurlShortener')
    tinyurl = shortener.short(url)
    tweet = tweet_cleanup(title)

    if subid in postedTweets:
        nonDuplicateFlag = False
        return

    post = title + tinyurl

    try:
        api.update_status(post)  #post the tweet
    except:
        print('Tweet not posted. Check Issue. Length= ', len(post))
        return

    postedTweets.append(subid)
    update_db()
def tinyURLShortner(inputlist):
    short = Shortener('Tinyurl', timeout=9000)
    outputlist = []
    for url in inputlist:
        shortenURL = short.short(''.join(url))
        outputlist.append(shortenURL)
    return outputlist
示例#9
0
def test_owly_bad_key():
    b = Shortener(shorteners.OWLY_SHORTENER)
    with pytest.raises(TypeError):
        b.short('http://www.test.com')

    with pytest.raises(TypeError):
        b.expand('http://www.test.com')
示例#10
0
文件: app.py 项目: gomberg5264/url2
def msg_received(command):
    global GOOGLE_KEY, follow
    response = None
    if (command['user'] == follow):
        print("message is from the person being followed")
        URL_REGEX = r"""(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))"""
        regexp = re.compile(URL_REGEX)

        #test = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
        #regexp = re.compile(test)
        output = regexp.findall(command['text'])
        if output:
            response = "Hi! Leo Here. New link(s): "
            for url in output:
                try:
                    s = Shortener('Google', api_key=GOOGLE_KEY)
                    short_url = s.short(url)
                    response += short_url + " "
                    print('short url is :' + short_url)
                    #print(s.shorten) # prints the short url
                    print('shortened from: ' + s.expanded)
                except ssl.SSLError as err:
                    pass
        else:
            print(
                "Couldn't parse the URL or no URL was present in the message")
    return response
def getShortenedLink(baseurl):
    try:
        shortener = Shortener('Isgd', timeout=3)
        url = shortener.short(baseurl)
    except:
        url = baseurl
    return url
示例#12
0
def short_2():
    fetch = mongo.db.fetch
    long_urls = request.json['long_urls']
    short_urls = {}
    invalid_urls = []
    for i in long_urls:

        if not validators.url(i):
            invalid_urls.append(i)
        else:
            # api_key = 'private'
            shortener = Shortener('Tinyurl')
            short_url = shortener.short(i)
            short_url = short_url.replace("http://tinyurl.com", "hck.re")
            short_urls[i] = short_url
    if invalid_urls != []:
        output = {
            "invalid_urls": invalid_urls,
            'status': "FAILED",
            "status_codes": ["INVALID_URLS"]
        }
        return jsonify(output)
    else:
        output = {
            'short_urls': short_urls,
            "invalid_urls": [],
            'status': "OK",
            "status_codes": []
        }
        return jsonify(output)
示例#13
0
    def get_item_str(self, item):
        global api_key
        global cache
        global shortener_service

        if api_key:
            shortener = Shortener(shortener_service, api_key=api_key)
        else:
            shortener = None

        short_url = None
        if cache is not None:
            short_url = cache.get(item['link'])
        if short_url is None:
            # Retry 3 times for goo.gl API
            for i in range(0,3):
                try:
                    short_url = shortener.short(item['link'])
                    if short_url is not None:
                        logger.debug("Saving short url to cache")
                        cache.put(item['link'], short_url)
                except Exception as e:
                    logger.debug("Shortener threw exception {}".format(e.message))
                    continue
                break
        else:
            logger.debug("Short url cache hit")
        if short_url is None:
            url = item['link']
        else:
            url = short_url
        return '[%s] %s <%s>' % (''.join([c for c in self.name][0:18]), item['title'], url)
示例#14
0
def worker(url, host):
    # Madwire, Google, and Rebrandly no longer supported by pyshortener hence removed
    shortener = Shortener()
    if host == "Bitly":
        shortener = Shortener(api_key=BITLY_TOKEN)
        short_url = shortener.bitly.short(url)
    elif host == "Cuttly":
        shortener = Shortener(api_key=CUTTLY_TOKEN)
        short_url = shortener.cuttly.short(url)
    elif host in similar_hosts:
        short_url = getattr(shortener, host.lower())
        short_url = short_url.short(url)
    elif host == "Tinyurl":
        short_url = shortener.tinyurl.short(url)
    elif host == "Osdb":
        short_url = shortener.osdb.short(url)
    elif host == "Chilpit":
        short_url = shortener.chilpit.short(url)
    elif host == "Clckru":
        short_url = shortener.clckru.short(url)
    elif host == "Dagd":
        short_url = shortener.dagd.short(url)
    elif host == "Qpsru":
        short_url = shortener.qpsru.short(url)
    else:
        short_url = "That service is no longer available via pyshortener"
    return short_url
示例#15
0
def link_meta(link, *args, **kwargs):
    """
    Get the topic counts meta
    """
    shortener = Shortener("Bitly", bitly_token=settings.BITLY_API_TOKEN)
    short_link = shortener.short(link)
    return h.handle("<a href=''>{}</a>".format(short_link))
示例#16
0
def test_owly_bad_key():
    b = Shortener('OwlyShortener')
    with pytest.raises(TypeError):
        b.short('http://www.test.com')

    with pytest.raises(TypeError):
        b.expand('http://www.test.com')
def url_shortener(text):
    try:
        shortener = Shortener('Bitly', bitly_token=bitly_token)
        return shortener.short(text)
    except:
        response = requests.get('http://tinyurl.com/api-create.php?url=' + text)
        return response.content.decode('utf-8')
示例#18
0
def mark_meta(line):

    if line[0:4] == 'http' or line[0:3] == 'www':
        ln = line.split("<")
        line = ln[0]

        l = r.get(line)

        if not l:
            try:
                shortener = Shortener("Bitly",
                                      bitly_token=settings.BITLY_API_TOKEN)
                ln = shortener.short(line)
                r.set(line, ln)
                line = ln.decode('utf-8')
            except Exception as e:
                pass
        else:
            line = l.decode('utf-8')

    #result_line = re.sub(r"\`(.+?)\`", r"<span class='italize'>\1</span>", line)


#    result_line = re.sub(r"(?<=\`|\`))(.*)(?=(\`|\`))", r"<span class='italize'>\1</span>", line)
    result_line = re.sub(r"(?<=`)(.*)(?=`)",
                         r"<span class='italize'>\1</span>", line)
    result_line = re.sub(r"(?<=`)(.*)(?=`)",
                         r"<span class='italize'>\1</span>", result_line)
    result_line = re.sub(r"\`(.+?)\`", r"<span class='italize'>\1</span>",
                         result_line)
    result_line = re.sub(r"\~(.+?)\~", r"<span class='erroneous'>\1</span>",
                         result_line)
    return mark_safe(result_line)
示例#19
0
def tweet_post(title, url, subid):
   
    #post found scores to twitter
    CONSUMERKEY = keys[0]
    CONSUMERSECRET = keys[1]
    ACCESSKEY = keys[2]
    ACCESSSECRET = keys[3]
    
    nonDuplicateFlag = True
    
    auth = tweepy.OAuthHandler(CONSUMERKEY, CONSUMERSECRET)
    auth.set_access_token(ACCESSKEY, ACCESSSECRET)
    api = tweepy.API(auth)

    #Clean link to prepare for tweeting
    title = tweet_cleanup(title)
   
    shortener = Shortener('TinyurlShortener')
    tinyurl = shortener.short(url)
    tweet = tweet_cleanup(title)
   
    if subid in postedTweets:
        nonDuplicateFlag = False
        return
    
    post = title + tinyurl

    try:
        api.update_status(post) #post the tweet
    except:
        print('Tweet not posted. Check Issue. Length= ', len(post))
        return

    postedTweets.append(subid)
    update_db()
示例#20
0
def shortening(url):
    try:
        shortener = Shortener('Google', api_key=api_key)
        short_link = shortener.short(url)
        return short_link
    except UnknownShortenerException as e:
        e1 = str(e)
        dt = str(datetime.now())
        c.execute("insert into zfeed_log values(?, ?, ?, ?, ?, ?)",
                  (dt, '', '', e1, '', url))
        zb.commit()
        return False
    except ShorteningErrorException as e:
        e1 = str(e)
        dt = str(datetime.now())
        c.execute("insert into zfeed_log values(?, ?, ?, ?, ?, ?)",
                  (dt, '', '', e1, '', url))
        zb.commit()
        return False
    except ExpandingErrorException as e:
        e1 = str(e)
        dt = str(datetime.now())
        c.execute("insert into zfeed_log values(?, ?, ?, ?, ?, ?)",
                  (dt, '', '', e1, '', url))
        zb.commit()
        return False
    except ReadTimeout as e:
        e1 = str(e)
        print(e1)
        dt = str(datetime.now())
        c.execute("insert into zfeed_log values(?, ?, ?, ?, ?, ?)",
                  (dt, '', '', e1, '', url))
        zb.commit()
        return False
示例#21
0
def util_create_short_url(fp, lBugs, text='Link'):
    url = "https://bugs.documentfoundation.org/buglist.cgi?bug_id="
    for bug in lBugs:
        url += str(bug) + "%2C"

    url = url[:-3]
    shortener = Shortener('Tinyurl', timeout=9000)
    print('\t\t+ ' + text + ': ' + shortener.short(url), file=fp)
示例#22
0
def test_bitly_bad_keys():
    s = Shortener(Shorteners.BITLY)

    with pytest.raises(TypeError):
        s.short(expanded)

    with pytest.raises(TypeError):
        s.expand(shorten)
示例#23
0
    def post(self, request):
        url = UrlForm(request.POST)

        if url.is_valid():
            shortener = Shortener('Isgd')
            new_url = url.save(shortener.short(url.cleaned_data['base_url']))
            messages.info(request, new_url.short_url)
            return render(request, 'urlapp/index.html')
示例#24
0
def tiny_url_gen():
    try:
        d = simpledialog.askstring(title="URL", prompt="Enter URL : ")
        shortener = Shortener('Tinyurl')
        pyperclip.copy(format(shortener.short(d)))
        Message.complete()
    except Exception as e:
        Message.on_error(str(e))
示例#25
0
def test_google_bad_params():
    s = Shortener(Shorteners.GOOGLE)

    with pytest.raises(TypeError):
        s.short(expanded)

    with pytest.raises(TypeError):
        s.expand(expanded)
示例#26
0
def hello():
    short = Shortener('TinyurlShortener')
    print("""
Hello World! Testing TinyurlShortener with www.google.com URL
Shorten url: {}
Expanded: {}
    """.format(short.short('http://www.google.com'),
               short.expand('http://goo.gl/fbsS')))
示例#27
0
def test_custom_shortener():
    class MyShortenerWithBlackJackAndHookers(BaseShortener):
        def short(self, url):
            return url

    s = Shortener(MyShortenerWithBlackJackAndHookers)
    url = 'http://www.test.com'
    assert s.short(url) == url
示例#28
0
def test_custom_shortener():
    class MyShortenerWithBlackJackAndHookers(BaseShortener):
        def short(self, url):
            return url

    s = Shortener(MyShortenerWithBlackJackAndHookers)
    url = 'http://www.test.com'
    assert s.short(url) == url
示例#29
0
def hello():
    short = Shortener('Tinyurl')
    print("""
Hello World! Testing TinyurlShortener with www.google.com URL
Shorten url: {}
Expanded: {}
    """.format(short.short('http://www.google.com'),
               short.expand('http://goo.gl/fbsS')))
示例#30
0
def hello():
    googl = Shortener('GoogleShortener')

    return """
    Hello World! Testing www.google.com
    Shorten url:{} - Expanded:{}
    """.format(googl.short('http://www.google.com'),
               googl.expand('http://goo.gl/fbsS')),
def tweet():
  args = get_args()
  creds = load_credentials()
  
  shortener = Shortener('Google', api_key=creds[0])
  tweet = Twitter(auth=OAuth(creds[1], creds[2], creds[3], creds[4]))
        
  url = "http://127.0.0.1:" + str(args.port) + "/raw_data"
  response = urllib.urlopen(url)
  dump = json.loads(response.read())
  new = copy.deepcopy(dump)
  old = {
    'pokemons': []
  }
  
  if os.path.isfile('data.json'):
    with open('data.json') as data_file:
      old = json.load(data_file)

  # Deletes encounter id for next step
  for e_new in new['pokemons']:
    for e_old in old['pokemons']:
      if e_new['encounter_id'] == e_old['encounter_id']:
        del e_new['encounter_id']
        break

  # Existing encounter ids are rare pokemon
  # This entire step is to parse the data for a tweet
  for e_new in new['pokemons']:
    if e_new['pokemon_id'] in rares:
      if 'encounter_id' in e_new:
        location = str(Geocoder.reverse_geocode(e_new['latitude'], e_new['longitude'])[0]).split(',')
        destination = location[0]
        if len(location) == 5:
          destination += ", " + location[1]
        time = datetime.datetime.fromtimestamp(e_new['disappear_time']/1000)
        ampm = "AM"
        hour = time.hour
        gmap = 'https://www.google.com/maps/dir/Current+Location/' \
                + str(e_new['latitude']) + ',' + str(e_new['longitude'])
        if hour > 12:
          hour -= 12
          ampm = "PM"
        elif hour == 12:
          ampm = "PM"
        elif hour == 0:
          hour = 12
        tweeting = "{} at {} until {}:{}:{} {}. #PokemonGo {}".format( \
          e_new['pokemon_name'], destination, \
          hour, str(time.minute).zfill(2), str(time.second).zfill(2), ampm, \
          shortener.short(gmap))
        tweet.statuses.update(status=tweeting)
        print tweeting
        # Google api timeout
        t.sleep(0.5)
    
  with open('data.json', 'w') as outfile:
    json.dump(dump, outfile)
def page_load(n_clicks, state):
    """
    Return a tinyurl whenever the `tinyurl-button` is clicked:
    """
    if not state:
        return "No url to shorten"
    if n_clicks > 0 and state:
        shortener = Shortener('Tinyurl')
        return shortener.short('http://127.0.0.1:8050' + state)
示例#33
0
def short_3(short_url_hash):
    fetch = mongo.db.fetch
    url_to = short_url_hash
    shortener = Shortener('Tinyurl')
    url_to = url_to.replace("hck.re", "http://tinyurl.com")

    long_url = shortener.expand(url_to)
    # return redirect(long_url, code=302)
    return jsonify({"q": url_to, "w": short_url_hash})
示例#34
0
def shorten_url(url):
    if url:
        try:
            shortener = Shortener(settings.SHORTEN_SERVICE,
                                  api_key=settings.SHORTEN_API_KEY)
            return shortener.short(url)
        except:
            return ""
    else:
        return ""
示例#35
0
def short_url(sopel, url):
    key = sopel.config.kpopsundry.google_api_key
    if key:
        googl = Shortener(
            'Google',
            api_key=sopel.config.kpopsundry.google_api_key
        )
        return googl.short(url)
    else:
        return url
示例#36
0
def test_qrcode():
    s = Shortener('TinyurlShortener')
    url = 'http://www.google.com'
    mock_url = '{}?url={}'.format(s.api_url, url)
    shorten = 'http://tinyurl.com/test'
    responses.add(responses.GET, mock_url, body=shorten,
                  match_querystring=True)
    s.short(url)
    # flake8: noqa
    assert s.qrcode() == 'http://chart.apis.google.com/chart?cht=qr&chl={0}&chs=120x120'.format(shorten)
示例#37
0
def shortenLink(s, url):
    try:
        for service in s.findall('service'):
            if service.get("name") == "bitly":
                sh = Shortener('Bitly', bitly_token=service.find("token").text)
                return sh.short(url)
        # If service not found
        return url
    except:
        return url
示例#38
0
def shorten_url(url):
    '''
    Generates a short URL using Bitly API
    '''

    ACCESS_TOKEN = 'd0292df237da27ae19d42c7dd89cac2519a4220a'

    url_shortener = Shortener('Bitly', bitly_token=ACCESS_TOKEN)

    return "{}".format(url_shortener.short(url))
示例#39
0
def test_qrcode():
    s = Shortener('TinyurlShortener')
    url = 'http://www.google.com'
    mock_url = '{}?url={}'.format(s.api_url, url)
    shorten = 'http://tinyurl.com/test'
    responses.add(responses.GET, mock_url, body=shorten,
                  match_querystring=True)
    s.short(url)
    # flake8: noqa
    assert s.qrcode() == 'http://chart.apis.google.com/chart?cht=qr&chl={0}&chs=120x120'.format(shorten)
示例#40
0
def shorten(website, link):
    print(link)
    logger.info("a user shortened {} just now".format(link))
    if website == "Bitly":
        bitly = "a3711a7b536d591236a934b81ad6316fd7095bb8"
        shortener = Shortener('Bitly', bitly_token=bitly)
        try:
            result = shortener.short(link)
            return result
        except:
            return "failed : invalid url"
    if website == "Google":
        api_key = "AIzaSyAENcBzlF5fK8lgopX38n8o9u8gLBEmNFc"
        shortener = Shortener('Google', api_key=api_key)
        try:
            result = shortener.short(link)
            # print("result")
            return result
        except:
            return "failed : url invalid"
    if website == "Adfly":
        uid = "17552095"
        api_key = "e48581125d5b9fc363913d6a1785f2e9"
        shortener = Shortener('Adfly', uid=uid, key=api_key, type='int')
        try:
            result = shortener.short(link)
        except:
            return "failed : url invalid"
    return "enter a valid url"
示例#41
0
 def construct_url(self):
     url = "Bugzilla Template with concactenated variables"
     for i in range(0, 100):
         while True:
             try:
                 shorten = Shortener('Tinyurl')
                 url = shorten.short(url)
             except requests.exceptions.ReadTimeout:
                 continue
             break
     return url
示例#42
0
def make_link(group_name, event_id, shorten=True):
    url = "https://meetup.com/{group_name}/events/{event_id}".format(
        group_name=group_name,
        event_id=event_id)
    if shorten:
        shortener = Shortener('Tinyurl')
        try:
            url =  shortener.short(url)
        except ReadTimeout:
            pass
    return url
示例#43
0
	def make_short(url, service):
		if service == "google":
			shortener = Shortener("Google", api_key=api_key)
		elif service == "bitly":
			shortener = Shortener("Bitly", bitly_token=access_token)
		elif service == "owly":
			shortener = Shortener("Owly", api_key=api_key)
		elif service == "tinyurl":
			shortener = Shortener("Tinyurl")
		new_url = shortener.short(url)
		return new_url
示例#44
0
    def sensu_event(self, kwargs):
        host_params = ['action', 'client', 'check', 'occurrences', 'timestamp']
        params = {
            param: kwargs.get(param, None)
            for param in host_params
        }

        logging.info("Received request on host endpoint: " + str(params))
        logging.debug("Unpacked parameters:" + str(kwargs))

        hostname = params['client']['name']
        check = params['check']['name']
        output = self._truncate_string(params['check']['output'], length=250)

        # Custom attributes
        # broadcast is a custom check attribute to know where to send IRC notifications
        try:
            if 'broadcast' in params['check']:
                broadcast = params['check']['broadcast']
            elif 'custom' in params['check'] and 'broadcast' in params['check']['custom']:
                broadcast = params['check']['custom']['broadcast']
            else:
                logging.info("This notification does not have a broadcast assigned, not doing anything with it.")
                return False
        except KeyError as e:
            logging.info("KeyError when trying to set broadcast config: " + str(e))
            return False

        dashboard = self.bot_config.MONITORING_DASHBOARD
        check_url = "{0}/#/client/uchiwa/{1}?check={2}".format(dashboard,
                                                               hostname,
                                                               check)
        shortener = Shortener('Tinyurl')
        check_url = shortener.short(check_url)

        msg_type = {
            'create': "NEW: {0} - {1} @ {2} |#| {3}",
            'resolve': "RESOLVED: {0} - {1} @ {2} |#| {3}",
            'flapping': "FLAPPING: {0} - {1} @ {2} |#| {3}",
            'unknown': "UNKNOWN: {0} - {1} @ {2} |#| {3}"
        }

        if params['action'] in msg_type:
            msg = msg_type[params['action']].format(hostname, check, check_url,
                                                    output)
        else:
            msg = msg_type['unknown'].format(hostname, check, check_url,
                                             output)

        self._monitoring_broadcast(msg, broadcast=broadcast)
示例#45
0
def tinyurlShort(self):
    # Determine if URL is absolute or relative
    tof = bool(urllib.parse.urlparse(self).netloc)
    if tof is True:
        return(self)
    else:
        self = (urllib.parse.urljoin('http://www.autotrader.com/', self))

    # Shorten URL or catch exceptions
    try:
        shortener = Shortener('TinyurlShortener', timeout=9000)
        autotraderFile.write((shortener.short(self)) + '\n\n')
    except Exception as err:
        autotraderFile.write('ERROR: Check the log.' + '\n\n')
        logging.error(str(err) + '\n')
示例#46
0
def generateText(match):
	report = ""
	report += "Update: "
	report += getTeamAlliance(match)
	if (didTeamWin(match) == 1):
		report += (" won " + getMatchTitle(match) + " against ")
	elif (didTeamWin(match) == -1):
		report += (" lost " + getMatchTitle(match) + " to ")
	elif (didTeamWin(match) == 0):
		report += (" tied " + getMatchTitle(match) + " with ")
	report += (getOpposingAlliance(match) + ", " + getScore(match))
	report += ". Full Tournament Results: "
	shortener = Shortener('GoogleShortener', api_key=shortenerAPIKey)
	robotEventsURL = "http://www.robotevents.com/%s.html#tabs-results" % eventSKU
	report += shortener.short(robotEventsURL)
	return report
示例#47
0
def test_is_valid_url():
    bad = 'www.google.com'
    good = 'http://www.google.com'

    assert is_valid_url(good)
    assert not is_valid_url(bad)

    s = Shortener('TinyurlShortener')
    with pytest.raises(ValueError):
        url = 'http://12'
        s.short(url)


    with pytest.raises(ValueError):
        url = 'www.11.xom'
        s.expand(url)
示例#48
0
def url_shorten(service, url):

    supported_services = ['Isgd']
    url = url if url.startswith('http') else ('http://%s' % url)

    if service not in supported_services:
        print 'Service "{}" is not supported, supported services are: {}'\
            .format(service, supported_services)
        return
    try:
        shortener = Shortener(service)
        print shortener.short(url)
    except ValueError:
        print 'Invalid url given'
    except Exception as e:
        print 'Unable to shorten the url'
示例#49
0
 def __init__(self, vk_api_token, google_api_token):
     __session = vk.Session(access_token=vk_api_token)
     __google_api_token = google_api_token
     self.vk_api = vk.API(__session)
     self.shortener = Shortener('Google', api_key=__google_api_token)
     # result_count <= 9
     self.result_count = 9
示例#50
0
def exhi_create(form):
    record = db(db.geo_exhibit.f_name == request.vars.f_name).select().first()
    arg = str(record.id)
    path = 'http://siri.pythonanywhere.com/byui_art/default/exhibit_details?exhibitId=' + arg + '&qr=True'
    tiny = ""
    try:
        shortener = Shortener('TinyurlShortener')
        tiny = "{}".format(shortener.short(path))
    except:
        session.tinyCreateException = "There was a problem with the url shortener. Please try again."
    
    code = qrcode.make(tiny)
    qrName='geo_exhibit.f_qrcode.%s.jpg' % (uuid.uuid4())
    code.save(request.folder + 'uploads/qrcodes/' + qrName, 'JPEG')
    qr_text(qrName, record.f_name, '', tiny)
    record.update_record(f_qrcode=qrName)
示例#51
0
    def get_send_url(self):
        # If we don't have a URL in the first place, return empty strings
        # Or return the short URL if it has already been made
        if not self.story_url:
            return (None, None)
        elif self.story_short_url:
            return (self.story_url, self.story_short_url)
        elif self.section.shorten_links == False:
            return(self.story_url, self.story_url)

        # Set up for Bitly Goodness
        try:
            BITLY_ACCESS_TOKEN = MeowSetting.objects.get(
                setting_key='bitly_access_token').setting_value
            shortener = Shortener('Bitly', bitly_token=BITLY_ACCESS_TOKEN)
        except:
            print("[WARN] URL Shortener is not properly configured!")
            return(self.story_url, self.story_url)

        # api=bitly_api.Connection(access_token=BITLY_ACCESS_TOKEN)

        # If Bitly fails, we'll just continue with our canonical URL
        # try:
        #     short_url = api.shorten(self.story_url)['url']
        # except bitly_api.BitlyError as e:
        #     self.log_error(e, self.section)
        #     short_url = None
        # except:
        #     e = sys.exc_info()[0]
        #     short_url = None
        #     self.log_error(e, self.section)

        try:
            short_url = shortener.short(self.story_url)
        except:
            e = sys.exc_info()[0]
            short_url = None
            self.log_error(e, self.section)

        if short_url:
            self.story_short_url = short_url
            self.save()
            return (self.story_url, short_url)
        else:
            return (self.story_url, self.story_url)
示例#52
0
	def on_post(self, req, resp):
		"""Handles incomming slack requests and returns lmgtfy link"""
		text = req.get_param('text').decode('ascii')
		token = req.get_param('token').decode('ascii')
		user_id = req.get_param('user_id').decode('ascii')
		channel_id = req.get_param('channel_id').decode('ascii')
		response_url = req.get_param('response_url').decode('ascii')
                url = "http://lmgtfy.com/?q=" + text.replace(" ","+")
		shortener = Shortener('Tinyurl')
		json_response = { 
			"token": token,
			"response_type": "in_channel",
			"channel": channel_id,
			"text": "Here's an answer to your question: " + shortener.short(url),
			"as_user": True,
			"scope": 'chat:write:user'
		}
		resp.body = json.dumps(json_response)
示例#53
0
文件: views.py 项目: ollavrova/test
def index(request):
    form = UrlInputForm()
    if request.method == 'POST':
        form = UrlInputForm(request.POST)
        if form.is_valid():
            url = request.POST.get('url')
            shortener = Shortener('TinyurlShortener')
            short = {
                'long_url': url[7:],  # exclude 'http://' from url string
                'short_url': shortener.short(url)[19:],  # exclude 'http://tinyurl.com/
                'user': random.choice(User.objects.all())
            }
            try:
                shorted = Shorted.objects.get(long_url=short['long_url'])
            except ObjectDoesNotExist:
                shorted = Shorted.objects.create(**short)
            return HttpResponseRedirect('/links/'+str(shorted.short_url))

    return render(request, 'app/index.html', {'form': form})
示例#54
0
def test_shortener_debug_enabled():
    url = 'http://www.test.com'
    small = 'http://small.com'
    responses.add(responses.GET, url, body=small)
    responses.add(responses.GET, small, body=url)

    s = Shortener(debug=True)
    s.short('http://www.test.com')
    s.expand('http://small.com')
    with pytest.raises(NotImplementedError):
        s.total_clicks('http://small.com')
示例#55
0
def main(argv, list_of_tags):
    if len(argv) > 1:
        url = argv
        if len(argv) > 20:
            shortener = Shortener('TinyurlShortener')
            url = shortener.short(url.strip())
    else:
        print("ERROR")
        url = "http://www.clarifai.com/img/metro-north.jpg"

    command = 'curl -H "Authorization: Bearer b3A9PCVEzVkAijC1CC0qEUPNKcS9GE" --data-urlencode "url='
    command = command + url + '" https://api.clarifai.com/v1/tag/'
    command = command + " | python -mjson.tool > test.json"
    os.system(command)

    with open('test.json') as test:
        data = json.load(test)

    with open('tag.txt', 'w') as f:
        pprint(data['results'][0]['result']['tag']['classes'], f)

    with open('tag.txt', 'r') as f:
        for x in f:
            list_of_tags.append(x.split("'")[1]) 
示例#56
0
class VkMusicSearcher:
    def __init__(self, vk_api_token, google_api_token):
        __session = vk.Session(access_token=vk_api_token)
        __google_api_token = google_api_token
        self.vk_api = vk.API(__session)
        self.shortener = Shortener('Google', api_key=__google_api_token)
        # result_count <= 9
        self.result_count = 9

    def print_menu(self, local_count):
        print "\nMenu:"
        print "-> Next page - [n]"
        print "-> Get info about audio - [1-{0}]".format(local_count - 1)
        print "-> Exit menu - [q]"

    def search_music(self, query):
        offset = 0

        for counter in range(10):
            query_result = self.vk_api.audio.search(q=query, count=self.result_count, offset=offset)
            local_count = len(query_result)
            query_result.pop(0)
            music_counter = 1
            for q in query_result:
                print "{0}) {1}\t: {2}".format(music_counter, uformat(q["artist"]), uformat(q["title"]))
                music_counter += 1

            self.print_menu(local_count)
            option = raw_input("\nInput option: ").lower()
            if option == "n":
                offset += local_count
                continue
            elif option == "q":
                break
            elif search(r"^[1-{0}]$".format(local_count - 1), option):
                music_number = int(option)
                music_info = query_result[music_number - 1]
                print "----> {0} : {1} | {2}\n".format(uformat(music_info["artist"]), uformat(music_info["title"]),
                                                       self.shortener.short(music_info["url"]))
            else:
                continue
示例#57
0
def test_expand_method_bad_response():
    responses.add(responses.GET, short, body='', status=400)
    s = Shortener()

    with pytest.raises(ExpandingErrorException):
        s.expand(short)
示例#58
0
def test_base_total_clicks():
    s = Shortener()
    s.shorten = 'http://test.com'
    with pytest.raises(NotImplementedError):
        s.total_clicks()