Exemple #1
0
def get_all_current_players(dataDictionary):

    counter = 0
    myList = []

    try:
        if len(dataDictionary) > 0:

            # tme = datetime.now().strftime('%H:%M:%S')
            # mssg = f"{tme}"
            # # mssg = f"""```css\n{tme}```"""
            # myList.append(mssg)

            for key, value in dataDictionary.items():
                if counter > 1:
                    myList.append('Player::(' + key + ') PlayTime::(' + value +
                                  ')\n')
                    # print('Player::('+ key + ') PlayTime::('+ value +')')
                else:
                    myList.append(key + " " + value + '\n')
                counter += 1
    except Exception as e:
        print('An error occured in Battlemetric get_just_joined_players ::' +
              str(e))
        watcherLogging.error_logs(
            'An error occured in Battlemetric get_just_joined_players ::' +
            str(e))

    return myList
def get_chunked_data(yourList):

    totalChars = 0
    stringList = list()
    stringChunk = ""

    try:
        for val in yourList:
            stringChunk += val
            # print(myStr)
            #playerCount += 1
            totalChars += int(len(val))
            if totalChars >= 1000:
                stringList.append(str(stringChunk + "\n"))
                stringChunk = ''
                #print('Total Chars:' , totalChars)
                totalChars = 0
        if (len(stringChunk) > 0):
            stringList.append(str(stringChunk + '\n'))

    except Exception as e:
        print("Error get_chunked_data ERROR ::" + e)
        watcherLogging.error_logs('Error get_chunked_data ERROR ::' + str(e))

    return stringList
Exemple #3
0
def get_all_recent_player_info(serverIP, ServerPort):
    global mainIpandPort

    try:
        resp = requests.get("http://" + serverIP + ':' +
                            ServerPort + "/recent.json", allow_redirects=True)
        print("check for all player recent info Address" + str(mainIpandPort))
        myList = []
        playerCount = 0

        # print(resp.content)

        players = json.loads(resp.content)

        for p in players:
            myList.append('player=(' + p['name'] + ') id=(' + p['id'] + ')\n')
            playerCount += 1
        myList.append("Total recent players::{}" .format(playerCount) + '\n')

    except Exception as e:
        print("Error has occured in PlayRust.io request get_all_recent_player_info ::" + str(e))
        watcherLogging.error_logs(
            'Error has occured in PlayRust.io request get_all_recent_player_info ::' + str(e))

    return myList
async def on_message(message):
    # id = client.get_guild(1234567890)
    # myLocalDic = myDiction
    # channels = ["the-watcher-commands"]
    global bot_channel_commands
    myAllList = []
    # cmdChannel = myBot.get_channel(1234567890)
    cmdChannel = myBot.get_channel(bot_channel_commands)
    if message.author == myBot.user:
        return
    # if str(message.channel) in channels:
    if message.channel.id == cmdChannel.id:
        myMessage = message.content.lower()
        if myMessage.startswith('>players'):
            print("Received players cmd")
            try:
                if myLocalDic is not None and len(myLocalDic) > 0:
                    # myDiction = battleMetricsScraping.get_Data_Now(mainUrl)
                    myAllList = battleMetricsScraping.get_all_current_players(
                        myLocalDic)
                    # for p in myAllList:
                    # print(p)
                    if len(myAllList) > 0:
                        print('running all players parse')
                        myChunkedList1 = chunkedData.get_chunked_data(
                            myAllList)
                        for allP in myChunkedList1:
                            print(allP)
                            await message.channel.send(allP)
                            # give the chunked data to the bot to send to the channel
                            # await message.channel.send("implement count players here")
                    else:
                        print('No player data Yet...')
                        await message.channel.send("No player data Yet...")
                        # await message.channel.send('No player data Yet...')
                else:
                    print('Bot not ready Yet...')
                    await message.channel.send("Bot not ready Yet...")
            except Exception as e:
                print('An error occured in on_message Discord Bot ::' + str(e))
                watcherLogging.error_logs(
                    'An error occured in on_message Discord Bot ::' + str(e))

        elif myMessage.startswith(">pinfo"):
            print("Received pinfo cmd")
            try:
                pInfoList = playerDatabase.get_DB_linked_player_Embed_List()
                for itmEmbed in pInfoList:
                    await message.channel.send(embed=itmEmbed)
            except Exception as e:
                print('An error occured in on_message Discord Bot ::' + str(e))
                watcherLogging.error_logs(
                    'An error occured in on_message Discord Bot ::' + str(e))

        elif myMessage.startswith(">help"):
            helpMsg = ">players :: All Online players \n"\
                ">pinfo :: All players saved from database \n"\
                ">help :: This help menu"
            await message.channel.send(helpMsg)
