예제 #1
0
def show_fsm(event):
    machine[event.source.user_id].get_graph().draw("fsm.png",
                                                   prog="dot",
                                                   format="png")
    #print(settings.STATIC_ROOT)
    CLIENT_ID = "20b51ca78c975e9"
    CLIENT_SECRET = "b6fe2a673a273dabaa027120e1de3e4bc54651a0"
    PATH = "fsm.png"
    im = pyimgur.Imgur(CLIENT_ID)
    uploaded_image = im.upload_image(PATH, title="upload")
    return uploaded_image.link
예제 #2
0
def upload_images():
    with open('imgurcreds.txt') as f:
        client_id = f.readline().rstrip('\n')
    plot_path = "plot.png"
    plot_deaths_path = "plot-deaths.png"
    im = pyimgur.Imgur(client_id)
    plot = im.upload_image(plot_path, title="Covid-19 graph")
    plot_deaths = im.upload_image(plot_deaths_path, title="Covid-19 deaths")
    print(plot.link)
    print(plot_deaths.link)
    return plot.link, plot_deaths.link
예제 #3
0
    def maybe_imgur(self, path):
        '''Uploads a file to imgur if requested via command line flags.
        
        Returns either "path" or "path url" depending on the course of action.
        '''
        if not FLAGS.imgur_client_id:
            return path

        im = pyimgur.Imgur(FLAGS.imgur_client_id)
        uploaded_image = im.upload_image(path)
        return '%s %s' % (path, uploaded_image.link)
예제 #4
0
 def save(self, *args, **kwargs):
     try:
         CLIENT_ID = "cdadf801dc167ab"
         bencode = b64encode(self.file.read())
         client = pyimgur.Imgur(CLIENT_ID)
         r = client._send_request('https://api.imgur.com/3/image', method='POST', params={'image': bencode})
         file = r['link']
         self.url = file
     except (Exception,):
         pass
     return super(FotoProduto, self).save(*args, **kwargs)
예제 #5
0
def upload(self):
    CLIENT_ID = "48b9a282f14d299"  #ClientID for legally uploading to imgur
    im1 = pyimgur.Imgur(CLIENT_ID)  #Ready an image to be uploaded to imgur
    filename = filedialog.askopenfilename()  #Choose the file to upload
    uploaded_image = im1.upload_image(
        filename, title="Uploaded with pyImgur")  #upload the image to imgur
    print(
        uploaded_image.title
    )  #Prints the Image title to the command line "Uploaded with pyImgur"
    print("Heres Your Link Below: ")
    print(uploaded_image.link)  #Prints the link to the image on imgur
    return
예제 #6
0
def imgur_upload_pic(s,path):
	for root, dirs, files in os.walk(path, topdown=False):
		for filename in files:
			if 'foo.png' in filename:
			
				CLIENT_ID = ""
				
				im = pyimgur.Imgur(CLIENT_ID)
				uploaded_image = im.upload_image(path+filename, title="Uploaded with PyImgur")
				
				print('[img]'+uploaded_image.link+'[/img]')
				
def imgur_rand_search(search_str):
    im = pyimgur.Imgur(os.environ['imgur_client_id'])
    gal_search = im.search_gallery(search_str)
    search_urls = []
    for pic in gal_search:
        if hasattr(pic, 'images'):
            for image in pic.images:
                if not image.is_nsfw:
                    search_urls.append(image.link)

    out_url = random.sample(search_urls, 1)[0]
    return (str(out_url))
예제 #8
0
def upload_image_to_imgur(fname, lname, rname):

    print("Uploading Image to Database")

    im = pyimgur.Imgur(CLIENT_ID)
    f_image = im.upload_image(fname, title="Garbage Image")
    l_image = im.upload_image(lname, title="Left Image")
    r_image = im.upload_image(rname, title="right Image")

    print("Image Successlly uploaded to databse")

    return f_image.link, l_image.link, r_image.link
예제 #9
0
def upload_file():
    import os

    PATH = os.path.abspath("tmp_image.png")

    im = pyimgur.Imgur(CLIENT_ID)
    uploaded_image = im.upload_image(PATH, title="tmp")
    print(uploaded_image.title)
    print(uploaded_image.link)
    print(uploaded_image.size)
    print(uploaded_image.type)
    return uploaded_image.link
