Twilio prints sid but it is no longer sending the messages - python

I use the twilio API to write a simple program to remember my father to take his meds. Here is my code which can be replicated by anyone who has an account in twilio, one phone number and the sheet medications.csv(see bellow):
from twilio.rest import Client
import pandas as pd
from datetime import datetime
import re
account_sid = 'XXXXXXXXXXXXX' #INSERT YOUR SID HERE
auth_token = 'XXXXXXXXXXXXX' #INSERT YOUR TOKEN HERE
client = Client(account_sid, auth_token)
def to_list_integer(dt_time):
return [dt_time.year,dt_time.month,dt_time.day, dt_time.hour,dt_time.minute]
df=pd.read_csv('medications.csv')
while True:
data_lista = to_list_integer(datetime.now())
x=datetime(*data_lista)
hora = x.strftime("%Hh%M")
for i in range(len(df)):
if (datetime.now().hour==df['hour'][i]) & (datetime.now().minute==df['minute'][i]) & (datetime.now().second==1):
text = '''*Lembrete: {0}*\n
Olá sr. X, agora são {1},
\nestá na hora de tomar {2} comprimido(s) de {0}
\n\n*recomendação médica: {3}*'''.format(df['name'][i],hora,re.search(r'\d+',df['recomendation'][i]).group(),
df['recomendation'][i])
persons=['whatsapp:+XXXXXXXXXXXXX','whatsapp:+XXXXXXXXXXXXX','whatsapp:+XXXXXXXXXXXXX',
'whatsapp:+XXXXXXXXXXXXX', 'whatsapp:+XXXXXXXXXXXXX']
for person in persons:
message = client.messages.create(
body=text,
from_='whatsapp:+XXXXXXXXXXX',#INSERT YOUR TWILIO NUMBER HERE
to=person
)
print(message.sid)
medications.csv:
name,dosage,recomendation,hour,minute
Selozek,100mg,Tomar 1 comprimido pela manhã,6,9
Vasopril Plus,20/12.5 mg,Tomar 1 comprimido pela manhã,6,10
Glifage XR,500mg,Tomar 2 comprimidos após o café e após a última refeição da noite,7,10
Clopidogrel,75mg,Tomar 1 comprimido após o almoço,13,10
AAS,100mg,Tomar 1 comprimido após o almoço,13,11
Enalapril,10mg,Tomar 2 comprimidos à noite,20,10
Glifage XR,500mg,Tomar 2 comprimidos após o café e após a última refeição da noite,20,11
Rosuvastatina,20mg,Tomar 1 comprimido após a última refeição da noite,20,12
The code was working properly yesterday but today it is no longer working. The program runs without errors and print the sids for each message. However, none of the phones in the list persons are receiving the message. What is wrong here?

Related

Python to excel using XLWT

I have this big output. Everytime that the url appears, the number below the url is the ID (and its important), and also if the url appears at the output is one request to the api
The preview of the output :
https://xxxxxx/api/v1/implantacao/projeto/254/tarefa?start=0&limit=50
254
INFORME DE FRANQUIA VENDIDA
T01
1
PONTO COMERCIAL
CONTRATO DE LOCAÇÃO ASSINADO
T04
1
PONTO COMERCIAL
INTEGRAÇÃO: TIMELINE | ACESSOS
T05
1
TIMELINE
E-MAIL: CRIAR E-MAILS
T144
1
TIMELINE
ACESSOS SULTS: CRIAR ACESSOS
T145
1
TIMELINE
PRECIFICAÇÃO: ANÁLISE DE MARGEM E MARK-UP
T142
2
MIX INICIAL
VETERINÁRIO: PERÍODO DE SELEÇÃO DE CLÍNICO GERAL
T86
2
VETERINÁRIO
ESPECIALISTAS: PESQUISA POR PROFISSIONAIS
T157
2
DRA. MEI
TREINAMENTO: VESTINDO A CAMISA (PRESENCIAL)
T91
2
That part of the code :
def unidades(data):
for i in data['data']:
name = (i['nome'])
codigo = (i['codigo'])
situation = (i['situacao'])
subName = (i['fase']['nome'])
How can i print this into excel, using xlwt ?
I tried :
line = 0
for i in data['data']:
name = (i['nome'])
sheet.write(1, line, name)
linha += 1
But this code above didn't worked, only printed 7 itens in my excel file

