Very simple working server

This commit is contained in:
Guy Van Sanden 2025-01-30 15:02:01 +01:00
parent e16f678338
commit 6650f0e042
6 changed files with 49 additions and 144 deletions

2
.gitignore vendored
View File

@ -60,3 +60,5 @@ target/
# Node # Node
node_modules/ node_modules/
client/node_modules/
server/node_modules/

View File

@ -26,7 +26,7 @@ def sendmessage(message):
urllib3.disable_warnings() urllib3.disable_warnings()
# http_client.HTTPConnection.debuglevel = 1 # http_client.HTTPConnection.debuglevel = 1
url = ("%s/skill/tellops/%s" % (baseurl, webhook)) url = ("%s/webhook/%s" % (baseurl, webhook))
r = requests.post(url, json = { 'message': mymessage, 'notify': notify, 'tts': args.tts }) r = requests.post(url, json = { 'message': mymessage, 'notify': notify, 'tts': args.tts })
if r.status_code == 200: if r.status_code == 200:
@ -39,7 +39,7 @@ def sendmessage(message):
ran = True ran = True
__version__ = "1.3.1" __version__ = "1.4.0"
versionstring='TellMe v' + __version__ versionstring='TellMe v' + __version__
signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGINT, signal_handler)

View File

@ -1,14 +0,0 @@
{
"name": "TellMe",
"version": "1.3.0",
"description": "TellMe CLI",
"scripts": {
"dev": "webpack-dev-server --inline --hot"
},
"author": "Guy Van Sanden <guy@taurix.net>",
"license": "AGPL",
"dependencies": {
"grunt": "~0.4.5",
"grunt-version": "~1.1.0"
}
}

45
server/src/tellmesrv.py Normal file
View File

@ -0,0 +1,45 @@
#!/bin/env python3
from flask import Flask, request, jsonify
# import asyncio
import websocket
import json
import random
app = Flask(__name__)
def sendmessage(target, message):
print("Sendmessage called")
uri = "ws://localhost:5080"
#message = "#Bottest Hello, world!"
msg = ("%s %s" % (target, message))
# Create a unique correlation ID
command = {
"corrId": f"id{random.randint(0, 999999)}",
"cmd": msg,
}
json_command = json.dumps(command)
""" Connects to WebSocket server, sends a message, and returns the response """
ws = websocket.create_connection(uri) # Blocking WebSocket connection
ws.send(json_command) # Send message to WebSocket
response = ws.recv() # Receive response
ws.close() # Close WebSocket connection
print(response)
return response
@app.route('/webhook', methods=['POST'])
def webhook_receiver():
data = request.json # Get the JSON data from the incoming request
# Process the data and perform actions based on the event
print("Received webhook data:", data)
return jsonify({'message': 'Webhook received successfully'}), 200
@app.route('/webhook', methods=['GET'])
def webhook_test():
print("Sending test")
sendmessage('#Bottest', 'Testing 123')
return jsonify({'message': 'Webhook received successfully'}), 200
if __name__ == '__main__':
app.run(debug=True)

View File

@ -1,5 +0,0 @@
{
"url": "",
"webhook": "",
"notify": "",
}

View File

@ -1,123 +0,0 @@
#!/usr/bin/env python3
import time
import sys
import platform
import os
# import urllib.request
import urllib3
import requests
import http.client as http_client
import argparse
import json
import signal
import subprocess
from xml.etree import ElementTree as etree
from time import gmtime, strftime
def signal_handler(signal, frame):
print('Exit...')
sys.exit(0)
def sendmessage(message):
global ran
# mymessage=hostname.upper() + ': ' +message
mymessage = ("%s on %s" % (message, hostname.upper()))
urllib3.disable_warnings()
# http_client.HTTPConnection.debuglevel = 1
url = ("%s/skill/tellops/%s" % (baseurl, webhook))
r = requests.post(url, json = { 'message': mymessage, 'notify': notify, 'tts': args.tts })
if r.status_code == 200:
print("Message has been sent successfully")
# print(message)
else:
print("Message sending FAILED (%s)" % (r.status_code))
# print(r.data)
ran = True
__version__ = "1.3.1"
versionstring='TellMe v' + __version__
signal.signal(signal.SIGINT, signal_handler)
hostname=platform.node()
home=os.getenv("HOME")
parser = argparse.ArgumentParser(description='TellMe command line client')
parser.add_argument("-m", "--message", default="Your process finished", help="Message to send")
parser.add_argument('-t', '--tts', default=False, action='store_true', help="Send message to TTS")
parser.add_argument('-v', '--version', action='version', version=versionstring)
parser.add_argument('-p', '--pid', action="store", dest="pid", type=int, default=0)
parser.add_argument('-n', '--notify', action="store", dest="notify", default=None, help="Notify specific id")
parser.add_argument('-i', '--interval', action="store", dest="interval", type=int, default=5, help="Set the interval of commands like watch that use it")
parser.add_argument('-w', '--watch', action="store", dest="watchcommand", help="Run the given command every n or 5 minutes")
parser.add_argument('-c', '--config', default=home +"/.config/tellme/config.json" ,help="Path to config file")
parser.add_argument('-P', '--ping', action="store", dest="pinghost", type=str, help="Ping a host until it is up")
#print parser.parse_args()
args = parser.parse_args()
configfile = args.config
# Read config
if not os.path.isfile(configfile):
print("No config file found in %s" %(configfile))
exit(1)
config = None
with open(configfile) as cfgfile:
config = json.load(cfgfile)
baseurl = config['url']
webhook = config['webhook']
message = args.message
notify = None
if args.notify is None:
if config.get('notify') is not None:
notify = config.get('notify')
else:
notify = args.notify
ran = False
if args.pid != 0:
path = "/proc/%i" %(args.pid)
print("Monitoring process %i" %(args.pid))
while os.path.exists(path):
time.sleep(10)
sendmessage(message)
if(args.watchcommand):
print("Watching %s every %i minutes" %(args.watchcommand,int(args.interval)))
while True:
output = subprocess.Popen(args.watchcommand, shell=True, stdout=subprocess.PIPE).stdout.read()
print(output)
sendmessage("|%s|" %(output))
time.sleep(60*int(args.interval))
if(args.pinghost):
print("Pinging %s" %(args.pinghost))
response = None
while response != 0:
response = os.system("ping -c 1 -w 1 %s >/dev/null" % (args.pinghost))
if response == 0:
print("Up")
sendmessage("Host %s is Up" % (args.pinghost))
else:
print("Down")
if args.interval:
interval = args.interval
else:
interval = 60
time.sleep(int(args.interval))
if ran is False:
sendmessage(message)