~josealberto4444/apodnasabot

ref: 84f3028ac6fc00b4a0b452caf160781f60d8d5cd apodnasabot/cronBot.py -rw-r--r-- 3.8 KiB
84f3028a — josealberto4444 Minor fixes. 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
import urllib.request
import urllib.response
import re
import os.path
import requests
import telebot
from time import gmtime, strftime

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/.*?)".*?<b> (.*?) </b> <br>''')
	scrap_a = re.compile('''Explanation: </b>(.*?) Tomorrow..s picture''')
	scrap_b = re.compile('''(.*?)<a href="(.*?)".?.?>(.*?)</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 TODO: Puede que no pille el texto después del último enlace
	
	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]
	
	global explanation
	explanation_raw = tupla_b
	explanation = toMarkDown(explanation_raw)

def toMarkDown(raw):
	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
		charexp = charexp+raw[ii][0]+'['+raw[ii][2]+']('+urlexp+')'
		
	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('''(\.)[^ ]''', '. ', charexp) TODO
	return re.sub('<.*?>', '', charexp) # Quitar todas las etiquetas HTML

def setImgPath():
	return '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("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)


f = open("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("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()