~josealberto4444/apodnasabot

ref: 84f3028ac6fc00b4a0b452caf160781f60d8d5cd apodnasabot/bot.py -rw-r--r-- 6.3 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import urllib.request
import urllib.response
import re
import os.path
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/.*?)".*?<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 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:
		print(message.chat.id)
		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()