예제 #10
0
def upload_image(client_id, path, name):
    im = pyimgur.Imgur(client_id)

    did_upload = False
    while not did_upload:
        try:
            uploaded_image = im.upload_image(path, title=name)
            did_upload = True
        except:
            print("[-] Error uploading file. Waiting 1 hour before retry")
            sleep(60 * 60)
    return uploaded_image.link
예제 #11
0
파일: bot.py 프로젝트: andredms/mock-stock
async def on_message(message):
    if message.author == client.user:
        return
    args = message.content.split()
    #INVEST
    if (message.content.startswith('$i')):
        args[1] = args[1].upper()
        await invest(message, args)
    #SELL
    if (message.content.startswith('$s')):
        args[1] = args[1].upper()
        await sell(message, args)
    #UPDATE
    if (message.content == '$u'):
        await update(message, False)
    #USER DETAILS
    if (message.content == '$p'):
        await profile(message)
    #GET COMPANY GRAPH
    if (message.content.startswith('$g')):
        get_graph(args[1].upper())
        embed = discord.Embed(title=str(args[1]) + " Graph 📊",
                              color=0xcc33ff)
        #uploads to imgur from local
        im = pyimgur.Imgur(CLIENT_ID)
        #gets link of imgur upload
        image = im.upload_image("graph.png")
        #embeds message in discord
        embed.set_image(url=image.link)
        await message.channel.send(embed=embed)
    #ADDS USER TO DATABASE
    if (message.content == '$etup'):
        add_user(message.author.id, message.author.name)
        name = message.author.name
        embed = discord.Embed(title=name + " has entered the market!",
                              color=0xcc33ff)
        await message.channel.send(embed=embed)
    #HELP
    if (message.content == '$help'):
        embed = discord.Embed(title="MockStock Commands 🔎", color=0xcc33ff)
        embed.add_field(name="Add user", value="$etup", inline=False)
        embed.add_field(name="Invest",
                        value="$i <company-acronym> <value>",
                        inline=False)
        embed.add_field(name="Sell",
                        value="$s <company-acronym>",
                        inline=False)
        embed.add_field(name="Update", value="$u", inline=False)
        embed.add_field(name="Profile", value="$p", inline=False)
        embed.add_field(name="Get graph",
                        value="$g <company-acronym>",
                        inline=False)
        await message.channel.send(embed=embed)
예제 #12
0
 def loadSettings(self):
     settings = QSettings()
     settings.beginGroup("uploaders")
     settings.beginGroup("imgur")
     self.uploadAnon = settings.value("anonymous", "true") in ['true', True]
     self.copyLink = settings.value("copy-link", "true") in ['true', True]
     self.copyDirectLink = settings.value("copy-direct-link",
                                          "false") in ['true', True]
     self.access_token = settings.value("access-token", "")
     self.refresh_token = settings.value("refresh-token", "")
     self.nameFormat = settings.value("name-format",
                                      "Screenshot at %H:%M:%S")
     self.username = settings.value("username", "")
     settings.endGroup()
     settings.endGroup()
     if self.uploadAnon:
         self.imgur = pyimgur.Imgur("7163c05b94dcf99")
     else:
         self.imgur = pyimgur.Imgur(
             "7163c05b94dcf99", "5132015d173997bbb52e1d9e093d882abed8d9f1",
             self.access_token, self.refresh_token)
예제 #13
0
def get_url_3month():
    # get html
    res = rs.get('https://rate.bot.com.tw/xrt/quote/ltm/JPY')
    res.encoding = 'utf-8'
    # get data table
    soup = BeautifulSoup(res.text, 'lxml')
    table = soup.find('table', {
        'class':
        'table table-striped table-bordered table-condensed table-hover'
    })
    table = table.find_all('tr')
    # remove table title
    table = table[2:]
    # add to dataframe
    col = ['掛牌日期', '幣別', '現金買入', '現金賣出', '匯率買入', '匯率賣出']
    data = []
    for row in table:
        row_data = []
        date = row.find('td', {'class': 'text-center'}).text
        currency = row.find('td', {'class': 'text-center tablet_hide'}).text
        cash = row.find_all(
            'td', {'class': 'rate-content-cash text-right print_table-cell'})
        sight = row.find_all(
            'td', {'class': 'rate-content-sight text-right print_table-cell'})
        row_data.append(date)
        row_data.append(currency)
        row_data.append(cash[0].text)
        row_data.append(cash[1].text)
        row_data.append(sight[0].text)
        row_data.append(sight[1].text)
        data.append(row_data)
    df = pd.DataFrame(data)
    df.columns = col
    df['掛牌日期'] = pd.to_datetime(df['掛牌日期'])
    df.set_index('掛牌日期', inplace=True)
    # draw the graph
    plt.figure(figsize=(20, 15))
    plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
    df_pic = df[['現金買入', '現金賣出', '匯率買入', '匯率賣出']]
    df_pic = df_pic.astype(float)
    df_pic = df_pic.plot()
    plt.grid()
    plt.title('日圓匯率近三月走勢圖', fontsize=16)
    plt.xlabel('掛牌日期', fontsize=14)
    plt.ylabel('匯率', fontsize=14)
    plt.savefig('JPY_df.png', dpi=300)
    plt.show()
    # upload to imgur and get url
    CLIENT_ID = "b4d6470eeacb77a"
    PATH = "JPY_df.png"
    im = pyimgur.Imgur(CLIENT_ID)
    uploaded_image = im.upload_image(PATH, title="upload")
    return uploaded_image.link
예제 #14
0
파일: bot.py 프로젝트: andredms/mock-stock
async def profile(message):
    worth = 0.0

    #get balance of user
    balance = float(wrapper_select_balance(message.author.id))
    balance = round(balance, 2)

    #get all companies of user
    all_companies = wrapper_all_companies(message.author.id)
    companies = [None] * len(all_companies)
    for ii, company in enumerate(all_companies):
        companies[ii] = company + " ($" + str(
            float(round(wrapper_select_curr_val(message.author.id, company),
                        2))) + ")"
        worth += float(wrapper_select_curr_val(message.author.id, company))

    #worth is current value of stocks + balance
    worth += balance
    worth = round(worth, 2)

    #get total profit of user
    profit = str(round(wrapper_select_profit(message.author.id), 2))

    #check for negative
    if ('-' in profit):
        profit = profit.replace('-', '-$')
    else:
        profit = "$" + profit

    #format message
    embed = discord.Embed(title="Profile 👤", color=0xcc33ff)
    embed.add_field(name="Name", value=message.author.mention, inline=False)
    embed.add_field(name="Balance", value="$" + str(balance), inline=False)
    embed.add_field(name="Worth", value="$" + str(worth), inline=False)
    embed.add_field(name="Toal Profit", value=profit, inline=False)
    embed.add_field(name="Companies", value=companies, inline=False)

    #generates graph with matplotlib and saves to .png named after userId
    graph(message.author.id, message.author.name)

    #get .png graph
    filename = str(message.author.id) + '.png'

    #uploads to imgur from local
    im = pyimgur.Imgur(CLIENT_ID)

    #gets link of imgur upload
    image = im.upload_image(filename)

    #embeds message in discord
    embed.set_image(url=image.link)

    await message.channel.send(embed=embed)
예제 #15
0
 def __init__(self, args):
     """
       Initialize the class as a subclass of BaseModule
       and call parent constructor with the defined matchers.
       These will be turned into regex-matchers that redirect to
       the provided function name
     """
     super(self.__class__, self).__init__(self)
     config = ConfigParser()
     config.read(["settings.ini"])
     self.imgur_handle = pyimgur.Imgur(config.get('belle', 'imgur_app_id'))
     self.QUOTE_CHANNEL = config.get('belle', 'quotes')
예제 #16
0
파일: imgur.py 프로젝트: AJubatus/Kiwishot
def upload(filepath):
    """
    Takes a filepath of an image and attempts to upload
    it to imgur.
        Arguments:
            filepath: String, filepath of image
        Returns:
            link: String, link to image on successful upload
    """
    im = pyimgur.Imgur(CLIENT_ID)
    uploaded_image = im.upload_image(filepath)
    return uploaded_image.link
예제 #17
0
def imgur(static_map, config):
    imgursuccess = 0
    while imgursuccess == 0:
        try:
            im = pyimgur.Imgur(config['client_id_imgur'])
            uploaded_image = im.upload_image(url=static_map)
            static_map = (uploaded_image.link)
            imgursuccess = 1
        except:
            print("Imgur error. Sleeping 1 hour")
            time.sleep(3600)
    return static_map
