Ejemplo n.º 1
0
def enable_channel(channel, dotaid, mmr=True, returntrueifnotnotable=False):
    en_chans = settings.getdata('dota_enabled_channels')

    settings.setdata('dota_enabled_channels', list(set(en_chans + [channel])))
    settings.trygetset('%s_common_name' % channel, channel)
    settings.setdata('%s_mmr_enabled' % channel, mmr)
    settings.setdata('%s_dota_id' % channel, dotaid)

    update_channels()
    if returntrueifnotnotable:
        if dotaid not in settings.getdata('dota_notable_players'):
            return True
Ejemplo n.º 2
0
def get_players_in_game_for_player(dotaid, checktwitch=False, markdown=False):
    # herodata = getHeroes()
    herodict = getHeroNamedict()
    herodict[0] = "Unknown hero"

    notable_players = settings.getdata('dota_notable_players')
    game = getSourceTVLiveGameForPlayer(dotaid)

    teamformat = '%s%s \n'                   # ('## ' if markdown else '', team)
    playerformat = '%s%s: %s\n'              # ('#### ' if markdown else '  ', hero, name)
    notableformat = '%sNotable player: %s\n' # ('###### ' if markdown else '   - ', name)
    linkformat = '   - %s%s\n'               # (linktype, linkdata)

    linktypes = {
        'steam': 'http://steamcommunity.com/profiles/',
        'dotabuff': 'http://www.dotabuff.com/players/',
        'twitch': 'http://twitch.tv/'
    }

    if game:
        data = ''

        playerinfos = node.get_player_info(*[int(p['account_id']) for p in game['players']])
        noinfoids = [p['account_id'] for p in playerinfos['player_infos'] if p['name'] is None]

        playerinfodict = {pl.pop('account_id'): pl for pl in playerinfos.copy()['player_infos']}

        if noinfoids:
            noinfodatas = {int(data['friendid']): data['player_name'] for data in node.get_friend_data([ID(i).steamid for i in noinfoids])}
            for x in noinfoids:
                playerinfodict[ID(x).dotaid] = {'name': noinfodatas[ID(x).steamid]}

        for team in ['Radiant', 'Dire']:
            data += teamformat % ('## ' if markdown else '', team)

            for player in game['players'][slice(None, 5) if team=='Radiant' else slice(5, None)]:
                pname = playerinfodict[player['account_id']]['name']

                data += playerformat % ('#### ' if markdown else '  ', herodict[player['hero_id']], pname)

                if player['account_id'] in notable_players:
                    npd = '###### ' if markdown else '   - '
                    data += notableformat % (UnicodeDammit(npd).unicode_markup.encode('utf8'), notable_players[player['account_id']])

                mkupsteamlink = linkformat % (linktypes['steam'], ID(player['account_id']).steamid)
                ressteam = requests.head(linktypes['steam'] + str(ID(player['account_id']).steamid)).headers.get('location')

                if ressteam:
                    data += mkupsteamlink.replace('\n', '') + ' (%s)\n' % ressteam.split('.com')[-1][:-1]
                else:
                    data += mkupsteamlink

                data += linkformat % (linktypes['dotabuff'], player['account_id'])
                if checktwitch:
                    tname = twitchapi.get_twitch_from_steam_id(ID(player['account_id']).steamid)
                    if tname:
                        data += linkformat % (linktypes['twitch'], tname)
                data += '\n'

        return data
Ejemplo n.º 3
0
def updateMMR(channel):
    try:
        dotaid = str(settings.getdata('%s_dota_id' % channel))
    except:
        raise TypeError("No id on record")

    return node.updateMMR(channel, dotaid)
Ejemplo n.º 4
0
def get_auto_notable_player_blurb(channel, ignore_online=False):
    playerid = settings.getdata('%s_dota_id' % channel)
    steamid = ID.dota_to_steam(playerid)
    isfriend = node.is_friends_with(steamid)

    if isfriend:
        user_rp_data = node.get_cached_rich_presence(steamid)[ID(playerid).steamid]
        if user_rp_data is None:
            user_rp_data = node.get_rich_presence(steamid)[ID(playerid).steamid]
    else:
        # If I decide this feature requires being on the friends list this is where I return
        user_rp_data = node.get_rich_presence(steamid)[ID(playerid).steamid]

    if user_rp_data:
        if user_rp_data['status'] in ["#DOTA_RP_HERO_SELECTION", "#DOTA_RP_PRE_GAME", "#DOTA_RP_GAME_IN_PROGRESS", "#DOTA_RP_PLAYING_AS"]:
            if user_rp_data['status'] == '#DOTA_RP_PLAYING_AS': # TODO: Check if PRE_GAME has the hero params
                playerheroid = user_rp_data['param0']
            else:
                playerheroid = None

            print "[Dota-Notable] Doing search for notable players%s" % (' using hero id' if playerheroid else '')
            players = searchForNotablePlayers(playerid, heroid=playerheroid, includemmr=True)
            # TODO: Check if game is ranked or not and set includemmr accordingly

            if players[0]:
                return "Notable players in this game: %s" % ', '.join(['%s (%s)' % (p,h) for p,h in players[0]])
Ejemplo n.º 5
0
def nowhosting(event):
    if event.data.startswith('HOSTTARGET') and event.data.split()[1] != '-':
        HOSTED_CHANNEL = event.data.split()[1]

        print event.etype, event.channel, event.data

        settings.setdata('%s_is_hosting' % event.channel, True)
        settings.setdata('%s_hosted_channel' % event.channel, event.data.split()[1])

        streamdata = twitchapi.get('streams/%s' % HOSTED_CHANNEL, 'stream')

        print '[Hosting] WE ARE NOW HOSTING %s' % HOSTED_CHANNEL

        if streamdata:
            if event.data.split()[2] == '-':
                return
            try:
                viewers = str(int(event.data.split()[2]))
            except:
                viewers = event.data.split()[2].split('=')[1].split(')')[0]

            event.bot.botsay("Now hosting %s, playing %s.  All %s of you, go check it out! %s" %
                (HOSTED_CHANNEL, str(streamdata['game']), viewers, 'http://twitch.tv/%s' % HOSTED_CHANNEL))
        else:
            print "[Hosting] %s is not streaming." % HOSTED_CHANNEL
    elif event.data.startswith('HOSTTARGET') and event.data.split()[1] == '-':
        print "[Hosting] Unhosting %s " % settings.getdata('%s_hosted_channel' % event.channel)

        settings.setdata('%s_is_hosting' % event.channel, False)
        settings.setdata('%s_hosted_channel' % event.channel, '')
Ejemplo n.º 6
0
def nowhosting(event):
    if event.data.startswith('HOSTTARGET') and event.data.split()[1] != '-':
        HOSTED_CHANNEL = event.data.split()[1]

        print event.etype, event.channel, event.data

        settings.setdata('%s_is_hosting' % event.channel, True)
        settings.setdata('%s_hosted_channel' % event.channel,
                         event.data.split()[1])

        streamdata = twitchapi.get('streams/%s' % HOSTED_CHANNEL, 'stream')

        print '[Hosting] WE ARE NOW HOSTING %s' % HOSTED_CHANNEL

        if streamdata:
            if event.data.split()[2] == '-':
                return
            try:
                viewers = str(int(event.data.split()[2]))
            except:
                viewers = event.data.split()[2].split('=')[1].split(')')[0]

            event.bot.botsay(
                "Now hosting %s, playing %s.  All %s of you, go check it out! %s"
                % (HOSTED_CHANNEL, str(streamdata['game']), viewers,
                   'http://twitch.tv/%s' % HOSTED_CHANNEL))
        else:
            print "[Hosting] %s is not streaming." % HOSTED_CHANNEL
    elif event.data.startswith('HOSTTARGET') and event.data.split()[1] == '-':
        print "[Hosting] Unhosting %s " % settings.getdata(
            '%s_hosted_channel' % event.channel)

        settings.setdata('%s_is_hosting' % event.channel, False)
        settings.setdata('%s_hosted_channel' % event.channel, '')
Ejemplo n.º 7
0
def checkifhostonline(event):
    HOSTED_CHANNEL = settings.getdata('%s_hosted_channel' % event.channel)

    IS_HOSTING = settings.trygetset('%s_is_hosting' % event.channel, True)
    AUTO_UNHOST = settings.trygetset('%s_auto_unhost' % event.channel, True)
    WHITELIST = settings.trygetset('hosting_whitelist', ['monkeys_forever', 'superjoe', 'imayhaveborkedit']) # This should only be temp

    if IS_HOSTING and AUTO_UNHOST and event.channel in WHITELIST:

        LAST_CHECK = settings.trygetset('%s_last_hosting_check' % event.channel, time.time())

        if LAST_CHECK is None:
            settings.setdata('%s_last_hosting_check' % event.channel, time.time())

        elif check_check_threshold(event.channel):
            print '[Hosting] Checking if host is online'
            try:
                streamdata = twitchapi.get('streams/%s' % HOSTED_CHANNEL, 'stream')
            except:
                print "[Hosting] Error grabbing stream data, probably a bad stream."
                event.bot.botsay("%s, I don't think that's a real stream.  If it is, the twitch api is kaput." % event.channel)
            else:
                if streamdata:
                    settings.setdata('%s_last_hosting_check' % event.channel, time.time())

                elif check_offline_threshold(event.channel):
                    print "[Hosting] %s has been offline for long enough, attempting to unhost" % HOSTED_CHANNEL
                    event.bot.botsay('/unhost')
Ejemplo n.º 8
0
def start_recurring(name):
    if not settings.exists(name, recurring_domain):
        return False

    recurring = _get_recurring(name)
    recurring.start(settings.getdata(name + '_data', recurring_domain)[0], True)

    print '[Recurring] Starting %s for %s' % (name, the_channel)
    return True
Ejemplo n.º 9
0
def get_players_in_game_for_player(dotaid, checktwitch=False, markdown=False):
    herodata = getHeroes()
    # herodict = {h['id']:str(h['localized_name']) for h in herodata['result']['heroes']}
    herodict = getHeroNamedict()
    herodict[0] = "Unknown hero"

    userstatus = node.get_user_status(dotaToSteam(dotaid))
    if userstatus == '#DOTA_RP_PLAYING_AS':
        heroid = node.get_user_playing_as(dotaToSteam(dotaid))
        heroid = getHeroIddict(False)[heroid[0]]
    else: heroid = None

    notable_players = settings.getdata('dota_notable_players')
    game = getSourceTVLiveGameForPlayer(dotaid, heroid)

    teamformat = '%s%s: \n'                  # ('## ' if markdown else '', team)
    playerformat = '%s%s: %s\n'              # ('#### ' if markdown else '  ', hero, name)
    notableformat = '%sNotable player: %s\n' # ('###### ' if markdown else '   - ', name)
    linkformat = '   - %s%s\n'               # (linktype, linkdata)
    
    linktypes = {
        'steam': 'http://steamcommunity.com/profiles/',
        'dotabuff': 'http://www.dotabuff.com/players/',
        'twitch': 'http://twitch.tv/'
    }

    if game:
        data = ''

        for team in ['Radiant', 'Dire']:

            data += teamformat % ('## ' if markdown else '', team)

            for player in game['goodPlayers' if team=='Radiant' else 'badPlayers']:
                data += playerformat % ('#### ' if markdown else '  ', herodict[player['heroId']], player['name'].decode('utf8'))

                if steamToDota(player['steamId']) in notable_players:
                    data += notableformat % ('###### ' if markdown else '   - ', notable_players[steamToDota(player['steamId'])].decode('utf8'))

                mkupsteamlink = linkformat % (linktypes['steam'], player['steamId'])
                
                ressteam = requests.head(linktypes['steam'] + player['steamId']).headers.get('location')

                if ressteam:
                    data += mkupsteamlink.replace('\n', '') + ' (%s)\n' % ressteam.split('.com')[-1][:-1]
                else:
                    data += mkupsteamlink

                data += linkformat % (linktypes['dotabuff'], steamToDota(long(player['steamId'])))
                if checktwitch:
                    tname = twitchapi.get_twitch_from_steam_id(player['steamId'])
                    if tname:
                        data += linkformat % (linktypes['twitch'], tname)
                data += '\n'

        return data
Ejemplo n.º 10
0
def start_recurring(name):
    if not settings.exists(name, recurring_domain):
        return False

    recurring = _get_recurring(name)
    recurring.start(
        settings.getdata(name + '_data', recurring_domain)[0], True)

    print '[Recurring] Starting %s for %s' % (name, the_channel)
    return True
Ejemplo n.º 11
0
def create_lobby(gameName, gameMode, password=None, serverRegion=None):
    with ZRPC() as zrpc:
        cid = settings.getdata('current_lobby_id', coerceto=str)

        if cid != '0':
            return None

        l_id = zrpc.createlobby(gameName, password, serverRegion, gameMode)
        settings.setdata('current_lobby_id', str(l_id))

        return l_id
Ejemplo n.º 12
0
def create_lobby(gameName, gameMode, password=None, serverRegion=None):
    with ZRPC() as zrpc:
        cid = settings.getdata('current_lobby_id', coerceto=str)

        if cid != '0':
            return None

        l_id = zrpc.createlobby(gameName, password, serverRegion, gameMode)
        settings.setdata('current_lobby_id', str(l_id))

        return l_id
Ejemplo n.º 13
0
def enable_channel(channel, dotaid, mmr=False):
    dotaid = steamToDota(determineSteamid(dotaid))
    en_chans = settings.getdata('dota_enabled_channels')

    settings.setdata('dota_enabled_channels', list(set(en_chans + [channel])))
    settings.trygetset('%s_common_name' % channel, channel)
    settings.setdata('%s_mmr_enabled' % channel, mmr)

    settings.setdata('%s' % channel, dotaToSteam(dotaid), domain='steamids')
    settings.setdata('%s_dota_id' % channel, dotaid)

    update_channels()
Ejemplo n.º 14
0
def latestBlurb(channel, override=False):
    if checktimeout(channel) or override:
        dotaid = settings.getdata('%s_dota_id' % channel)
        if dotaid is None:
            print "[Dota] No ID on record for %s.  I should probably sort this out." % channel
            return

        try:
            mat = steamapi.GetMatchHistory(account_id=dotaid, matches_requested=25)
            matches = mat['result']['matches']
        except requests.exceptions.ConnectionError:
            return
        except Exception as e:
            if mat == {}:
                # print "Bad data from GetMatchHistory:", mat
                return
            else:
                print 'Error with steam api data:', e
                print mat
                print traceback.format_exc()
                return

        settings.setdata('%s_last_match_fetch' % channel, time.time(), announce=False)

        latestmatch = matches[0]
        previousnewmatch = matches[1]
        previoussavedmatch = settings.trygetset('%s_last_match' % channel, latestmatch)

        if previoussavedmatch['match_id'] != latestmatch['match_id'] or override:
            if previoussavedmatch['match_id'] != previousnewmatch['match_id']:
                # Other matches have happened.

                matchlist = [m['match_id'] for m in matches]

                # If there was a problem here it either was never a problem or doesn't exist now?

                try:
                    skippedmatches = matchlist.index(previoussavedmatch['match_id']) - 1
                except:
                    skippedmatches = 0
                print '[Dota] Skipped %s matches MAYBE PROBABLY I HOPE SO' % skippedmatches
            else:
                skippedmatches = 0

            update_channels()
            notable_check_timeout = settings.trygetset('%s_notable_check_timeout' % channel, 900.0)

            settings.setdata('%s_notable_last_check' % channel, time.time() - notable_check_timeout + 60.0, announce=False)
            settings.setdata('%s_notable_message_count' % channel, settings.trygetset('%s_notable_message_limit' % channel, 50), announce=False)

            print "[Dota] Match ID change found (%s:%s) (Lobby type %s)" % (previoussavedmatch['match_id'], latestmatch['match_id'], str(latestmatch['lobby_type']))
            return getLatestGameBlurb(channel, dotaid, latestmatch, skippedmatches=skippedmatches, getmmr = get_enabled_channels()[channel][1] and str(latestmatch['lobby_type']) == '7')
Ejemplo n.º 15
0
def searchForNotablePlayers(targetdotaid, pages=10, heroid=None, includemmr=False):
    t0 = time.time()
    herodata = getHeroes()
    notable_players = settings.getdata('dota_notable_players')

    if heroid:
        if pages > 10: pages = 10

        print '[Dota-Notable] Searching using heroid %s' % heroid

    game = getSourceTVLiveGameForPlayer(targetdotaid, heroid)

    if not game:
        return (None, None) if includemmr else None

    players = game['players']
    notable_players_found = []
    target_found = False

    for player in players:
        if player['account_id'] in notable_players:
            # print '[Dota-Notable] %s (%s)' % ('', notable_players[player['account_id']])

            try:
                playerhero = str([h['localized_name'] for h in herodata['result']['heroes'] if str(h['id']) == str(player['hero_id'])][0])
            except:
                playerhero = POSITION_COLORS[players.index(player)]

            if ID(player['account_id']) != ID(targetdotaid):
                notable_players_found.append((notable_players[player['account_id']], playerhero))

        if ID(player['account_id']) == ID(targetdotaid):
            # print '[Dota-Notable] found target player'
            target_found = True

    #TODO: ADD THE OTHER DATA IN HERE SOMEWHERE

    if target_found:
        if notable_players_found:
            print '[Dota-Notable] Found: %s' % notable_players_found
        else:
            print '[Dota-Notable] No notable players.'

        if includemmr:
            return (notable_players_found, game['average_mmr'])
        else:
            return notable_players_found
    else:
        print (None, None) if includemmr else None
        return (None, None) if includemmr else None
Ejemplo n.º 16
0
def set_timeout(name, newtimeout, imediatestart=True):
    if not settings.exists(name, recurring_domain):
        return False

    recurring = _get_recurring(name)
    oldtimeout, message, createdat = settings.getdata(name + '_data', recurring_domain)

    recurring.stop()
    recurring.start(newtimeout, imediatestart)

    settings.setdata(name + '_data', (newtimeout, message, createdat), recurring_domain)

    print '[Recurring] Changed %s timeout: %s -> %s, %simediate' % (name, oldtimeout, newtimeout, '' if imediatestart else 'not ')
    return True
Ejemplo n.º 17
0
    def __init__(self, ID_=None, channel=None):
        ID_ = int(ID_)
        if ID_:
            if ID_ > self.STEAM_TO_DOTA_CONSTANT:
                self.steamid = ID_
                self.dotaid = self.steam_to_dota(self.steamid)
            elif ID_ < self.STEAM_TO_DOTA_CONSTANT:
                self.dotaid = ID_
                self.steamid = self.dota_to_steam(self.dotaid)
            else:
                raise ValueError()

        elif channel:
            self.dotaid = settings.getdata('%s_dota_id' % channel, coerceto=int)
            self.steamid = self.dota_to_steam(self.dotaid)
