camm9909 / valheim-discord-bot

Valheim Discord bot that reports in-game players and events
34 stars 19 forks source link

Troubles getting the bot running. #8

Open wtfcolt opened 3 years ago

wtfcolt commented 3 years ago
wtfcolt@reckless-server:~/valheim-discord-bot/code$ python3 ./vdb_main.py
csv/playerstats.csv found!
csv/deathlog.csv found!
Main loop: init
Bot connected as Valheim#7322 :)
Log channel : 883147625321353237
VoIP channel: 889234004002340865
Task exception was never retrieved
future: <Task finished name='Task-13' coro=<serverstatsupdate() done, defined at ./vdb_main.py:181> exception=BrokenMessageError("Invalid value (65) for field 'response_type'")>
Traceback (most recent call last):
  File "/home/wtfcolt/.local/lib/python3.8/site-packages/valve/source/messages.py", line 91, in validate
    raise ValueError
ValueError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./vdb_main.py", line 187, in serverstatsupdate
    await channel.edit(name=f"{emoji.emojize(':eggplant:')} In-Game: {server.info()['player_count']}" +" / 10")
  File "/home/wtfcolt/.local/lib/python3.8/site-packages/valve/source/a2s.py", line 140, in info
    return messages.InfoResponse.decode(self.get_response())
  File "/home/wtfcolt/.local/lib/python3.8/site-packages/valve/source/messages.py", line 415, in decode
    values[field.name], buffer = field.decode(buffer, values)
  File "/home/wtfcolt/.local/lib/python3.8/site-packages/valve/source/messages.py", line 41, in needs_buffer
    return func(self, buffer, *args, **kwargs)
  File "/home/wtfcolt/.local/lib/python3.8/site-packages/valve/source/messages.py", line 130, in decode
    return (self.validate(
  File "/home/wtfcolt/.local/lib/python3.8/site-packages/valve/source/messages.py", line 93, in validate
    raise BrokenMessageError(
valve.source.messages.BrokenMessageError: Invalid value (65) for field 'response_type'

Did I misconfigure something?

spud11 commented 3 years ago

I was having the same issue after upgrading to H&H. My solution was to replace the python-valve library (which is currently unmaintained) with python-a2s. Below are the changes I made after installing the python-a2s library.

File: code/_logsubprocess.py

 from datetime import datetime
-import time, os, re
+from socket import timeout
+import time, os, re, a2s
 import csv, asyncio
-from valve.source.a2s import ServerQuerier, NoResponseError
 import config

 pdeath = '.*?Got character ZDOID from (\w+) : 0:0'
@@ -15,13 +15,13 @@
 async def writecsv():
     while True:
         try:
-            with ServerQuerier(config.SERVER_ADDRESS) as server:
-                with open('csv/playerstats.csv', 'a', newline='') as f:
-                    csvup = csv.writer(f, delimiter=',')
-                    curtime, players = await timenow(), server.info()['player_count']
-                    csvup.writerow([curtime, players])
-                    print(curtime, players)
-        except NoResponseError:
+            server = a2s.info(config.SERVER_ADDRESS)
+            with open('csv/playerstats.csv', 'a', newline='') as f:
+                csvup = csv.writer(f, delimiter=',')
+                curtime, players = await timenow(), server.player_count
+                csvup.writerow([curtime, players])
+                print(curtime, players)
+        except timeout:
             with open('csv/playerstats.csv', 'a', newline='') as f:
                 csvup = csv.writer(f, delimiter=',')
                 curtime, players = await timenow(), '0'

File: code/vdb_main.py

-import os, time, re, csv, discord, asyncio, config, emoji, sys, colorama, typing, signal, errno
-from valve.source.a2s import ServerQuerier, NoResponseError
+import os, time, re, csv, a2s, discord, asyncio, config, emoji, sys, colorama, typing, signal, errno
 from matplotlib import pyplot as plt
 from datetime import datetime, timedelta
 from colorama import Fore, Style, init
@@ -7,6 +6,7 @@
 from config import VCHANNEL_ID as chanID
 from config import file
 from discord.ext import commands
+from socket import timeout
 import matplotlib.dates as md
 import matplotlib.ticker as ticker
 import matplotlib.spines as ms
@@ -182,11 +182,10 @@
    await bot.wait_until_ready()
    while not bot.is_closed():
            try:
-                       with ServerQuerier(config.SERVER_ADDRESS) as server:
-                               channel = bot.get_channel(chanID)
-                               await channel.edit(name=f"{emoji.emojize(':eggplant:')} In-Game: {server.info()['player_count']}" +" / 10")
-
-           except NoResponseError:
+                       server = a2s.info(config.SERVER_ADDRESS)
+                       channel = bot.get_channel(chanID)
+                       await channel.edit(name=f"{emoji.emojize(':eggplant:')} In-Game: {server.player_count} / {server.max_players}")
+           except timeout:
                        print(Fore.RED + await timenow(), 'No reply from A2S, retrying (30s)...' + Style.RESET_ALL)
                        channel = bot.get_channel(chanID)
                        await channel.edit(name=f"{emoji.emojize(':cross_mark:')} Server Offline")
wtfcolt commented 3 years ago

Thanks @spud11! It seems to be running just fine now. It might be worth considering putting that into a pull request .

ArmEagle commented 2 years ago

Indeed thanks! This works flawlessly!

tiagojofran commented 2 years ago

Hi! So, I started testing the bot today and it records deaths to the CSV file and posts messages for the in-game events to my discord server as expected, but I can't get the functionality related to player stats to work. The playerstats.csv file is not getting any update when players join the server, and the script is looping this message indefinitely:

valheim-server python3[2340]: 09/01/2022 23:32:05 No reply from A2S, retrying (30s)...

As a result, the stats command always returns a blank plot. Any tips on how to solve this issue? By the way, I'm using the code from the forked repo by bayoumaroon. Thanks in advance!

stolenvw commented 2 years ago

Hi! So, I started testing the bot today and it records deaths to the CSV file and posts messages for the in-game events to my discord server as expected, but I can't get the functionality related to player stats to work. The playerstats.csv file is not getting any update when players join the server, and the script is looping this message indefinitely:

valheim-server python3[2340]: 09/01/2022 23:32:05 No reply from A2S, retrying (30s)...

As a result, the stats command always returns a blank plot. Any tips on how to solve this issue? By the way, I'm using the code from the forked repo by bayoumaroon. Thanks in advance!

are you running the server with Public = 1 ? And did you set the correct ip and port for SERVER_ADDRESS in the bots config

tiagojofran commented 2 years ago

are you running the server with Public = 1 ? And did you set the correct ip and port for SERVER_ADDRESS in the bots config

No, on my server, Public is set to 0. The bot script is running on the same machine as the game server, so I'm using the loopback IP (127.0.0.1) for SERVER_ADDRESS and PORT is set to 2457 (2456 +1 as recommended by the creator of the bot).

By the way, I just remembered that when I tried to run the bot script for the first time, it returned an error related to the import of A2S module, so I manually included the line python-a2s==1.3.0 to the requirements.txt file and installed this module with pip, and the error was gone. Do you think that may have caused the issue?

stolenvw commented 2 years ago

are you running the server with Public = 1 ? And did you set the correct ip and port for SERVER_ADDRESS in the bots config

No, on my server, Public is set to 0. The bot script is running on the same machine as the game server, so I'm using the loopback IP (127.0.0.1) for SERVER_ADDRESS and PORT is set to 2457 (2456 +1 as recommended by the creator of the bot).

By the way, I just remembered that when I tried to run the bot script for the first time, it returned an error related to the import of A2S module, so I manually included the line python-a2s==1.3.0 to the requirements.txt file and installed this module with pip, and the error was gone. Do you think that may have caused the issue?

Thats why it dont work then. A2S dont work if server is set to Public = 0

tiagojofran commented 2 years ago

are you running the server with Public = 1 ? And did you set the correct ip and port for SERVER_ADDRESS in the bots config

No, on my server, Public is set to 0. The bot script is running on the same machine as the game server, so I'm using the loopback IP (127.0.0.1) for SERVER_ADDRESS and PORT is set to 2457 (2456 +1 as recommended by the creator of the bot). By the way, I just remembered that when I tried to run the bot script for the first time, it returned an error related to the import of A2S module, so I manually included the line python-a2s==1.3.0 to the requirements.txt file and installed this module with pip, and the error was gone. Do you think that may have caused the issue?

Thats why it dont work then. A2S dont work if server is set to Public = 0

Absolutely correct, sir! I just changed Public to 1 and now it works perfectly! Thank you so much for the help, I really appreciate that. Have a great day!