def read_cofig():

    myDic = {}

    try:
        from configparser import ConfigParser
    except ImportError:
        from ConfigParser import ConfigParser  # ver. < 3.0

    # instantiate
    config = ConfigParser()

    try:
        filename = inspect.getframeinfo(inspect.currentframe()).filename
        path = os.path.dirname(
            os.path.abspath(filename)) + "/Setup/the_watcher_config.ini"
        print("Config Path :" + path)

        # parse existing file
        config.read(path)

        # read values from a section
        battlemetrics_url = config.get('section_a', 'battlemetrics_url')
        myDic['battlemetrics_url'] = battlemetrics_url

        server_ip = config.get('section_a', 'server_ip')
        myDic['server_ip'] = server_ip

        server_port = config.get('section_a', 'server_port')
        myDic['server_port'] = server_port

        bot_id = config.get('section_b', 'bot_id')
        myDic['bot_id'] = bot_id

        bot_channel_player_joined = config.getint('section_b',
                                                  'bot_channel_player_joined')
        myDic['bot_channel_player_joined'] = bot_channel_player_joined

        bot_channel_commands = config.getint('section_b',
                                             'bot_channel_commands')
        myDic['bot_channel_commands'] = bot_channel_commands

        bot_player_name_changes = config.getint('section_b',
                                                'bot_player_name_changes')
        myDic['bot_player_name_changes'] = bot_player_name_changes

        bot_enable_name_changes = config.getboolean('section_b',
                                                    'bot_enable_name_changes')
        myDic['bot_enable_name_changes'] = bot_enable_name_changes

        return myDic

    except Exception as e:
        print("Error reading config ::" + str(e))
        watcherLogging.error_logs('Error has occured in read_cofig ::' +
                                  str(e))
Exemple #6
0
def get_logged_off_players(originalDiction, newDiction):

    myList = []
    # skips the first 2 rows as its the sitename and player count
    counter = 0

    siteHeader = ""
    siteTotPlayer = ""
    headerCount = 0

    try:
        if len(newDiction) > 0:

            tme = datetime.now().strftime('%H:%M:%S')
            mssg = f":red_circle: Logged {tme}\n"
            myList.append(mssg)

            for nKey, nVal in newDiction.items():
                if headerCount == 0:
                    siteHeader = nKey + " " + nVal + "\n"
                    myList.append(siteHeader)
                elif headerCount == 1:
                    siteTotPlayer = nKey + " " + nVal + "\n"
                    myList.append(siteTotPlayer)
                headerCount += 1

            for orgKey, orgVal in originalDiction.items():
                if counter > 1:
                    if orgKey in newDiction.keys():
                        print('Still On :' + orgKey + ' Playing For :' +
                              orgVal)
                        # print('Still On :' + orgKey + ' Playing For :' + orgVal)
                        # print(' ')
                    else:
                        print(':x: :' + orgKey + ' Played For :' + orgVal)
                        myList.append(':x: ::(' + orgKey + ') PlayTime::(' +
                                      orgVal + ")\n")
                # else:
                # myList.append(orgKey + " " + orgVal + '\n')
                counter += 1

    except Exception as e:
        print('An error occured in Battlemetric get_logged_off_players ::' +
              str(e))
        watcherLogging.error_logs(
            'An error occured in Battlemetric get_logged_off_players ::' +
            str(e))

    return myList
Exemple #7
0
def get_just_joined_players(dataDictionaryNew, dataDictionaryOld):

    myTime = datetime.strptime('12:12', '%H:%M')
    myCompareTime = datetime.strptime('00:01', '%H:%M')
    myList = []
    counter = 0

    try:
        if len(dataDictionaryNew) > 0:

            tme = datetime.now().strftime('%H:%M:%S')
            mssg = f":green_circle: Joined {tme}\n"
            myList.append(mssg)

            for key, value in dataDictionaryNew.items():

                # print('Player::('+ key + ') PlayTime::('+ value +')')
                # skip the first 2 as they are headers(servername/playercount)
                if counter > 1:
                    if key in dataDictionaryOld:
                        print("Key Found ::" + str(key))
                    else:
                        myTime = datetime.strptime(value, '%H:%M')
                        if myTime.time() <= myCompareTime.time():
                            # print('Player Joined::('+ key + ') PlayTime::('+ value +')')
                            myList.append(':white_check_mark: ::(' + key +
                                          ') PlayTime::(' + value + ')\n')
                else:
                    myList.append(key + " " + value + '\n')
                counter += 1
    except Exception as e:
        print('An error occured in Battlemetric get_just_joined_players ::' +
              str(e))
        watcherLogging.error_logs(
            'An error occured in Battlemetric get_just_joined_players ::' +
            str(e))

    return myList
