Telegram-server-status/listener.py
2020-08-12 22:23:49 -04:00

62 lines
2.0 KiB
Python

import requests, json, time, os, random
# 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', 'quote']
def listener():
sendTelegram("Script First Start")
startingbit = 0
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'].lower()
# Skip all first recieved messages
if startingbit == 0:
continue
# Check if the function is programmed
for x in functions:
if x in message: runfunc(x)
startingbit = 1
time.sleep(3) # Don't spam telegram API
def runfunc(torun):
if torun == 'status': status()
if torun == 'ping': ping()
if torun == 'quote': quote()
def quote():
f = open("quotes.txt", "r")
lines = f.readlines()
randomquote = random.randint(0, 182) * 3
sendTelegram(lines[randomquote])
sendTelegram(lines[randomquote+1])
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()