I am attempting to use gtts to generate an audio file of text I am passing in as a variable ( eventually I will be scraping the text to be read, but not in this script, that is why I am using a variable) and I want to text myself the .mp3 file I am generating. It is not working though - here is my code. Any idea how to text message an .mp3 file with twilio?
import twilio
from gtts import gTTS
from twilio.rest import Client
accountSID = '********'
authToken = '****************'
twilioCli = Client(accountSID, authToken)
myTwilioNumber = '*******'
myCellPhone = '*****'
v = 'test'
#add voice
tts = gTTS(v)
y = tts.save('hello.mp3')
message = twilioCli.messages.create(body = y, from_=myTwilioNumber, to=myCellPhone)
this is the error i get, but the link it directs me to does not speak to texting mp3 audio files:
raise self.exception(method, uri, response, 'Unable to create record')
twilio.base.exceptions.TwilioRestException:
[31m[49mHTTP Error[0m [37m[49mYour request was:[0m
[36m[49mPOST /Accounts/********/Messages.json[0m
[37m[49mTwilio returned the following information:[0m
[34m[49mUnable to create record: The requested resource /2010-04-01/Accounts/********/Messages.json was not found[0m
[37m[49mMore information may be available here:[0m
[34m[49mhttps://www.twilio.com/docs/errors/20404[0m
Twilio developer evangelist here.
You can't send an mp3 file as the body of a text message. If you do send a body, it should be a string.
You can deliver mp3 files as media messages in the US and Canada. In this case you need to make the mp3 file available at a URL. Then you set that URL as the media_url for the message, like this:
message = twilioCli.messages.create(
from_=myTwilioNumber,
to=myCellPhone,
media_url="http://example.com/hello.mp3"
)
I recommend reading through the documentation on sending media via MMS and what happens to MIME types like mp3 in MMS.
Related
For example, I have an existing message created by
bot.send_message(message.chat_id, "Hello, world!")
Then I changed it in callback_query_handler as follows
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Hello, Stackoverflow!", reply_markup=tutors_markup, parse_mode = 'Markdown')
After that I do some manipulations. And then I need to add a photo to the message with "Hello, Stackoverflow!".
How can i do it?
(I use telebot library)
I was trying to edit by
photo = open(f'photo_{result[0]}.jpg', 'rb')
bot.edit_message_media(media=telebot.types.InputMedia(type='photo', media=photo, caption = "noitpac"), chat_id=call.message.chat.id, message_id=call.message.message_id)
But got
telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: there is no media in the message to edit
And I understand this error, but don't what to do.
I am trying to trigger an external api from postman by passing the uploadFile in the body as form-data. Below code throws me an error as 'FileNotFoundError: [Errno 2] No such file or directory:'
Note: In postman, uploadFile takes file from my local desktop as input. have also modified the postman settings to allow access for files apart from working directory
Any help would be highly appreciable.
Below is the Code:
#app.route('/upload', methods=['POST'])
#auth.login_required
def post_upload():
payload = {
'table_name': 'incident', 'table_sys_id': request.form['table_sys_id']
}
files = {'file': (request.files['uploadFile'], open(request.files['uploadFile'].filename,
'rb'),'image/jpg', {'Expires': '0'})}
response = requests.post(url, headers=headers, files=files, data=payload)
return jsonify("Success- Attachment uploaded successfully ", 200)
Below code throws me an error as 'FileNotFoundError: [Errno 2] No such file or directory:
Have you defined UPLOAD_FOLDER ? Please see: https://flask.palletsprojects.com/en/latest/patterns/fileuploads/#a-gentle-introduction
i am passing the attribute (upload file) in body as form-data, can this be passed as raw json
You cannot upload files with JSON. But one hacky way to achieve this is to base64 (useful reference) encode the file before sending it. This way you do not upload the file instead you send the file content encoded in base64 format.
Server side:
import base64
file_content = base64.b64decode(request.data['file_buffer_b64'])
Client side:
-> Javascript:
const response = await axios.post(uri, {file_buffer_b64: window.btoa(file)})
-> Python:
import base64
with open(request.data['uploadFile'], "rb") as myfile:
encoded_string = base64.b64encode(myfile.read())
payload = {"file_buffer_b64": encoded_string}
response = requests.post(url, data=payload)
I want my client to download (not render) a dynamically generated PDF file via pyramid. Right now I do it like this:
def get_pdf(request):
pdfFile = open('/tmp/example.pdf', "wb")
pdfFile.write(generator.GeneratePDF())
response = FileResponse('/tmp/example.pdf')
response.headers['Content-Disposition'] = ('attachment; filename=example.pdf')
return response
From the client point-of-view it's exactly what I need. However,
It leaves behind an orphaned file
It isn't thread-safe (though I could use random filenames)
The docs say:
class FileResponse
A Response object that can be used to serve a static file from disk simply.
So FileResponse is probably not what I should be using. How would you replace it with something more dynamic but indistinguishable for the client?
Just use a normal response with the same header:
def get_pdf(request):
response = Response(body=generator.GeneratePDF())
response.headers['Content-Disposition'] = ('attachment;filename=example.pdf')
return response
I had written a code in python to fetch the huge set (80 lines) of data from DB, now I would like to post that data in slack through webhook. I tried posting the data directly,but its not working for me, so I decided to save the data in txt/.png file and post it in slack
I tried below code in python after saving my data in report.txt file, but its not helping me
headers = {
'Content-type': 'application/json',
}
data = open('\\results\report.txt')
response = requests.post('https://jjjjjjj.slack.com/services/mywebhook', headers=headers, data=data)
Please share me the Curl command which will fit in python script to post the attachment in slack or please suggest me any better approach to post more than 50 lines for data to slack
I would suggest to upload long text as text file. That way Slack will automatically format it with a preview and users can click on it to see the whole content.
To upload a file you need to use files_upload API method. With it you can also include an initial message with your upload.
Here is an example using the standard Slack library. Here I am reading the data from a file, but you would of course use your data instead:
import slack
import os
# init slack client with access token
slack_token = os.environ['SLACK_TOKEN']
client = slack.WebClient(token=slack_token)
# fetch demo text from file
with open('long.txt', 'r', encoding='utf-8') as f:
text = f.read()
# upload data as file
response = client.files_upload(
content=text,
channels='general',
filename='long.txt',
title='Very long text',
initial_comment='Here is the very long text as requested:'
)
assert response['ok']
The trick is to use content not file to pass the data. If you use file the API will try to load a file from your filesystem.
The below code works fine for me..... :)
headers = { 'Authorization': 'Bearer xxxx-XXXXX-XXXXX', #Bot Token }
files = {
'file': ('LocationOfthefile\report.txt', open('LocationOfthefile\report.txt', 'rb')),
'initial_comment': (None, 'Some Text For Header'),
'channels': (None, 'Channel_Names'),
}
response = requests.post('slack.com/api/files.upload', headers=headers, files=files)
I ingested data to (Kinesis Video Stream) KVS via AWS Connect service now using GetMedia API am able to extract the Payload but how can I convert this output to a mp3/wav ? I want to ingest this output to AWS Transcribe service to get text format of audio call ingested by AWS Connect service to KVS.
Output of Payload for below code is like :
00#AWS_KINESISVIDEO_CONTINUATION_TOKEND\x87....\x1faudio/L16;rate=8000;channels=1;\x12T\xc......00"AWS_KINESISVIDEO_MILLIS_BEHIND_NOWD\x87\x10\x00\x00\x074564302g\xc8\x10\x00\x00^E\xa3\x10\x00\x00#AWS_KINESISVIDEO_CONTINUATION_TOKEND\x87\x10\x00\x00/91343852333181432506572546233025969374566791063'
Note: Above response was too long, so pasted some of it.
import json
import boto3
kinesis_client = boto3.client('kinesisvideo', region_name='us-east-1')
response = kinesis_client.get_data_endpoint(
StreamARN='arn:aws:kinesisvideo:us-east-1:47...,
APIName='GET_MEDIA')
t = response['DataEndpoint']
video_client = boto3.client('kinesis-video-media', endpoint_url=t, region_name='us-east-1')
stream = video_client.get_media(
StreamARN='arn:aws:kinesisvideo:us-east-1:47...',
StartSelector={'StartSelectorType': 'EARLIEST'})
streamingBody = stream['Payload']
print(streamingBody.read())
Please suggest how can I convert payload output to mp3/wav etc.
I am facing the same problem, I can export the payload to S3 as a raw file but when I listen it, it is not properly audible like it was a crypted conversation.
I just save the payload into a file.
f = open("myAudio.wav", 'w+b')
f.write(stream['Payload'].read())
f.close()