Browse Source

Add stub for Discord Bot, and logging stubs.

Mike Greene 4 months ago
parent
commit
0f98ee5191
6 changed files with 144 additions and 11 deletions
  1. 25 0
      DiscordBot.md
  2. 99 0
      discord-bot.py
  3. 2 1
      gatherMarket.py
  4. 10 0
      logger.py
  5. 1 10
      market.py
  6. 7 0
      player.py

+ 25 - 0
DiscordBot.md

@@ -0,0 +1,25 @@
+# Booby Legends Economy Discord Bot
+I wanted to track the economy in the game Booby Legends so that I could decide how to best sell and purchase cards.  It works great for me, but I wanted to share it with my friends.  They can't neccessarily easily use a python session, so it was essesntially only usable by me.  Since we already use a Discord server, I decided to implement a quick interface for the historical card database from within Discord.  I think it works ok.
+
+The discord bot requires a file "discord.json" in the folder of the script.  it must look like:
+
+```javascript
+{
+	"Tokens":{
+		"BoobyLegendsEcon":{
+			"Token":"aroiusyghtbflaiwhgtlihw4itrehawilughtliuaygw4tliuawl4uktwgWsttw",
+			"ClientID":"1232413434323543242345",
+			"SecretKey":"awoiurtghl234hru234hgtb3j24bgtjgb34tbl3"
+		}
+	}
+}
+```
+
+I found this tutorial helpful in creating an app and getting it logged into our Discord Server.
+(https://discordpy.readthedocs.io/en/stable/discord.html)
+
+I jsut run the python with:
+```bash
+python3 discord-bot.py
+```
+The new discord.py stuff requires python 3.8 or better.

+ 99 - 0
discord-bot.py

@@ -0,0 +1,99 @@
+import json
+import sys
+import logging
+import discord
+from config import Config
+from logger import logger
+from db import MarketDB
+
+TOKEN = Config["Tokens"]["BoobyLegendsEcon"]["Token"]
+
+def parse(input,author):
+	# parse the input string from the message so that we can see what we need to do
+    parts = input.strip().split()
+    logger.debug(input)
+    logger.debug(parts)
+
+    #global decoder
+ 
+    AuthorName = author
+
+	#drop out if this is not a Roll command
+    if len(parts) == 0:
+        return None
+    if parts[0].upper() not in ['!','/','\\']:
+		#Try to make a command if first character is !
+        if parts[0][0]=="!":
+            pt=["!",parts[0][1:]]
+            pt.extend(parts[1:])
+            parts=pt
+            logger.debug(parts)
+        else:
+            logger.debug("Not a command")
+            return None
+
+    try:
+        logger.debug("Command: "+parts[1].upper())
+        if parts[1].upper() == "HISTORY":
+            name = ' '.join(parts[2:])
+            logger.info("History for: "+name)
+            history=""
+			#give user message so he knows it's saved
+            retstr = "{Author} requested history for {name}:\n{history}".format(
+				Author=author,
+		        name=name,
+                history=history
+		        )
+            logger.debug(retstr)
+        elif parts[1].upper() == "TODAY":
+           logger.info("Today")
+           retstr = ""
+        elif parts[1].upper() in ["LOGLEVEL"]:
+            if parts[2].upper() == "DEBUG":
+                logger.setLevel(logging.DEBUG)
+            elif parts[2].upper() == "INFO":
+                logger.setLevel(logging.INFO)
+            retstr= "LogLevel set to "+parts[2].upper()
+        elif parts[1].upper() in ["HELP"]:
+            retstr = '''
+My Key words are "!", "/", or "\\"
+Show a Card's Historical cost with:```!History Eva Elfie```
+Show the current day's average prices with:```!Today```
+'''
+        else:
+            retstr = '{Author}, your command was not understood.'.format(Author=author)
+    except Exception as e:
+        print(e)
+        retstr = None
+
+    return retstr
+
+
+#########################################################################
+# Main Program
+#########################################################################
+
+intents = discord.Intents.default()
+intents.message_content = True
+
+client = discord.Client(intents=intents)
+
+# This block is the work horse part
[email protected]
+async def on_message(message):
+    # we do not want the bot to reply to itself
+    if message.author == client.user:
+        return
+    # get the output for the given message
+    output = parse(message.content,message.author.display_name)
+    if output is not None:
+        await message.channel.send(output)
+
[email protected]
+async def on_ready():
+	print('Logged in as')
+	print(client.user.name)
+	print(client.user.id)
+	print('------')
+
+client.run(TOKEN)

+ 2 - 1
gatherMarket.py

@@ -2,12 +2,13 @@ from market import Market
 import schedule
 import time
 from datetime import datetime
+from logger import logger
 
 m=Market()
 
 
 def job():
-    print("Gathering Market Data: "+datetime.utcnow().isoformat())
+    logger.info("Gathering Market Data.")
     m.fetchData()
     m.commit()
 

+ 10 - 0
logger.py

@@ -0,0 +1,10 @@
+import sys
+import logging
+logger = logging.getLogger(__name__)
+stdout = logging.StreamHandler(stream=sys.stdout)
+fmt = logging.Formatter(
+    "%(asctime)s | %(levelname)s | %(message)s"
+)
+stdout.setFormatter(fmt)
+logger.addHandler(stdout)
+logger.setLevel(logging.INFO)

+ 1 - 10
market.py

@@ -10,18 +10,9 @@ import json
 import sys
 from player import Player
 from config import Config
+from logger import logger
 from db import MarketDB
 
-import logging
-logger = logging.getLogger(__name__)
-stdout = logging.StreamHandler(stream=sys.stdout)
-fmt = logging.Formatter(
-    "%(asctime)s | %(levelname)s | %(message)s"
-)
-stdout.setFormatter(fmt)
-logger.addHandler(stdout)
-logger.setLevel(logging.INFO)
-
 
 @dataclass
 class Market():

+ 7 - 0
player.py

@@ -7,6 +7,7 @@ from datetime import datetime
 import pandas as pd
 import re
 from config import Config
+from logger import logger
 
 @dataclass
 class Player():
@@ -20,6 +21,7 @@ class Player():
 
 
     def fetchData(self):
+        logger.debug("Fetch Player Data.")
         self.loadPage()
         self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
         userInfo=self.driver.find_element(By.CLASS_NAME, 'user-infos')
@@ -45,23 +47,28 @@ class Player():
         self.loadDF()
 
     def initPage(self):
+        logger.debug("Init Player Page.")
         self.driver = webdriver.Chrome()
         self.driver.get(self.url)
         self.driver.add_cookie(Config["cookie"])
 
     def loadPage(self):
+        logger.debug("Load Player Page.")
         if self.driver is None: self.initPage()
         self.driver.get(self.url)
         self.asOf=datetime.utcnow()
 
     def closePage(self):
+        logger.debug("Close Player Page.")
         self.driver.close()
 
     def loadDF(self):
+        logger.debug("Load Player pandas DF.")
         self.df=pd.DataFrame(self.Cards)
         self.df.sort_values(by='card-num', ascending=True, inplace=True)
 
     def show(self,fields=['card-num','name','level','stock'],filter=''):
+        logger.debug("Show Player Data.")
         print("Rank: {Rank}\tScore: {Score}\n".format(Rank=self.rank,Score=self.score))
         if filter != '':
             pdf=self.df.query(filter)