예제 #18
0
def run_bot(reddit):
    print("Obtaining Submissions...")

    for comment in reddit.inbox.mentions(limit=None):
        footer = "\n\n ^I'm&nbsp;a&nbsp;bot.&nbsp;|&nbsp;Creator:&nbsp;[u/JoshuaScript](https://www.reddit.com/u/JoshuaScript).&nbsp;|&nbsp;[Source&nbsp;Code](https://github.com/Joshuascript/Palette_Bot)"
        #checks if the mention is unread, which is only the case if it hasn't been replied to
        if comment.new:
            try:
                #calls the showPalette (which creates and saves the image) method on the image link
                Haishoku.showPalette(comment.submission.url)
                CLIENT_ID = config.imgur_id
                PATH = haishoku.haillow.image_name
                im = pyimgur.Imgur(CLIENT_ID)
                uploaded_image = im.upload_image(
                    PATH,
                    title=
                    f"Color Palette for Reddit Post: {comment.submission.title} ({comment.submission.url})"
                )
                print(uploaded_image.title)
                print(uploaded_image.link)
                print(uploaded_image.size)
                print(uploaded_image.type)
                comment.reply(
                    f"\n\n Here is the color palette of this image visualized: {uploaded_image.link}. The color sizes are proportionate to their dominance in the image. {footer}"
                )
                #Marks the comment as read so it won't be replied to again
                comment.mark_read()
                print(
                    f"Replied to {comment.submission.title} ({comment.submission.url})"
                )
                #deletes generated palette image from local storage
                os.remove(PATH)
            except OSError as e:
                comment.reply(
                    f"This is most likely a non-image post. Try mentioning me in a new comment and I may be able to get this post's palette if it is an image.{footer}"
                )
                print(
                    f"Comment was most likely on a non-image post ({e}) \n\n Title: {comment.submission.title}, Link: {comment.submission.url}"
                )
                comment.mark_read()
            except TypeError as e:
                comment.reply(
                    f"I was unable to get the palette of this image, most likely because it's a gif, which is currently unsupported.{footer}"
                )
                print(
                    f"Image was likely a gif ({e}) \n\n Title: {comment.submission.title}, Link: {comment.submission.url}"
                )
                comment.mark_read()
            except Exception as e:
                print(e.__class__.__name__ + e)
        else:
            continue
예제 #19
0
def main(state):
    from PIL import ImageGrab
    import pyimgur
    import os

    save_fn = "temp.png"

    im = ImageGrab.grab()
    im.save(save_fn)
    imgur = pyimgur.Imgur(state["imgur_key"])
    uploaded_image = imgur.upload_image(save_fn, title="...")
    os.remove(save_fn)
    state["result"] = uploaded_image.link
예제 #20
0
def upload():
    if request.method == 'POST':
        filename = photos.save(request.files['image'])
        filepath = photos.path(filename)
        im = pyimgur.Imgur(IMGUR_CLIENT_ID)
        uploaded_image = im.upload_image(filepath, title=filename)
        os.remove(os.path.join(app.config['UPLOADED_PHOTOS_DEST'], filename))
        uppic_url = uploaded_image.link
        return jsonify(fromuser=request.form['fromuser'],
                       touser=request.form['touser'],
                       img_url=uppic_url)
    else:
        return redirect(url_for('index'))
예제 #21
0
파일: main.py 프로젝트: balvinderz/uploader
def uploadtoimgur(path):
    #path = "testpic2.jpg"
    im = pyimgur.Imgur(CLIENT_ID)
    # print(authorization_url)
    #global refresh_token
    # if(refresh_token==""):
    # 3authorization_url = client.get_auth_url('code')
    # print(authorization_url)
    # credentials = client.authorize(, 'pin')

    uploaded_image = im.upload_image(path)
    print(uploaded_image.link)
    return uploaded_image.link
예제 #22
0
 def __init__(self, discordClient):
     self.bot = discordClient
     self.imgurClient = pyimgur.Imgur(client_id)
     self.db = 'guild_settings.db'
     self.table = 'settings'
     self.settings = {
         'guild_id': 'guild_id',
         'guild_name': 'guild_name',
         'commands_disabled': 'commands_disabled',
         'roll_channel': 'roll_channel',
         'osu_channel': 'osu_channel',
         'admin_role': 'admin_role'
     }
