Ejemplo n.º 1
0
    def __init__(self, start_seq, end_seq):
        api.set_api_key(API_KEY)

        # start and end sequence number
        self.start_seq = start_seq
        self.end_seq = end_seq

        # total games
        self.total_games = 0
        # total slected game
        self.total_selected_games = 0
        # total yasp games
        self.yasp_games = 0
        # logging
        self.logger = logging.getLogger('dota2')
        self.logger.setLevel(logging.INFO)
        # create file handler which logs even debug messages
        fh = logging.FileHandler('log/%s.txt' % start_seq)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)
        # init mongo client
        client = MongoClient()
        self.collection = client.Dota2.matches
Ejemplo n.º 2
0
def Api(api_key=None):
    global _dotaApi
    if not _dotaApi and api_key:
        api.set_api_key(api_key)
        return api
    else:
        return api
Ejemplo n.º 3
0
def setup():
    '''Setup the API, etc.'''
    logger.setLevel(logging.DEBUG)

    API_KEY = os.getenv('DOTABOT_API_KEY')
    if not API_KEY:
        raise NameError('Please set the DOTABOT_API_KEY environment variables.')
    api.set_api_key(API_KEY)
Ejemplo n.º 4
0
 def __init__(self, chave, game_mode=(1,2), skill=3, info_heroi=("gold_per_min", "xp_per_min")):
     api.set_api_key(chave)
     self.info_heroi = info_heroi
     self.game_mode = game_mode
     self.skill = skill
     self.herois = self.faz_tabela_herois()
     self.colunas = self.faz_todas_colunas()
     self.dados = pd.DataFrame()
Ejemplo n.º 5
0
def setup():
    '''Setup the API, MongoDB connection, etc.'''
    logger.setLevel(logging.DEBUG)

    API_KEY = os.getenv('DOTABOT_API_KEY')
    if not API_KEY:
        raise NameError('Please set the DOTABOT_API_KEY environment variables.')
    api.set_api_key(API_KEY)
Ejemplo n.º 6
0
    def __init__(self):
        token_dir = str(os.path.dirname(os.path.abspath(__file__)))
        self.steam_token_file = token_dir + '/steam_token.txt'
        self.steam_token = open(self.steam_token_file, 'r').read().strip()
        dota_api.set_api_key(self.steam_token)

        self.heroes = ''

        self.loadHeroesJson()
Ejemplo n.º 7
0
def setup():
    '''Setup the API, etc.'''
    logger.setLevel(logging.DEBUG)

    #API_KEY = os.getenv('DOTABOT_API_KEY')
    API_KEY = '8F002160EB2A8474EBC95F9CAAA24A1F'
    if not API_KEY:
        raise NameError(
            'Please set the DOTABOT_API_KEY environment variables.')
    api.set_api_key(API_KEY)
Ejemplo n.º 8
0
def setup(bot):
	if dotaAvailable is False:
		raise RuntimeError("You don't have dota2py installed, run\n```pip3 install dota2py```And try again")
		return
	if not key:
		raise RuntimeError("Please set the DOTA2_API_KEY environment variable")
		return
	if tabulateAvailable is False:
		raise RuntimeError("You don't have dota2py installed, run\n```pip3 install tabulate```And try again")
		return
	api.set_api_key(key)
	bot.add_cog(Dota(bot))
Ejemplo n.º 9
0
    def __init__(self, skill,
                 public=None, league=None, team=None, solo=None, ranked=None,
                 ap=None, cm=None, ar=None, rap=None):
        self._skill = skill

        self._public = public
        self._league = league
        self._team = team
        self._solo = solo
        self._ranked = ranked
        self._ap = ap
        self._ar = ar
        self._cm = cm
        self._rap = rap

        api_key = "6A4B23E0046B2FCFAAFD91E8B30904FA"
        api.set_api_key(api_key)
Ejemplo n.º 10
0
def load_data(key, dest, start_point, num):
    api.set_api_key(key)
    match_id = start_point
    store = [];
    count = 0;
    file_index = 0;
    valid_mode = [0, 1, 2, 3, 4, 5]
    for i in range(num):
        try:
            match = api.get_match_details(match_id + i)["result"]
            if match["game_mode"] in valid_mode:
                match_collection.insert(match)
        except:
            continue

        if i% 500 == 0:
            print ("finished ", i)
Ejemplo n.º 11
0
	async def setkey(self, ctx, key):
		"""Sets the Dota 2 Wep API key (PM ONLY)"""

		# Perform the PM check
		if ctx.message.channel.is_private:

			self.dota_settings["key"] = key.strip()
			fileIO("data/dota/settings.json", "save", self.dota_settings)

			# Set the client's API key
			api.set_api_key(self.dota_settings["key"])

			# Change the current key status
			self.key = True

			await self.bot.say("Key saved and applied")
		else:
			await self.bot.say("Please run this command in PM")
Ejemplo n.º 12
0
    async def setkey(self, ctx, key):
        """Sets the Dota 2 Wep API key (PM ONLY)"""

        # Perform the PM check
        if ctx.message.channel.is_private:

            self.dota_settings["key"] = key.strip()
            fileIO("data/dota/settings.json", "save", self.dota_settings)

            # Set the client's API key
            api.set_api_key(self.dota_settings["key"])

            # Change the current key status
            self.key = True

            await self.bot.say("Key saved and applied")
        else:
            await self.bot.say("Please run this command in PM")
Ejemplo n.º 13
0
	def __init__(self, bot):
		self.bot = bot
		self.dota_settings = fileIO("data/dota/settings.json", "load")

		# Check for key either in settings or in ENV
		if "key" in self.dota_settings.keys() and self.dota_settings["key"] != "":

			# If exists in setting and is set
			api.set_api_key(self.dota_settings["key"])
			self.key = True

		elif os.environ.get("DOTA2_API_KEY") is not None:

			# If exists in env vars and is set
			api.set_api_key(os.environ.get("DOTA2_API_KEY"))
			self.key = True

		else:
			self.key = False
Ejemplo n.º 14
0
	def __init__(self, bot):
		self.bot = bot
		self.dota_settings = fileIO("data/dota/settings.json", "load")

		# Check for key either in settings or in ENV
		if "key" in self.dota_settings.keys() and self.dota_settings["key"] != "":

			# If exists in setting and is set
			api.set_api_key(self.dota_settings["key"])
			self.key = True

		elif os.environ.get("DOTA2_API_KEY") is not None:

			# If exists in env vars and is set
			api.set_api_key(os.environ.get("DOTA2_API_KEY"))
			self.key = True

		else:
			self.key = False
Ejemplo n.º 15
0
def LOAD(data_folder):
    data = new_load_data(data_folder)
    add_lineups(data)
    add_players(data)
    teams_df, teams, teams_inversed = construct_teams(data)
    data = data.drop(get_dull_columns(), axis=1)
    data = data.drop(get_useless_columns(), axis=1)
    
    regenerate_list_of_match(data_folder)
    
    API_KEY = '0DED3F75E799ED36033051911B23BD79'
    api.set_api_key(API_KEY)
    final_matches = pd.read_csv(os.path.join(data_folder, "final_matches_id.csv"), header=None, names=[0, 'match_id'])
    final_matches_data = []
    for match_id_ in final_matches['match_id']:
        final_matches_data.append(api.get_match_details(match_id=match_id_)['result'])

    data = append_data(data, final_matches_data)
    
    return data
Ejemplo n.º 16
0
    def __init__(self, client):
        Module.__init__(self, 'PredictGame', client)
        # set the api key using the config
        api.set_api_key(config['steamApi'])

        # initialize the predictions field
        self.predictions = defaultdict(lambda: {'predictions': {}, 'info': None})

        # cached league names
        self.league_cache = {}

        # mongo setup
        self.dbclient = pymongo.MongoClient('localhost', 27017)
        self.db = self.dbclient['botdooder']
        self.fredpoints = self.db['fredpoints']

        # default channel
        self.default_channel = None

        # start the 60 second status check loop
        self.client.loop.create_task(self.check_game_status())
Ejemplo n.º 17
0
    def __init__(self, league_id):
        api.set_api_key(API_KEY)

        # start and end sequence number
        self.league_id = league_id
        self.current_match_id = None

        # total games
        self.total_games = 0
        # total slected game
        self.total_selected_games = 0
        # total yasp games
        self.yasp_games = 0
        # logging
        self.logger = logging.getLogger('dota2')
        self.logger.setLevel(logging.INFO)
        # create file handler which logs even debug messages
        fh = logging.FileHandler('log/league_%s.txt' % league_id)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)
        # init mongo client
        client = MongoClient()
        self.collection = client.Dota2.matches
Ejemplo n.º 18
0
 def setUp(self):
     key = os.environ.get("DOTA2_API_KEY")
     if not key:
         raise NameError("Please set the DOTA2_API_KEY environment variable")
     api.set_api_key(key)
Ejemplo n.º 19
0
    def run(self):
        api.set_api_key(self.steam_api_key)
        hist = api.get_match_history(account_id=self.steamid)['result']
        recent_matches = []
        while len(recent_matches) < self.matches:
            recent_matches.append(hist['matches'].pop(0))

        player_team_per_match = []
        # create a list of tuples where each tuple is:
        # [match_id, bool]
        # The bool will be true if the player is on Radiant and alse if they
        # are on Dire.
        for match in recent_matches:
            this_match = [match['match_id']]
            for player in match['players']:
                # 64bit player ID
                long_id = player['account_id'] + 76561197960265728
                if long_id == self.steamid:
                    if player['player_slot'] < 128:
                        this_match.append(True)
                    else:
                        this_match.append(False)
            player_team_per_match.append(this_match)

        outcomes = []
        for match in player_team_per_match:
            if api.get_match_details(match[0])['result']['radiant_win'] == match[1]:
                outcomes.append(1)
            else:
                outcomes.append(0)

        wins = outcomes.count(1)
        losses = outcomes.count(0)
        win_percent = float(sum(outcomes) / float(len(outcomes))) * 100

        if win_percent >= float(self.good_threshold):
            color = self.good_color
        elif win_percent <= float(self.bad_threshold):
            color = self.bad_color
        else:
            color = self.caution_color

        if self.screenname == 'retrieve':
            from urllib.request import urlopen
            import json
            response = urlopen(
                'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=%s&steamids=%s' %
                (self.steam_api_key, self.steamid))
            screenname = json.loads(bytes.decode(response.read()))['response']['players'][0]['personaname']
        else:
            screenname = self.screenname

        cdict = {
            "screenname": screenname,
            "wins": wins,
            "losses": losses,
            "win_percent": "%.2f" % win_percent,
        }

        self.output = {
            "full_text": self.format.format(**cdict),
            "color": color
        }
