~josealberto4444/apodnasabot

ref: 287628141c39dba46a74b7691e70a88a3c19d94a apodnasabot/cronBot.py -rw-r--r-- 4.5 KiB
28762814 — josealberto4444 Testing testing branch. 6 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import urllib.request
import urllib.response
import re
import requests
import telebot
from time import gmtime, strftime
from configparser import ConfigParser
import os

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 os.path.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/.*?)".*?<b> (.*?) </b> <br>''')
	scrap_a = re.compile('''Explanation: </b>(.*?) Tomorrow..s picture''')
	scrap_b = re.compile('''(.*?)<a href="(.*?)".?.?>(.*?)</a>''')
	scrap_c = re.compile('''(?!.*</a>)/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(os.path.dirname(__file__)+"/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], os.path.dirname(__file__)+'/pictures/'+strftime("%Y-%m-%d", gmtime())+'.jpg')
		flastpicw = open(os.path.dirname(__file__)+"/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 os.path.dirname(__file__)+'/pictures/'+strftime("%Y-%m-%d", gmtime())+'.jpg'

def send_APOD_photo(chatid):
	IMGPATH = setImgPath()
	try:
		photo = open(IMGPATH, 'rb')
		bot.send_photo(chatid, photo, pictitle)
		bot.send_message(chatid, explanation, parse_mode='Markdown', disable_web_page_preview=True)
		pass
	except:
		ScrapAndSavePic()
		photo = open(IMGPATH, 'rb')
		bot.send_photo(chatid, photo, pictitle)
		bot.send_message(chatid, explanation, parse_mode='Markdown', disable_web_page_preview=True)

flastpic = open(os.path.dirname(__file__)+"/lastpic.txt",'r')
lastpic = flastpic.read()
flastpic.close()

configFile = os.path.dirname(__file__)+'/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)


f = open(os.path.dirname(__file__)+"/subscribers.txt",'r')

for line in f:
	try:
		send_APOD_photo(int(line))
		#bot.send_message(int(line), "Probando envío automático")
		pass
	except:
		fbug = open(os.path.dirname(__file__)+"/logBugsCron.txt","a")
		fbug.write(strftime("%Y-%m-%d", gmtime())+" || "+str(int(line))+"\n")
		fbug.close()
		bot.send_message(int(line), "Te he intentado enviar la APOD del día, pero ha habido un problema. Contacta con @Speedy. =(")

f.close()