'trying to send data from one script in python to another script

I am trying to write a script so when an IP address can't be seen a message gets sent with a telegram letting me know which computer is offline

I have been able to get the telegram side working but i have not been able to pass the data from the main script where it is testing the ip address , at the moment i have test data in there but i would like it to send the error with the computer name

main.py

import socket
import ssl
from datetime import datetime
import pickle

import subprocess
import platform

class Server:
    def __init__(self, name, port, connection, priority):
        self.name = name
        self.port = port
        self.connection = connection.lower()
        self.priority = priority.lower()

        self.history = []
        self.alert = False

    def check_connection(self):
        msg = ""
        success = False

        now = datetime.now().strftime("%d-%m-%Y %H:%M")

        try:
            if self.connection == "plain":
                socket.create_connection((self.name, self.port), timeout=10)
                msg = f"{self.name} is up. On port {self.port} with {self.connection}"
                success = True
                self.alert = False
            elif self.connection == "ssl":
                ssl.wrap_socket(socket.create_connection((self.name, self.port), timeout=10))
                msg = f"{self.name} is up. On port {self.port} with {self.connection}"
                success = True
                self.alert = False
            else:
                if self.ping():
                    msg = f"{self.name} is up. On port {self.port} with {self.connection}"
                    success = True
                    self.alert = False
        except socket.timeout:
            msg = f"server: {self.name} timeout. On port {self.port}"
        except (ConnectionRefusedError, ConnectionResetError) as e:
            msg = f"server: {self.name} {e}"
        except Exception as e:
            msg = f"No Clue??: {e}"

        if success == False and self.alert == False:
            # Send Alert
            self.alert = True
            import tg_start
            tg_start.send_message("Happy days")

        self.create_history(msg, success, now)

    def create_history(self, msg, success, now):
        history_max = 100
        self.history.append((msg, success, now))

        while len(self.history) > history_max:
            self.history.pop(0)

    def ping(self):
        try:
            output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower(
            ) == "windows" else 'c', self.name), shell=True, universal_newlines=True)
            if 'unreachable' in output:
                return False
            else:
                return True
        except Exception:
            return False


if __name__ == "__main__":
    try:
        servers = pickle.load(open("servers.pickle", "rb"))
    except:
        servers = [
            # Server("ifmc-repserver", 80, "plain", "high"),
            # Server("ifmc-repserver", 80, "plain", "high"),
            # Server("ifmc-repserver", 465, "ssl", "high"),
            # Server("ifmc-repserver", 80, "ping", "high"),
            Server("ifmc-repserver", 80, "ping", "high")
        ]

    for server in servers:
        server.check_connection()
        print(len(server.history))
        print(server.history[-1])

    pickle.dump(servers, open("servers.pickle", "wb"))

and tg_start.py

import requests

message = "global"
alert = ""

def send_message(text):
    global alert
    global message
    print ("this is text messsage" + " " + text)
    #text = "Superman"
    alert = text
    print("Sending ALERT ...")
    token = "token"
    chat_id = "chat_id"
    print("test message" + " " + alert)

    url_req = "https://api.telegram.org/bot" + token + "/sendMessage" + "?chat_id=" + chat_id + "&text=" + alert

    print(url_req)
    #results = requests.get(url_req)
    results = requests.post(url_req) # this request is a post, not a get

    print(results.json())
    # text = "my name" + text


send_message(alert)



Solution 1:[1]

You code worked with a slight change, sendMessage require a POST request, not a GET request.

def send_message(text):
    global alert
    global message
    print ("this is text messsage" + " " + text)
    alert = text
    print("Sending ALERT ...")
    token = "token"
    chat_id = "chat_id"
    print("test message" + " " + alert)

    url_req = f"https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={alert}"

    print(url_req)
    results = requests.post(url_req) # this request is a post, not a get
    print(results.json())
    # text = "my name" + text

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1