Exemple #8
0
def check_for_player_name_changes(serverIP, ServerPort):
    global mainIpandPort
    playerDbList = []
    myReturnList = []
    try:
        resp = requests.get("http://" + serverIP + ':' +
                            ServerPort + "/recent.json", allow_redirects=True)
        print("check for player name changes Address" + str(mainIpandPort))
        #myDic = {}

        # print(resp.content)

        players = json.loads(resp.content)

        for p in players:
            playerDbList = playerDatabase.check_for_existing_player(p['id'])
            if len(playerDbList) > 0:
                for pData in playerDbList:
                    if pData[2] != p['name']:
                        # check if the name has changed
                        playerDatabase.update_player_name(p['id'], p['name'])
                        myReturnList.append(
                            "Player ::" + pData[1] + " Now Playing as ::" + p['name'] + '\n')
                        print("player changed name")
            else:
                # add new player to the database
                playerDatabase.add_player_data(p['id'], p['name'], p['name'])
                print("Added new player :: Id:" +
                      p['id'] + " Name:" + p['name'])

            # add or check player in the database

    except Exception as e:
        print("Error has occured in PlayRust.io request check_for_player_name_changes ::" + str(e))
        watcherLogging.error_logs(
            'Error has occured in PlayRust.io request check_for_player_name_changes ::' + str(e))

    return myReturnList
async def update_players():
    await myBot.wait_until_ready()

    global battlemetrics_url
    global server_ip
    global server_port
    global bot_channel_player_joined

    print('Started....')
    thirtyMinCounter = 0
    # create the table if its not been created on launch
    playerDatabase.create_player_table()
    loggedDictionCompare = {}
    myDiction = {}

    while not myBot.is_closed():
        print('===========')
        try:
            if isReady:

                # myDiction = {}
                myDiction = battleMetricsScraping.get_Data_Now(
                    battlemetrics_url)
                global myLocalDic
                global myDictionOLD
                myLocalDic = myDiction

                # GET ALL CURRENT PLAYERS
                print('running all players call')
                myAllList = battleMetricsScraping.get_all_current_players(
                    myDiction)
                # for p in myAllList:
                # print(p)
                if len(myAllList) > 0:
                    print('running all players parse')
                    myChunkedList1 = chunkedData.get_chunked_data(
                        myAllList)
                    for allP in myChunkedList1:
                        print(allP)
                        # give the chunked data to the bot to send to the channel

                # GET JUST JOINED PLAYERS
                print('running player joined call')
                myPList = battleMetricsScraping.get_just_joined_players(
                    myDiction, myDictionOLD)

                if len(myPList) > 3:
                    print('running player joined bot parse')
                    myChunkedList2 = chunkedData.get_chunked_data(
                        myPList)
                    for pJoin in myChunkedList2:
                        # give the chunked list to the bot to send to the channel
                        print(pJoin)

                        # send to player-joined-logged channel with the channel id
                        channel = myBot.get_channel(
                            bot_channel_player_joined)
                        await channel.send(pJoin + '\n')
                    # last list of updated players if it contains the same players dont resend a minute later
                    myDictionOLD = myDiction
                else:
                    myDictionOLD = {}

                # GET PLAYERS LOGGED OFF
                print('running player logged call')
                if len(loggedDictionCompare) > 0:
                    myLoggedOutList = battleMetricsScraping.get_logged_off_players(
                        loggedDictionCompare, myDiction)
                    print(f"Player logged off debug ::{len(myLoggedOutList)}")
                    if len(myLoggedOutList) > 3:
                        print('running player logged parse')
                        # for item in myLoggedOutList:
                        # print(item)
                        myChunkedList3 = chunkedData.get_chunked_data(
                            myLoggedOutList)
                        # give the chunked list to the bot to send to the channel
                        for pLogged in myChunkedList3:
                            print(pLogged)
                            # send to player-joined-logged channel
                            channel = myBot.get_channel(
                                bot_channel_player_joined)
                            await channel.send(pLogged + '\n')

                # GET PLAYER NAME CHANGES
                if(thirtyMinCounter >= 30 and bot_enable_name_changes == True):
                    print('running player name changes not setup yet')
                    pNameChangeList = []
                    pNameChangeList = playRustIO.check_for_player_name_changes(
                        server_ip, server_port)
                    myChunkedList4 = chunkedData.get_chunked_data(
                        pNameChangeList)
                    # give to the discord bot to send to the channel
                    for pName in myChunkedList4:
                        print(pName)
                        # send to player-name-changes channel
                        channel = myBot.get_channel(bot_player_name_changes)
                        await channel.send(pName + '\n')

                    thirtyMinCounter = 0
                else:
                    thirtyMinCounter = 0

            thirtyMinCounter += 1
            loggedDictionCompare = myDiction
            # myLocalDic = myDiction
            print("Thirty Minute Counter Value :{}".format(thirtyMinCounter))
            print('Sleeping for 1 min')
            # sleep for 5 mins
            # await asyncio.sleep(30)
            # #send to player-joined-logged channel
            # channel = myBot.get_channel(1234567890)
            # await channel.send('This ia Test')
            # print('Msg sent')
        except Exception as e:
            print("Rust Bot Loop ERROR::" + str(e))
            watcherLogging.error_logs(
                "Rust Bot Loop ERROR::" + str(e))
            await asyncio.sleep(10)

        await asyncio.sleep(60)
