Exemplo n.º 1
3
def upload(image_path):
    """ Takes a file path, and returns it's URL on Imgur """
    if CLIENT_ID == 'None':
        raise ImgurException('client_id not specified in env')
    if CLIENT_SECRET == 'None':
        raise ImgurException('client_secret not specified in env')
    try:
        client = ImgurClient(CLIENT_ID, CLIENT_SECRET)
        imgur_response = client.upload_from_path(image_path)
    except ImgurClientError as e:
        raise ImgurException(e.error_message)
    return imgur_response['link']
Exemplo n.º 2
0
def BikiniBottomTwitter():

    load_dotenv()
    client_id = os.getenv('IMGUR_TOKEN')
    client_secret = os.getenv('IMGUR_SECRET')

    client = ImgurClient(client_id, client_secret)
    items = client.gallery(section='r',
                           sort='BikiniBottomTwitter',
                           show_viral=False)
    item = random.choice(items)
    return item.link
Exemplo n.º 3
0
 def __init__(self):
     self.client_id = os.environ.get('Client_ID')
     self.client_secret = os.environ.get('Client_Secret')
     self.access_token = os.environ.get('access_token')
     self.refresh_token = os.environ.get('refresh_token')
     # self.client_id = config['imgur_api']['Client_ID']
     # self.client_secret = config['imgur_api']['Client_Secret']
     # self.access_token = config['imgur_api']['access_token']
     # self.refresh_token = config['imgur_api']['refresh_token']
     self.client = ImgurClient(self.client_id, self.client_secret,
                               self.access_token, self.refresh_token)
     self.logger = None
Exemplo n.º 4
0
 def __init__(self,
              generate_img,
              name='img',
              description='',
              position=1,
              app_url=app_url):
     super(SendImgur, self).__init__(name, description, position, 'img',
                                     app_url)
     self.client_secret = os.environ['IMGUR_SECRET']
     self.client_id = os.environ['IMGUR_ID']
     self.client = ImgurClient(self.client_id, self.client_secret)
     self.generate_img = generate_img
Exemplo n.º 5
0
def authenticate():
    #client_id = '854786241b5ff16'
    #client_secret = '90c6a5b0068fa60c3b6b047fffec2388fe6cd6c8'

    config = configparser.ConfigParser()
    config.read('auth.ini')

    client_id = config.get('credentials', 'client_id')
    client_secret = config.get('credentials', 'client_secret')

    imgur_username = config.get('credentials', 'imgur_username')
    imgur_password = config.get('credentials', 'imgur_password')

    client = ImgurClient(client_id, client_secret)

    authorization_url = client.get_auth_url('pin')

    print("Go to the following URL: {0}".format(authorization_url))

    browser = webdriver.Chrome()
    browser.get(authorization_url)

    username = browser.find_element_by_xpath('//*[@id="username"]')
    password = browser.find_element_by_xpath('//*[@id="password"]')
    username.clear()
    username.send_keys(imgur_username)
    password.send_keys(imgur_password)

    browser.find_element_by_name("allow").click()

    timeout = 2
    try:
        element_present = EC.presence_of_element_located((By.ID, 'pin'))
        WebDriverWait(browser, timeout).until(element_present)
        pin_element = browser.find_element_by_id('pin')
        pin = pin_element.get_attribute("value")
    except TimeoutException:
        print("Timed out waiting for page to load")

    print("Your pin is : " + pin)

    # ... redirect user to `authorization_url`, obtain pin (or code or token) ...
    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'],
                         credentials['refresh_token'])

    print("Authentication successful! Here are the details:")
    print("   Access token:  {0}".format(credentials['access_token']))
    print("   Refresh token: {0}".format(credentials['refresh_token']))

    browser.close()

    return client
Exemplo n.º 6
0
def upload_images(album_title, paths):
    client = ImgurClient(client_id, client_secret)
    client.set_user_auth(imgur_access_token, imgur_refresh_token)
    fields = {'title': album_title}
    album = client.create_album(fields)

    for i, img in enumerate(paths):
        config = {'album': album['id'], 'name': str(i), 'title': str(i)}
        image = client.upload_from_path(img, config=config, anon=False)
        remove(img)

    return album
