Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AARP41298/b195669b5072a717e78d51e3240f1aff to your computer and use it in GitHub Desktop.
Save AARP41298/b195669b5072a717e78d51e3240f1aff to your computer and use it in GitHub Desktop.
from datetime import datetime
import subprocess
import requests
import time
import locale
import os
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(SCRIPT_DIR)
#ex. 123456789:ABCDEF12345678
BOT_TOKEN = "YOUR_TOKEN"
#ex. -123456789
CHAT_ID = "YOUR_CHAT_ID"
#ex. myduckdomain.duckdns.org
DUCK_DNS = "YOUR_DNS"
BEDROCK_EXE = "bedrock_server.exe"
CHECK_INTERVAL = 10 * 60 # segundos entre chequeos
TRES_MIN = 3 * 60
QUINCE_SEG = 15
encoding = locale.getpreferredencoding()
def send_telegram_message(message):
print(f"Enviando por Telegram: {message}")
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
try:
requests.post(url, data={"chat_id": CHAT_ID, "text": message})
except Exception as e:
print(f"Error enviando mensaje: {e}")
def is_connected():
now = datetime.now()
timestamp = (
now.strftime("%Y-%m-%d %H:%M:%S") + f":{int(now.microsecond / 1000):03d}"
)
print(f"[{timestamp}] Haciendo ping")
try:
subprocess.check_output(
["ping", "-n", "1", "google.com"], stderr=subprocess.DEVNULL
)
return True
except subprocess.CalledProcessError:
return False
def get_public_ip():
try:
result = subprocess.check_output(
["curl", "-4", "ifconfig.me"], stderr=subprocess.DEVNULL
)
return result.decode(encoding).strip()
except Exception:
return None
def is_bedrock_running():
try:
output = subprocess.check_output(
["tasklist"], stderr=subprocess.DEVNULL
).decode(encoding)
return BEDROCK_EXE.lower() in output.lower()
except Exception as e:
print(f"Error al verificar bedrock_server: {e}")
return False
def start_bedrock_server():
try:
subprocess.Popen(
[BEDROCK_EXE], creationflags=subprocess.CREATE_NEW_CONSOLE
)
print("Bedrock server iniciado.")
return True
except Exception as e:
print(f"Error al iniciar bedrock server: {e}")
return False
def actualizar_pato():
url = "https://www.duckdns.org/update"
params = {
"domains": "DOMINIO_DEL_PATO",
"token": "TOKEN_DEL_PATO",
"ip": "" # dejar vacío para que DuckDNS detecte automáticamente tu IP pública
}
try:
response = requests.get(url, params=params, verify=False) # verify=False omite verificación SSL
print("Pato actualizado:", response.text)
except Exception as e:
print("Error al actualizar DuckDNS:", e)
def monitor_connection():
prev_disconnected = True
last_ip = None
while True:
if is_connected():
if prev_disconnected:
prev_disconnected = False
ip = get_public_ip()
if last_ip != ip:
send_telegram_message(f"Nueva IP: {ip}\nPero mejor usa el pato wey: {DUCK_DNS}")
actualizar_pato()
last_ip = ip
else:
# se desconecto, bandera para avisar
prev_disconnected = True
# reintentar hasta que haya conexion
while True:
time.sleep(QUINCE_SEG)
if is_connected():
send_telegram_message("Se reconecto el server.")
break
else:
print("Sigues desconectado, reintentando")
if not prev_disconnected:
time.sleep(1 * 60)
if __name__ == "__main__":
try:
welcome = "Bienvenido al bot. "
if not is_bedrock_running():
if start_bedrock_server():
send_telegram_message(welcome + "Iniciando servidor.")
else:
send_telegram_message("Error: no se pudo iniciar el servidor.")
else:
print("El servidor ya está en ejecución.")
send_telegram_message(welcome + "Servidor ya iniciado")
# Comienza la monitorización
monitor_connection()
except KeyboardInterrupt:
print("Sobres")
send_telegram_message("Adios putines.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment