Compare commits

...

10 Commits

Author SHA1 Message Date
Deadswitch
6223fac898 of course, as usual some bugfixes... 2022-06-17 16:45:19 -05:00
Deadswitch
2f299c96f0 ignore email addresses without an at sign 2022-06-17 15:47:33 -05:00
Joe Tretter
fe8f240cfc only change the e-mail address. 2022-01-17 17:40:35 -06:00
Joe Tretter
a583d89172 Fix and add simple telegram sending. 2022-01-12 19:46:05 -06:00
Deadswitch
dcfb6a2892 get rid of telegram sending - not compatible with threading 2022-01-11 19:58:56 -06:00
Joe Tretter
b571b636fd Merge branch 'master' of ssh://kawomi.com/var/local/git/deadswitch into master
# Conflicts:
#	api1.py
2022-01-11 19:37:51 -06:00
Joe Tretter
bb39aab3d0 Add basic telegram sending to myself. 2022-01-11 19:33:18 -06:00
Deadswitch
f2dcc1c316 handle CORS header, only basic implementation for get. 2021-04-13 19:10:03 -05:00
Deadswitch
1a05b85d19 include the url in the email 2021-01-07 18:51:33 -06:00
Joe Tretter
61ac649fb1 add .gitignore 2020-12-17 08:32:22 -06:00
5 changed files with 109 additions and 16 deletions

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
/deadswitch.sqlite3
/session.session
__pycache__

75
api1.py
View File

@@ -1,10 +1,12 @@
import flask
import sys
from flask import request, jsonify, g
from flask import request, jsonify, g, make_response
from flask_apscheduler import APScheduler
from datetime import datetime,timedelta,timezone
import sqlite3
import smtplib
from telethon.sync import TelegramClient
import asyncio
# testing:
# start dummy web server for dev with root: python3 -m smtpd -c DebuggingServer -n localhost:25
@@ -25,24 +27,69 @@ class Config(object):
SCHEDULER_API_ENABLED = True
def sendMail(topic,toAddr):
def sendSelfTelegram(message,toId):
print(f"sending telegram message to myself")
# get your api_id, api_hash, token
# from telegram as described above
api_id = '2452309'
api_hash = '4cc6a58946508e59547d15d530a421ae'
# your phone number
phone = '+13616553044'
# creating a telegram session and assigning
# it to a variable client
client = TelegramClient('session', api_id, api_hash)
# connecting and building the session
client.connect()
# in case of script ran first time it will
# ask either to input token or otp sent to
# number or sent or your telegram id
if not client.is_user_authorized():
client.send_code_request(phone)
# signing in the client
client.sign_in(phone, input('Enter the code: '))
try:
client.send_message(toId, message, parse_mode='html')
except Exception as e:
# there may be many error coming in while like peer
# error, wwrong access_hash, flood_error, etc
print(e);
# disconnecting the telegram session
client.disconnect()
def sendNotification(topic,toAddr):
print(f"sending mail to {toAddr} for topic {topic}")
port = 25
server=smtplib.SMTP("localhost", port)
sender_email = "deadswitch@kawomi.com"
receiver_email = toAddr
message = f"""Subject: deadSwitch not pushed on topic {topic}\n\nNotification of deadSwitch not pushed on topic {topic}."""
message = f"""Subject: deadSwitch not pushed on topic {topic}\n\nNotification of deadSwitch not pushed on topic {topic}.
https://deadswitch.kawomi.com/api/v1?topic={topic}
"""
sendSelfTelegram(message, 5070349790)
if not "@" in toAddr:
print(f"not sending mail - {toAddr} not an email-address.")
return False
server.sendmail(sender_email, receiver_email, message)
def expiryCheck():
asyncio.set_event_loop(asyncio.SelectorEventLoop())
print('.',end='')
db=sqlite3.connect(DATABASE,detect_types=sqlite3.PARSE_DECLTYPES)
cursor = db.cursor()
for theRow in cursor.execute("select expiry,topic,email from entries where active=True and isNotified=False and expiry < datetime()"):
print(theRow)
for theEmailAddr in theRow[2].split(','):
sendMail(theRow[1],theEmailAddr)
sendNotification(theRow[1],theEmailAddr)
db.execute("update entries set isNotified=True where topic=?",[theRow[1]])
db.commit()
db.close()
@@ -75,15 +122,23 @@ if __name__ == '__main__':
def home():
return """<h1>Dead-Switch web service</h1>
<hr>
<h2>2020-10-29 - j.tretter@gmail.com</h2>
<h2>2020-10-29 - joe@kawomi.com</h2>
<hr>
Examples:
<ul>
<li>curl "https://deadswitch.kawomi.com/api/v1?topic=sys.demo"</li>
<li>curl -d "" -X POST "https://deadswitch.kawomi.com/api/v1?topic=sys.demo&secs=60&email=demo@demo.com"</li>
<li>curl -d "" -X POST "https://deadswitch.kawomi.com/api/v1?topic=sys.demo&secs=60&email=joe@kawomi.com"</li>
</ul>"""
@app.route('/api/v1', methods=['OPTIONS'])
def api_returnOptions():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add('Access-Control-Allow-Headers', "*")
response.headers.add('Access-Control-Allow-Methods', "*")
return response
@app.route('/api/v1', methods=['GET'])
def api_getByTopic():
if 'topic' in request.args:
@@ -97,7 +152,7 @@ if __name__ == '__main__':
if theRow is None:
return jsonify({'success':False, 'error':f"No entry found for topic _{topic}_"})
return jsonify({'success':True, 'topic':topic, 'active':bool(theRow[0]), 'expiry':theRow[1].strftime("%Y-%m-%d %H:%M:%S"), 'lastSeen':theRow[5].strftime("%Y-%m-%d %H:%M:%S"),'isExpired':bool(theRow[4]),'email':theRow[2], 'isNotified':bool(theRow[3])})
return _corsify_actual_response(jsonify({'success':True, 'topic':topic, 'active':bool(theRow[0]), 'expiry':theRow[1].strftime("%Y-%m-%d %H:%M:%S"), 'lastSeen':theRow[5].strftime("%Y-%m-%d %H:%M:%S"),'isExpired':bool(theRow[4]),'email':theRow[2], 'isNotified':bool(theRow[3])}))
@app.route('/api/v1', methods=['PUT','POST'])
def api_setRecord():
@@ -128,4 +183,8 @@ if __name__ == '__main__':
return jsonify({'success':True, 'expiry':expiryDateTime.strftime("%Y-%m-%d %H:%M:%S"), 'email':email})
def _corsify_actual_response(response):
response.headers.add("Access-Control-Allow-Origin", "*")
return response
app.run(use_reloader=False,port=5123)

Binary file not shown.

View File

@@ -1,4 +1,3 @@
import telebot
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerUser, InputPeerChannel
from telethon import TelegramClient, sync, events
@@ -36,17 +35,14 @@ if not client.is_user_authorized():
try:
# receiver user_id and access_hash, use
# my user_id and access_hash for reference
print(client.get_me().stringify())
print("A")
#receiver = InputPeerUser('user_id', 'user_hash')
receiver = InputPeerUser('1463709677', '4835783730631176464')
#print(client.get_me().stringify())
# send message to self...
receiver = InputPeerUser( str(client.get_me().id), str(client.get_me().access_hash))
print("B ")
print(receiver)
#print(receiver)
# sending message using telegram client
#client.send_message(receiver, message, parse_mode='html')
client.send_message(1463709677, "test message", parse_mode='html')
print("C")
except Exception as e:
# there may be many error coming in while like peer

35
telegramtest2.py Normal file
View File

@@ -0,0 +1,35 @@
from telethon.sync import TelegramClient
# get your api_id, api_hash, token
# from telegram as described above
api_id = '2452309'
api_hash = '4cc6a58946508e59547d15d530a421ae'
# your phone number
phone = '+13616553044'
# creating a telegram session and assigning
# it to a variable client
client = TelegramClient('session', api_id, api_hash)
# connecting and building the session
client.connect()
# in case of script ran first time it will
# ask either to input token or otp sent to
# number or sent or your telegram id
if not client.is_user_authorized():
client.send_code_request(phone)
# signing in the client
client.sign_in(phone, input('Enter the code: '))
try:
schlingelId=5070349790
client.send_message(schlingelId, "test message", parse_mode='html')
except Exception as e:
# there may be many error coming in while like peer
# error, wwrong access_hash, flood_error, etc
print(e);
# disconnecting the telegram session
client.disconnect()