How can i delete all my tweets using twitter api

I'm trying to delete all the tweets/replies from my account, at first it worked, but it got to a point where he stopped deleting, and he can't receive the tweets anymore, giving the error:
File "main.py", line 29, in fetch_tweets
oldest = all_tweets[-1].id - 1
IndexError: list index out of range
and on my account, even if it doesn't appear on the profile (I don't know why) there are still 19.2k tweets to be deleted, does anyone have any idea how to fix this?
code:
'''
Script para apagar todos os meus tweets mais antigos que determinada data
'''
from keep_alive import keep_alive
import tweepy
from config import *
import datetime
import pandas as pd
client = tweepy.Client(bearer_token, api_key, api_secret, access_token, access_token_secret)
auth = tweepy.OAuth1UserHandler(api_key, api_secret, access_token, access_token_secret)
api = tweepy.API(auth)
def fetch_tweets(username):
'''
Baixa todos os tweets do usuário
determinado em 'username'
'''
print("Resgatando Tweets. . .")
all_tweets = []
new_tweets = api.user_timeline(screen_name=username, tweet_mode='extended', count=200, exclude_replies=False)
all_tweets.extend(new_tweets)
# Salva o id do tweet antigo menos um
oldest = all_tweets[-1].id - 1
while len(new_tweets) > 0: # Continua pegando tweets até a requisição retornar nada
# Todos as requests posteriores usam max_id "para avançar no tempo"
new_tweets = api.user_timeline(screen_name=username, tweet_mode='extended', count=200, max_id=oldest)
all_tweets.extend(new_tweets)
# Atualiza o id
oldest = all_tweets[-1].id - 1
# Transform the tweepy tweets into a 2D array that will populate the csv
output = [
[ tweet.id,
tweet.created_at,
tweet.created_at.strftime("%d-%m-%Y"),
tweet.retweet_count,
tweet.favorite_count,
username ] for tweet in all_tweets
]
for sublist in output:
sublist.append(username)
return output
def validate_date(date_text):
'''
Verifica se a data entrada pelo usuário
está no foramto YYYY-MM-DD. Se não estiver,
levanta uma exeção com mensagem de erro.
'''
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
except ValueError:
raise ValueError("A data não está no formato YYYY-MM-DD. Execute o programa novamente.")
def filter_tweets(start, tweets):
'''
Usa o dataframe com todos os tweets
e a data de corte, depois da qual os
tweets devem ser mantidos, para gerar
uma lista com os ids das publicações
devem ser removidas.
'''
print("Filtrando Tweets. . .")
now = datetime.datetime.now()
start_date = pd.to_datetime(start, format = "%Y-%m-%d")
# Filtra intervalo de tweets que quero manter
keep_dates = pd.date_range(start=start_date, end=now)
keep_dates = [str(date)[:10] for date in keep_dates]
# Cria uma lista de ids cujo tweet deve ser mantido
tweets_to_delete = [ tweet[0] for tweet in tweets if str(pd.to_datetime(tweet[1]))[:10] not in keep_dates ]
return tweets_to_delete
def delete_tweets(tweet_ids):
'''
Deleta os tweets cujos números
identificadores estão na lista
tweet_ids
'''
print("Deletando Tweets. . .")
# Começa a deletar:
delete_count = 0
for tweet_id in tweet_ids:
try:
api.destroy_status(tweet_id)
print(tweet_id, 'deletado!', delete_count)
delete_count += 1
except:
print(tweet_id, 'não pode ser deletado!')
print('Pronto!', delete_count, 'tweets foram deletados, ao todo.')
##########################
### Execução principal ###
##########################
def main():
print("Iniciando. . .")
username = "xxxxxxxxxx"
start = "2022-10-25"
while True:
try:
tweets = fetch_tweets(username)
tweets = filter_tweets(start, tweets)
delete_tweets(tweets)
except tweepy.TweepyException as e
try:
print(e)
except:
print("error")
keep_alive()
main()
I already tried to change the parameters, put a conditional to check if the list is empty, but none of that worked
The API can only go back so far in retrieving older Tweets.
Another option would be to request your Twitter Archive, which would contain the Tweet IDs and content - you can then potentially use the API to delete Tweets by ID.
Note that there are account and API rate limits that will restrict the speed at which you can run this operation.

