hi i'm new in flask and twilio, i'm try to send 2 images with 1 request but just appears the last image that i put in the array
this is my code
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
from dotenv import load_dotenv
import os
load_dotenv()
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello, World!"
#app.route("/sms", methods=['POST'])
def sms_reply():
"""Respond to incoming calls with a simple text message."""
# Fetch the message
msg = request.form.get('Body')
# CLIENT
client = Client(os.getenv("TWILIO_ID"), os.getenv("AUTH_TOKEN"))
number = request.values.get('From', '')
# creating the message
if msg == "imagen":
message = client.messages.create(
from_='whatsapp:+14155238886',
media_url=["https://demo.twilio.com/owl.png", "https://demo.twilio.com/bunny.png"],
to=number
)
resp = MessagingResponse()
resp.message("imagen : {}".format(message.body))
return str(resp)
how could see in the "media_url" parameter i put 2 urls, but twilio just send my 1, i made a mistake?. i try it in this way too
mss = MessagingResponse()
resp = mss.message("this is a message")
resp.body("imagen1")
resp.media("https://demo.twilio.com/owl.png")
resp.body("imagen2")
resp.media("https://demo.twilio.com/bunny.png")
return str(resp)
but is the same. thnks for ur help
Twilio developer evangelist here. That code should work, it's just that there is no bunny image at that URL. You will need your image to be hosted at a publicly-accessible URL like these:
message = client.messages.create(
from_="YOUR-TWILIO-NUMBER",
to="NUMBER-TO-RECEIVE-IMAGES",
body="Test sending two messages",
media_url=["https://data.whicdn.com/images/339398954/original.gif", "https://thumbs.gfycat.com/PrestigiousUntidyBetafish-max-1mb.gif"],
)
That returns this image:
I'd recommend using Twilio Runtime Assets, our static file hosting service that allows developers to quickly upload and serve the files needed to support their applications. host your files that support web, voice, and messaging applications. Assets is commonly used to host .mp3 audio files used in TwiML, to serve images sent through MMSes, or store configuration used by Twilio Functions. You can also deploy the images to be hosted on web servers.
Let me know if this helps at all!
Related
I am trying to deploy a python script in Google Cloud Functions where the user submits a yes-or-no answer from Whatsapp and it reaches the Twilio API. If this function receives a 'Yes' it activates a query in Google Big Query table and reply with a report. My point is: if I create this function with no authentication, it works fine. However, it doesn't work for me, because it gives private information about my company.
So, in order to avoid problems, I create a function authenticating with Cloud IAM. When I pass the service account to this function, I give permission to invoke cloud function, the account inherit all permissions to read and execute jobs in Big Query and I give permission to service agents. Even following all these steps, I'm still receiving a 403 error.
Here is the code I'm trying to deploy in Google Cloud Functions:
from datetime import datetime, timedelta
from dotenv import load_dotenv
import os
from sales import Sales
from flask import Flask, request
from functools import wraps
from utils import format_currency, emoji_alerts
load_dotenv()
app = Flask(__name__)
def message_sales():
data = (datetime.now()-timedelta(days=1)).strftime('%d/%m/%Y')
resultado = Sales()
return f""" message """
#here is where the message is generated, this f-string queries results in bigquery
#app.route('/reply', methods=['GET','POST'])
def send_message(request):
from twilio.rest import Client
from twilio.twiml.messaging_response import MessagingResponse
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
incoming_msg = request.values.get('Body', '').lower()
resp = MessagingResponse()
msg = resp.message()
responded = False
report = message_sales()
if 'yes' in incoming_msg:
msg.body(report)
responded = True
elif 'no' in incoming_msg:
msg.body('Ok')
responded = True
return str(resp)
if __name__ == "__main__":
app.run(debug=False, host='0.0.0.0', port=2020)
And here is the connection function to big query and a example of a query:
def run_google_query(query):
credentials = service_account.Credentials.from_service_account_file(GOOGLE_APPLICATION_CREDENTIALS)
client = bigquery.Client(project='project-id', credentials=credentials)
return [row[0] for row in client.query(query)][0]
def get_resultado_dia(self):
return f"""
SELECT RESULTADO_ATUAL FROM `table`
WHERE DATA_VENDA = '{self.ontem.strftime('%Y-%m-%d')}'
"""
This is my last deploy. I have tried to use Secret Manager library, I have created a service account with the necessary permissions, I've given more permission to actual service accounts and nothing worked.
I believe that I need to authenticate the Twilio API with Google Cloud, but I can't find a clear explanation on how to procedure with that. Anyway, create a unauthenticated http request won't be an option, since the information shouldn't be open.
I built a simple flask server in order to automate python scripts based on an HTTP POST Request coming in from an outside service. This service sends these requests in response to events that we have created based on data conditions. All the flask server needs to do is parse the requests, and take the numerical value stored in the request and use it to run the corresponding python script. At one point, this system was working consistently. Fast forward a few months, the server was no longer working when tried again. No changes were made to the code. According to wireshark, The computer hosting the flask server is receiving the request to the correct port, but the request is now timing out. The host system is failing to respond to the request. Any Idea what is going on here? The firewall has temporarily been turned off.
Alternatively, is there another better package to achieve this goal with?
from flask import Flask, request
import threading
import runpy
app = Flask(__name__)
#app.route('/', methods=['POST'])
def PostHandler():
directory = {}
with open(r"M:\redacted") as f:
for line in f:
(key,val) = line.split()
directory[int(key)] = val
print(directory)
path = r"M:\redacted"
content = request.json
content = content['value']
print(content)
sel_script = int(content)
print(directory[sel_script])
runpy.run_path(path_name=path + directory[sel_script])
return
app.run(host="10.244.xx.xx", port=8080, threaded=True)
I'm currently working on the Twilio SMS Quickstart; specifically I'm stuck on the "Reply to an incoming message using Twilio SMS".
*update, I've realized I haven't used the 'request' module I imported from Flask. Would appreciate any tips on if I need to utilize this module and, if I do, how do I use it in this specific script?
Up to this point I've successfully sent a message using a Twilio script called "send_sms.py". I'm now stuck with being unable use my virtualenv to receive and reply to messages. Here's the code titled 'run.py':
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
#app.route('/sms', methods=['POST'])
def sms_ahoy_reply():
"""Respond to incoming messages with a friendly SMS."""
# Start our response
resp = MessagingResponse()
# Add a message
resp.message("Ahoy! Thanks so much for your message.")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
I get an error from my code editor, Spyder, next to 'from flask import Flask, request'; however, when I delete ', request' the error goes away.
As a result of this issue I'm unable to successfully run the script which would allow me to receive and reply to text messages via Twilio.
I have built a SMS service (using Twilio) that the user texts to get realtime bus information. At the moment i have been hosting this on my personal computer using ngrok. Now i want to use AWS to host this service, but I am not sure as to how i should go about it. I have tried running a flask webserver and trying to get ngrok to run on AWS, but no luck.
Here is my code concerning Flask and Twilio's REST Api:
app = Flask(__name__)
#app.route("/sms", methods=['GET', 'POST'])
def hello_monkey():
resp = MessagingResponse()
response = request.form['Body']
if (" " in response):
response = response.split(" ")
result = look_up(response[0], response[1])
else:
result = look_up(response, False)
resp.message(result)
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
There is a blog post on the Twilio blog on How to Send SMS Text Messages with AWS Lambda and Python 3.6. It does not use Flask, but it can definitely be modified to achieve your goal. Alternatively, you could read about using Flask with AWS Elastic Beanstalk here.
Running ngrok on AWS is not the correct approach to this. If you wanted to host your own Flask server, you could use something like Lightsail, but that's overkill for this usage.
I have been writing a simple app to test how to send emails via an SMTP method (needs to be SMTP to be portable to different SMTP services) using Flask-Mail. For this I am trying to use Mailgun through Heroku, but after much trial, error and research I still cannot seem to get emails to send.
My question is on a similar vein to this question, Flask on Heroku with MailGun config issues, however I can see no resolution in this question other than to use Mailgun's API, which isn't feasible for the project I am working on.
Currently I have the flask/flask-mail code set up as follows (stripped down of course):
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.mail import Message
app = Flask(__name__)
mail = Mail(app)
app.config.setdefault('SMTP_SERVER', environ.get('MAILGUN_SMTP_SERVER'))
app.config.setdefault('SMTP_LOGIN', environ.get('MAILGUN_SMTP_LOGIN'))
app.config.setdefault('SMTP_PASSWORD', environ.get('MAILGUN_SMTP_PASSWORD'))
app.config.setdefault('MAIL_SERVER', environ.get('MAILGUN_SMTP_SERVER'))
app.config.setdefault('MAIL_USERNAME', environ.get('MAILGUN_SMTP_LOGIN'))
app.config.setdefault('MAIL_PASSWORD', environ.get('MAILGUN_SMTP_PASSWORD'))
app.config.setdefault('MAIL_USE_TLS', True)
def EmailFunction(UserEmail):
msg = Message("Hello",
sender='testing#test.com',
recipients=[UserEmail])
msg.html = "<b>testing</b>"
mail.send(msg)
return msg.html
#app.route('/EmailTest/')
def EmailTestPage():
EmailFunction('developer#test.com')
return 'Email Sent'
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=True)
Am I missing something? And is there a way to test what is going wrong as the code passes and 'Email Sent' is returned, but no email is sent/received seemingly.
Thanks for any help you can provide!
It looks like you're not reading in the SMTP port. By default Flask mail likely tries to use 25 whereas mailgun uses 587.