<commit_before>import discord
from discord.ext import commands
from .utils import checks
from cogs.utils.dataIO import dataIO, fileIO
from __main__ import send_cmd_help


import json
import os
import asyncio
import aiohttp
import datetime
import random
import time

try: # check if BeautifulSoup4 is installed
	from bs4 import BeautifulSoup
	soupAvailable = True
except:
	soupAvailable = False


class APIError(Exception):
	pass

class ShinyAPIError(Exception):
	pass

class APIKeyError(Exception):
	pass

class Gw2:
	"""This cog finds tp prices"""

	def __init__(self, bot):
		self.bot = bot
		self.session = aiohttp.ClientSession(loop=self.bot.loop)
		self.gemtrack = dataIO.load_json("data/gw2/gemtrack.json")

	def save_gemtrack(self):
		dataIO.save_json("data/gw2/gemtrack.json", self.gemtrack)
	
	async def getGemPrice(self, numberOfGems : int = 400):
		try:
			endpoint = "commerce/exchange/coins?quantity=10000000"
			gemsresult = await self.call_api(endpoint)
		except APIKeyError as e:
			await self.bot.say(e)
			return 0
		
		gemCost = gemsresult['coins_per_gem']*numberOfGems
		return gemCost

	@commands.command(pass_context=True)
	async def trackgems(self, ctx, price : int):
		"""This requests to be notified when the cost of 400 gems drops below a specified price"""
		user = ctx.message.author
		color = self.getColor(user)
		
		self.gemtrack[user.id] = { "user_id": user.id, "price": price }
		self.save_gemtrack()
		
		await self.bot.say("{0.mention}, you'll be notified when the price of 400 gems drops below {1}".format(user, self.gold_to_coins(price)))

	# tracks gemprices and notifies people
	async def _gemprice_tracker(self):
		while self is self.bot.get_cog("Gw2"):
			gemCost = await self.getGemPrice()
			user = await self.bot.get_user_info(99253329003044864)
			await self.bot.send_message(user, "Hey, {0}. Gem prices are currently {1}!".format(user.name, self.gold_to_coins(gemCost)))
			
			doCleanup = False
			
			if gemCost != 0:
				for user_id, data in self.gemtrack.items():
					if gemCost < data["price"]:
						user = await self.bot.get_user_info(user_id)
						await self.bot.send_message(user, "Hey, {0.mention}. Gem prices have dropped below {1}!".format(user, data["price"]))
						self.gemtrack[user_id]["price"] = 0
						doCleanup = True;
			
				if doCleanup:
					keys = [k for k, v in self.gemtrack.items() if v["price"] == 0]
					for x in keys:
						del self.gemtrack[x]
					self.save_gemtrack()
			
			await asyncio.sleep(60)

	@commands.command(pass_context=True)
	async def tpdata(self, ctx, *, tpitemname: str):
		"""This finds the current buy and sell prices of an item
		If multiple matches are found, displays the first"""
		user = ctx.message.author
		tpitemname = tpitemname.replace(" ", "%20")
		color = self.getColor(user)
		try:
			shiniesendpoint = tpitemname
			shiniesresults = await self.call_shiniesapi(shiniesendpoint)
			itemnameresult = shiniesresults[0]["name"]
			tpbuyid = shiniesresults[0]["item_id"]
			commerce = 'commerce/prices/'
			endpoint = commerce + tpbuyid
			results = await self.call_api(endpoint)
		except APIKeyError as e:
			await self.bot.say(e)
			return
		except ShinyAPIError as e:
			await self.bot.say("{0.mention}, API has responded with the following error: "
							   "`{1}`".format(user, e))
			return
		except APIError as e:
			data = discord.Embed(description='I was unable to match that to an item on the TP , listing all - use !tpid (id) to select one', colour=color)
			#For each item returned, add to the data table
			counter = 0
			for name in shiniesresults:
				if counter < 10:
					data.add_field(name=name['name'], value=name['item_id'])
					counter += 1	<commit_msg>gemprice tracker improvements<commit_after>import discord
from discord.ext import commands
from .utils import checks
from cogs.utils.dataIO import dataIO, fileIO
from __main__ import send_cmd_help


import json
import os
import asyncio
import aiohttp
import datetime
import random
import time

try: # check if BeautifulSoup4 is installed
	from bs4 import BeautifulSoup
	soupAvailable = True
except:
	soupAvailable = False


class APIError(Exception):
	pass

class ShinyAPIError(Exception):
	pass

class APIKeyError(Exception):
	pass

class Gw2:
	"""This cog finds tp prices"""

	def __init__(self, bot):
		self.bot = bot
		self.session = aiohttp.ClientSession(loop=self.bot.loop)
		self.gemtrack = dataIO.load_json("data/gw2/gemtrack.json")
		
	def __unload(self):
		self.session.close()

	def save_gemtrack(self):
		dataIO.save_json("data/gw2/gemtrack.json", self.gemtrack)
	
	async def getGemPrice(self, numberOfGems : int = 400):
		try:
			endpoint = "commerce/exchange/coins?quantity=10000000"
			gemsresult = await self.call_api(endpoint)
		except APIKeyError as e:
			await self.bot.say(e)
			return 0
		
		gemCost = gemsresult['coins_per_gem']*numberOfGems
		return gemCost

	@commands.command(pass_context=True)
	async def trackgems(self, ctx, price : int):
		"""This requests to be notified when the cost of 400 gems drops below a specified price"""
		user = ctx.message.author
		color = self.getColor(user)
		
		self.gemtrack[user.id] = { "user_id": user.id, "price": price }
		self.save_gemtrack()
		
		await self.bot.say("{0.mention}, you'll be notified when the price of 400 gems drops below {1}".format(user, self.gold_to_coins(price)))

	# tracks gemprices and notifies people
	async def _gemprice_tracker(self):
		while self is self.bot.get_cog("Gw2"):
			gemCost = await self.getGemPrice()			
			doCleanup = False
			
			if gemCost != 0:
				for user_id, data in self.gemtrack.items():
					if gemCost < data["price"]:
						user = await self.bot.get_user_info(user_id)
						await self.bot.send_message(user, "Hey, {0.mention}! The price of 400 gems has dropped to {1}.".format(user, self.gold_to_coins(gemCost)))
						self.gemtrack[user_id]["price"] = 0
						doCleanup = True;
			
				if doCleanup:
					keys = [k for k, v in self.gemtrack.items() if v["price"] == 0]
					for x in keys:
						del self.gemtrack[x]
					self.save_gemtrack()
			
			await asyncio.sleep(300)

	@commands.command(pass_context=True)
	async def tpdata(self, ctx, *, tpitemname: str):
		"""This finds the current buy and sell prices of an item
		If multiple matches are found, displays the first"""
		user = ctx.message.author
		tpitemname = tpitemname.replace(" ", "%20")
		color = self.getColor(user)
		try:
			shiniesendpoint = tpitemname
			shiniesresults = await self.call_shiniesapi(shiniesendpoint)
			itemnameresult = shiniesresults[0]["name"]
			tpbuyid = shiniesresults[0]["item_id"]
			commerce = 'commerce/prices/'
			endpoint = commerce + tpbuyid
			results = await self.call_api(endpoint)
		except APIKeyError as e:
			await self.bot.say(e)
			return
		except ShinyAPIError as e:
			await self.bot.say("{0.mention}, API has responded with the following error: "
							   "`{1}`".format(user, e))
			return
		except APIError as e:
			data = discord.Embed(description='I was unable to match that to an item on the TP , listing all - use !tpid (id) to select one', colour=color)
			#For each item returned, add to the data table
			counter = 0
			for name in shiniesresults:
				if counter < 10:
					data.add_field(name=name['name'], value=name['item_id'])
					counter += 1	
{'fraction_non_alphanumeric': 0.10985838031073834, 'fraction_numerical': 0.014986937989825382, 'mean_word_length': 3.944935418082937, 'pattern_counts': {'":': 4, '<': 7, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '850951', 'n_tokens_mistral': 2848, 'n_tokens_neox': 2428, 'n_words': 697}