コード例 #1
0
ファイル: imgur.py プロジェクト: sigmonsays/screenshot
 def upload(self, meta, filename, shortname, md):
    client_id = self.config['client_id']
    client_secret = self.config['client_secret']
    up = PyImgur(client_id, client_secret)
    result = up.upload_image(filename, title=shortname)
    self.set_url('http://imgur.com/v/'+result.id)
    return True
コード例 #2
0
 def __init__(self, parent=None):
     super(trayApp, self).__init__(parent)
     self.loadSettings()
     self.setIcon(QIcon("icon.png"))
     self.createSysTrayMenu()
     self.setGlobalHotkeys()
     self.imgurClient = Imgur("", "")
     self.clipboard = QApplication.clipboard()
コード例 #3
0
ファイル: imgur.py プロジェクト: BarnacleBob/screenshot
 def upload(self, meta, filename, shortname):
    imgur = Imgur(
       self.config['client_id'],
       self.config['client_secret']
    )
    result = imgur.upload_image(filename, title=shortname)
    self.set_url('http://imgur.com/v/'+result.id)
    return True
コード例 #4
0
ファイル: doge.py プロジェクト: drsm79/mybot
 def get_link(self, words):
     key = config.__dict__.get(u'IMGUR_ID', False)
     if key:
         imgur = Imgur(key)
         words = '/'.join(words)
         try:
             doge = imgur.upload_image(url="http://dogr.io/%s/wow.png" % words)
             return doge.link
         return "No upload, so unfulfil, much sad, very broken, wow"
コード例 #5
0
 def get_link(self, words):
     key = config.__dict__.get(u'IMGUR_ID', False)
     if key:
         imgur = Imgur(key)
         words = '/'.join(words)
         try:
             doge = imgur.upload_image(url="http://dogr.io/%s/wow.png" % words)
             return doge.link
         except:
             return "No upload, so unfulfil, much sad, very broken, wow"
コード例 #6
0
ファイル: utils.py プロジェクト: ZeGmX/PiflouzBot
def upload_image_to_imgur(path):
    """
  Uploads an image file to imgur and returns the link
  --
  input:
    path: str
  --
  output:
    res: str
  """
    imgur = Imgur(Constants.IMGUR_CLIENT_ID)
    img = imgur.upload_image(path)
    return img.link
コード例 #7
0
ファイル: embed.py プロジェクト: VincyBot07/plugins
    async def send(self, ctx: Context, title: str, *, message: str) -> None:
        """Invia un embed."""
        try:
            colorcode = (await
                         self.db.find_one({"_id":
                                           "embedcolor-config"}))["colorcode"]
        except (KeyError, TypeError):
            colorcode = "0x3498DB"  # blue

        embed = Embed(
            title=title,
            description=message,
            color=Color(int(colorcode, 0)),
            timestamp=datetime.utcnow(),
        )

        embed.set_author(name=ctx.author.display_name,
                         icon_url=ctx.author.avatar_url)

        if len(ctx.message.attachments) == 1:
            try:
                imgur = Imgur("0f032be3851849a")
                image_url = ctx.message.attachments[0].url

                uploaded_image = imgur.upload_image(url=image_url,
                                                    title="Modmail")
                embed.set_image(url=uploaded_image.link)
            except BaseException:
                pass
        elif len(ctx.message.attachments) > 1:
            await ctx.message.delete()

            embed = Embed(
                title="Embedder",
                url=
                "https://github.com/Ergastolator1/fhmail-plugins/blob/master/embedder",
                description="Puoi solo usare un immagine per embed.",
                color=self.bot.main_color,
            )

            error: Message = await ctx.send(embed=embed)
            return await error.delete(5000)

        await ctx.send(embed=embed)
        await ctx.message.delete()
コード例 #8
0
def auth_with_pin(client: Imgur):
    """Authorize Imgur client with a PIN

    Arguments:
        client {Imgur} -- Imgur client

    Returns:
        [tuple] -- (access_token, refresh_token) tuple
    """
    auth_url = client.authorization_url('pin')
    webbrowser.open(auth_url)
    pin = input('What is the pin: ')
    response = client.exchange_pin(pin)

    config.set_multi(config.IMGUR_SECTION, ('access_token', response[0]),
                     ('refresh_token', response[1]))

    return response
コード例 #9
0
ファイル: fryer.py プロジェクト: paramkpr/DankBot
def __upload_to_imgur(path, caption):
    if not isfile(path):
        return

    # TODO: Convert to GIF and upload.
    if path[-3:] == 'mp4':
        remove(path)
        return

    im = Imgur(environ.get('IMGUR_CLIENT_ID'), environ.get('IMGUR_CLIENT_KEY'),
               environ.get('IMGUR_ACCESS_TOKEN'),
               environ.get('IMGUR_REFRESH_TOKEN'))
    for _ in range(5):
        # noinspection PyBroadException
        try:
            im.upload_image(path=abspath(path),
                            title=caption,
                            album=environ.get('IMGUR_ALBUM'))
        except Exception:
            im.refresh_access_token()
            sleep(10)
            continue

        remove(path)
        return
コード例 #10
0
ファイル: fryer.py プロジェクト: annihilatorrrr/DankBot
def __upload_to_imgur(path, caption):
    log_debug('__upload started')
    if not isfile(path):
        log_warn('File to be uploaded not found')
        return

    # TODO: Convert to GIF and upload.
    if path[-3:] == 'mp4':
        remove(path)
        log_warn('Skipping mp4 upload')
        return

    log_debug('Authorizing imgur client')
    im = Imgur(environ.get('IMGUR_CLIENT_ID'), environ.get('IMGUR_CLIENT_KEY'),
               environ.get('IMGUR_ACCESS_TOKEN'),
               environ.get('IMGUR_REFRESH_TOKEN'))

    for _ in range(5):
        try:
            im.upload_image(path=abspath(path),
                            title=caption,
                            album=environ.get('IMGUR_ALBUM'))
            log_debug('Image successfully uploaded')
            break
        except Exception:
            log_warn('Upload failed, refreshing token')
            im.refresh_access_token()
            sleep(10)
            continue
    else:
        log_error('Upload failed, proceeding')

    log_debug('Deleting file')
    remove(path)
    return
コード例 #11
0
ファイル: bot.py プロジェクト: dionysio/AsciiBot
class Uploader():
    def __init__(self):
        self.uploader = Imgur(client_id=imgur_key, client_secret=imgur_secret)


    def upload_screenshot(self, path_to_picture,text):
        '''Uploads screenshot from url to imgur.
        
        :param url: url of uploaded picture
        :param text: text to describe the image
        '''
    
        uploaded_image = self.uploader.upload_image(path_to_picture, title=text)
        return uploaded_image.link.encode('ascii','ignore')
コード例 #12
0
ファイル: imdb2bb.py プロジェクト: traineryou/imdb
def upload(config, tmp_dir):
    print('Uploading screens and sample videos...')
    links = {}
    imgur_client_id = config['imgur_client_id']
    imgur = Imgur(imgur_client_id)
    for i in range(1, 5):
        file = f'screen-0{i}.jpeg'
        path = os.path.join(tmp_dir, file)
        try:
            links[file] = imgur.upload_image(path).link
        except:
            sys.exit('Error uploading to Imgur! Exiting.')
    streamable_username = config['streamable_username']
    streamable_password = config['streamable_password']
    streamable = StreamableApi(streamable_username, streamable_password)
    for i in range(1, 3):
        file = f'sample-00{i}.mkv'
        path = os.path.join(tmp_dir, file)
        try:
            links[
                file] = f'https://streamable.com/{streamable.upload_video(path)["shortcode"]}'
        except:
            sys.exit('Error uploading to Streamable! Exiting.')
    return links
コード例 #13
0
def upload_image(client: Imgur,
                 album: Album,
                 img_path,
                 img_name,
                 links,
                 overwrite=False):
    """Uploads a single image to Imgur

    Arguments:
        client {Imgur} -- Imgur client
        album {Album} -- Imgur album
        img_path {str} -- Path of the image to upload
        img_name {str} -- Name of the image to upload
        links {list(str)} -- List of links of uploaded images

    Keyword Arguments:
        overwrite {bool} -- If an image is found within the album, overwrite it?(default: {False})
    """
    for image in album.images:
        if img_name == image.title:
            if overwrite:
                # print('Overriding pre-existing image!')
                album.remove_images(image)
            else:
                MUTEX.acquire()
                # print('FOUND %s: %s' % (image.title, image.link))
                links[img_name] = image.link
                MUTEX.release()
                return

    image = client.upload_image(path=img_path, title=img_name)
    album.add_images(image)

    MUTEX.acquire()
    # print('UPLOADED %s: %s' % (image.title, image.link))
    links[img_name] = image.link
    MUTEX.release()
コード例 #14
0
def get_authed_client():
    refresh_token = config.get(config.IMGUR_SECTION, 'refresh_token')
    if refresh_token:
        client = Imgur(client_id=config.IMGUR_CLIENT_ID,
                       client_secret=config.IMGUR_CLIENT_SECRET,
                       refresh_token=refresh_token)
    else:
        client = Imgur(client_id=config.IMGUR_CLIENT_ID,
                       client_secret=config.IMGUR_CLIENT_SECRET)
        auth_with_pin(client)

    try:
        access_token = client.refresh_access_token()
        config.set(config.IMGUR_SECTION, 'access_token', access_token)
    except Exception as e:
        print(e)
        print('Access token failed to refresh')
        auth_with_pin(client)
        client = Imgur(client_id=config.IMGUR_CLIENT_ID,
                       client_secret=config.IMGUR_CLIENT_SECRET,
                       refresh_token=config.get(config.IMGUR_SECTION,
                                                'refresh_token'))

    return client
コード例 #15
0
ファイル: bot.py プロジェクト: dionysio/AsciiBot
 def __init__(self):
     self.uploader = Imgur(client_id=imgur_key, client_secret=imgur_secret)
