botonotes

Get your notes from telegram right into your local files.
git clone git://git.konyahin.xyz/botonotes
Log | Files | Refs | LICENSE

botonotes (1776B)


      1 #!/usr/bin/env python3
      2 
      3 import datetime
      4 import json
      5 import os
      6 import requests
      7 import subprocess
      8 
      9 master = int(subprocess.check_output(["pass", "botonotes/user"]))
     10 token  = subprocess.check_output(["pass", "botonotes/token"]).decode("utf-8").strip("\n")
     11 
     12 def url(method):
     13     return "https://api.telegram.org/bot{}/{}".format(token, method)
     14 
     15 def getUpdates(maxid):
     16     params = {}
     17     if maxid:
     18         params["offset"] = maxid + 1
     19 
     20     answer = json.loads(requests.get(url("getUpdates"), params = params).content)
     21     if (not answer["ok"]):
     22         print("Got error: ", answer["description"])
     23         exit()
     24 
     25     return answer["result"]
     26 
     27 def sendMessage(chat, message):
     28     requests.get(url("sendMessage"), params = {"chat_id": chat, "text": message})
     29 
     30 def saveNote(note):
     31     text = note["message"]["text"]
     32     date = datetime.datetime.fromtimestamp(note["message"]["date"]) \
     33         .strftime("# %Y-%m-%d %H:%M:%S\n")
     34     path = os.environ["SCRATCH_PATH"]
     35     with open(path, 'a+') as f:
     36         f.write(date)
     37         f.write(text + "\n\n")
     38 
     39 maxid = 0
     40 notes = 0
     41 strangers = set()
     42 
     43 while True:
     44     updates = getUpdates(maxid)
     45     if (not updates):
     46         break
     47 
     48     for update in updates:
     49         id = update["update_id"]
     50         if id > maxid:
     51             maxid = id
     52 
     53         if "message" not in update:
     54             continue
     55 
     56         user = update["message"]["from"]["id"]
     57         chat = update["message"]["chat"]["id"]
     58 
     59         if user != master:
     60             strangers.add(chat)
     61             continue
     62 
     63         saveNote(update)
     64         notes += 1
     65 
     66 if notes:
     67     sendMessage(master, "✍🏻")
     68 
     69 print("Got {} notes.".format(notes))
     70 
     71 for stranger in strangers:
     72     sendMessage(stranger, "Sorry, this is a private bot.")
     73 
     74 print("Greeted {} strangers.".format(len(strangers)))