I can't send emails from a list of emails on a spreadsheet using python

So, what I need to do is: send e-mails to a list of e-mail that are on a spreadsheet. And I need to send them from Outlook.
I am really new at programming, actually, this the first time I try to program.
This is the code I have:
import win32com.client as win32
import pandas as pd
# criar a integração com o outlook
outlook = win32.Dispatch('outlook.application')
# criar um email
email = outlook.CreateItem(0)
email_list = pd.read_excel('D:\Projeto Zurich/email_list.xlsx')
cliente = email_list['EMAIL']
# configurar as informações do seu e-mail
email.To = "cliente"
email.Subject = "Informações sobre o seu sinistro!"
email.HTMLBody = """
<p>Prezado(a) segurado(a),</p>
<p>Foram realizadas diversas tentativas de contato sem sucesso para agendar a realização da visita da assistência técnica Electrolux, por esse motivo estamos cancelando o seu sinistro.</p>
<p>Para solicitar a reabertura, você pode entrar em contato pelos nossos canais de atendimento:</p>
<p>4020 4848 (capitais e regiões metropolitanas)</p>
<p>0800 285 4141 (demais localidades)</p>
<p>Ou através dos nossos canais digitais em https://www.zurich.com.br/pt-br/atendimento</p>
<p>Atenciosamente,</p>
<p>Zurich Seguros</p>
"""
email.Send()
print("Email Enviado")
And this is the spreadsheet I have:
Is there anything I can do to make this work?
PS.: The code works when I am not trying to use the spreadsheet, like when I add a real email address at email.To =
Clientele is a string. If you wanted to use clientele as a variable you'd have to delete the quotes around it. That being said I would overcome the problem with a simple for loop. It really depends on if you want to send one giant group email or if you want to send to the recipients individually. If you wanted to send it individually, the code could be updated as
for x in clientele:
email.To = x
email.Subject = "Informações sobre o seu sinistro!"
email.HTMLBody = """
<p>Prezado(a) segurado(a),</p>
<p>Foram realizadas diversas tentativas de contato sem sucesso para agendar a
realização da visita da assistência técnica Electrolux, por esse motivo estamos
cancelando o seu sinistro.</p>
<p>Para solicitar a reabertura, você pode entrar em contato pelos nossos canais de atendimento:</p>
<p>4020 4848 (capitais e regiões metropolitanas)</p>
<p>0800 285 4141 (demais localidades)</p>
<p>Ou através dos nossos canais digitais em https://www.zurich.com.br/pt-br/atendimento</p>
<p>Atenciosamente,</p>
<p>Zurich Seguros</p>
"""
email.Send()
print("Email Enviado")
This will substitute the TO address with each individual's email and send them one at a time.

Dealing with special characters in pandas Data Frame´s column Name

