Listen for messages and respond accordingly
This commit is contained in:
parent
7bce25f095
commit
6d7c7a57a4
50
listener.py
Normal file
50
listener.py
Normal file
@ -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()
|
||||
23
messageredirector.py
Normal file
23
messageredirector.py
Normal file
@ -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()
|
||||
|
||||
Loading…
Reference in New Issue
Block a user