Exemplo n.º 7
0
 def __init__(self, subreddit):
     self._db = Database('database.db')
     self._reddit = praw.Reddit(**apidata.reddit)
     self._subreddit = self._reddit.subreddit(subreddit)
     self._imgur = ImgurClient(**apidata.imgur)
     self._template = (
         '[Image with added title]({image_url})\n\n'
         '{upscaled}---\n\n'
         'summon me with /u/titletoimagebot | '
         '[feedback](https://reddit.com/message/compose/'
         '?to=TitleToImageBot&subject=feedback%20{submission_id}) | '
         '[source](https://github.com/gerenook/titletoimagebot)')
Exemplo n.º 8
0
def img_upload(_access_token, _refresh_token):

    client = ImgurClient(client_id, client_secret)
    client.set_user_auth(_access_token, _refresh_token)
    client.mashape_key = x_mash_key

    conf = {"album" : "JtebE",
         "description": "Hello World",
         "title" : "Hi"}
    res = client.upload_from_path("./image_1_2.gif", config = conf, anon = False)
    print(res)
    print(res["link"])
Exemplo n.º 9
0
 def imgur_auth_from_cache(self) -> Optional[ImgurClient]:
     # Try to authenticate with saved credentials present in auth.json.
         try:
             imgur_client = ImgurClient(**self.auth["imgur"])
             imgur_client.get_account("namen")
             return imgur_client
         except Exception as e:
             log.exception("Could not authenticate for some reason. Fetching new access/refresh tokens.",
                           exc_info=True)
             # log.info("Could not authenticate for some reason. Fetching new access/refresh tokens.")
             log.info("Error returned:({0.__class__.__name__}: {0}".format(e), file=sys.stderr)
             return None
Exemplo n.º 10
0
def CreateAlbumAndUploadImages(albumName, albumDescription, images):
    access_token, refresh_token, client_id, client_secret = Config.getImgurKeys(
    )
    client = ImgurClient(client_id, client_secret)
    client.set_user_auth(access_token, refresh_token)
    fields = {}
    fields['title'] = albumName
    fields['description'] = albumDescription
    fields['privacy'] = 'public'
    x = client.create_album(fields)
    y = client.album_add_images(x['id'], images)
    return x
Exemplo n.º 11
0
def get_client():
    """
    Get an API client for Imgur

    Returns:
        Imgur client if it is available

    """
    try:
        return ImgurClient(IMGUR_ID, IMGUR_SECRET)
    except helpers.error.ImgurClientError:
        print('Error: imgur client error')
Exemplo n.º 12
0
    def __init__(self, bot):
        super().__init__()
        self.bot = bot

        self.db = sql.MySQL()

        try:
            self.imgur = ImgurClient(
                'a7a517a27f5cb30', '8587bb31ad9b16494ac4f1b5318bf224f65fd043')
        except:
            print("Imgur Error!")
            self.bot.remove_command("hug")
Exemplo n.º 13
0
def speech(label_text):
    client_id = 'c2058ecfc76d75f'
    client_secret = '5fe636c3e7a032b56b2120fe82eb3071c790c5ff'

    client = ImgurClient(client_id, client_secret)

    text = label_text
    tts = gTTS(text=text, lang='en-uk', slow=True)
    tts.save("C:/labelReadOut.wav")
    os.system("start C:/labelReadOut.wav")

    webbrowser.open_new(item.link)
Exemplo n.º 14
0
 def __init__(self, bot):
     super().__init__(bot)
     with open(IMGUR_CREDENTIALS_FILE, "r") as f:
         credentials = json.load(f)
         try:
             self.imgur_client = ImgurClient(credentials["client_id"],
                                             credentials["client_secret"])
         except ImgurClientError as e:
             self.logger.warning(
                 "Imgur client creation failed with `{}`, try checking the values in `{}`"
                 .format(e, IMGUR_CREDENTIALS_FILE))
             self.imgur_client = e
Exemplo n.º 15
0
def get_meme():
    try:
        client = ImgurClient(ImgurClientID, ImgurClientSecret)
    except BaseException as e:
        print('[EROR] Error while authenticating with Imgur:', str(e))
        return

    items = client.gallery()
    list = []
    for item in items:
        list.append(item.link)
    return random.choice(list)
Exemplo n.º 16
0
def _imgur_search(conf, query="", filetype='gif', random_result=False):
    ''' returns an image from imgur '''

    # basic api client setup
    client_id = conf['imgur_client_id']
    client_secret = conf['imgur_client_secret']
    client = ImgurClient(client_id, client_secret)

    # get the image url for an imgur album
    def _get_direct_url(url):

        scrape_start = '<link rel="image_src"'
        scrape_end = '"/>'

        request = urllib.request.Request(url)
        result = urllib.request.urlopen(request)
        charset = result.info().get_content_charset()
        html = result.read().decode(charset)

        direct_url = html[html.find(scrape_start):]
        direct_url = direct_url[direct_url.find('href="') +
                                len('href="'):direct_url.find(scrape_end)]

        return direct_url

    # handle random
    if random_result:
        gifs = []

        for item in client.gallery_random():
            if item.is_album:
                direct_url = _get_direct_url(item.link)

            else:
                direct_url = item.link

            if '.gif' in direct_url:
                gifs.append(direct_url)

        return random.choice(gifs)

    # handle queries
    else:
        query = query.split(' ')
        advanced_dict = {'q_all': query, 'q_type': filetype}
        item = random.choice(client.gallery_search("", advanced=advanced_dict))

        if item.is_album:
            return _get_direct_url(item.link)

        else:
            return item.link
Exemplo n.º 17
0
 async def on_message(self, message):
     if message.author == self.user:
         return
     elif message.content[0] == prefix:
         command = message.content[1:].split()
         if command[0].lower() in ['lvl', 'level']:
             session = db_session.create_session()
             user = session.query(User).filter(
                 User.name == str(message.author))[0]
             await message.channel.send(
                 f'Ваш уровень: {user.lvl}, {user.xp}/{(user.lvl + 1) * 100} xp'
             )
             session.commit()
         elif command[0].lower() in ['leaderboard', 'top']:
             session = db_session.create_session()
             users = session.query(User).all().sort()
             if len(users) > 10:
                 users = users[:10]
             m = ''
             for user in users:
                 m += f'{user.name[:-5]}: {user.lvl} lvl, {user.xp}/{(user.lvl + 1) * 100} xp\n'
             await message.channel.send(m)
         elif command[0].lower() == 'play':
             self.vc = message.author.voice
             if self.vc is None:
                 await message.channel.send(
                     'Вы не подключены к голосовому каналу')
             else:
                 await message.channel.send(' '.join(command[1:]) +
                                            ' Добавлено в очередь')
                 await self.queue.put([command[1:], message.channel])
         elif command[0].lower() == 'song':
             await message.channel.send(self.track.title)
         elif command[0].lower() == 'stop':
             while not self.queue.empty():
                 self.queue.get_nowait()
             await self.player.disconnect()
         # -meme СКОРЕЕ ВСЕГО НЕ РАБОТАЕТ, ПОКА НЕ ПРОВЕРЯЛ
         elif command[0].lower() == 'meme':
             client_id = '5d6d51c3b6b7dc2'
             client_secret = '5a419654aae91de31d31a6697f3f07ff1d952748'
             client = ImgurClient(client_id, client_secret)
             embed = discord.Embed()
             embed.set_image(url=client.default_memes())
             await message.channel.send(embed=embed)
     session = db_session.create_session()
     user = session.query(User).filter(User.name == str(message.author))[0]
     user.xp += randint(7, 13)
     if user.xp >= (user.lvl + 1) * 100:
         user.lvl += 1
         user.xp = 0
     session.commit()
