Skip to content

Instantly share code, notes, and snippets.

@rodrigogs
Last active April 15, 2024 15:13
Show Gist options
  • Save rodrigogs/f0a1af5b4c8b9690cd7bfdce300aa063 to your computer and use it in GitHub Desktop.
Save rodrigogs/f0a1af5b4c8b9690cd7bfdce300aa063 to your computer and use it in GitHub Desktop.
Novinha Drops Plugin
from phBot import *
import QtBind
import ssl
import os
import json
import socket
import time
from threading import Thread
from urllib.parse import urlparse
log('[Plugin] Novinha Drops - Loaded.')
gui = QtBind.init(__name__, 'Novinha Drops')
QtBind.createLabel(gui, 'Aqui a nova dropa e a mãe vê!', 10, 10)
QtBind.createLabel(gui, 'Webhook URL', 10, 35)
webhook_url_edit = QtBind.createLineEdit(gui, '', 10, 55, 400, 20)
QtBind.createButton(gui, 'test_message', 'Test', 420, 55)
QtBind.createLabel(gui, 'Polling Interval (minutes)', 10, 80)
polling_interval_edit = QtBind.createLineEdit(gui, '', 10, 100, 50, 20)
enable_logs_check_box = QtBind.createCheckBox(gui, 'toggle_enable_logs', 'Enable logs', 10, 130)
QtBind.createButton(gui, 'save_button_clicked', 'Save', 10, 155)
config = {
'webhook_url': '',
'polling_interval': 5,
'logs_enabled': False
}
initial_load_done = False
# Custom logging function that respects the 'logs_enabled' configuration
def plugin_log(message):
if config['logs_enabled']:
log(f'[Novinha Drops] {message}')
def test_message():
if initial_load_done:
send_discord_message('Test message')
def get_script_directory():
return os.path.dirname(os.path.abspath(__file__))
def load_config():
global config
config_path = os.path.join(get_script_directory(), 'novinha_drops_config.json')
if os.path.exists(config_path):
with open(config_path, 'r') as file:
config.update(json.load(file))
else:
plugin_log('Configuration file not found. Using defaults.')
QtBind.setText(gui, webhook_url_edit, config['webhook_url'])
QtBind.setText(gui, polling_interval_edit, str(config['polling_interval']))
QtBind.setChecked(gui, enable_logs_check_box, config['logs_enabled'])
def save_config():
config['webhook_url'] = QtBind.text(gui, webhook_url_edit)
config['polling_interval'] = int(QtBind.text(gui, polling_interval_edit))
config['logs_enabled'] = QtBind.isChecked(gui, enable_logs_check_box)
with open(os.path.join(get_script_directory(), 'novinha_drops_config.json'), 'w') as file:
json.dump(config, file, indent=4)
plugin_log('Configuration saved.')
def initialize():
load_config()
Thread(target=initialize_rare_items, daemon=True).start()
def send_discord_message(message):
if not config.get('webhook_url'):
return
parsed_url = urlparse(config.get('webhook_url'))
headers = {
"Content-Type": "application/json"
}
data = json.dumps({"content": message})
try:
context = ssl.create_default_context()
with socket.create_connection((parsed_url.hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=parsed_url.hostname) as ssock:
ssock.sendall(f'POST {parsed_url.path} HTTP/1.1\r\n'.encode('utf-8'))
ssock.sendall(f'Host: {parsed_url.hostname}\r\n'.encode('utf-8'))
for header, value in headers.items():
ssock.sendall(f'{header}: {value}\r\n'.encode('utf-8'))
ssock.sendall(f'Content-Length: {len(data)}\r\n\r\n'.encode('utf-8'))
ssock.sendall(data.encode('utf-8'))
ssock.recv(4096)
plugin_log('Discord message sent: ' + message)
except Exception as e:
plugin_log(f'Failed to send Discord message. Error: {e}')
def initialize_rare_items():
global initial_load_done
if initial_load_done:
return # Only initialize once on startup
# Track initial rare items without alerting
rare_item_ids = get_rare_item_ids()
plugin_log(f'Found {len(rare_item_ids)} rare items in inventory.')
if rare_item_ids is None:
plugin_log('Failed to load inventory. Retrying in 5 seconds.')
time.sleep(5)
initialize_rare_items()
return
save_rare_items(rare_item_ids)
initial_load_done = True
plugin_log('Initial rare items recorded.')
start_polling_thread()
def get_rare_item_ids():
inventory = get_inventory()
if inventory is None:
return None
rare_item_ids = [item['model'] for item in inventory['items'] if item is not None and item['servername'].endswith('_RARE')]
return rare_item_ids
def rare_items_file_path():
char_name = get_character_data().get('name', 'unknown')
return os.path.join(get_script_directory(), f'{char_name}_rare_items.json')
def get_saved_rare_item_ids():
saved_rare_items = []
file_path = rare_items_file_path()
if os.path.exists(file_path):
with open(file_path, 'r') as file:
saved_rare_items = json.load(file)
return saved_rare_items
def save_rare_items(rare_items):
with open(rare_items_file_path(), 'w') as file:
json.dump(rare_items, file, indent=4)
def update_rare_items():
if not initial_load_done:
return
plugin_log('Checking for new rare items in inventory.')
current_rare_item_ids = get_rare_item_ids()
saved_rare_item_ids = get_saved_rare_item_ids()
new_items_found = False
for item_id in current_rare_item_ids:
if item_id not in saved_rare_item_ids:
item = get_item(int(item_id))
character_name = get_character_data()["name"]
send_discord_message(f'{character_name} found a rare item: {item["name"]} ({item["level"]})')
new_items_found = True
if new_items_found:
save_rare_items(current_rare_item_ids)
plugin_log('Rare items updated.')
else:
plugin_log('No new rare items found.')
def poll_inventory():
while True:
time.sleep(config.get('polling_interval', 5) * 60)
plugin_log('Polling inventory for rare items.')
update_rare_items()
def start_polling_thread():
Thread(target=poll_inventory, daemon=True).start()
plugin_log('Started polling thread for inventory updates.')
def save_button_clicked():
save_config()
def toggle_enable_logs(_):
save_config()
initialize()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment