本文整理汇总了Python中imgurpython.ImgurClient方法的典型用法代码示例。如果您正苦于以下问题:Python imgurpython.ImgurClient方法的具体用法?Python imgurpython.ImgurClient怎么用?Python imgurpython.ImgurClient使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类imgurpython
的用法示例。
在下文中一共展示了imgurpython.ImgurClient方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: convertImgurIndirectUrlToImg
# 需要导入模块: import imgurpython [as 别名]
# 或者: from imgurpython import ImgurClient [as 别名]
def convertImgurIndirectUrlToImg(submission, imgurAuth, url):
# Login to imgur
# This is required since they made NSFW images require login
imgurClient = imgur.ImgurClient(imgurAuth.clientId, imgurAuth.clientSecret)
if not checkImgurAPICredits(imgurClient):
return None
imageId = imgurIdFromUrl(url)
if not imageId:
logger.log("Failed to convert {} to image id".format(url))
try:
return imgurClient.get_image(imageId).link
except Exception as e:
errorMessage = ('Failed to convert imgur to image link: '
'[ERROR] Exception: Url {} raised exception:\n\t {}'.format(url, e))
logger.log(errorMessage)
LikedSavedDatabase.db.addUnsupportedSubmission(submission, errorMessage)
return None
示例2: authenticate
# 需要导入模块: import imgurpython [as 别名]
# 或者: from imgurpython import ImgurClient [as 别名]
def authenticate():
# Get client ID and secret from config.py
client = ImgurClient(client_id, client_secret)
# Authorization flow, pin example (see docs for other auth types)
authorization_url = client.get_auth_url('pin')
print("Go to the following URL: {0}".format(authorization_url))
# Read in the pin, handle Python 2 or 3 here.
pin = get_input("Enter pin code: ")
# ... 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']))
return client
# If you want to run this as a standalone script, so be it!
示例3: authenticate
# 需要导入模块: import imgurpython [as 别名]
# 或者: from imgurpython import ImgurClient [as 别名]
def authenticate():
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')
driver = webdriver.Firefox()
driver.get(authorization_url)
username = driver.find_element_by_xpath('//*[@id="username"]')
password = driver.find_element_by_xpath('//*[@id="password"]')
username.clear()
username.send_keys(imgur_username)
password.send_keys(imgur_password)
driver.find_element_by_name("allow").click()
timeout = 5
try:
element_present = EC.presence_of_element_located((By.ID, 'pin'))
WebDriverWait(driver, timeout).until(element_present)
pin_element = driver.find_element_by_id('pin')
pin = pin_element.get_attribute("value")
except TimeoutException:
print("Timed out waiting for page to load")
driver.close()
credentials = client.authorize(pin, 'pin')
client.set_user_auth(credentials['access_token'], credentials['refresh_token'])
print("Authentication successful!")
return client
示例4: __init__
# 需要导入模块: import imgurpython [as 别名]
# 或者: from imgurpython import ImgurClient [as 别名]
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
示例5: search_imgur
# 需要导入模块: import imgurpython [as 别名]
# 或者: from imgurpython import ImgurClient [as 别名]
def search_imgur(self, ctx: Context, *, query: str):
"""Imgur search."""
search_id = 0
await self.bot.send_typing(ctx.message.channel)
try:
client_id = self.settings["imgur"]["id"]
client_secret = self.settings["imgur"]["secret"]
except KeyError:
await self.bot.say("Please set imgur id and secret.")
return
try:
search_id = self.settings["imgur"]["search_id"]
except KeyError:
self.settings["imgur"]["search_id"] = 0
# count = 0
client = ImgurClient(client_id, client_secret)
results = client.gallery_search(query)
try:
result = next(islice(results, search_id, None))
if result.is_album:
img = client.get_image(result.cover)
else:
img = result
await self.bot.say(str(img.link))
search_id += 1
except StopIteration:
search_id = 0
self.settings["imgur"]["search_id"] = search_id
dataIO.save_json(JSON, self.settings)
示例6: image_uploader
# 需要导入模块: import imgurpython [as 别名]
# 或者: from imgurpython import ImgurClient [as 别名]
def image_uploader(speech_text):
if profile.data['imgur']['client_id'] == "xxxx" \
or profile.data['imgur']['client_secret'] == "xxxx":
msg = 'upload requires a client id and secret'
print msg
tts(msg)
return
words_of_message = speech_text.split()
words_of_message.remove('upload')
cleaned_message = ' '.join(words_of_message)
if len(cleaned_message) == 0:
tts('upload requires a picture name')
return
image_listing = img_list_gen()
client = ImgurClient(profile.data['imgur']['client_id'],
profile.data['imgur']['client_secret'])
for i in range(0, len(image_listing)):
if cleaned_message in image_listing[i]:
result = client.upload_from_path(image_listing[i], config=None,
anon=True)
conn = sqlite3.connect(profile.data['memory_db'])
conn.execute("INSERT INTO image_uploads "
"(filename, url, upload_date) VALUES (?, ?, ?)",
(image_listing[i], result['link'],
datetime.strftime(datetime.now(), '%d-%m-%Y')))
conn.commit()
conn.close()
print result['link']
tts('Your image has been uploaded')
示例7: init_imgur_client
# 需要导入模块: import imgurpython [as 别名]
# 或者: from imgurpython import ImgurClient [as 别名]
def init_imgur_client():
global imgur_client
imgur_client = ImgurClient(secret_keys.imgur_client_id, secret_keys.imgur_client_secret)
示例8: initialize_imgur_client
# 需要导入模块: import imgurpython [as 别名]
# 或者: from imgurpython import ImgurClient [as 别名]
def initialize_imgur_client(self, channel):
"""
Check if imgur client id or secret are set, and if so initialize
imgur API client
"""
if self.imgur_client is None:
imgur_client_id = self.registryValue("imgurClientID")
imgur_client_secret = self.registryValue("imgurClientSecret")
imgur_handler_enabled = self.registryValue("imgurHandlerEnabled", channel=channel)
if imgur_handler_enabled and imgur_client_id and imgur_client_secret:
log.debug("SpiffyTitles: enabling imgur handler")
# Initialize API client
try:
from imgurpython import ImgurClient
from imgurpython.helpers.error import ImgurClientError
try:
self.imgur_client = ImgurClient(imgur_client_id, imgur_client_secret)
except ImgurClientError as e:
log.error("SpiffyTitles: imgur client error: %s" % (e.error_message))
except ImportError as e:
log.error("SpiffyTitles ImportError: %s" % str(e))
else:
log.debug("SpiffyTitles: imgur handler disabled or empty client id/secret")
示例9: handle_message
# 需要导入模块: import imgurpython [as 别名]
# 或者: from imgurpython import ImgurClient [as 别名]
def handle_message(event):
if isinstance(event.message, ImageMessage):
ext = 'jpg'
message_content = line_bot_api.get_message_content(event.message.id)
with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix=ext + '-', delete=False) as tf:
for chunk in message_content.iter_content():
tf.write(chunk)
tempfile_path = tf.name
dist_path = tempfile_path + '.' + ext
dist_name = os.path.basename(dist_path)
os.rename(tempfile_path, dist_path)
try:
client = ImgurClient(client_id, client_secret, access_token, refresh_token)
config = {
'album': album_id,
'name': 'Catastrophe!',
'title': 'Catastrophe!',
'description': 'Cute kitten being cute on '
}
path = os.path.join('static', 'tmp', dist_name)
client.upload_from_path(path, config=config, anon=False)
os.remove(path)
print(path)
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='上傳成功'))
except:
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='上傳失敗'))
return 0
elif isinstance(event.message, VideoMessage):
ext = 'mp4'
elif isinstance(event.message, AudioMessage):
ext = 'm4a'
elif isinstance(event.message, TextMessage):
if event.message.text == "看看大家都傳了什麼圖片":
client = ImgurClient(client_id, client_secret)
images = client.get_album_images(album_id)
index = random.randint(0, len(images) - 1)
url = images[index].link
image_message = ImageSendMessage(
original_content_url=url,
preview_image_url=url
)
line_bot_api.reply_message(
event.reply_token, image_message)
return 0
else:
line_bot_api.reply_message(
event.reply_token, [
TextSendMessage(text=' yoyo'),
TextSendMessage(text='請傳一張圖片給我')
])
return 0