#!/bin/python
import urllib.request
import urllib.response
import re
import requests
import telebot
from time import gmtime, strftime
from configparser import ConfigParser
from os.path import exists
def CheckCfg(cfg_file, bName):
"""Check if the config file exists and return the token if so. If not, create a new config file."""
if exists(cfg_file):
config = ConfigParser() # We get the config parser from the module.
config.read(cfg_file) # We tell the parser to read this file. ¿Esto no se queda abierto? ¿No habría que cerrar nada? No entiendo esta sintaxis de cosa.algo
Token = config[bName]['Token']
return (True, Token)
else:
from shutil import copy
copy("config.cfg.new",cfg_file)
return (False, "A new configuration file has been created in "+cfg_file+", write there your bot name and the token @BotFather gave you for it.")
def ScrapAndSavePic():
request = urllib.request.urlopen("http://apod.nasa.gov/apod/astropix.html")
sourcecode = request.read()
sourcecode = str(sourcecode)
scrap = re.compile('''IMG SRC="(image/.*?)".*? (.*?)
''')
scrap_a = re.compile('''Explanation: (.*?) Tomorrow..s picture''')
scrap_b = re.compile('''(.*?)(.*?)''')
scrap_c = re.compile('''(?!.*)/a>(.*?)$''')
tupla = scrap.search(sourcecode).groups() # URL de la imagen
tupla_a = scrap_a.search(sourcecode).groups() # Nombre del texto explicativo
tupla_b = scrap_b.findall(tupla_a[0]) # Texto con enlaces
tupla_c = scrap_c.search(tupla_a[0]).groups() # Final del texto (a partir del último enlace no se pilla con el patrón anterior)
flastpic = open("lastpic.txt",'r')
lastpic = flastpic.read()
flastpic.close()
if (tupla[0] != lastpic) or (lastpic == 0):
pic = urllib.request.urlretrieve('http://apod.nasa.gov/apod/'+tupla[0],'pictures/'+strftime("%Y-%m-%d", gmtime())+'.jpg')
flastpicw = open("lastpic.txt",'w')
flastpicw.write(tupla[0])
flastpicw.close()
global pictitle
pictitle = tupla[1].replace('\\\'', '\'') #Limpiar todos los \'
global explanation
explanation_raw = tupla_b
explanation = toMarkDown(explanation_raw, tupla_c[0])
def toMarkDown(raw, end):
charexp = ''
for ii in range(0,len(raw)):
urlexp = raw[ii][1]
if not(urlexp.startswith('http')) or (urlexp.startswith(' http')):
urlexp = 'http://apod.nasa.gov/apod/'+urlexp
urlexp = urlexp.replace('\\n', '')
charexp = charexp+raw[ii][0]+'['+raw[ii][2]+']('+urlexp+')'
charexp = charexp+end
charexp = charexp.replace('\\n', ' ') #Limpiar todos los \n
charexp = charexp.replace('\\\'', '\'') #Limpiar todos los \'
charexp = charexp.replace(' http', 'http') #Limpiar los http precedidos de espacio
charexp = re.sub(r'\s+', ' ', charexp) # Limpiar los espacios múltiples
charexp = charexp.replace(' .', '.') # Limpiar los puntos precedidos de espacio
charexp = charexp.replace(' ,', ',') # Limpiar las comas precedidas de espacio
return re.sub('<.*?>', '', charexp) # Quitar todas las etiquetas HTML
def setImgPath():
return 'pictures/'+strftime("%Y-%m-%d", gmtime())+'.jpg'
def newSubscriber(chatid):
userslist = open("subscribers.txt","a")
userslist.write(str(chatid)+"\n")
userslist.close()
def searchSubscriber(chatid):
userslist = open("subscribers.txt","r")
for idx, line in enumerate(userslist):
if (line == str(chatid)+'\n'):
return [True, (idx+1)]
return [False, -1]
def unsubscribe_line(subs_line):
fn = 'subscribers.txt'
f = open(fn, 'r')
output = []
for idx, line in enumerate(f):
if subs_line != idx+1:
output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()
flastpic = open("lastpic.txt",'r')
lastpic = flastpic.read()
flastpic.close()
configFile = 'config.cfg'
botName = 'ApodNasaBot' # Bot name as written in config file.
# We get the token from the config file or create a config file
BToken = CheckCfg(configFile, botName) # We execute the function once and save the result. Comments needed from now on
if BToken[0]:
TOKEN = BToken[1]
else:
import sys
print(BToken[1])
sys.exit()
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=['pic'])
def send_APOD_photo(message):
IMGPATH = setImgPath()
try:
photo = open(IMGPATH, 'rb')
bot.send_photo(message.chat.id, photo, pictitle)
bot.send_message(message.chat.id, explanation, parse_mode='Markdown', disable_web_page_preview=True)
pass
except:
ScrapAndSavePic()
photo = open(IMGPATH, 'rb')
bot.send_photo(message.chat.id, photo, pictitle)
bot.send_message(message.chat.id, explanation, parse_mode='Markdown', disable_web_page_preview=True)
@bot.message_handler(commands=['file'])
def send_APOD_file(message):
IMGPATH = setImgPath()
try:
photo = open(IMGPATH, 'rb')
bot.send_document(message.chat.id, photo)
bot.send_message(message.chat.id, explanation, parse_mode='Markdown', disable_web_page_preview=True)
pass
except:
ScrapAndSavePic()
photo = open(IMGPATH, 'rb')
bot.send_document(message.chat.id, photo)
bot.send_message(message.chat.id, explanation, parse_mode='Markdown', disable_web_page_preview=True)
@bot.message_handler(commands=['all'])
def send_APOD_all(message):
IMGPATH = setImgPath()
try:
photo = open(IMGPATH, 'rb')
bot.send_photo(message.chat.id, photo, pictitle)
photo = open(IMGPATH, 'rb')
bot.send_document(message.chat.id, photo)
bot.send_message(message.chat.id, explanation, parse_mode='Markdown', disable_web_page_preview=True)
pass
except:
ScrapAndSavePic()
photo = open(IMGPATH, 'rb')
bot.send_photo(message.chat.id, photo, pictitle)
photo = open(IMGPATH, 'rb')
bot.send_document(message.chat.id, photo)
bot.send_message(message.chat.id, explanation, parse_mode='Markdown', disable_web_page_preview=True)
@bot.message_handler(commands=['subscribe'])
def create_new_subscription(message):
try:
if (searchSubscriber(message.chat.id)[0] == False):
newSubscriber(message.chat.id)
bot.reply_to(message, "La suscripción se ha realizado correctamente. Recibirás la APOD cada día. =)")
else:
bot.reply_to(message, "Ya estabas suscrito.")
pass
except:
bot.reply_to(message, "La suscripción no se ha podido realizar. Contacta con @Speedy. =(")
@bot.message_handler(commands=['unsubscribe'])
def delete_subscription(message):
try:
subs_line = searchSubscriber(message.chat.id)
if (subs_line[0] == True):
unsubscribe_line(subs_line[1])
bot.reply_to(message, "La suscripción se ha anulado correctamente. Ya no recibirás la APOD NUNCA más. NUNCA. =(")
else:
bot.reply_to(message, "Aún no estabas suscrito. ¡Date prisa y hazlo!")
pass
except:
bot.reply_to(message, "La anulación no se ha podido realizar. Contacta con @Speedy. =(")
@bot.message_handler(func=lambda message: True)
def echo_vivo(message):
bot.reply_to(message, "¡¡Estoy vivo!!")
bot.polling()