Foppe Hemminga 5 роки тому
батько
коміт
c1d771dd3d
3 змінених файлів з 109 додано та 1 видалено
  1. 1 1
      .gitignore
  2. 90 0
      cron.py
  3. 18 0
      sqlite.php

+ 1 - 1
.gitignore

@@ -2,4 +2,4 @@
 slork.sqlite
 .idea/
 settings.php
-
+settings.py

+ 90 - 0
cron.py

@@ -0,0 +1,90 @@
+import json
+import requests
+import sqlite3
+import time
+import settings
+from pprint import pprint
+
+
+def send_notification(maintainer, player, property, old_value, new_value):
+    query = """SELECT discord FROM discord WHERE maintainer = ?;"""
+    conn = sqlite3.connect(settings.db_path + '/slork.sqlite')
+    conn.row_factory = sqlite3.Row
+    cur = conn.cursor()
+    cur.execute(query, (maintainer))
+    discord = cur.fetchone()['discord']
+    query = """SELECT value FROM player
+        WHERE maintainer = ?
+        AND player = ?
+        AND property = 'name';"""
+    cur.execute(query, (maintainer, player))
+    name = cur.fetchone()['name']
+    message = f"{name} [{player}] property '{property}' changed from {old_value} to {new_value}"
+    message_json = {"content": message}
+    response = requests.post(url, json=message_json)
+    if response.status_code in [200, 204]:
+        print("Webhook executed")
+    else:
+        print("status code {}: {}".format(response.status_code, response.content.decode("utf-8")))
+        if response.status_code == int(429):
+            sys.exit(1)
+
+def update_value(maintainer, player, property, new_value):
+    query = """INSERT OR REPLACE INTO player (maintainer, player, property, value)
+        VALUES (?, ?, ?, ?)"""
+    conn = sqlite3.connect(settings.db_path + '/slork.sqlite')
+    conn.row_factory = sqlite3.Row
+    cur = conn.cursor()
+    cur.execute(query, (maintainer, player, property, value))
+
+def cron():
+    query = """SELECT player_properties.maintainer,
+            maintainer.api, player_properties.player,
+            player_properties.property
+            FROM player_properties
+            JOIN maintainer ON player_properties.maintainer = maintainer.maintainer;"""
+    conn = sqlite3.connect(settings.db_path + '/slork.sqlite')
+    conn.row_factory = sqlite3.Row
+    cur = conn.cursor()
+
+    for row in cur.execute(query):
+        print(f"{row['maintainer']} - {row['api']} - {row['player']} - {row['property']}")
+        url = f"https://api.torn.com/user/{row['player']}?selections=personalstats,basic&key={row['api']}"
+        print(url)
+        response = requests.get(url)
+        player_json = None
+        print(response.text[:10])
+        if response and response.text:
+            player_json = json.loads(response.text)
+            # pprint(faction_json)
+        if 'error' in player_json:
+            pprint(faction_json)
+            break
+
+        # Check for changes
+        properties = json.loads(row['property'])
+        if 'name' not in properties:
+            properties.append(name)
+        query = """SELECT player.value, properties.parent
+            FROM player
+            JOIN properties ON player.property = properties.property
+            WHERE maintainer = ?
+            AND player = ?
+            AND player.property = ?;"""
+        for property in properties:
+            for p_row in cur.execute(query, (row['maintainer'], row['player'], property)):
+                print(f"property: '{property}' parent: '{p_row['parent']}' -> value: '{p_row['value']}'")
+                new_value = ''
+                if (p_row['parent']):
+                    new_value = player_json[p_row['parent']][property]
+                else:
+                    new_value = player_json[property]
+                print(f"new_value: '{new_value}'")
+                if p_row['value'] != new_value:
+                    send_notification(row['maintainer'], row['player'], property, p_row['value'], new_value)
+                    update_value(row['maintainer'], row['player'], property, new_value)
+
+        time.sleep(1)
+
+if __name__ == '__main__':
+    cron()

+ 18 - 0
sqlite.php

@@ -46,6 +46,24 @@ $query = <<<QUERY
 QUERY;
 $pdo->exec( $query );
 
+$pdo->exec( "DROP TABLE IF EXISTS discord" );
+$query = <<<QUERY
+	CREATE TABLE discord (
+	    id INTEGER PRIMARY KEY, 
+		maintainer INTEGER, 
+		discord TEXT, 
+		UNIQUE(maintainer));
+QUERY;
+$pdo->exec( $query );
+$query = <<<QUERY
+	INSERT OR REPLACE INTO discord (maintainer, discord)
+		VALUES (?, ?)
+QUERY;
+$stmt = $pdo->prepare( $query );
+$stmt->execute( [204836, "https://discordapp.com/api/webhooks/706228042124623944/UGEYMQi-2iMUyg8jvGiFSc6CfcThv1dMSBgNhzziPL9aBoNxoNA03fPJZ1iwxQ-_xm7r"] );
+$stmt->execute( [1900827, "https://discordapp.com/api/webhooks/706229815166107669/vCNCc7uGe__JI9YHmoUUXozgOMc6FZclbX3SPLSQSy75B7m9AT8_36gExdRRZMYxTrwq"] );
+$stmt->execute( [1337627, "https://discordapp.com/api/webhooks/706230061275283478/DCUzGepweoYvufNr2KDXFt06j6cexdfVxhfbjrn1h7r77k9I0FlY0xuzyl3UInZgybGj"] );
+
 // properties.php contains queries for a subsequent
 // table properties containing default property names.
 require_once "properties.php";