Ejemplo n.º 20
0
    def update_dota(self):
         # Get a list of recent matches for the player
        total_added = 0
        api.set_api_key(AbstractResponse.key)
        current_time = int(time.time())
        last_update_time = AbstractResponse.get_last_update_time()
        new_records = ""
        for name, account_id in AbstractResponse.GroupMetoDOTA.items():
            print "Starting: {0}".format(name)
            # Get a list of recent matches for the player

            matches = api.get_match_history(account_id=account_id)["result"]["matches"]

            #Go through every match
            for match in matches:
                print "\tChecking: " + str(match["match_id"])

                if match["start_time"] < last_update_time["last_update"]:
                    print "\tWe've seen these matches"
                    break

                if (not AbstractResponse.has_dotaMatch(match["match_id"])):
                    single_match = api.get_match_details(match["match_id"])["result"]
                    print "\t\tAdding: " + str(single_match["match_id"])
                    AbstractResponse.add_dotaMatch(single_match)
                    total_added += 1

                    #Did this match set any new records# ?
                    for player in single_match["players"]:
                        #Is this a player we are tracking?
                        if AbstractResponse.has_dotaID_num(int(player["account_id"])):
                            #Yes! Check if they broke a record
                            old_record = AbstractResponse.get_record(player["hero_id"])
                            print player["hero_id"]
                            hero_dict = data.get_hero_name(player["hero_id"])
                            if not hero_dict:
                                print("For hero id = {}, not in dota2py".format(player["hero_id"]))
                                continue
                            hero_name = data.get_hero_name(player["hero_id"])["localized_name"]
                            player_name = AbstractResponse.dotaID_to_name(int(player["account_id"]))

                            if old_record is None:

                                #this is auto a new record!
                                new_record = {"hero_id": player["hero_id"],
                                              "max_kills": player["kills"],
                                              "max_kills_player": player["account_id"],
                                              "max_deaths": player["deaths"],
                                              "max_deaths_player": player["account_id"],
                                              "max_GPM": player["gold_per_min"],
                                              "max_GPM_player": player["account_id"],
                                              "min_GPM": player["gold_per_min"],
                                              "min_GPM_player": player["account_id"],
                                              "max_XPM": player["xp_per_min"],
                                              "max_XPM_player": player["account_id"],
                                              "min_XPM": player["xp_per_min"],
                                              "min_XPM_player": player["account_id"],
                                              }
                                AbstractResponse.set_record(new_record)

                            else:
                                #There is an existing record.. Lets see if this match was a game changer
                                new_record = old_record.copy()

                                if old_record["max_kills"] < player["kills"]:
                                    new_records += "{0} just got {1} kills with {2}, a new record!\n".format(player_name, player["kills"], hero_name )
                                    new_record["max_kills"] = player["kills"]
                                    new_record["max_kills_player"] = player["account_id"]

                                if old_record["max_deaths"] < player["deaths"]:
                                    new_records += "{0} just got {1} deaths with {2}, a new low!\n".format(player_name, player["deaths"], hero_name )
                                    new_record["max_deaths"] = player["deaths"]
                                    new_record["max_deaths_player"] = player["account_id"]

                                if old_record["max_GPM"] < player["gold_per_min"]:
                                    new_records += "{0} just got {1} GPM with {2}, a new record!\n".format(player_name, player["gold_per_min"], hero_name )
                                    new_record["max_GPM"] = player["gold_per_min"]
                                    new_record["max_GPM_player"] = player["account_id"]

                                if old_record["min_GPM"] > player["gold_per_min"]:
                                    new_records += "{0} just got {1} GPM with {2}, a new low!\n".format(player_name, player["gold_per_min"], hero_name )
                                    new_record["min_GPM"] = player["gold_per_min"]
                                    new_record["min_GPM_player"] = player["account_id"]

                                if old_record["max_XPM"] < player["xp_per_min"]:
                                    new_records += "{0} just got {1} XPM with {2}, a new record!\n".format(player_name, player["xp_per_min"], hero_name )
                                    new_record["max_XPM"] = player["xp_per_min"]
                                    new_record["max_XPM_player"] = player["account_id"]

                                if old_record["min_XPM"] > player["xp_per_min"]:
                                    new_records += "{0} just got {1} XPM with {2}, a new low!\n".format(player_name, player["xp_per_min"], hero_name )
                                    new_record["min_XPM"] = player["xp_per_min"]
                                    new_record["min_XPM_player"] = player["account_id"]

                                AbstractResponse.set_record(new_record)

                else:
                    print "\t Was Duplicate"

            print "Updated {0} Matches".format(total_added)
        if last_update_time == None:
            time_dict = {'last_update' : current_time}
        else:
            time_dict = last_update_time.copy()
            time_dict["last_update"] = current_time
        AbstractResponse.set_last_update_time(time_dict)
        return new_records
Ejemplo n.º 21
0
import sys
from os.path import abspath, join, dirname
import os

# Some path fiddling to make sure we can access the module
sys.path.append(abspath(join(abspath(dirname(__file__)), "..")))

from dota2py import api

key = os.environ.get("DOTA2_API_KEY")
if not key:
    raise NameError("Please set the DOTA2_API_KEY environment variable")
api.set_api_key(key)

# Get all the most recent match played by the player 'acidfoo'
account_id = int(api.get_steam_id("acidfoo")["response"]["steamid"])

# Get a list of recent matches for the player
matches = api.get_match_history(account_id=account_id)["result"]["matches"]

# Get the full details for a match
match = api.get_match_details(matches[0]["match_id"])
print 'Match information:\n%s' % (match, )
Ejemplo n.º 22
0
# Connect to MongoDB and authenticate to the Dota2 database
client = MongoClient()
db = client.dota2
db.authenticate('dota2', 'dota2')

# TODO
# Fetch all matches through match history and then update db.ti5_matches

# get all match ids for ti5 present in the database
ti5_matches_mongo = db.ti5_matches
ti5_match_details = db.ti5_match_details
# collect all the match ids
all_match_ids_mongo = list(ti5_matches_mongo.distinct('match_id'))
# set api key
api.set_api_key("SECRET API KEY")
# fetch all ti5 matches till date (league id - 2733)
ti5_matches = match_history.latest_matches(league_id=2733)
for match in ti5_matches['matches']:
    if not match['match_id'] in all_match_ids_mongo:
        ti5_matches_mongo.insert(match)
# recollect all the match ids
all_match_ids_mongo = list(ti5_matches_mongo.distinct('match_id'))
match_ids_details_fetched = list(ti5_match_details.distinct('match_id'))

# Match ids for which we need to fetch details
match_ids = list(set(all_match_ids_mongo) - set(match_ids_details_fetched))

# fetch existing match details from mongo
all_match_details = {}
for match_id in match_ids_details_fetched:
Ejemplo n.º 23
0
 def __init__(self, chave, account_id, game_mode=(1,2), info_heroi=("gold_per_min", "xp_per_min")):
     api.set_api_key(chave)
     self.info_heroi=info_heroi
     self.account_id=account_id
     self.game_mode = game_mode
     self.ids = []
Ejemplo n.º 24
0
    def update_dota(self):
        # Get a list of recent matches for the player
        total_added = 0
        api.set_api_key(AbstractResponse.key)
        current_time = int(time.time())
        last_update_time = AbstractResponse.get_last_update_time()
        new_records = ""
        for name, account_id in AbstractResponse.GroupMetoDOTA.items():
            print "Starting: {0}".format(name)
            # Get a list of recent matches for the player

            matches = api.get_match_history(
                account_id=account_id)["result"]["matches"]

            #Go through every match
            for match in matches:
                print "\tChecking: " + str(match["match_id"])

                if match["start_time"] < last_update_time["last_update"]:
                    print "\tWe've seen these matches"
                    break

                if (not AbstractResponse.has_dotaMatch(match["match_id"])):
                    single_match = api.get_match_details(
                        match["match_id"])["result"]
                    print "\t\tAdding: " + str(single_match["match_id"])
                    AbstractResponse.add_dotaMatch(single_match)
                    total_added += 1

                    #Did this match set any new records# ?
                    for player in single_match["players"]:
                        #Is this a player we are tracking?
                        if AbstractResponse.has_dotaID_num(
                                int(player["account_id"])):
                            #Yes! Check if they broke a record
                            old_record = AbstractResponse.get_record(
                                player["hero_id"])
                            print player["hero_id"]
                            hero_dict = data.get_hero_name(player["hero_id"])
                            if not hero_dict:
                                print(
                                    "For hero id = {}, not in dota2py".format(
                                        player["hero_id"]))
                                continue
                            hero_name = data.get_hero_name(
                                player["hero_id"])["localized_name"]
                            player_name = AbstractResponse.dotaID_to_name(
                                int(player["account_id"]))

                            if old_record is None:

                                #this is auto a new record!
                                new_record = {
                                    "hero_id": player["hero_id"],
                                    "max_kills": player["kills"],
                                    "max_kills_player": player["account_id"],
                                    "max_deaths": player["deaths"],
                                    "max_deaths_player": player["account_id"],
                                    "max_GPM": player["gold_per_min"],
                                    "max_GPM_player": player["account_id"],
                                    "min_GPM": player["gold_per_min"],
                                    "min_GPM_player": player["account_id"],
                                    "max_XPM": player["xp_per_min"],
                                    "max_XPM_player": player["account_id"],
                                    "min_XPM": player["xp_per_min"],
                                    "min_XPM_player": player["account_id"],
                                }
                                AbstractResponse.set_record(new_record)

                            else:
                                #There is an existing record.. Lets see if this match was a game changer
                                new_record = old_record.copy()

                                if old_record["max_kills"] < player["kills"]:
                                    new_records += "{0} just got {1} kills with {2}, a new record!\n".format(
                                        player_name, player["kills"],
                                        hero_name)
                                    new_record["max_kills"] = player["kills"]
                                    new_record["max_kills_player"] = player[
                                        "account_id"]

                                if old_record["max_deaths"] < player["deaths"]:
                                    new_records += "{0} just got {1} deaths with {2}, a new low!\n".format(
                                        player_name, player["deaths"],
                                        hero_name)
                                    new_record["max_deaths"] = player["deaths"]
                                    new_record["max_deaths_player"] = player[
                                        "account_id"]

                                if old_record["max_GPM"] < player[
                                        "gold_per_min"]:
                                    new_records += "{0} just got {1} GPM with {2}, a new record!\n".format(
                                        player_name, player["gold_per_min"],
                                        hero_name)
                                    new_record["max_GPM"] = player[
                                        "gold_per_min"]
                                    new_record["max_GPM_player"] = player[
                                        "account_id"]

                                if old_record["min_GPM"] > player[
                                        "gold_per_min"]:
                                    new_records += "{0} just got {1} GPM with {2}, a new low!\n".format(
                                        player_name, player["gold_per_min"],
                                        hero_name)
                                    new_record["min_GPM"] = player[
                                        "gold_per_min"]
                                    new_record["min_GPM_player"] = player[
                                        "account_id"]

                                if old_record["max_XPM"] < player["xp_per_min"]:
                                    new_records += "{0} just got {1} XPM with {2}, a new record!\n".format(
                                        player_name, player["xp_per_min"],
                                        hero_name)
                                    new_record["max_XPM"] = player[
                                        "xp_per_min"]
                                    new_record["max_XPM_player"] = player[
                                        "account_id"]

                                if old_record["min_XPM"] > player["xp_per_min"]:
                                    new_records += "{0} just got {1} XPM with {2}, a new low!\n".format(
                                        player_name, player["xp_per_min"],
                                        hero_name)
                                    new_record["min_XPM"] = player[
                                        "xp_per_min"]
                                    new_record["min_XPM_player"] = player[
                                        "account_id"]

                                AbstractResponse.set_record(new_record)

                else:
                    print "\t Was Duplicate"

            print "Updated {0} Matches".format(total_added)
        if last_update_time == None:
            time_dict = {'last_update': current_time}
        else:
            time_dict = last_update_time.copy()
            time_dict["last_update"] = current_time
        AbstractResponse.set_last_update_time(time_dict)
        return new_records
