from discord_webhook import DiscordWebhook, DiscordEmbed
import subprocess, vlc, cv2

cameraURL = "rtsp://10.85.3.33:554/11"
webhookURL = "https://discordapp.com/api/webhooks/719690867811811348/8LExCQbqOPP0XAdNcbV8JHrVYupOSYmeLwkBJWCDCe72JoPyc4Yy_R2wzbkKSN33MPAn"
maxCharPerMessage = 1994

#out = subprocess.Popen(['cat /etc/bacula/scripts/test.md'], 
out = subprocess.Popen(['echo messages | bconsole'], # Use this command to get the messages out of bconsole
           stdout=subprocess.PIPE, # Save the output
           stderr=subprocess.STDOUT, # Save the output
           shell=True) # This is a already formatted shell command

stdout,stderr = out.communicate() # Extract the outputs
#print(stdout) # Print the output
print(stderr) # Print any errors

cleaned_stdout = (stdout.partition(b"\nmessages\n")[2] + b"").decode("utf-8")  # Trim the messages by removing timestamp and connection info
print(cleaned_stdout) # Print the cleaned output

# Discord limits each message to 2000 chars, if the message is longer than that, truncate it
truncated_stdout = [cleaned_stdout[i:i+maxCharPerMessage] for i in range(0, len(cleaned_stdout), maxCharPerMessage)] 
print (truncated_stdout) # Print the truncated message

if (truncated_stdout[0] != "You have no messages.\n"): # If the first part of the truncated message is empty (no messages) dont send it.
    vidcap = cv2.VideoCapture("rtsp://10.85.3.33:554/11")
    success,image = vidcap.read()
    print(success)
    if success:
        cv2.imwrite("LibraryFrame.png", image)
#        imagewebhook = DiscordWebhook(url=webhookURL, content="Live Snapshot")
#        with open("LibraryFrame.png", "rb") as f:
#            imagewebhook.add_file(file=f.read(), filename='LibraryFrame.png')
#            response = imagewebhook.execute()

    for message_part in truncated_stdout: # For every message part in the truncated output, run this loop
        message_part = "```" + message_part + "```" # Encapsulate the messsage
        print(message_part)
        webhook = DiscordWebhook(url=webhookURL, content=message_part) # Attach the message       
        if success:
            with open("LibraryFrame.png", "rb") as f:
                webhook.add_file(file=f.read(), filename='LibraryFrame.png')
        response = webhook.execute() # Hit send
else:
    print("Done.")