Ejemplo n.º 18
0
def update_verified_notable_players():
    class DotabuffParser(HTMLParser):
        table_active = False
        img_section_active = False
        player_datas = list()

        def handle_starttag(self, tag, attrs):
            if tag == 'tbody':
                self.table_active = True
            if tag == 'img':
                self.img_section_active = True
            if not self.table_active: return
            if not self.img_section_active: return

            fulldatas = dict((x,y) for x,y in attrs)
            self.player_datas.append((int(fulldatas['data-tooltip-url'].split('/')[2]), fulldatas['title']))

        def handle_endtag(self, tag):
            if tag == 'tbody':
                self.table_active = False
            if tag == 'img':
                self.img_section_active = False
            if not self.table_active: return
            if not self.img_section_active: return

    parser = DotabuffParser()

    r = requests.get('http://www.dotabuff.com/players', headers = {'User-agent': USER_AGENT})
    if r.status_code == 429:
        return 429

    htmldata = unicode(r.text).encode('utf8')
    parser.feed(htmldata)

    old_players = settings.getdata('dota_notable_players')
    updated_players = dict(old_players.items() + parser.player_datas)

    settings.setdata('dota_notable_players', updated_players, announce=False)

    tn = 0
    for p in dict(parser.player_datas):
        o = old_players.get(p, 'none')
        n = dict(parser.player_datas)[p]
        if o != n:
            print '[Dota-Notable] Updated player: %s -> %s' % (o, n)
            tn += 1

    return tn
Ejemplo n.º 19
0
def set_timeout(name, newtimeout, imediatestart=True):
    if not settings.exists(name, recurring_domain):
        return False

    recurring = _get_recurring(name)
    oldtimeout, message, createdat = settings.getdata(name + '_data',
                                                      recurring_domain)

    recurring.stop()
    recurring.start(newtimeout, imediatestart)

    settings.setdata(name + '_data', (newtimeout, message, createdat),
                     recurring_domain)

    print '[Recurring] Changed %s timeout: %s -> %s, %simediate' % (
        name, oldtimeout, newtimeout, '' if imediatestart else 'not ')
    return True
Ejemplo n.º 20
0
def latestBlurb(channel, override=False):
    # if node.get_user_status(dota.dotaToSteam(settings.getdata('%s_dota_id' % channel))) is not None:
    if checktimeout(channel) or override:
        dotaid = settings.getdata('%s_dota_id' % channel)
        if dotaid is None:
            print "[Dota] No ID on record for %s.  I should probably sort this out." % channel
            return

        try:
            matches = steamapi.GetMatchHistory(account_id=dotaid, matches_requested=25)['result']['matches']
        except:
            return

        settings.setdata('%s_last_match_fetch' % channel, time.time(), announce=False)

        latestmatch = matches[0]
        previousnewmatch = matches[1]
        previoussavedmatch = settings.trygetset('%s_last_match' % channel, latestmatch)

        if previoussavedmatch['match_id'] != latestmatch['match_id'] or override:
            if previoussavedmatch['match_id'] != previousnewmatch['match_id']:
                # Other matches have happened.

                matchlist = [m['match_id'] for m in matches]

                # TODO: Fix -1 issues for lastmatch
                # For some reason, a failed match (early abandon) was never saved as the lastest match
                try:
                    skippedmatches = matchlist.index(previoussavedmatch['match_id']) - 1
                except:
                    skippedmatches = 0
                print '[Dota] Skipped %s matches MAYBE PROBABLY I HOPE SO' % skippedmatches
            else:
                skippedmatches = 0

            update_channels()
            notable_check_timeout = settings.trygetset('%s_notable_check_timeout' % channel, 900.0)

            settings.setdata('%s_notable_last_check' % channel, time.time() - notable_check_timeout + 60.0, announce=False)
            settings.setdata('%s_notable_message_count' % channel, settings.trygetset('%s_notable_message_limit' % channel, 50), announce=False)

            print "[Dota] Match ID change found (%s:%s) (Lobby type %s)" % (previoussavedmatch['match_id'], latestmatch['match_id'], str(latestmatch['lobby_type']))
            return getLatestGameBlurb(channel, dotaid, latestmatch, skippedmatches=skippedmatches, getmmr = enabled_channels[channel][1] and str(latestmatch['lobby_type']) == '7')