Ejemplo n.º 25
0
    def run(self):
        api.set_api_key(self.steam_api_key)

        if not isinstance(self.steamid, int):
            # find by username
            self.steamid = int(
                api.get_steam_id(self.steamid)['response']['steamid'])

        hist = api.get_match_history(account_id=self.steamid)['result']
        recent_matches = []
        while len(recent_matches) < self.matches:
            recent_matches.append(hist['matches'].pop(0))

        player_team_per_match = []
        # create a list of tuples where each tuple is:
        # [match_id, bool]
        # The bool will be true if the player is on Radiant and alse if they
        # are on Dire.
        for match in recent_matches:
            this_match = [match['match_id']]
            for player in match['players']:
                # 64bit player ID
                long_id = player['account_id'] + 76561197960265728
                if long_id == self.steamid:
                    if player['player_slot'] < 128:
                        this_match.append(True)
                    else:
                        this_match.append(False)
            player_team_per_match.append(this_match)

        outcomes = []
        for match in player_team_per_match:
            if api.get_match_details(
                    match[0])['result']['radiant_win'] == match[1]:
                outcomes.append(1)
            else:
                outcomes.append(0)

        wins = outcomes.count(1)
        losses = outcomes.count(0)
        win_percent = float(sum(outcomes) / float(len(outcomes))) * 100

        if win_percent >= float(self.good_threshold):
            color = self.good_color
        elif win_percent <= float(self.bad_threshold):
            color = self.bad_color
        else:
            color = self.caution_color

        if self.screenname == 'retrieve':
            from urllib.request import urlopen
            import json
            response = urlopen(
                'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=%s&steamids=%s'
                % (self.steam_api_key, self.steamid))
            screenname = json.loads(bytes.decode(
                response.read()))['response']['players'][0]['personaname']
        else:
            screenname = self.screenname

        cdict = {
            "screenname": screenname,
            "wins": wins,
            "losses": losses,
            "win_percent": win_percent,
        }

        self.output = {
            "full_text": self.format.format(**cdict),
            "color": color
        }
Ejemplo n.º 26
0
 def __init__(self, chave, game_mode=(1, 2), skill=3, min_players=10):
     api.set_api_key(chave)
     self.game_mode = game_mode
     self.skill = skill
     self.min_players = min_players