I am importing an excel worksheet that has the following columns name:
N° Pedido
1234
6424
4563
The column name ha a special character (°). Because of that, I can´t merge this with another Data Frame or rename the column. I don´t get any error message just the name stays the same. What should I do?
This is the code I am using and the result of the Dataframes:
import pandas as pd
import numpy as np
# Importando Planilhas
CRM = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
Vendas\relatorio_vendas_CRM.xlsx', encoding= 'utf-8')
protheus = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
Vendas\relatorio_vendas_protheus.xlsx', encoding= 'utf-8')
#transformando em Data Frame
df_crm = CRM.parse('190_pedido_export (33)')
df_protheus = protheus.parse('Relatorio de Pedido de Venda')]
# Transformando Campos em float o protheus
def turn_to_float(x):
return np.float(x)
df_protheus["TES"] = df_protheus["TES"].apply(turn_to_float)
df_protheus["Qtde"] = df_protheus["Qtde"].apply(turn_to_float)
df_protheus["Valor"] = df_protheus["Valor"].apply(turn_to_float)
#Tirando Tes de não venda do protheus
# tirando valores com código errado 6
df_protheus_1 = df_protheus[df_protheus.TES != 513.0]
df_protheus_2 = df_protheus_1[df_protheus_1.TES != 576.0]
**df_crm.columns = df_crm.columns.str.replace('N° Pedido', 'teste')
df_crm.columns**
Orçamento Origem N° Pedido Nº Pedido ERP Estabelecimento Tipo de
Pedido Classificação(Tipo) Aplicação Conta CNPJ/CPF Contato ...
Aprovação Parcial Antecipa Entrega Desconto da Tabela de Preço
Desconto do Cliente Desconto Informado Observações Observações NF Vl
Total Bruto Vl Total Completo
0 20619.0 23125 NaN Optitex 1 - Venda NaN Industrialização/Revenda
XAVIER E ARAUJO LTDA ME 7970626000170 NaN ... N N 0 0 0
Note that I used other codes for the bold part with the same result:
#renomeando tabela para dar Merge
#df_crm['proc'] = df_crm['N\xc2\xb0 Pedido']
#df_crm['N Pedido'] = df_crm['N° Pedido']
#df_crm.drop('N° Pedido',inplace=True,axis=1)
#df_crm
#df_crm['N Pedido'] = df_crm['N° Pedido']
#df.drop('N° Pedido',inplace=True,axis=1)
#df_crm
#df_crm_1 = df_crm.rename(columns={"N°Pedido": "teste"})
#df_crm_1
Thanks for posting the link to the Google Sheet. I downloaded it and loaded it via pandas:
df = pd.read_excel(r'~\relatorio_vendas_CRM.xlsx', encoding = 'utf-8')
df.columns = df.columns.str.replace('°', '')
df.columns = df.columns.str.replace('º', '')
Note that the two replace statements are replacing different characters, although they look very similar.
Help from: Why do I get a SyntaxError for a Unicode escape in my file path?
I was able to copy the values into another column. You could try that
df['N Pedido'] = df['N° Pedido']
df.drop('N° Pedido',inplace=True,axis=1)

UPDATE mysql error with Python

Here's my situation:
I got a table on a database, as following:
nome_imagem estado type
57260-tracker-_tracker_face awake 0
57261-tracker-_tracker_face drowsiness 1
57268-tracker-_tracker_face noface 2
57289-tracker-_tracker_face distracted 3
57290-tracker-_tracker_face awake 1
57291-tracker-_tracker_face drowsiness 2
57293-tracker-_tracker_face noface 3
And I want to update de type column according to serveral if conditions, but I'm getting a error on line 29:
mysql.connector.errors.InternalError: Unread result found
I'm pretty sure its the way im making the query, and I already searched another questions about this before opening this one, but I couldnt solve it anyway.
EDIT 1: Changed the query and applied the solution gave by gzc to get rid of the error, but now it updates all the type column instead of just the cases where the if is true
import mysql.connector
from mysql.connector import errorcode
import os
cnx = mysql.connector.connect(user='root', database='empresa')
cursor = cnx.cursor()
fileDir = os.path.dirname(os.path.realpath(__file__))
textDir = os.path.join(fileDir, "test_img")
query = ("SELECT nome_imagem, estado, type FROM alertas ")
cursor.execute(query)
results = list(cursor)
for (nome_imagem, estado, type) in results:
print nome_imagem, estado
my_file_name = nome_imagem+'.txt'
my_file = open("test_img/"+my_file_name, 'r')
content = my_file.readline()
status = content.strip().split()[-1].split("=")[1]
face = content.strip().split()[0].split("=")[1]
print status, face #1 tem face, 0 nao tem
if (face == '1' and estado == status): #se tem cara e o estado que tem na bd for igual ao estado que o programa classificou = correto
print "correto"
cursor.execute("UPDATE alertas SET type='1' WHERE nome_imagem=nome_imagem")
if (face == '1' and estado == 'drowsiness' and status == 'awake') or (face == 1 and estado == 'awake' and status == 'drowsiness'): #verificar isto
print "trocado"
if (estado != '' and face == '0'): # se tiver estado mas nao tiver cara classifico logo como errado 3
print "errado"
if (estado == 'distracted' and face == '1'): # se tem cara mas for distracted deixo normal pois nao consigo classificar
print "normal"
cursor.close()
cnx.close()
What am I doing wrong?
Thanks
EDIT 2: gzc solver it again :)
You must read all results before doing another operation on the same cursor.
...
query = ("SELECT nome_imagem, estado, type FROM alertas ")
cursor.execute(query)
results = list(cursor)
for (nome_imagem, estado, type) in results:
...

Categories