Exemplo n.º 18
0
    def _get_imgur_secrets(self,
                           imgur_secrets: str) -> configparser.ConfigParser:
        """
        _get_imgur_secrets checks if the Imgur api secrets file exists.
        - If the file exists, this methods reads the the files and returns the secrets in as a dict.
        - If the file doesn't exist it asks the user over stdin to supply these values and then
          saves them into the imgur_secrets file

        Arguments:
            imgur_secrets (string): file name of secrets file for API credentials

        Returns:
            imgur_config (dict): Dictionary containing the client id and client secret needed to
            login to Imgur
        """

        if not os.path.exists(imgur_secrets):
            self.logger.warning(
                'Imgur API keys not found. (See wiki if you need help).')

            # Whitespaces are stripped from input: https://stackoverflow.com/a/3739939
            imgur_client_id = ''.join(
                input("[ .. ] Enter Imgur client ID: ").split())
            imgur_client_secret = ''.join(
                input("[ .. ] Enter Imgur client secret: ").split())
            # Make sure authentication is working
            try:
                imgur_client = ImgurClient(imgur_client_id,
                                           imgur_client_secret)

                # If this call doesn't work, it'll throw an ImgurClientError
                imgur_client.get_album('dqOyj')
                # It worked, so save the keys to a file
                imgur_config = configparser.ConfigParser()
                imgur_config['Imgur'] = {
                    'ClientID': imgur_client_id,
                    'ClientSecret': imgur_client_secret,
                }
                with open(imgur_secrets, 'w') as file:
                    imgur_config.write(file)
                file.close()
            except ImgurClientError as imgur_error:
                self.logger.error('Error while logging into Imgur: %s',
                                  imgur_error)
                self.logger.error(FATAL_TOOTBOT_ERROR)
                sys.exit(1)
        else:
            # Read API keys from secret file
            imgur_config = configparser.ConfigParser()
            imgur_config.read(imgur_secrets)

        return imgur_config
Exemplo n.º 19
0
def load_api(bot):
    global imgur_api

    api_keys = bot.config.get("api_keys", {})
    client_id = api_keys.get("imgur_client_id")
    client_secret = api_keys.get("imgur_client_secret")

    if not (client_id and client_secret):
        # Either the client id or secret aren't specified
        imgur_api = None
        return
    else:
        imgur_api = ImgurClient(client_id, client_secret)
Exemplo n.º 20
0
def albumToImage(album):

    client_id = 'ayy'
    client_secret = 'lmao'
    client = ImgurClient(client_id, client_secret)

    lolisAlbum = client.get_album_images(album)
    loliList = []
    for loli in lolisAlbum:
        loliList.append(loli.link)

    chosenLoli = random.choice(loliList)
    return chosenLoli
Exemplo n.º 21
0
def stats():
    client = ImgurClient(imgur_id, imgur_secret)
    # looks like {u'UserLimit': 500, u'UserRemaining': 500, u'UserReset': 1449849295, u'ClientLimit': 12500, u'ClientRemaining': 11351}
    template = (
        "<html><body>"
        "---Imgur API info---<br>"
        "Total credits that can be allocated: {UserLimit}<br>"
        "Total credits available: {UserRemaining}<br>"
        "Timestamp (unix epoch) for when the credits will be reset. {UserReset}<br>"
        "Total credits that can be allocated for the application in a day: {ClientLimit}<br>"
        "Total credits remaining for the application in a day: {ClientRemaining}<br>"
        "</body></html>")
    return template.format(**client.credits)
def authenticate():
    """
    Authenticates with Imgur API. Used in this app to upload images and create a gallery
    containing subject, style, output
    """
    load_dotenv(dotenv_path='imgur.env')
    CLIENT_ID = os.getenv("CLIENT_ID")
    CLIENT_SECRET = os.getenv("CLIENT_SECRET")
    ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
    REFRESH_TOKEN = os.getenv("REFRESH_TOKEN")

    client = ImgurClient(CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN, REFRESH_TOKEN)
    return client
Exemplo n.º 23
0
def upload_photo(imagePath):
    client_id = '63b649c82008bf4'
    client_secret = '6650cc6094124cb02846462bddcaa3e769628072'
    access_token = 'e3fad34caf7021955728b9cfd1b1bbb092f891cb'
    refresh_token = 'e601fc841e38a9722315d557e7781873cfa1066c'
    client = ImgurClient(client_id, client_secret, access_token, refresh_token)
    album = None  # You can also enter an album ID here
    config = {
        'album': album,
    }

    image = client.upload_from_path(imagePath, config=config, anon=False)
    return image['link']
Exemplo n.º 24
0
def pic_to_web(pic):
    client = ImgurClient(client_id, client_secret, access_token, refresh_token)
    config = {
        'album': album_id,
        'name': 'test-name!',
        'title': 'test-title',
        'description': 'test-description'
    }
    print("Uploading image... ")
    image = client.upload_from_path(pic, config=config, anon=False)
    print(image['link'])
    return image['link']
    print("Done")
Exemplo n.º 25
0
def venue():
    u = User.query.get(1)
    client = ImgurClient(
        current_app.config['IMGUR_CLIENT_ID'],
        current_app.config['IMGUR_CLIENT_SECRET'],
        access_token=u.access_token,
        refresh_token=u.refresh_token)
    album = client.get_album('izwJA')
    if client.auth.current_access_token != u.access_token:
        u.access_token = client.auth.current_access_token
        db.session.add(u)
        db.session.commit()
    return render_template('venue.html', album=album)
Exemplo n.º 26
0
def language():
    client = ImgurClient(client_id, client_secret)
    images = client.get_album_images(album_id)

    intro = '英文是我一直以來都有在持續學習的語言 對於聽說讀寫都有一定的信心\n' + \
            '大二時考的多益成績是810分' + '\uDBC0\uDC8D' * 2 + '\n' \
            '且因為自己的興趣 大學時曾修過基礎韓文 以下是我的多益成績單和韓文課證書' + '\uDBC0\uDC30'
    content = [TextSendMessage(intro), 
    ImageSendMessage(original_content_url=images[0].link,preview_image_url=images[0].link),
    ImageSendMessage(original_content_url=images[1].link,preview_image_url=images[1].link),
    ]

    return content
Exemplo n.º 27
0
def upload2imgur(id):
    client = ImgurClient(client_id, client_secret, access_token, refresh_token)
    path = "./event(%s).jpg" % id
    config = {
        'album': album_id,
        'name': id,
        'title': id,
        'description': 'test-description'
    }
    print("Uploading image... ")
    image = client.upload_from_path(path, config=config, anon=False)
    print("Done")
    return image.get('link')
Exemplo n.º 28
0
    def get_imgur() -> ImgurClient:
        """Get an imgur api client

        :return: imgur api client
        :rtype: ImgurClient
        """
        logging.debug("Generating Imgur Client")
        return ImgurClient(
            client_id=getenv("IMGUR_CLIENT"),
            client_secret=getenv("IMGUR_SECRET"),
            access_token=getenv("IMGUR_ACCESS_TOKEN"),
            refresh_token=getenv("IMGUR_REFRESH_TOKEN"),
        )
Exemplo n.º 29
0
    def __init__(self, subreddit, refresh_token, spamcruncher=None, un=None, users_tracked=False, botbans=False):

        self.imgur = ImgurClient(credentials.get_token("IMGUR_CLIENT_ID", 'credentials'),
                                 credentials.get_token("IMGUR_CLIENT_SECRET", 'credentials'))
        self.users_tracked = users_tracked
        self.subreddit = subreddit
        self.un = un
        self.refresh_token = refresh_token
        self.spamcruncher = spamcruncher
        self.botbans = botbans
        self.r = praw.Reddit(user_agent="Snoohelper 0.1 by /u/Santi871",
                                 client_id=REDDIT_APP_ID, client_secret=REDDIT_APP_SECRET,
                                 refresh_token=self.refresh_token)
Exemplo n.º 30
0
    def handle(self, *args, **options):
        client = ImgurClient(CONSUMER_ID, CONSUMER_SECRET)

        url = client.get_auth_url('pin')
        print "Url:", url
        print "Please visit this website and press the 'Allow' button, then paste the PIN code you receive from Imgur."
        pin = raw_input().strip()

        # This will fail if the user didn't visit the above URL and hit 'Allow'
        credentials = client.authorize(pin, 'pin')

        print "IMGUR_ACCESS_TOKEN = '%s'" % credentials['access_token']
        print "IMGUR_ACCESS_TOKEN_REFRESH = '%s'" % credentials['refresh_token']