Ejemplo n.º 27
0
    def respond(self):

        if random.random() < ResponseLast.SASS_PERCENTAGE:
            print("#last - sassy override")
            return "Bitch, you can't last for shit"

        print "Starting"

        canonical_name = (
            key for key, value in AbstractResponse.GroupMeIDs.items()
            if value == self.msg.sender_id).next()

        if not AbstractResponse.has_steamID(canonical_name):
            return "I don't know your SteamID! Set it with '#set ID'"

        if not AbstractResponse.has_dotaID(canonical_name):
            return "I don't know your DOTA ID! Set it with '#setDota ID'"

        print "Setting Key & Account ID"
        api.set_api_key(AbstractResponse.key)

        account_id = AbstractResponse.name_to_steamID(canonical_name)

        print "Got Account ID"
        # Get a list of recent matches for the player
        matches = api.get_match_history(
            account_id=account_id)["result"]["matches"]

        #Get the full details for a match
        match = api.get_match_details(matches[0]["match_id"])

        match_id = match['result']['match_id']

        dotabuff_link = ResponseLast.DOTABUFF_LINK_TEMPLATE.format(id=match_id)

        print "Got Match Details"
        player_num = 0

        for x in match["result"]["players"]:
            if int(x["account_id"]) == AbstractResponse.name_to_dotaID(
                    canonical_name):
                out = ""
                print "Got self.sender Data"

                #Stats?
                print player_num
                msg = ResponseLast.match_performance_template.format(
                    hero=data.get_hero_name(x["hero_id"])["localized_name"],
                    k=str(x["kills"]),
                    d=str(x["deaths"]),
                    a=str(x["assists"]),
                    GPM=str(x["gold_per_min"]),
                    level=str(x["level"]))
                out += msg + "\n"

                #Items?
                finalItems = "Your items: "
                for itemNum in range(0, 6):
                    if x["item_" + str(itemNum)] != 0 and x[
                            "item_" + str(itemNum)] is not None:
                        try:
                            finalItems += str(
                                data.get_item_name(
                                    x["item_" + str(itemNum)])["name"]) + ", "
                        except:
                            finalItems += "unknown item ({}), ".format(
                                x["item_" + str(itemNum)])

                out += finalItems + "\n"

                #Win?
                #@todo fix this to incorporate woody's bugfix
                if player_num < 5 and match["result"]["radiant_win"]:
                    out += "You Won! "
                elif player_num > 4 and not match["result"]["radiant_win"]:
                    out += "You Won! "
                else:
                    out += "You Lost.... Bitch "
                out += str(match_id) + " " + dotabuff_link
                return out
            player_num = player_num + 1
Ejemplo n.º 28
0
import sys
from os.path import abspath, join, dirname
import os
from datetime import date, timedelta
import msg_texts
import register as reg
from time import sleep

sys.path.append(abspath(join(abspath(dirname(__file__)), "..")))

app_key = os.environ.get("DB_APP_KEY")
app_secret = os.environ.get("DB_APP_SEC")
key = os.environ.get("DOTA2_API_KEY")
if not key:
    raise NameError("Please set the DOTA2_API_KEY environment variable")
api.set_api_key(key)
token = os.environ.get("TG_BOT_TOKEN")
BASE_URL = "https://api.telegram.org/bot%s" % token
LAST_UPDATE_ID = None
try:
    from urllib.error import URLError
except ImportError:
    from urllib2 import URLError  # python 2