コード例 #16
0
from discord.ext import commands
from utils import Crombed, chance, is_mention, extract_id, random_string
from garlic_functions import (generate_scream, generate_screech, ProbDist,
                              string_to_bf, run_bf, ooojoy, generate_gibberish)
import usernumber
import random
import json
import zlib
import base64
import requests
import os
from pyimgur import Imgur

imgur = Imgur(os.environ["IMGUR_CLIENT_ID"])

REPLY_CHAIN_LENGTH = int(os.environ["REPLY_CHAIN_LENGTH"])


class GarlicCommands(commands.Cog):
    """ Commands made by garlicOS®! """
    def __init__(self, bot):
        self.bot = bot

    @commands.command(aliases=["aaa"])
    async def scream(self, ctx: commands.Context):
        """ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA """
        await ctx.send(generate_scream())

    @commands.command(aliases=["eee", "ree"])
    async def screech(self, ctx: commands.Context):
        """ EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE """
コード例 #17
0
class trayApp(QSystemTrayIcon):
    def __init__(self, parent=None):
        super(trayApp, self).__init__(parent)
        self.loadSettings()
        self.setIcon(QIcon("icon.png"))
        self.createSysTrayMenu()
        self.setGlobalHotkeys()
        self.imgurClient = Imgur("", "")
        self.clipboard = QApplication.clipboard()

    def createSysTrayMenu(self):
        self.sysTrayMenu = QMenu()
        self.setContextMenu(self.sysTrayMenu)
        self.createSysTrayActions()

    def createSysTrayActions(self):
        self.sysTrayMenuRegionAction = self.createAction("&Capture region", self.createDrawSurface, self.hotkey)
        self.sysTrayMenuHotkeyAction = self.createAction("&Change hotkey...", self.createKeySequenceDialog)
        self.sysTrayMenuUploadAction = self.createAction("&Upload to imgur", checkable=True)
        self.sysTrayMenuUploadAction.setChecked(self.upload)
        self.sysTrayMenuSaveAction = self.createAction("&Save locally", checkable=True)
        self.sysTrayMenuSaveAction.setChecked(self.save)
        self.sysTrayMenuExitAction = self.createAction("&Exit", self.quit)

        self.addActions(self.sysTrayMenu, (self.sysTrayMenuRegionAction,
                                           None,
                                           self.sysTrayMenuHotkeyAction,
                                           self.sysTrayMenuUploadAction,
                                           self.sysTrayMenuSaveAction,
                                           self.sysTrayMenuExitAction))

    def createAction(self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False):
        action = QAction(text, self)
        if slot is not None:
            action.triggered.connect(slot)
        if shortcut is not None:
            action.setShortcut(shortcut)
        if icon is not None:
            action.setIcon(QIcon(":/{}.png".format(icon)))
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if checkable:
            action.setCheckable(True)
        return action

    def addActions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def createKeySequenceDialog(self):
        self.keySequenceDialog = KeySequenceDialog(self.hotkey)
        self.keySequenceDialog.accepted.connect(self.changeHotkey)
        self.keySequenceDialog.show()

    def changeHotkey(self):
        text = self.keySequenceDialog.keySequenceLineEdit.text()
        if text:
            self.hotkey = text
            self.sysTrayMenuRegionAction.setShortcut(self.hotkey)
            self.sysTrayMenuRegionGlobalHotkey.setShortcut(QKeySequence(self.hotkey))

    def loadSettings(self):
        settings = QSettings("ninjapic", "settings")
        self.upload = settings.value("upload").toBool()
        self.save = settings.value("save").toBool()
        self.hotkey = settings.value("hotkey").toString()
        if not self.hotkey:
            self.hotkey = "Alt+C"

    def saveSettings(self):
        settings = QSettings("ninjapic", "settings")
        settings.setValue("upload", self.sysTrayMenuUploadAction.isChecked())
        settings.setValue("save", self.sysTrayMenuSaveAction.isChecked())
        settings.setValue("hotkey", self.hotkey)

    def createDrawSurface(self):
        self.surface = Surface()
        self.surface.imageReady.connect(self.storeImage)
        self.surface.show()

    def setGlobalHotkeys(self):
        self.sysTrayMenuRegionGlobalHotkey = QxtGlobalShortcut()
        self.sysTrayMenuRegionGlobalHotkey.setShortcut(QKeySequence(self.hotkey))
        self.sysTrayMenuRegionGlobalHotkey.activated.connect(self.createDrawSurface)

    def storeImage(self):
        if not self.surface.image.save("screenshot.png", "PNG", -1):
            QMessageBox.warning(None, "Image Error", "The image couldn't be saved.")
            return
        if self.sysTrayMenuUploadAction.isChecked():
            try:
                uploaded_image = self.imgurClient.upload_image("screenshot.png")
                self.clipboard.setText(uploaded_image.link)
                webbrowser.open(uploaded_image.link)
            except HTTPError, e:
                self.surface.dispose()
                QMessageBox.warning(None, "Imgur Error", unicode(e))
        if not self.sysTrayMenuSaveAction.isChecked():
            os.remove("screenshot.png")