Ejemplo n.º 21
0
def notablePlayerBlurb(channel, pages=10, override=False, updatetimers=True):
    playerid = settings.getdata('%s_dota_id' % channel)
    checkstatus = node.get_cached_rich_presence(ID(playerid).steamid)[ID(playerid).steamid]

    if checkstatus:
        userstatus = node.get_rich_presence(ID(playerid).steamid)[ID(playerid).steamid]
        if userstatus and userstatus['status'] in ["#DOTA_RP_HERO_SELECTION", "#DOTA_RP_PRE_GAME", "#DOTA_RP_GAME_IN_PROGRESS", "#DOTA_RP_PLAYING_AS"]:

            if getNotableCheckReady(channel) or override:
                if twitchapi.is_streaming(channel):
                    if userstatus['status'] == '#DOTA_RP_PLAYING_AS':
                        playerheroid = userstatus['param0']
                    else:
                        playerheroid = None

                    print "[Dota-Notable] Doing search for notable players%s" % (' using hero id' if playerheroid else '')
                    players = searchForNotablePlayers(playerid, pages, playerheroid)

                    if any(players):
                        settings.setdata('%s_notable_message_count' % channel, 0, announce=False)
                        settings.setdata('%s_notable_last_check' % channel, time.time(), announce=False)
                        return "Notable players in this game: %s" % ', '.join(['%s (%s)' % (p,h) for p,h in players])
Ejemplo n.º 22
0
def download_all_available_replays(channel, dotaid=None, games=500):
    if not dotaid:
        dotaid = settings.getdata('%s_dota_id' % channel)

    if not os.path.isdir(node.get_replay_dir(channel)):
        os.mkdir(node.get_replay_dir(channel))

    predownloadedgames = sorted([int(f.split('.')[0]) for f in os.listdir(node.get_replay_dir(channel)) if f.endswith('.dem')])
    matchids = collect_match_ids(dotaid, games)
    gamestodownload = list(set(matchids) - set(predownloadedgames))
    gamestodownload.sort(reverse=True)

    for game in gamestodownload:
        #TODO: Add check for existing json file and check replay "freshness"

        mdetails = node.get_match_details(game)
        print 'Got %s info: %s' % (game, mdetails['match']['replayState']),

        try:
            replaysize = node.download_replay(channel, game, mdetails)
            print '- %s bytes' % replaysize
        except node.Error, e:
            print '- Ded'
Ejemplo n.º 23
0
def checkifhostonline(event):
    HOSTED_CHANNEL = settings.getdata('%s_hosted_channel' % event.channel)

    IS_HOSTING = settings.trygetset('%s_is_hosting' % event.channel, True)
    AUTO_UNHOST = settings.trygetset('%s_auto_unhost' % event.channel, True)
    WHITELIST = settings.trygetset(
        'hosting_whitelist',
        ['monkeys_forever', 'superjoe', 'imayhaveborkedit'
         ])  # This should only be temp

    if IS_HOSTING and AUTO_UNHOST and event.channel in WHITELIST:

        LAST_CHECK = settings.trygetset(
            '%s_last_hosting_check' % event.channel, time.time())

        if LAST_CHECK is None:
            settings.setdata('%s_last_hosting_check' % event.channel,
                             time.time())

        elif check_check_threshold(event.channel):
            print '[Hosting] Checking if host is online'
            try:
                streamdata = twitchapi.get('streams/%s' % HOSTED_CHANNEL,
                                           'stream')
            except:
                print "[Hosting] Error grabbing stream data, probably a bad stream."
                event.bot.botsay(
                    "%s, I don't think that's a real stream.  If it is, the twitch api is kaput."
                    % event.channel)
            else:
                if streamdata:
                    settings.setdata('%s_last_hosting_check' % event.channel,
                                     time.time())

                elif check_offline_threshold(event.channel):
                    print "[Hosting] %s has been offline for long enough, attempting to unhost" % HOSTED_CHANNEL
                    event.bot.botsay('/unhost')
Ejemplo n.º 24
0
def notablePlayerBlurb(channel, pages=33):
    playerid = settings.getdata('%s_dota_id' % channel)
    userstatus = node.get_user_status(dotaToSteam(playerid))
    if userstatus:
        # print 'Dota status for %s: %s' % (channel, userstatus)

        if userstatus in ["#DOTA_RP_HERO_SELECTION", "#DOTA_RP_PRE_GAME", "#DOTA_RP_GAME_IN_PROGRESS", "#DOTA_RP_PLAYING_AS"]:
            if getNotableCheckReady(channel):
                if twitchapi.is_streaming(channel):
                    if userstatus == '#DOTA_RP_PLAYING_AS':
                        playerheroid = node.get_user_playing_as(dotaToSteam(playerid))
                        playerheroid = getHeroIddict(False)[playerheroid[0]]
                    else:
                        playerheroid = None

                    print "[Dota-Notable] Doing search for notable players%s" % (' using hero id' if playerheroid else '')
                    players = searchForNotablePlayers(playerid, pages, playerheroid)
                    settings.setdata('%s_notable_message_count' % channel, 0, announce=False)

                    if players:
                        return "Notable players in this game: %s" % ', '.join(['%s (%s)' % (p,h) for p,h in players])
        else:
            notable_check_timeout = settings.trygetset('%s_notable_check_timeout' % channel, 600.0)
            settings.setdata('%s_notable_last_check' % channel, time.time() - notable_check_timeout + 60.0, announce=False)
