· 6 years ago · Oct 21, 2019, 06:56 PM
1#!/usr/bin/python
2# coding: utf8
3import logging
4import sys
5import os
6import time, datetime
7import json
8import requests
9import telegram
10from myKeys import TGkey, NASAkey, file
11from random import randint
12from telegram.ext import CommandHandler
13from telegram.ext import MessageHandler, Filters
14from telegram.ext import Updater
15
16# logging, definizione utf-8, API key per TelegramBot e creazione files per subscribe
17logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
18level=logging.INFO)
19reload(sys)
20sys.setdefaultencoding('utf8')
21bot=telegram.Bot(token=TGkey)
22botupd=Updater(token=TGkey)
23botdis=botupd.dispatcher
24botjob=botupd.job_queue
25try:
26 with open(file, 'r') as lstsub:
27 lstsub.close()
28except IOError:
29 with open(file, 'w') as lstsub:
30 lstsub.close()
31try:
32 with open(file + '.temp', 'w') as lstsub_temp:
33 lstsub_temp.close()
34except:
35 pass
36
37# Verifico correttezza della data:
38def validate(date_text):
39 try:
40 data = datetime.datetime.strptime(date_text, '%d-%m-%Y').strftime('%Y-%m-%d')
41 except ValueError:
42 data = "Data o formato errati. Deve essere: DD-MM-AAAA"
43 return data
44
45# messaggio APOD per data
46def msg_apod(date_text, str_r, bot, update):
47 # genero la stringa per le API di APOD
48 r = requests.get(str_r)
49 apod = r.json()
50 # se c'è un foto parte il messaggio
51 try:
52 LinkToPic = '<a href="' + apod['url'] + '">' + date_text + ': ' + apod['title'] + '</a>'
53 bot.send_message(chat_id=update.message.chat_id, text=LinkToPic, parse_mode='HTML')
54 bot.send_message(chat_id=update.message.chat_id, text=apod['explanation'])
55 # altrimenti (non è detto che ci sia sempre una foto) avverto che la foto non c'è
56 except KeyError:
57 bot.send_message(chat_id=update.message.chat_id, text='Nessuna immagine APOD per il ' + date_text)
58
59# genera messaggio di benvenuto allo start del bot:
60def start(bot, update):
61 bot.send_message(chat_id=update.message.chat_id, text='Semplice bot per esplorare le magnifiche foto del sito Astronomy Picture of the Day\nUsa il comando /help per l\'elenco dei comandi')
62
63# genera messaggi con la apod:
64def apod(bot, update):
65 # c'è qualcosa dopo il comando /apod?
66 BoolDate = len(update.message.text.split(' ')[1:])
67 # no! allora apod di oggi
68 if BoolDate == 0:
69 # si ma occhio che apod gira con TZ east coast America
70 os.environ['TZ'] = 'America/New_York'
71 time.tzset()
72 date_text = time.strftime("%Y-%m-%d", time.localtime())
73 data = time.strftime("%d-%m-%Y", time.localtime())
74 # preparo la chiamata alle API APOD:
75 str_r = 'https://api.nasa.gov/planetary/apod?api_key=' + NASAkey + '&date=' + time.strftime("%Y-%m-%d", time.localtime())
76 # chiamo la func. che manda i messaggi
77 msg_apod(data, str_r, bot, update)
78 # SI!! qualcuno prova una data (o ha scritto stronzate)
79 else:
80 # se sono vaccate o la data è sbagliata cazzio
81 date_text = str(update.message.text.split(' ')[1])
82 data = validate(date_text)
83 if data == 'Data o formato errati. Deve essere: DD-MM-AAAA':
84 bot.send_message(chat_id=update.message.chat_id, text=data)
85 # altrimenti sparo il messaggio forzando la data
86 else:
87 str_r = 'https://api.nasa.gov/planetary/apod?api_key=' + NASAkey + '&date=' + data
88 msg_apod(date_text, str_r, bot, update)
89
90# Mostra APOD di una data random:
91def random(bot, update):
92 while True:
93 # mi invento una data
94 date_text = str(randint(1,31)) + '-' + str(randint(1,12)) + '-' + str(randint(1995,int(time.strftime("%Y", time.localtime()))))
95 # se è valida..
96 data = validate(date_text)
97 if data != 'Data o formato errati. Deve essere: DD-MM-AAAA':
98 # chiedo ad apod se ha una foto
99 str_r = 'https://api.nasa.gov/planetary/apod?api_key=' + NASAkey + '&date=' + data
100 r = requests.get(str_r)
101 apod = r.json()
102 try:
103 # se ce l'ha messeggio ed esco..
104 LinkToPic = '<a href="' + apod['url'] + '">' + date_text + ': ' + apod['title'] + '</a>'
105 msg_apod(date_text, str_r, bot, update)
106 break
107 # altrimenti altro giro altro regalo..
108 except KeyError:
109 pass
110
111# subscribe invio automatico
112def sub(bot, update):
113 # uso chat_id per identificare utente:
114 new_user = str(update.message.chat_id)
115 # apro file in lettura e controllo che l'utente non sia già registrato:
116 is_reg = False
117 with open(file, 'r') as lstsub:
118 lst = lstsub.readlines()
119 # contronto con lista registrati, se presente segnalo ed esco.
120 for u in lst:
121 if u[:-1] == new_user:
122 bot.send_message(chat_id=update.message.chat_id, text="Sei già registrato all'invio giornaliero dell'APOD")
123 is_reg = True
124 lstsub.close()
125 break
126 # se non presente aggiungo utente al file
127 if not(is_reg):
128 with open(file, 'a') as lstsub:
129 lstsub.write(str(new_user) + '\n')
130 bot.send_message(chat_id=update.message.chat_id, text="OK! Registrazione effettuata; tutte le mattine alle 7:30 riceverai la foto dal sito dell'APOD.")
131 lstsub.close()
132
133# unsubscribe invio automatico
134def unsub(bot, update):
135 # uso chat_id per identificare utente:
136 new_user = str(update.message.chat_id)
137 removed = False
138 # apro file in lettura e controllo che l'utente sia già registrato:
139 with open(file, 'r') as lstsub:
140 lst = lstsub.readlines()
141 # contronto con lista registrati, se presente rimuovo ed esco.
142 for u in lst:
143 if u[:-1] == new_user:
144 with open(file + '.temp', 'w') as lstsub_temp:
145 lst.remove(new_user + '\n')
146 bot.send_message(chat_id=update.message.chat_id, text="Ok registrazione eliminata")
147 lstsub_temp.writelines(lst)
148 lstsub.close()
149 lstsub_temp.close()
150 os.rename(file + '.temp', file)
151 removed = True
152 break
153 # se non presente avverto utente:
154 if removed == False:
155 bot.send_message(chat_id=update.message.chat_id, text="Non sei attualmente registrato all'invio automatico dell'APOD")
156 lstsub.close()
157
158# Spedisco l'apod a chi si è iscritto:
159def send_apod(bot, update):
160 with open(file, 'r') as lstsub:
161 lst = lstsub.readlines()
162 os.environ['TZ'] = 'America/New_York'
163 time.tzset()
164 date_text = time.strftime("%Y-%m-%d", time.localtime())
165 data = time.strftime("%d-%m-%Y", time.localtime())
166 # preparo la chiamata alle API APOD:
167 str_r = 'https://api.nasa.gov/planetary/apod?api_key=' + NASAkey + '&date=' + time.strftime("%Y-%m-%d", time.localtime())
168 # genero la stringa per le API di APOD
169 r = requests.get(str_r)
170 apod = r.json()
171 # se c'è un foto parte il messaggio
172 for u in lst:
173 try:
174 LinkToPic = '<a href="' + apod['url'] + '">' + date_text + ': ' + apod['title'] + '</a>'
175 bot.send_message(chat_id=u, text=LinkToPic, parse_mode='HTML')
176 bot.send_message(chat_id=u, text=apod['explanation'])
177 # altrimenti (non è detto che ci sia sempre una foto) avverto che la foto non c'è
178 except KeyError:
179 bot.send_message(chat_id=u, text='Nessuna immagine APOD per il ' + date_text)
180
181# Mostra messaggio di help:
182def Help(bot, update):
183 bot.send_message(chat_id=update.message.chat_id, text="""Comandi disponibili:
184/start: messaggio di presentazione del Bot
185/help: se state leggendo, vi siete fatti un idea..
186/apod: mostra l'APOD di oggi se non si passa una data. Altimenti è possibile dare:
187/apod GG-MM-YYYY: mostra l'APOD della data inserita
188/random: mostra l'APOD di un giorno casuale (a patto che esista)
189/subscribe: iscrizione all'invio automatico dell'APOD tutte le mattina alle 7:30
190/unsubscribe: cancellazione dall'invio automatico dell'APOD""")
191
192# Funzione principale con handler telegram:
193def main():
194 start_handler = CommandHandler('start', start)
195 botdis.add_handler(start_handler)
196 apod_handler = CommandHandler('apod', apod)
197 botdis.add_handler(apod_handler)
198 random_handler = CommandHandler('random', random)
199 botdis.add_handler(random_handler)
200 help_handler = CommandHandler('help', Help)
201 botdis.add_handler(help_handler)
202 sub_handler = CommandHandler('subscribe', sub)
203 botdis.add_handler(sub_handler)
204 unsub_handler = CommandHandler('unsubscribe', unsub)
205 botdis.add_handler(unsub_handler)
206 sendapod = botjob.run_daily(send_apod, datetime.time(07, 30))
207 #sendapod = botjob.run_repeating(send_apod, datetime.timedelta(1), datetime.datetime.combine(datetime.date.today(), datetime.time(07, 30)))
208 sendapod.enable = True
209
210 botjob.start()
211 botupd.start_polling()
212 botupd.idle()
213
214# lancio tutto da qua:
215if __name__ == '__main__':
216 main()