예제 #23
0
 def refresh_helpers(self, specific_helper=None):
     if (specific_helper
             and specific_helper == "client_id") or "client_id" in self.nv:
         self.im = pyimgur.Imgur(self.nv["client_id"])
     if (specific_helper and specific_helper
             == "youtube_api_key") or "youtube_api_key" in self.nv:
         self.youtube_api_key = self.nv["youtube_api_key"]
     if (specific_helper and specific_helper
             == "sqlite_path") or "sqlite_path" in self.nv:
         self.linkdb = sqlite3.connect(self.nv["sqlite_path"])
     if (specific_helper
             and specific_helper == "channel") or "channel" in self.nv:
         self.channel = self.nv["channel"]
예제 #24
0
def upload_image(Path):
    CLIENT_ID = "af3a88200ef32c0"
    im = pyimgur.Imgur(CLIENT_ID)

    for i in range(len(Path)):
        PATH = Path[i]
        title = str(i)
        uploaded_image = im.upload_image(PATH, title=title)
        Products.objects.create(title=uploaded_image.title,
                                link=uploaded_image.link,
                                size=uploaded_image.size,
                                filetype=uploaded_image.type,
                                deletehash=uploaded_image.deletehash)
def glucose_graph(food, ug):
    t = np.linspace(0, 180, 1801)
    plt.figure()
    plt.rcParams['savefig.dpi'] = 50  #图片像素
    plt.rcParams['figure.dpi'] = 50  #分辨率
    plt.title(food + "'s Glucose image")
    plt.plot(t, ug)
    plt.savefig('send.png')
    CLIENT_ID = "233a2069365aee6"
    PATH = "send.png"
    im = pyimgur.Imgur(CLIENT_ID)
    uploaded_image = im.upload_image(PATH, title="Glucose Image")
    print(uploaded_image.link)
    return uploaded_image.link
예제 #26
0
def stock_plot(CLIENT_ID, stock_id):

    stock_df = scrape_stock_price_f(stock_id)
    perf_df = scrape_busi_perf_f(stock_id)

    stock_name = stock_id  #+"_" + stock_list.loc[i,"NAME"]
    stock_df = Stock_f(stock_df, stock_name)
    stock_df.strategy_MACD_line()
    stock_df.plot_result(1, 0)

    PATH = "/tmp/stock_chart.jpg"
    im = pyimgur.Imgur(CLIENT_ID)
    uploaded_image = im.upload_image(PATH)
    return uploaded_image.link
예제 #27
0
def uploadImage(path, direction):
    CLIENT_ID = "d5e44e95a75c648"  #my account's key, found on https://imgur.com/account/settings/apps
    PATH = path
    im = pyimgur.Imgur(CLIENT_ID)
    uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur")

    print(uploaded_image.link)
    #Sends the request
    url = 'http://localhost:3000'
    response = requests.post(url,
                             data={
                                 'imgurLink': uploaded_image.link,
                                 'direction': direction
                             })
def upload_to_imgur(beehive_id,
                    imgur_cred_path='imgur_credits.json',
                    path_to_file='beehive/data/gif/capture.gif'):
    with open(imgur_cred_path) as imgur_credits_file:
        imgur_credits = eval(imgur_credits_file.read())

    imgur = pyimgur.Imgur(imgur_credits['imgurClientID'])
    image_title = 'MakersBeehive ' + str(
        beehive_id) + ' | ' + datetime.datetime.now().__str__()[:-7]
    uploaded_image = imgur.upload_image(path_to_file, title=image_title)
    image_link = uploaded_image.link
    print(f'>>>> image/gif uploaded at {image_link}')

    return image_link
예제 #29
0
 def save(self, *args, **kwargs):
     self.pagina_listapresentes = Pagina_ListaPresentes.objects.first()
     try:
         CLIENT_ID = "cdadf801dc167ab"
         bencode = b64encode(self.file.read())
         client = pyimgur.Imgur(CLIENT_ID)
         r = client._send_request('https://api.imgur.com/3/image',
                                  method='POST',
                                  params={'image': bencode})
         file = r['link']
         self.foto_url = file
     except (Exception, ):
         pass
     return super(ItemListaPresentes, self).save(*args, **kwargs)
예제 #30
0
    def __init__(self, **kwargs):
        self._subreddit = kwargs["subreddit"]

        self._reddit = PrawReddit(
            username=kwargs["username"],
            password=kwargs["password"],
            client_id=kwargs["app_id"],
            client_secret=kwargs["app_secret"],
            user_agent="Reddit processing bot"
        )
        self._pimg = pyimgur.Imgur(
            client_id = kwargs["pimg_id"],
            client_secret = kwargs["pimg_secret"]
        )