Beispiel #1
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')
Beispiel #2
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
Beispiel #3
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
Beispiel #4
0
def blurb(channel, bot, override=False):
    t1 = time.time()
    r = latestBlurb(channel, override)

    if r is not None:
        t2 = time.time()
        print "[Dota] Blurb time: %4.4fms (posting in 6 seconds)" % ((t2-t1)*1000)

        settings.setdata('%s_matchblurb_running' % channel, False, announce=False)
        reactor.callLater(6.0, bot.botsay, r)

    return r is not None
Beispiel #5
0
def alert(event):
    message = 'Only the channel owner and channel editors can use the /unhost command.'

    if event.channel:
        if event.etype == 'jtvmsg' and message in event.data:
            print "[Hosting] Not an editor, cannot unhost."
            settings.setdata('%s_auto_unhost' % event.channel, False)

        if event.etype in ['infomsg', 'jtvmsg']:  # Should only need jtvmsg
            nowhosting(event)  # This needs to be called before the check goes
            # checkifhostonline(event) # This line might need to be outside the if check

        return
Beispiel #6
0
def alert(event):
    message = 'Only the channel owner and channel editors can use the /unhost command.'
    
    if event.channel:
        if event.etype == 'jtvmsg' and message in event.data:
                print "[Hosting] Not an editor, cannot unhost."
                settings.setdata('%s_auto_unhost' % event.channel, False)

        if event.etype in ['infomsg', 'jtvmsg']:  # Should only need jtvmsg
            nowhosting(event)  # This needs to be called before the check goes
            # checkifhostonline(event) # This line might need to be outside the if check

        return
Beispiel #7
0
def alert(event):
    if event.channel in get_enabled_channels():
        # msgtimer = timer.Timer('Dota message Timer')
        # msgtimer.start()
        if event.etype == 'msg': # Meh
            mes_count = settings.trygetset('%s_notable_message_count' % event.channel, 1)
            settings.setdata('%s_notable_message_count' % event.channel, mes_count + 1, announce=False)

            try:
                if not settings.trygetset('%s_matchblurb_running' % event.channel, False):
                    settings.setdata('%s_matchblurb_running' % event.channel, True, announce=False)
                    blurb(event.channel, event.bot)
                else:
                    raise RuntimeWarning('Blurb already running')
            except RuntimeWarning as e:
                pass
            except Exception as e:
                print '[Dota-Error] Match blurb failure: %s' % e
                settings.setdata('%s_matchblurb_running' % event.channel, False, announce=False)
            else:
                settings.setdata('%s_matchblurb_running' % event.channel, False, announce=False)

            # msgtimer.stop()
            # print '[Dota] Matchblurb completed in %4.4f seconds.' % msgtimer.runtime()

        if event.etype == 'timer':
            try:
                rss_update = check_for_steam_dota_rss_update(event.channel)
                if rss_update:
                    print '[Dota] RSS update found: ' + rss_update
                    event.bot.botsay(rss_update)
            except Exception, e:
                print '[Dota-Error] RSS check failure: %s (%s)' % (e,type(e))
Beispiel #8
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, '')
Beispiel #9
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
Beispiel #10
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, '')
Beispiel #11
0
def getNotableCheckReady(channel):
    lastcheck = settings.trygetset('%s_notable_last_check' % channel, time.time())
    message_limit = settings.trygetset('%s_notable_message_limit' % channel, 50)
    notable_check_timeout = settings.trygetset('%s_notable_check_timeout' % channel, 900.0)

    if time.time() - lastcheck > notable_check_timeout:
        mes_count = settings.trygetset('%s_notable_message_count' % channel, 1)
        if mes_count <= message_limit:
            return False
        settings.setdata('%s_notable_last_check' % channel, time.time(), announce=False)
        return True
    else:
        # print notable_check_timeout - (time.time() - lastcheck)
        return False
Beispiel #12
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
Beispiel #13
0
def check_for_steam_dota_rss_update(channel, setkey=True):
    last_rss_check = settings.trygetset('%s_last_dota_rss_check' % channel, time.time())

    if time.time() - last_rss_check < 30.0:
        return

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

    rs = [li for li in node.get_steam_rss() if li]
    last_feed_url = settings.trygetset('%s_dota_last_steam_rss_update_url' % channel, '0')

    for item in rs:
        if not item: continue
        if item['author'] == 'Valve' and 'Dota 2 Update' in item['title']:
            if item['guid'] != last_feed_url:
                if last_feed_url == 'derp': last_feed_url = '0'

                try:
                    bpn_old = int([x for x in last_feed_url.split('/') if x][-1])
                    bpn_new = int([x for x in item['guid'].split('/') if x][-1])

                    if bpn_old >= bpn_new:
                        break
                except Exception as e:
                    print '[Dota-RSS] Error checking steam rss:', e
                    break

                settings.setdata('%s_dota_last_steam_rss_update_url' % channel, str(item['guid']))
                settings.setdata('%s_last_dota_rss_check' % channel, last_rss_check, announce=False)

                return str("Steam News Feed: %s - %s" % (item['title'], item['guid']))
            else:
                break


    rs = [li for li in node.get_dota_rss() if li]
    last_feed_url = settings.trygetset('%s_dota_last_dota2_rss_update_url' % channel, '0')

    for item in rs:
        if not item: continue
        if item['guid'] != last_feed_url:
            if last_feed_url == 'derp': last_feed_url = '0'

            try:
                bpn_old = int(last_feed_url.split('=')[-1])
                bpn_new = int(item['guid'].split('=')[-1])

                if bpn_old >= bpn_new:
                    break
            except Exception as e:
                print '[Dota-RSS] Error checking dota rss:', e
                break

            settings.setdata('%s_dota_last_dota2_rss_update_url' % channel, str(item['guid']))

            return str("Dota 2 Blog Post: %s - %s" % (item['title'], item['link']))
        else:
            break
Beispiel #14
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
Beispiel #15
0
def register_new_recurring(bot, name, message, timeout, duration=None, autostart=True):
    if settings.exists(name, recurring_domain):
        return False

    timeout = int(timeout)
    message = str(message)

    recurtask = task.LoopingCall(_online_check_wrapper, the_channel, message, bot)
    recurringid = id(recurtask)

    settings.setdata(name, recurringid, recurring_domain)
    settings.setdata(name + '_data', (timeout, message, time.time()), recurring_domain)

    print '[Recurring] Creating recurring %s for %s' % (name, the_channel)

    if autostart:
        recurtask.start(timeout, False)

    return True
Beispiel #16
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()
Beispiel #17
0
def register_new_recurring(bot, name, message, timeout, autostart=True):
    if settings.exists(name, recurring_domain):
        return False

    timeout = int(timeout)
    message = str(message)

    recurtask = task.LoopingCall(_online_check_wrapper, the_channel, message,
                                 bot)
    recurringid = id(recurtask)

    settings.setdata(name, recurringid, recurring_domain)
    settings.setdata(name + '_data', (timeout, message, time.time()),
                     recurring_domain)

    print '[Recurring] Creating recurring %s for %s' % (name, the_channel)

    if autostart:
        recurtask.start(timeout, False)

    return True
Beispiel #18
0
def checktimeout(channel):
    twitchchecktimeout = settings.trygetset('%s_twitch_online_check_timeout' % channel, 15)
    lastonlinecheck = settings.trygetset('%s_twitch_online_last_check' % channel, time.time())
    laststreamingstate = settings.trygetset('%s_last_twitch_streaming_state' % channel, False)

    try:
        if time.time() - int(lastonlinecheck) > twitchchecktimeout:
            is_streaming = twitchapi.is_streaming(channel)
            settings.setdata('%s_last_twitch_streaming_state' % channel, is_streaming, announce=False)
        else:
            return laststreamingstate
    except Exception as e:
        print '[Dota] twitch api check error: ',e
        return False

    if is_streaming:
        if time.time() - int(twitchchecktimeout) > float(lastonlinecheck):
            settings.setdata('%s_twitch_online_last_check' % channel, time.time(), announce=False)
        else:
            return True
    else:
        return False

    laststreamcheck = settings.trygetset('%s_last_is_streaming_check' % channel, time.time())
    streamchecktimeout = settings.trygetset('%s_is_streaming_timeout' % channel, 30)

    if time.time() - int(streamchecktimeout) > float(laststreamcheck):
        getmatchtimeout = settings.trygetset('%s_get_online_match_timeout' % channel, 20)
        settings.setdata('%s_last_is_streaming_check' % channel, time.time(), announce=False)

    getmatchtimeout = settings.trygetset('%s_get_match_timeout' % channel, 30)
    lastmatchfetch = settings.trygetset('%s_last_match_fetch' % channel, time.time())

    return time.time() - int(getmatchtimeout) > float(lastmatchfetch)
Beispiel #19
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])
Beispiel #20
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')
Beispiel #21
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)
Beispiel #22
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
Beispiel #23
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')
Beispiel #24
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')
Beispiel #25
0
def setup(bot):
    settings.setdata('%s_is_hosting' % bot.channel.replace('#', ''), False)
    settings.setdata('%s_hosted_channel' % bot.channel.replace('#', ''), '')
Beispiel #26
0
def setup(bot):
    settings.setdata('%s_is_hosting' % bot.channel.replace('#', ''), False)
    settings.setdata('%s_hosted_channel' % bot.channel.replace('#', ''), '')
Beispiel #27
0
def setup(bot):
    settings.setdata('%s_matchblurb_running' % bot.chan(), False, announce=False)
Beispiel #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
Beispiel #29
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)
Beispiel #30
0
def leave_lobby():
    with ZRPC() as zrpc:
        settings.setdata('current_lobby_id', '0')
        return zrpc.leavelobby()
Beispiel #31
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)

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

    try:
        matchdata['result']['players']
    except Exception as e:
        print 'Error with match data:', e
        raise e

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

    notableplayerdata = None
    separate_notable_message = False

    if notableplayers:
        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']:
            if p['account_id'] in notable_players:
                playerhero = str([h['localized_name'] for h in herodata['result']['heroes'] if str(h['id']) == str(p['hero_id'])][0]) # p['heroId'] ?

                if ID(p['account_id']) != ID(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']

    d_victory = matchdata['result']['radiant_win'] ^ (d_team != 'Radiant')

    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 = ''

    if playerdata['leaver_status'] in [2, 3]:
        winstatus = 'abandoned'
    elif playerdata['leaver_status'] == 4:
        winstatus = 'afk abandoned'
    elif playerdata['leaver_status'] in [5, 6]:
        winstatus = 'failed to connect to'
    elif d_victory:
        winstatus = 'won'
    else:
        winstatus = 'lost'

    matchoutput = "%s%s has %s a game.  http://www.dotabuff.com/matches/%s" % (
        matchskipstr,
        get_enabled_channels()[channel][0],
        winstatus,
        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 + (' -- ' + get_match_mmr_string(channel) if getmmr else '') + (' -- ' + notableplayerdata if notableplayerdata else '')

    if splitlongnotable:
        pass

    return finaloutput
Beispiel #32
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
Beispiel #33
0
def leave_lobby():
    with ZRPC() as zrpc:
        settings.setdata('current_lobby_id', '0')
        return zrpc.leavelobby()