def generate_chart_one_data_set(dates, data_set): url = None LOGGER = logging.getLogger() LOGGER.setLevel(logging.INFO) try: qc = QuickChart() qc.width = 500 qc.height = 300 qc.device_pixel_ratio = 2.0 qc.config = { "type": "line", "data": { "labels": dates, "datasets": [{ "label": "Daily Deaths", "data": data_set }] }, "pointRadius": "0", "fill": "False" } url = qc.get_short_url() except Exception as ex: LOGGER.INFO(ex) finally: return url
def get_quick_chart(json_data, output_file): qc = QuickChart() qc.width = 500 qc.width = 500 labels = [] #Declare to hold the x-axis tick labels weather_readings = [] #get the data labels for index in range(1, 8): local_time = datetime.datetime.fromtimestamp( json_data['daily'][index]['dt'], tz=pytz.timezone('Asia/Singapore')) labels.append(local_time.strftime('%a %d/%m ')) weather_readings.append( round(json_data['daily'][index]['temp']['day'], 1)) qc.config = """{ type: 'line', data: { labels: """ + str(labels) + """, datasets: [ { backgroundColor: 'rgb(255, 99, 132)', data: """ + str(weather_readings) + """, lineTension: 0.4, fill: false, } ], }, options: { title: { display: true, text: '7-Day Weather Forecast' }, legend: { display: false}, scales: { yAxes: [ { scaleLabel: { display: true, labelString: 'Temperature Degrees Celcius' } } ]}, plugins: { datalabels: { display: true, align: 'bottom', backgroundColor: '#ccc', borderRadius: 3 }, } }, }""" print(qc.get_short_url()) #Print out the chart URL qc.to_file(output_file) #Save to a file
def sparkline(data): # generate image for badge qc = QuickChart() qc.width = 75 qc.height = 25 #qc.device_pixel_ratio = 2.0 qc.config = {"type": "sparkline", "data": {"datasets": [{"data": data}]}} url = qc.get_short_url() badge = requests.get(url).content # serve image with suitable cache control headers res = make_response(badge) res.headers.set('Content-Type', 'image/png') res.headers.set('Cache-Control', 'no-cache, no-store, must-revalidate, max-age=0') res.headers.set('Pragma', 'no-cache') res.headers.set('Expires', '0') return res
from quickchart import QuickChart qc = QuickChart() qc.config = { "type": "bar", "data": { "labels": ["Hello world", "Test"], "datasets": [{ "label": "Foo", # Count from 0 to 100 "data": list(range(0, 100)), }] } } print(qc.get_short_url()) # # Example output (note that this shortened URL is now expired and will not display a chart): # # https://quickchart.io/chart/render/f-b4bf9221-0499-4bc6-b1ae-6f7c78be9d93 #
async def get_profile_embed(bot, ctx, member, alt=False): if alt: tag = await tag_convertor(bot, ctx, member, alt=True) if tag is None: return badEmbed( "This user has no alt saved! Use [prefix]savealt <tag>") else: tag = await tag_convertor(bot, ctx, member) if tag is None: return badEmbed( "This user has no tag saved! Use [prefix]save <tag>") if tag == "": desc = "/p\n/profile @user\n/p discord_name\n/p discord_id\n/p #BSTAG" return discord.Embed(title="Invalid argument!", colour=discord.Colour.red(), description=desc) bs_cog = bot.get_cog("BrawlStarsCog") try: player = await bs_cog.ofcbsapi.get_player(tag) except brawlstats.errors.NotFoundError: return badEmbed("No player with this tag found, try again!") except brawlstats.errors.RequestError as e: return badEmbed("BS API ERROR: " + str(e)) except brawlstats.errors.RequestError as e: return badEmbed("BS API ERROR: " + str(e)) colour = player.name_color if player.name_color is not None else "0xffffffff" embed = discord.Embed(color=discord.Colour.from_rgb( int(colour[4:6], 16), int(colour[6:8], 16), int(colour[8:10], 16))) player_icon_id = player.raw_data["icon"]["id"] if bs_cog.icons is None: bs_cog.icons = await bs_cog.starlist_request( "https://api.brawlapi.com/v1/icons") try: player_icon = bs_cog.icons['player'][str(player_icon_id)]['imageUrl2'] except: if type(member) is discord.Member: player_icon = member.avatar_url else: player_icon = None if player_icon == "none": player_icon = None embed.set_author(name=f"{player.name} {player.raw_data['tag']}", icon_url=player_icon) embed.add_field( name="Trophies", value=f"{get_league_emoji(player.trophies)} {player.trophies}") embed.add_field( name="Highest Trophies", value= f"{get_league_emoji(player.highest_trophies)} {player.highest_trophies}" ) embed.add_field(name="Level", value=f"<:exp:614517287809974405> {player.exp_level}") star_powers = sum([len(x.star_powers) for x in player.brawlers]) gadgets = sum([len(x['gadgets']) for x in player.raw_data['brawlers']]) embed.add_field( name="Unlocked Brawlers", value= f"<:brawlers:614518101983232020> {len(player.brawlers)} <:star_power:729732781638156348> {star_powers} <:gadget:716341776608133130> {gadgets}" ) if "tag" in player.raw_data["club"]: try: club = await bs_cog.ofcbsapi.get_club(player.club.tag) embed.add_field( name="Club", value= f"{bs_cog.get_badge(club.raw_data['badgeId'])} {player.club.name}" ) for m in club.members: if m.tag == player.raw_data['tag']: embed.add_field( name="Role", value= f"<:role:614520101621989435> {m.role.capitalize()}") break except brawlstats.errors.RequestError: embed.add_field( name="Club", value=f"<:bsband:600741378497970177> {player.club.name}") embed.add_field( name="Role", value= f"<:offline:642094554019004416> Error while retrieving role") else: embed.add_field(name="Club", value=f"<:noclub:661285120287834122> Not in a club") embed.add_field( name="3v3 Wins", value= f"{get_gamemode_emoji(get_gamemode_id('gemgrab'))} {player.raw_data['3vs3Victories']}" ) embed.add_field( name="Showdown Wins", value= f"{get_gamemode_emoji(get_gamemode_id('showdown'))} {player.solo_victories} {get_gamemode_emoji(get_gamemode_id('duoshowdown'))} {player.duo_victories}" ) rr_levels = ["-", "Normal", "Hard", "Expert", "Master", "Insane"] if player.best_robo_rumble_time > 5: rr_level = f"Insane {player.best_robo_rumble_time - 5}" else: rr_level = rr_levels[player.best_robo_rumble_time] embed.add_field( name="Best RR Level", value=f"{get_gamemode_emoji(get_gamemode_id('roborumble'))} {rr_level}" ) #embed.add_field( # name="Best Time as Big Brawler", # value=f"<:biggame:614517022323245056> {player.best_time_as_big_brawler//60}:{str(player.best_time_as_big_brawler%60).rjust(2, '0')}") if "highestPowerPlayPoints" in player.raw_data: value = f"{player.raw_data['highestPowerPlayPoints']}" embed.add_field(name="Highest PP Points", value=f"<:powertrophies:661266876235513867> {value}") reset = reset_trophies(player) - player.trophies embed.add_field( name="Season Reset", value= f"<:bstrophy:552558722770141204> {reset} <:starpoint:661265872891150346> {calculate_starpoints(player)}" ) emo = "<:good:450013422717763609> Qualified" if player.raw_data[ 'isQualifiedFromChampionshipChallenge'] else "<:bad:450013438756782081> Not qualified" embed.add_field(name="Championship", value=f"{emo}") # try: # log = (await bs_cog.ofcbsapi.get_battle_logs(player.raw_data['tag'])).raw_data # plsolo = None # plteam = None # for battle in log: # if "type" in battle['battle']: # if battle['battle']['type'] == "soloRanked" and plsolo is None: # for play in (battle['battle']['teams'][0]+battle['battle']['teams'][1]): # if play['tag'] == player.raw_data['tag']: # plsolo = play['brawler']['trophies'] # break # if battle['battle']['type'] == "teamRanked" and plteam is None: # for play in (battle['battle']['teams'][0]+battle['battle']['teams'][1]): # if play['tag'] == player.raw_data['tag']: # plteam = play['brawler']['trophies'] # break # if plsolo is not None and plteam is not None: # break # lastsolo = 0 # lastteam = 0 # if plsolo is not None: # await bs_cog.config.user(member).plsolo.set(plsolo) # await bs_cog.config.user(member).lastsolo.set(int(datetime.datetime.timestamp(datetime.datetime.now()))) # elif isinstance(member, discord.Member): # lastsolo = await bs_cog.config.user(member).lastsolo() # if (datetime.datetime.now() - datetime.datetime.fromtimestamp(lastsolo)).days > 0: # plsolo = await bs_cog.config.user(member).plsolo() # if plteam is not None: # await bs_cog.config.user(member).plteam.set(plteam) # await bs_cog.config.user(member).lastteam.set(int(datetime.datetime.timestamp(datetime.datetime.now()))) # elif isinstance(member, discord.Member): # lastteam = await bs_cog.config.user(member).lastteam() # if (datetime.datetime.now() - datetime.datetime.fromtimestamp(lastteam)).days > 0: # plteam = await bs_cog.config.user(member).plteam() # if plsolo is not None: # embed.add_field(name="Current Solo League", value=get_power_league(plsolo)) # if plteam is not None: # embed.add_field(name="Current Team League", value=get_power_league(plteam)) # except: # pass texts = [ "Check out all your brawlers using /brawlers!", "Want to see your club stats? Try /club!", "Have you seen all our clubs? No? Do /clubs!", "You can see stats of other players by typing /p @user.", "You can display player's stats by using his tag! /p #TAG", "Did you know LA Bot can display CR stats as well? /crp", "Check www.laclubs.net to see all our clubs!" ] if "name" in player.raw_data["club"] and player.raw_data["club"][ "name"].startswith("LA "): try: history_url = "https://laclubs.net/api/history/player?tag=" + player.raw_data[ 'tag'].strip("#") data = None chart_data = [] async with aiohttp.ClientSession(connector=aiohttp.TCPConnector( ssl=True)) as session: async with session.get(history_url) as resp: data = await resp.json() if data is not None and data['status'] == "ok": one_day = int( datetime.datetime.timestamp(datetime.datetime.now() - datetime.timedelta(hours=24))) one_week = int( datetime.datetime.timestamp(datetime.datetime.now() - datetime.timedelta(days=7))) stats = "" for time in data['times']: if time > one_day: day_diff = player.trophies - data['trophies'][ data['times'].index(time)] if day_diff >= 0: stats += f"<:stonks:841606734066090015> **1 day** +{day_diff}\n" else: stats += f"<:stinks:841606733997670430> **1 day** {day_diff}\n" break for time in data['times']: if time > one_week: week_diff = player.trophies - data['trophies'][ data['times'].index(time)] if week_diff >= 0: stats += f"<:stonks:841606734066090015> **1 week** +{week_diff}\n" else: stats += f"<:stinks:841606733997670430> **1 week** {week_diff}\n" break if stats != "": embed.add_field(name="Trophy Progression", value=stats, inline=False) for time, trophies in zip( data['times'][:-20:4] + data['times'][-20::2], data['trophies'][:-20:4] + data['trophies'][-20::2]): chart_data.append("{t:new Date(" + str(time * 1000) + "),y:" + str(trophies) + "}") chart_data.append("{t:new Date(" + str( int( datetime.datetime.timestamp(datetime.datetime.now()) * 1000)) + "),y:" + str(player.trophies) + "}") qc = QuickChart() qc.config = """ { type: 'line', data: { datasets: [{ data : """ + str(chart_data).replace("\'", "") + """, label: "trophies", fill: true, cubicInterpolationMode: 'monotone', borderColor: 'rgba(10, 180, 20, 1)', backgroundColor: 'rgba(10, 180, 20, 0.3)' }] }, options: { scales: { xAxes: [{ type: 'time', time: { unit: 'day' }, distribution: 'linear' }] }, responsive: false, legend: { display: false }, tooltips: { mode: 'index', intersect: false }, title: { display: false, text: 'TROPHY PROGRESSION', fontStyle: 'bold' }, layout: { padding: { left: 5, right: 10, top: 0, bottom: 5 } } } } """ embed.set_image(url=qc.get_short_url()) except (aiohttp.client_exceptions.ContentTypeError): pass embed.set_footer(text=random.choice(texts)) return embed
def get_chart(symbol, duration): """Fetches Finnhub candle data and creates a chart using QuickChart.io API""" start = math.trunc(time.time()) stop = 0.0 resoultion = '' res_long = '' step = 60 if duration.lower().strip( ) == 'd': # sets some variables to be used later based on chart duration stop = math.trunc(time.time() - (86400 * 1)) resolution = '1' res_long = 'Day' step = 60 * 1 elif duration.lower().strip() == 'w': stop = math.trunc(time.time() - (86400 * 7)) resolution = '5' res_long = 'Week' step = 60 * 5 elif duration.lower().strip() == 'm': stop = math.trunc(time.time() - (86400 * 30)) resolution = '30' res_long = 'Month' step = 60 * 30 elif duration.lower().strip() == 'y': stop = math.trunc(time.time() - (86400 * 365)) resolution = 'D' res_long = 'Year' step = 60 * 1440 else: return 'invalid_duration' r = requests.get( f'https://finnhub.io/api/v1/stock/candle?symbol={symbol.upper()}&resolution={resolution}&from={stop-86400}&to={start-86400}&token={API_KEY}' ) json = r.json() # print(json) FIX THIS # print(datetime.datetime.today().weekday()) #Test this over a weekend if json == {'s': 'no_data'} or json['s'] == 'no_data': if datetime.datetime.today().weekday() >= 5: return 'invalid_weekend' else: return 'invalid_symbol' r2 = requests.get( f'https://finnhub.io/api/v1/stock/profile2?symbol={symbol.upper()}&token={API_KEY}' ) # Gets company name. Makes two API calls, could be removed if needed json2 = r2.json() name = json2['name'] data = json['c'] # stock price (close) data lables = [ time.strftime('%b %d %H:%M', datetime.fromtimestamp(i).timetuple()) for i in json['t'] ] # lables for x axis qc = QuickChart() qc.width = 700 qc.height = 500 qc.device_pixel_ratio = 1.0 qc.background_color = '#ffffff' qc.config = { # configuration data for chart formatting. See https://www.chartjs.org/. "type": "line", "data": { "labels": lables, "datasets": [{ "data": data, "fill": "false", "spanGaps": True, "pointRadius": 0, "showLine": True, "borderWidth": 2.5, "borderColor": "#000000" }] }, "options": { "title": { "display": True, "text": f"{symbol.upper()} ({name}) {res_long} Price Chart", "fontSize": 18, "fontFamily": "Helvetica", "fontColor": "#000000" }, "legend": { "display": False, }, "scales": { "xAxes": [{ "scaleLabel": { "display": True, "labelString": "Date" }, }], "yAxes": [{ "scaleLabel": { "display": True, "labelString": "US Dollars" }, "ticks": { "suggestedMin": .95 * min(data), "suggestedMax": 1.05 * max(data) }, }] } } } return qc.get_short_url()
async def bitcoin(self, ctx, mode=None, amount=None): if stocks_up: await open_account(ctx.author) user = ctx.author users = await get_bank_data() bal = await update_bank(ctx.author) if mode == None: await ctx.send( f'{ctx.author.mention}: You must specify if you want to view or sell' ) elif mode == 'view': if amount == None: amount = '14' amount = int(amount) if amount < 0: await ctx.send( f'{ctx.author.mention}: Only positive numbers allowed') elif amount > 100: await ctx.send( f'{ctx.author.mention}: You cannot go past 100 days') else: btc_prices = [] label_count = [] for i in range(amount, 0, -1): label_count.append(str(btc.index.date[i])) btc_prices.append(btc['1a. open (CAD)'][i]) qc = QuickChart() qc.width = 500 qc.height = 300 qc.background_color = 'white' qc.device_pixel_ratio = 2.0 qc.config = { "type": "line", "data": { "labels": label_count, "datasets": [{ "label": "BTC", "data": btc_prices, "fill": False, "borderColor": 'orange' }] } } bitcoin_chart = qc.get_short_url() em = discord.Embed(title=f"Price of Bitcoin", color=discord.Color.orange()) em.set_image(url=bitcoin_chart) em.add_field(name='BTC', value=f'Prices for the last {amount} days', inline=False) em.add_field(name='Current Price', value='```%sMM```' % bitcoin_price, inline=False) await ctx.send(embed=em) elif mode == 'sell': await open_account(ctx.author) if amount == None: await ctx.send( f"{ctx.author.mention}: Please enter the amount") return bal = await update_bank(ctx.author) if amount == 'all': amount = bal[6] amount = float(amount) earnings = int(amount * bitcoin_price) if amount > bal[6]: await ctx.send( f"{ctx.author.mention}: You don't have that much bitcoin" ) return if amount < 0: await ctx.send( f"{ctx.author.mention}: You must enter a positive number" ) return await ctx.send( f"{ctx.author.mention}: You sold {amount} bitcoin and earned {earnings}MM" ) await update_bank(ctx.author, -1 * amount, 'bitcoin') await update_bank(ctx.author, earnings, 'bank') else: await ctx.send( f'{ctx.author.mention}: That option doesn\'t exist') else: await ctx.send( 'Stock API is down for now. Reload in a minute and try again.')