コード例 #1
0
ファイル: log_parser.py プロジェクト: wchesley/discord_bot.py
 def remove_text_inside_brackets(text, brackets="{}[]()"):
     """Helper function to remove brackets, and text within them, from string"""
     # Pulled from answer by jfs at https://stackoverflow.com/questions/14596884/remove-text-between-and/14603508#14603508
     # Count open/closed brackets
     count = [0] * (len(brackets) // 2)  # count open/close brackets
     saved_chars = []
     for character in text:
         for i, b in enumerate(brackets):
             if character == b:  # found bracket
                 kind, is_close = divmod(i, 2)
                 count[kind] += (-1)**is_close  # `+1`: open, `-1`: close
                 if count[kind] < 0:  # unbalanced bracket
                     count[kind] = 0  # keep it
                 else:  # found bracket to remove
                     break
         else:  # character is not a [balanced] bracket
             if not any(count):  # outside brackets
                 saved_chars.append(character)
     # Rejoin the characters into a string: 
     message = ''.join(saved_chars)
     default.s_print(f'Messsage before strip: {message}')
     # Remove any trailing or leading whitespace
     message = message.strip()
     default.s_print(f'returning: {message}')
     return message
コード例 #2
0
ファイル: mongoDB.py プロジェクト: wchesley/discord_bot.py
 def icontains_get_player_by_zdoid(zdoid):
     """ Search for player by valheim name using mongonengine icontains. Returns all 
     possible matches for the quersy in a case INsensitive manor"""
     try:
         player = Player.objects.get(zdoid__icontains=zdoid)
         return player
     except Exception as e:
         default.s_print(f'Error finding player via icontains: {e}')
         return 1
コード例 #3
0
ファイル: mongoDB.py プロジェクト: wchesley/discord_bot.py
 def get_player_by_steam_id(steamID):
     try:
         player = Player.objects.get(steamID=steamID)
         return player
     except Exception as e:
         default.s_print(
             f'Error getting player:\nget_player_by_steam_id threw:\n\t {e}'
         )
         return 1
コード例 #4
0
ファイル: mongoDB.py プロジェクト: wchesley/discord_bot.py
 def update_player_death_count(zdoid):
     try:
         player = Player.objects.get(valheim_name=zdoid)
         player.death_count += 1
         player.save()
         default.s_print(
             f'updated player death count: {player.death_count}')
     except Exception as e:
         default.s_print(f'Something happened? {e}')
コード例 #5
0
ファイル: mongoDB.py プロジェクト: wchesley/discord_bot.py
 def player_disconnect(SteamID):
     try:
         player = Player.objects.get(steamID=SteamID)
         player.online_state = False
         MongoDB_Context.update_online_count(-1)
     except DoesNotExist:
         default.s_print(
             f'Cannot disconnect player not in database!\n{SteamID} Was not found in Database!'
         )
コード例 #6
0
ファイル: log_parser.py プロジェクト: wchesley/discord_bot.py
 def remove_date(log_line):
     """ Remove date from valheim server log message, retuns message and date as datetime object."""
     # Incoming format has to be: 04/12/2021 19:55:55: Closing socket 76561197999876368
     #log_line = log_line.strip() # Remove leading and trailing whitespace: 
     default.s_print(f'Received: \n{log_line}\n^^^ REMOVE_DATE()')
     new_date = LogLine.strip_date_from_string(log_line)
     message = log_line.replace(str(new_date) + ': ','')
     default.s_print(f'New date type: {type(new_date)}\nData: {new_date}\nMessage type: {type(message)}\nData: {message}')
     return new_date, message
コード例 #7
0
ファイル: mongoDB.py プロジェクト: wchesley/discord_bot.py
 def get_player_by_zdoid(zdoid):
     """ Find player by their valheim name, return their player object"""
     try:
         player = Player.objects.get(valheim_name=zdoid)
         return player
     except Exception as e:
         default.s_print(
             f'Error getting player:\nget_player_death_count threw: \n\t{e}'
         )
         return 1
コード例 #8
0
 async def on_death(self, death_count, player_name):
     """ Announce death of player in valheim Server """
     death_message = [
         "was squased by a troll", "fell victim to gredwarves",
         "ascended to the 10th dead world", "was fondled by greylings",
         "took a deathsquito from behind", "was collected by the Valkyrie",
         "failed Odin's test", "In Soviet Russia, tree fell you!"
     ]
     rng_death_msg = random.choice(death_message)
     # Knights of Ni Bot Spam Channel ID: 831250902470885406
     default.s_print(f'Death event for {player_name} {rng_death_msg}')
     bot_spam = self.bot.channel.get(831250902470885406)
     await bot_spam.send(
         f'RIP {player_name} {rng_death_msg}\nTotal Vikings lost: {death_count}'
     )
コード例 #9
0
ファイル: mongoDB.py プロジェクト: wchesley/discord_bot.py
 def update_total_player_count():
     player_count = len(Player.objects)
     try:
         player_server_stats = PlayerServerStats.objects.get(
             key="242c7b80-314b-4d38-b92b-839035f62382")
         player_server_stats.total = player_count
         player_server_stats.save()
         default.s_print(f'updated total player count: {player_count}')
     except DoesNotExist:
         player_server_stats = PlayerServerStats(
             key="242c7b80-314b-4d38-b92b-839035f62382",
             online_count=1,
             offline_count=0,
             total=player_count)
         player_server_stats.save()
         default.s_print(f'Created playerServerStats Document')
コード例 #10
0
ファイル: mongoDB.py プロジェクト: wchesley/discord_bot.py
 def update_online_count(count):
     """ updates online count of players, count can be positive or negative, depending if a player is coming or going. """
     try:
         player_server_stats = PlayerServerStats.objects.get(
             key="242c7b80-314b-4d38-b92b-839035f62382")
         player_server_stats.online_count += count
         player_server_stats.save()
         default.s_print(
             f'Updated PlayerServerStats: {player_server_stats.online_count}'
         )
     except DoesNotExist:
         player_server_stats = PlayerServerStats(
             key="242c7b80-314b-4d38-b92b-839035f62382",
             online_count=1,
             offline_count=0,
             total=1)
         player_server_stats.save()
         default.s_print(f'Created playerServerStats Document')
コード例 #11
0
ファイル: log_parser.py プロジェクト: wchesley/discord_bot.py
 def strip_date_from_string(date, removal_char=':'):
     count = 0
     #removal_char = ':'
     date_chars = ''
     for char in date:
         if char == removal_char:
             count += 1
         if count == 3:
             break
         date_chars += char
     date_string = "".join(date_chars)
     # try:
     #     date_string = datetime.strptime(date_string, "%m/%d/%Y %H:%M:%S")
     #     return date_string
     # except ValueError as e:
     #     default.s_print(f"error parsing date: {e}")
     default.s_print(f'strip date from string: {date_string}')
     return date_string
コード例 #12
0
ファイル: mongoDB.py プロジェクト: wchesley/discord_bot.py
    def update_player(player_obj):
        """ 
        Update or create player in Valheim database. \n
        Attempts to find player by SteamID, if not found creates a new entry in the database \n
        Increments Total Player count by 1
        """
        default.s_print(f'Received player_obj:')
        for item in player_obj.items():
            default.s_print(item)
        try:
            player = Player.objects.get(steamID=player_obj['SteamID'])

            if player_obj['SteamName'] != player.steam_name:
                default.s_print(
                    f'Updating steamName: {player_obj["SteamName"]}')
                player.steam_name = player_obj['SteamName']
            else:
                default.s_print(
                    f'Values matched: {player_obj["SteamName"]} == {player.steam_name}'
                )

            if player_obj['ZDOID'] != player.valheim_name:
                default.s_print(f'Updating steamName: {player_obj["ZDOID"]}')
                player.steam_name = player_obj['SteamName']
            else:
                default.s_print(
                    f'Values matched: {player_obj["ZDOID"]} == {player.valheim_name}'
                )

            try:
                player.last_login_time = player_obj['steam_logim_time']
            except Exception as e:
                default.s_print(
                    f'Could not save date to DB, setting default time: \nDATETIME ERROR: {e}'
                )
                player.last_login_time = datetime.now()

            player.online_state = True
            MongoDB_Context.update_online_count(1)
            player.save()
        except DoesNotExist:
            player = Player(steamID=player_obj['SteamID'],
                            steam_name=player_obj['SteamName'],
                            valheim_name=player_obj['ZDOID'],
                            death_count=0,
                            last_login_time=player_obj['steam_login_time'],
                            online_state=True)
            player.save()
            default.s_print(
                f'Created new player: \n{player.steamID} / {player.steam_name} / {player.valheim_name}'
            )
            MongoDB_Context.update_online_count(1)
            MongoDB_Context.update_total_player_count()
コード例 #13
0
import os, tracemalloc, sys
import discord
import logging
import asyncio

from utils import default
from utils.data import Bot, HelpFormat
from data.mongoDB import MongoDB_Context
from valheim_server.log_dog import ValheimLogDog

# tracemalloc.start()
config = default.config()
default.s_print("Logging in...")

bot = Bot(
    command_prefix=config["prefix"], prefix=config["prefix"],
    owner_ids=config["owners"], command_attrs=dict(hidden=True), help_command=HelpFormat(),
    allowed_mentions=discord.AllowedMentions(roles=False, users=True, everyone=False),
    intents=discord.Intents(  # kwargs found at https://discordpy.readthedocs.io/en/latest/api.html?highlight=intents#discord.Intents
        guilds=True, members=True, messages=True, reactions=True, presences=True
    )
)

for file in os.listdir("cogs"):
    if file.endswith(".py"):
        name = file[:-3]
        bot.load_extension(f"cogs.{name}")
        logging.info(f'Loaded extension: {name}')

try:
    asyncio.get_event_loop().create_task(ValheimLogDog(bot).start())