def main():
    update_id = None
    global BASE_URL
    logging.basicConfig(filename="botlog.log", format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")

    logging.getLogger().addHandler(logging.StreamHandler())
Ejemplo n.º 29
0
 def setUp(self):
     key = os.environ.get("DOTA2_API_KEY")
     if not key:
         raise NameError(
             "Please set the DOTA2_API_KEY environment variable")
     api.set_api_key(key)
Ejemplo n.º 30
0
    def respond(self):

        if random.random() < ResponseLast.SASS_PERCENTAGE:
            print("#last - sassy override")
            return "Bitch, you can't last for shit"

        print "Starting"

        canonical_name = (key for key,value in AbstractResponse.GroupMeIDs.items() if value==self.msg.sender_id).next()

        if not AbstractResponse.has_steamID(canonical_name):
            return "I don't know your SteamID! Set it with '#set ID'"

        if not AbstractResponse.has_dotaID(canonical_name):
            return "I don't know your DOTA ID! Set it with '#setDota ID'"

        print "Setting Key & Account ID"
        api.set_api_key(AbstractResponse.key)

        account_id = AbstractResponse.name_to_steamID(canonical_name)

        print "Got Account ID"
        # Get a list of recent matches for the player
        matches = api.get_match_history(account_id=account_id)["result"]["matches"]

        #Get the full details for a match
        match = api.get_match_details(matches[0]["match_id"])

        match_id = match['result']['match_id']

        dotabuff_link = ResponseLast.DOTABUFF_LINK_TEMPLATE.format(id=match_id)

        print "Got Match Details"
        player_num = 0

        for x in match["result"]["players"]:
            if int(x["account_id"]) == AbstractResponse.name_to_dotaID(canonical_name):
                out = ""
                print "Got self.sender Data"

                #Stats?
                print player_num
                msg = ResponseLast.match_performance_template.format(hero=data.get_hero_name(x["hero_id"])["localized_name"],
                                                            k=str(x["kills"]),
                                                            d=str(x["deaths"]),
                                                            a=str(x["assists"]),
                                                            GPM=str(x["gold_per_min"]),
                                                            level=str(x["level"])
                                                            )
                out += msg + "\n"

                #Items?
                finalItems = "Your items: "
                for itemNum in range(0, 6):
                    if x["item_" + str(itemNum)] != 0 and x["item_" + str(itemNum)] is not None:
                        try:
                            finalItems += str(data.get_item_name(x["item_" + str(itemNum)])["name"]) + ", "
                        except:
                            finalItems += "unknown item, "

                out += finalItems + "\n"

                #Win?
                #@todo fix this to incorporate woody's bugfix
                if player_num < 5 and match["result"]["radiant_win"]:
                    out += "You Won! "
                elif player_num > 4 and not match["result"]["radiant_win"]:
                    out += "You Won! "
                else:
                    out += "You Lost.... Bitch "
                out += str(match_id) + " " + dotabuff_link
                return out
            player_num = player_num + 1
Ejemplo n.º 31
0
from __future__ import division
from dota2py import api
import time
import sys
API_KEY = sys.argv[1] # Stick your API key here, obtain it at 
account_id = ACCOUNT_ID = '9372254' # My account ID
api.set_api_key(API_KEY)

matches = api.get_match_history(account_id=account_id, date_min=time.time() - 604800)['result']['matches']

total_games = 0
games_won = 0
for match in matches:
	match_details = api.get_match_details(match.get('match_id'))['result']
	if match.get('lobby_type') is 5:
		continue
	radiant_win = match_details['radiant_win']

	players = match_details.get('players')
	team_radiant = None
	match_won = None

	for player in players:
		# This is the player
		if player.get('account_id') == account_id:
			if player.get('player_slot') < 5:
				team_radiant = True
			else:
				team_radiant = False
	
	if team_radiant and radiant_win:
Ejemplo n.º 32
0
try:
    import rpi_functions as rpf
except ImportError:
    logging.warning('failed to import rpi functions. Ignore this if they are not needed')
    rpi = False
else:
    rpi = True

sys.path.append(abspath(join(abspath(dirname(__file__)), "..")))

app_key = os.environ.get('DB_APP_KEY')
app_secret = os.environ.get('DB_APP_SEC')
steam_key = os.environ.get('DOTA2_API_KEY')
if not steam_key:
    raise NameError('Please set the DOTA2_API_KEY environment variable')
api.set_api_key(steam_key)
token = os.environ.get('TG_BOT_TOKEN')
BASE_URL = 'https://api.telegram.org/bot%s' % token
LAST_UPDATE_ID = None
try:
    from urllib.error import URLError
except ImportError:
    from urllib2 import URLError  # python 2

def main():
    update_id = None
    motion_on = False
    global BASE_URL
    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',file='botlog.log')

#    logging.getLogger().addHandler(logging.StreamHandler())
Ejemplo n.º 33
0
 def __init__(self, key):
     api.set_api_key(key)
     self.heroes = self.getHeroes()
     self.playerInfos = self.makePlayersInfos("hero_id", "gold_per_min", "xp_per_min")
     self.matchInfos = self.makeMatchInfos("match_id","radiant_win", "duration", "start_time", "leagueid", "game_mode")
     self.columns = self.makeColumns()