~josealberto4444/apodnasabot

16b0bc26354658de9b15f2b6c03e847a5f468d4e — josealberto4444 5 years ago 5390b6e
Minor fixes.
2 files changed, 12 insertions(+), 187 deletions(-)

M bot.py
D oldBot.py
M bot.py => bot.py +12 -13
@@ 5,20 5,20 @@ 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."""
    from configparser import ConfigParser
    from os.path import exists
    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.")
	"""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")


@@ 107,7 107,6 @@ botName = 'ApodNasaBot' # Bot name as written in 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]
    print(TOKEN)
else:
    import sys
    print(BToken[1])

D oldBot.py => oldBot.py +0 -174
@@ 1,174 0,0 @@
import urllib.request
import urllib.response
import re
import os.path
import requests
import telebot
from time import gmtime, strftime

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

	fecha = strftime("%Y-%m-%d", gmtime())
	
	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],fecha+'.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 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()

TOKEN = '136057639:AAF638jIkeX8bU0Mb7lwN1QFWvXnyt-x0hc'
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()