Ejemplo n.º 25
0
def disable_channel(channel, mmr=False):
    en_chans = settings.getdata('dota_enabled_channels')
    settings.setdata('dota_enabled_channels', list(set(en_chans) - set([channel])))
    settings.setdata('%s_mmr_enabled' % channel, not mmr)
Ejemplo n.º 26
0
def check_check_threshold(chan):
    return time.time() - settings.getdata('%s_last_hosting_check' % chan, coerceto=float) > CHECK_THRESHOLD
Ejemplo n.º 27
0
def searchForNotablePlayers(targetdotaid, pages=4, heroid=None):
    # Needs check for if in a game (maybe need a status indicator for richPresence)
    t0 = time.time()
    herodata = getHeroes()
    notable_players = settings.getdata('dota_notable_players')


    if heroid:
        if pages > 17: pages = 17

        print '[Dota-Notable] Searching using heroid %s' % heroid


    for pagenum in range(0, pages):
        # print 'searching page %s, T+%4.4fms' % (pagenum, (time.time()-t0)*1000)
        games = node.get_source_tv_games(pagenum, heroid)['games']
        # print 'received game page %s, T+%4.4fms' % (pagenum, (time.time()-t0)*1000)

        for game in games:
            try:
                game['goodPlayers']
                game['badPlayers']
            except Exception, e:
                print "MALFORMED GAME DATA, DO SOMETHING ABOUT IT (Radiant: %s, Dire: %s)" % (len(game.get('goodPlayers', [])), len(game.get('badPlayers', [])))
                continue

            players = []
            players.extend(game['goodPlayers'])
            players.extend(game['badPlayers'])
            notable_players_found = []
            target_found = False

            for player in players:
                if steamToDota(player['steamId']) in notable_players:
                    print '[Dota-Notable] %s (%s)' % (player['name'], notable_players[steamToDota(player['steamId'])])

                    try:
                        playerhero = str([h['localized_name'] for h in herodata['result']['heroes'] if str(h['id']) == str(player['heroId'])][0])
                    except:
                        playerhero = POSITION_COLORS[players.index(player)]

                    if long(steamToDota(player['steamId'])) != long(targetdotaid):
                        notable_players_found.append((notable_players[steamToDota(player['steamId'])], playerhero))
                    # else:
                        # print '[Dota-Notable] Discounting target player'

                if steamToDota(player['steamId']) == long(targetdotaid):
                    print '[Dota-Notable] found target player'
                    target_found = True

            #TODO: ADD THE OTHER DATA IN HERE SOMEWHERE

            if target_found:
                if notable_players_found:
                    print '[Dota-Notable] Found: %s' % notable_players_found
                else:
                    print '[Dota-Notable] No notable players.'

                return notable_players_found
            # print 'searched game %s, T+%4.4fms' % (games.index(game), (time.time()-t0)*1000)

        print '[Dota-Notable] searched page %s, T+%4.4fms' % (pagenum, (time.time()-t0)*1000)
Ejemplo n.º 28
0
def fetch_mmr_for_channel(channel, save=False):
    data = fetch_mmr_for_dotaid(settings.getdata('%s_dota_id' % channel))
    if save:
        settings.setdata('%s_last_mmr' % channel, data)
    return data
Ejemplo n.º 29
0
def get_mmr_for_channel(channel):
    try:
        return settings.getdata('%s_last_mmr' % channel)
    except:
        return (None, None)
Ejemplo n.º 30
0
def get_lobby():
    with ZRPC() as zrpc:
        return settings.getdata('current_lobby_id', coerceto=str)
Ejemplo n.º 31
0
def check_offline_threshold(chan):
    return time.time() - settings.getdata('%s_last_hosting_check' % chan,
                                          coerceto=float) > OFFLINE_THRESHOLD
Ejemplo n.º 32
0

LOAD_ORDER = 35

STEAM_TO_DOTA_CONSTANT = 76561197960265728
POSITION_COLORS = ['Blue', 'Teal', 'Purple', 'Yellow', 'Orange',      'Pink', 'Gray', 'Light Blue', 'Green', 'Brown']

#####
# This line evidently gives people problems when they try to run the bot when the dota_enabled_channels key isnt set
# For now, to fix this, run in an interpreter:
#
# import settings; settings.setdata('dota_enabled_channels', [])
#
# This will give it an empty list so it doesn't complain about not having the key

enabled_channels = {ch:(settings.getdata('%s_common_name' % ch),settings.getdata('%s_mmr_enabled' % ch)) for ch in settings.getdata('dota_enabled_channels')}

#####

herodata = None


def dotaToSteam(dotaid):
    return int(dotaid) + STEAM_TO_DOTA_CONSTANT

def steamToDota(steamid):
    return int(steamid) - STEAM_TO_DOTA_CONSTANT

def update_channels():
    global enabled_channels
    # print "[Dota] Updating enabled channels"
Ejemplo n.º 33
0
def get_lobby():
    with ZRPC() as zrpc:
        return settings.getdata('current_lobby_id', coerceto=str)
Ejemplo n.º 34
0
def getLatestGameBlurb(channel, dotaid, latestmatch=None, skippedmatches=0, getmmr=False, notableplayers=True, splitlongnotable=True):
    if latestmatch is None:
        latestmatch = steamapi.getlastdotamatch(dotaid)

    settings.setdata('%s_last_match' % channel, latestmatch, announce=False)

    matchdata = steamapi.GetMatchDetails(latestmatch['match_id'])
    herodata = getHeroes()

    playerdata = None
    for p in matchdata['result']['players']:
        if str(p['account_id']) == str(dotaid):
            playerdata = p
            break

    notableplayerdata = None
    separate_notable_message = False

    if notableplayers:
        # print "notable player lookup requested"
        notable_players = settings.getdata('dota_notable_players')
        notable_players_found = []

        if dotaid in notable_players:
            notable_players.pop(dotaid)

        for p in matchdata['result']['players']:
            # print 'looking up %s' % p['account_id']
            if p['account_id'] in notable_players:
                # print '[Dota-Notable] Found notable player %s' % notable_players[p['account_id']]
                playerhero = str([h['localized_name'] for h in herodata['result']['heroes'] if str(h['id']) == str(p['hero_id'])][0]) # p['heroId'] ?

                if int(p['account_id']) != int(dotaid):
                    notable_players_found.append((notable_players[p['account_id']], playerhero))

        if notable_players_found:
            separate_notable_message = len(notable_players_found) > 3

            notableplayerdata = "Notable players: %s" % ', '.join(['%s - %s' % (p,h) for p,h in notable_players_found])
            print "[Dota-Notable] notable player data: " + notableplayerdata
        else:
            print '[Dota-Notable] No notable players found'

    try:
        d_hero = [h['localized_name'] for h in herodata['result']['heroes'] if str(h['id']) == str(playerdata['hero_id'])][0]
    except:
        d_hero = 'Unknown Hero'

    d_team = 'Radiant' if int(playerdata['player_slot']) < 128 else 'Dire'
    d_level = playerdata['level']

    d_kills = playerdata['kills']
    d_deaths = playerdata['deaths']
    d_assists = playerdata['assists']

    d_lasthits = playerdata['last_hits']
    d_denies = playerdata['denies']

    d_gpm = playerdata['gold_per_min']
    d_xpm = playerdata['xp_per_min']

    if matchdata['result']['radiant_win'] ^ (d_team == 'Radiant'):
        d_victory = 'Defeat'
    else:
        d_victory = 'Victory'

    print "[Dota] Skipped %s matches" % skippedmatches

    if skippedmatches == -1:
        matchskipstr = '(Previous match) '
    elif skippedmatches < -1:
        matchskipstr = '(%s games ago) ' % skippedmatches * -1
    elif skippedmatches > 1:
        matchskipstr = '(%s skipped) ' % skippedmatches
    else:
        matchskipstr = ''

    matchoutput = "%s%s has %s a game.  http://www.dotabuff.com/matches/%s" % (
        matchskipstr,
        enabled_channels[channel][0],
        'won' if d_victory == 'Victory' else 'lost',
        latestmatch['match_id'])

    extramatchdata = "Level {} {} {} - KDA: {}/{}/{} - CS: {}/{} - GPM: {} - XPM: {}".format(
        d_level, d_team, d_hero, d_kills, d_deaths, d_assists, d_lasthits, d_denies, d_gpm, d_xpm)


    finaloutput = matchoutput + ' -- ' + extramatchdata + (' -- ' + getmatchMMRstring(channel, dotaid) if getmmr else '') + (' -- ' + notableplayerdata if notableplayerdata else '')

    if splitlongnotable:
        pass

    return finaloutput
Ejemplo n.º 35
0
def update_channels():
    global enabled_channels
    # print "[Dota] Updating enabled channels"
    enabled_channels = {ch:(settings.getdata('%s_common_name' % ch),settings.getdata('%s_mmr_enabled' % ch)) for ch in settings.getdata('dota_enabled_channels')}
Ejemplo n.º 36
0
def _get_recurring(name):
    return dill.detect.at(int(settings.getdata(name, recurring_domain)))
Ejemplo n.º 37
0
def _get_recurring(name):
    return dill.detect.at(int(settings.getdata(name, recurring_domain)))
Ejemplo n.º 38
0
def check_offline_threshold(chan):
    return time.time() - settings.getdata('%s_last_hosting_check' % chan, coerceto=float) > OFFLINE_THRESHOLD
Ejemplo n.º 39
0
def check_check_threshold(chan):
    return time.time() - settings.getdata('%s_last_hosting_check' % chan,
                                          coerceto=float) > CHECK_THRESHOLD