1
source code here too: https://pastebin.com/DesqWJfY
Objective: to catch events in http://www.bhaktiyogapura.com/2018/03/calendario-vaisnava-marco-2018/
Each month, the URL changes only the fine, for example, in April will be:
http://www.bhaktiyogapura.com/2018/03/calendario-vaisnava-abril-2018/
Since I can’t pick up the page directly (I can’t do it), I copy and paste in Calendar.txt, then run my script.
The script sends by email and posts on facebook
What’s left: I’d like to take it straight from the URL without having to stick to Calendar.txt
I would also like, if possible, to post the events in a Whatsapp or Telegram group. It is possible?
# -- coding: utf-8 --
from datetime import datetime #usado para o contador do numero de emails enviados!
from datetime import date
import facebook
import requests
###############################facebook
######add body email
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import requests, time
from bs4 import BeautifulSoup as bs
from datetime import datetime
import re
f = open('/Gopala1/scripts/ptbr/calendar.txt', 'r')
content = f.read()
data_desejada = time.strftime("%d %b %Y", time.localtime(time.time() + (3600 * 24 * 2))) # daqui a 2 dias
amanha = time.strftime("%d %b %Y", time.localtime(time.time() + (3600 * 24 * 1))) #amanha
# Localizando todas as datas no arquivo:
dates = re.findall(r"[0-9]{1,2}\s.+\s[0-9]{4}", content)
# Verifica se a data existe no arquivo:
if not amanha in dates:
raise Exception("Data não definida")
# Localiza a data desejada no arquivo:
start = content.find(amanha)
# Verifica o índice da data na lista de datas:
index = dates.index(amanha)
# Verifica se não é a última data da lista:
if index < len(dates)-1:
# Verifica qual é a data posterior à desejada:
next_date = dates[index+1]
# Localiza a próxima data no arquivo:
end = content.find(next_date)
else:
# É a última data da lista, então exibe até o final do arquivo:
end = len(content)
# Exibe o conteúdo:
#print(content[start:end])
url = "http://www.bhaktiyogapura.com/calendario-vaisnava/"
print ("Prezados devotos, ")
print()
print()
print()
print("Amanhã, %s, teremos o(s) seguinte(s) evento(s) no Calendario Vaisnava: " %(amanha ))
print()
print(content[start:end])
##
##print()
#print("Amanhã %s, teremos o(s) seguinte(s) evento(s) no Calendario Vaisnava: " %(amanha))
print()
#print(calendar[data_nova2],end ="" )
print()
print("Para mais detalhes acessem: %s " %(url))
print()
print("Jay Radhe!")
arq = open('CalendarioVaisnava.txt', 'w')
texto = []
texto.append("Prezados devotos,")
texto.append('\n')
texto.append('\n')
texto.append('\n')
texto.append('\n')
texto.append("Amanhã, %s, teremos o(s) seguinte(s) evento(s) no Calendario \
Vaisnava : " %(amanha))
texto.append('\n')
texto.append('\n')
##texto.append('\n')
texto.append(content[start:end])
texto.append('Para mais detalhes acessem: Para mais detalhes: http://www.bhaktiyogapura.com/calendario-vaisnava/')
texto.append('\n')
#texto.append('José Lima\n')
arq.writelines(texto)
arq.close()
####parte envio email
COMMASPACE = ', '
def main():
sender = '[email protected]'
gmail_password = 'xxxxxxxxxxxx'
recipients = ['[email protected]']
#criando um contador do numero de emails enviados desde 25fev2017
## inicio = datetime.strptime ('2017-02-25' ,"%Y-%m-%d")
## hoje = date.today()
## contador = hoje.toordinal() - inicio.toordinal()
##
##
# Create the enclosing (outer) message
outer = MIMEMultipart()
#titulo = 'Lembrete número ' + str(contador)+ " sobre o calendario Vaisnava"
titulo = "Lembrete sobre o calendario Vaisnava"
outer['Subject'] = titulo
outer['To'] = COMMASPACE.join(recipients)
outer['From'] = sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
###OBS sempre colocar o caminho completo da imagem
# List of attachments
#attachments = ['/Gopala1/scripts/p.jpg','CalendarioVaisnava.txt']
#attachments =['CalendarioVaisnava.txt']
attachments = ['/Gopala1/scripts/ptbr/p.jpg','CalendarioVaisnava.txt']
# Create the body of the message (a plain-text and an HTML version).
#text = open("CalendarioVaisnava.txt","r")
arq = open("CalendarioVaisnava.txt",'r')
text = arq.read()
html ="""
<html>
<head></head>
<body>
<embed src="CalendarioVaisnava.txt">
<p><h1>Jay Radhe!</h1><br>
Anadi-Krsna Das<br><br /><br />
Para mais detalhes, acessem <a href="Para mais detalhes: http://www.bhaktiyogapura.com/calendario-vaisnava/">link</a>.
</p>
<figure>
<img src="http://oi68.tinypic.com/2n9ajj6.jpg" alt="Jay Guru Parampara!" >
</figure>
</body>
</html>
"""
# Now add the related image to the html part.
#data_uri = open('parampara.jpg', 'rb').read().encode('base64').replace('\n', '')
## data_uri = base64.b64encode(open('parampara.jpg', 'rb').read()).decode('utf-8').replace('\n', '')
## img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri)
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
outer.attach(part1)
outer.attach(part2)
# Add the attachments to the message
for file in attachments:
try:
with open(file, 'rb') as fp:
msg = MIMEBase('application', "octet-stream")
msg.set_payload(fp.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
outer.attach(msg)
except:
print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
raise
composed = outer.as_string()
# Send the email
try:
with smtplib.SMTP('smtp.gmail.com', 587) as s:
s.ehlo()
s.starttls()
s.ehlo()
s.login(sender, gmail_password)
s.sendmail(sender, recipients, composed)
s.close()
print("Email sent!")
except:
print("Unable to send the email. Error: ", sys.exc_info()[0])
raise
arq.close()
if __name__ == '__main__':
main()
###########facebook
def some_action(post):
""" Here you might want to do something with each post. E.g. grab the
post's message (post['message']) or the post's picture (post['picture']).
In this implementation we just print the post's created time.
"""
post['lllllllllllllllllllllllllllllll']
#token de [email protected]
access_token ='lalalalala'
#This new long-lived access token will expire on June 24th, 2017:
user = '33333333' #pagina Vaishnava
graph = facebook.GraphAPI(access_token)
profile = graph.get_object(user)
posts = graph.get_connections(profile['id'], 'posts')
#graph.put_object("me", "feed", message="O salomao taaaaa durmindo")
#graph.put_photo(image=open('DSC02274.JPG', 'rb'), message='Look at this cool photo!')
#graph.put_photo(image=open('salompas.jpg', 'rb'), message='lindinhu')
##arq = open("CalendarioVaisnava.txt",'r')
##attachment= arq.readlines()
#graph.put_photo(image=open('CalendarioVaisnava.txt', 'r'), message='Look at this cool photo!')
f = open('CalendarioVaisnava.txt', 'r')
listao=[]
listao = f.readlines() # converte o arquivo em lista
mensagem = ''.join(listao) #transforma a lista em string
#print("a mensagem eh", mensagem)
###OBS sempre colocar o caminho completo da imagem
#posting on a principal page
##nao consigo postar IMAGEM
graph.put_photo(image=open('/Gopala1/scripts/ptbr/p.jpg', 'rb'), message='Jay Guru Parampara!')
#graph.put_photo(image=open('p.jpg', 'rb'), message='Jay Guru Parampara!')
#graph.put_photo(image='http://oi68.tinypic.com/2n9ajj6.jpg', message='Jay Guru Parampara!
graph.put_object("me", "feed", message=mensagem)
#posting on a wall
#graph.put_photo(image=open('parampara.jpg', 'rb'), message='Jay Guru Parampara!',album_path="232568853880500")
#graph.put_object("1290498430996462", "feed", message=mensagem) #[email protected]
graph.put_object("1290498430996462", "feed", message=mensagem) #[email protected]
I advise you to use the beautifulsoup and the way the site is structured should capture the div
the_content_wrapper
and then make a loop of each elephant<p>
and separate them case<p>
only have as content
See this link– lazyFox
@lazyFox: could you post an example? I’m pretty bad at programming. The above code was built collaboratively!
– Ed S
Right now I’m leaving the company for my extended weekend :). But it is something relatively simple friend, follow the link I sent and do tests and put here the new questions. However some Python guru will also appear that can help you with the algorithm.
– lazyFox
@lazyFox: thank you very much!
– Ed S
To get the url (it’s illogical because you’re already requesting that url), you can do: https://repl.it/repls/ScrawnyInferiorOrganization
– Miguel