From 6d7c7a57a40c4db715a92beb65fd9ebe6fe46f98 Mon Sep 17 00:00:00 2001 From: imp4ct Date: Wed, 12 Aug 2020 18:02:04 -0400 Subject: [PATCH] Listen for messages and respond accordingly --- listener.py | 50 ++++++++++++++++++++++++++++++++++++++++++++ messageredirector.py | 23 ++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 listener.py create mode 100644 messageredirector.py diff --git a/listener.py b/listener.py new file mode 100644 index 0000000..00ebf98 --- /dev/null +++ b/listener.py @@ -0,0 +1,50 @@ +import requests, json, time, os + +# API Key from Telegram BotFather. +apikey = '' +# Key of your chat. +chatid = '' +# Keep a list of seen updates +updateids = [] # +# List of functions we can run +functions = ['status', 'uptime', 'ping'] + +def listener(): + sendTelegram("STARTING SCRIPT: Ignore duplicate messages\n\n") + while True: + response = requests.get('https://api.telegram.org/bot' + apikey + '/GetUpdates', verify=True) + responsejson = json.loads(response.content) + print('\nNew Messages:') + for x in responsejson['result']: + # Check if we have seen this message + if str(x['update_id']) in updateids: + continue # Then skip + # Add a read message to internal DB + updateids.append(str(x['update_id'])) + # Print new request to screen + print(x['update_id'], x['message']['text']) + # assign message contents to message var + message = x['message']['text'] + # Check if the function is programmed + for x in functions: + if x in message: runfunc(x) + time.sleep(3) # Don't spam telegram API + +def runfunc(torun): + if torun == 'status': status() + if torun == 'ping': ping() + + +def ping(): + statusmessage = 'Pong' + sendTelegram(statusmessage) + +def status(): + statusmessage = 'Script is running!' + sendTelegram(statusmessage) + + +def sendTelegram(message): + os.system("curl --silent -X POST https://api.telegram.org/bot" + apikey + "/sendMessage -d chat_id=" + chatid +" -d text=\""+ message +"\"") + +listener() \ No newline at end of file diff --git a/messageredirector.py b/messageredirector.py new file mode 100644 index 0000000..0aba5fd --- /dev/null +++ b/messageredirector.py @@ -0,0 +1,23 @@ +import os +from flask import Flask, request, jsonify +app = Flask(__name__) + +# API Key from Telegram BotFather. +apikey = '' +# Key of your chat. +chatid = '' + +# Will recieve a post with json information at hostname:5000/update +# and it will forward that to the correct user in telegram. + +@app.route('/update', methods=['POST']) +def hello(): + data = request.json + print(data['message']) + os.system("curl --silent -X POST https://api.telegram.org/bot" + apikey + "/sendMessage -d chat_id=" + chatid +" -d text=\""+ data['message'] +"\"") + return('Good') + + +if __name__ == '__main__': + app.run() +