Exemple #10
0
def get_Data_Now(myUrl):

    myDic = {}

    mainUrl = myUrl

    # isGoodRequest = False

    # # Windows 10 with Google Chrome
    # user_agent_Windows = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '\
    #     'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 '\
    #     'Safari/537.36'

    # # Windows 10 with Firefox Full headers
    # user_agent_Windows = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0'

    # Windows 10 with Firefox
    user_agent_Windows = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0',
        'Accept': 'text/html; charset=utf-8',
        'Accept-Language': 'en-US,en;q=0.5'
    }

    session = requests.session()
    session.headers.update(user_agent_Windows)

    # non ascii charcters converter, normally used for IDLE
    non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)

    try:

        response = session.get(mainUrl, allow_redirects=True, timeout=(
            2, 5
        ))  # Send request (tuple #1 = get request timeout #2 = read timeout)

        if response.history:
            print("Request was redirected")
            for resp in response.history:
                print(resp.status_code, resp.url)
                print("Final destination:")
                print(response.status_code, response.url)
        else:
            print("Request was not redirected")

        code = response.status_code  # HTTP response code

        if code == 200:
            print(f'Good Request From Battlemetrics: {code}')
            # isGoodRequest = True
        else:
            # isGoodRequest = False
            print(f'Error to load Battlemetrics: {code}')
            watcherLogging.error_logs(f'Error to load Battlemetrics: {code}')
            return myDic

        serverName = ''

        soup = BeautifulSoup(response.text, 'html.parser')

        # this spits out raw html as a string
        # print('PrintOut =' + str(soup.encode("utf-8")))

        myDic = {}

        if soup is None:
            return

        # findServerName = soup.find(id='serverPage').get_text()
        div = soup.find('div', id="main")
        if div is not None:
            # table = div.find_all('h2')
            # print('Found =' + div[0])
            print('List Count =' + str(len(div)))
        else:
            print('Not Found')
            return

        # temp = soup.get_text()
        temp = soup.find("h2").find_all(text=True, recursive=False)
        if temp != None and len(temp) >= 1:
            serverName = temp[0]
            # serverName = temp.get_text()
        else:
            return

        temp2 = soup.find(class_='css-1i1egz4').find_all('dd')[1]
        if temp2 != "":
            getPyCount = temp2.get_text()

        myDic = {"Server::": serverName, "Players Online::": getPyCount}

        i = 0

        playTime = soup.find_all('tbody')
        for pTime in playTime:
            py = pTime.find_all('a')
            pt = pTime.find_all('time')
            for p in py:
                # print('Player::('+ p.get_text() + ') PlayTime::('+ pt[i].get_text()+')')
                # myDic[p.get_text()] = pt[i].get_text()
                pNameUni = str(p.get_text()).translate(non_bmp_map)
                myDic[pNameUni] = pt[i].get_text()
                # print(pt[i].get_text())
                i = i + 1

    except requests.exceptions.HTTPError as e:
        print('HTTP ERROR::' + str(e))
        watcherLogging.error_logs(
            'An error occured in hhtp Battlemetric web scraping ::' + str(e))
    except requests.exceptions.ConnectionError as e:
        print('CONNECTION ERROR::' + str(e))
        watcherLogging.error_logs(
            'An error occured in connection Battlemetric web scraping ::' +
            str(e))
    except Exception as e:
        print('An error occured in Battlemetric web scraping ::' + str(e))
        watcherLogging.error_logs(
            'An error occured in Battlemetric web scraping ::' + str(e))
        return myDic

    return myDic