With the conversational Bot, I need to hit a URL which returns a PDF file in response.content JSON. I want to send this file directly to the User without saving it on the server. How can this be done?
Sample Code:
response = requests.get(url)
pdf = open("pdffile.pdf", 'wb')
pdf.write(response.content)
pdf.close()
file = "pdffile.pdf"
update.message.reply_document(document=open(file, 'rb'))
I don't want to perfrom the write operation
As hinted in my comments above, you can pass a bytes stream to send_document. Here is minimal example based on your code snippet (plug in your bot token and your chat id):
import requests
from telegram import Bot
bot = Bot("TOKEN")
response = requests.get('https://python-telegram-bot.readthedocs.io/_/downloads/en/stable/pdf/')
bot.send_document(YOUR_CHAT_ID, document=response.content, filename='python-telegram-bot.pdf')
Note that I passed the filename parameter. This allows you to give a custom filename that will be displayed for the recipient.
Disclaimer: I'm currently the maintainer of python-telegram-bot.
Related
In my API request, with the request payload the complete image is also getting loaded. Is there any way I can script it through JMeter using Groovy?
UI Call where I am uploading image:
enter image description here
Main Request POST Call: enter image description here
Image in the request payload: enter image description here
Can it be done through groovy on JMeter.
Out of interest, why do you want to do this in Groovy? I believe using normal HTTP Request sampler would be much easier, moreover you will be able to even record the request(s) using HTTP(S) Test Script Recorder, this way you will get more metrics and won't need to handle the request and response.
If you still want to do this in Groovy I believe the best option would be calling relevant Apache HttpComponents functions, example code:
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.ContentType
import org.apache.http.entity.mime.HttpMultipartMode
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.impl.client.HttpClientBuilder
def imageFileName = "/path/to/your/image.png"
def post = new HttpPost("http://your-server");
def file = new File(imageFileName);
def builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, imageFileName);
def entity = builder.build();
post.setEntity(entity);
def response = HttpClientBuilder.create().build().execute(post)
//do what you need with the response here
More information: How to Send Groovy HTTP and HTTPS Requests
i have are requirement to read email attachments. Extract data from the excel sheet attached in the email and query dynamodb. AWS documentation suggests we can easy ready the email body but does not provide a example to read email attachments.
After some research we found the solution. You get a message id to get the original message. You can extract the attachments from original message by converting the original message into string and get the exact attachment details in content after "Content-Description: Extract File". Attachments are obtained in base64 and then can be processed.
I am currently trying to run a custom function in Zoho Desk that is triggered on ticket creation, targeting tickets created by our support#zoho... email address, that converts incoming emails into tickets.
More specifically, when an email contains a JSON attachment, I would like the custom function to be able to read the attachment and pull the JSON data from the attachment.
Is this possible? Has anyone had any success?
Below is the code I have, thought I was on the right track but run into the error below
//TicketID is set as an Argument for the custom function
ORGID = "********";
getthread = zoho.desk.getRelatedRecords(ORGID,"threads","tickets",TicketID);
threadid = getthread.getJSON("data").getJSON("id");
getthreadcontent = zoho.desk.getRelatedRecordById(ORGID,"threads",threadid,"tickets",TicketID);//.getJSON("content");
info getthreadcontent.getJSON("attachments").getJSON("name"); //Prints the Attachment Name (Works)
info getthreadcontent;//.getJSON("attachments").getJSON("href");//Prints the Attachment URL (Works)
response = invokeUrl
[
url: getthreadcontent.getJSON("attachments").getJSON("href")
type: GET
];
The above code returns this error:
{"errorCode":"UNAUTHORIZED","message":"You are not authenticated to perform this operation."}
Any help or pointers would be greatly appreciated :)
It looks like you might need to add your Zoho Auth Token to the URL, first, and then make the invoke_url() call.
I have 2 Laravel(5.8) apps. One is a user application, the other is more of an API.
The Api has pdfs stored in the storage directory, I need to be able to allow a user to download the pdfs in the other application.
Really got no clue how to send the file over from app to the other.
The user app makes an api to the api with relevant file ids and things (fine), just can't work out how to send the file back, and then download it on the other end.
Tried things like return response()->stream($pdf) on the api and return response()->download($responeFromApiCall) and loads of other things but really getting nowhere fast.
Any advice welcome.
The laravel code you posted is basically correct, you can use one of stream(), download() or file() helper to serve a file.
file()
Serve a file using a binary response, the most straightforward solution.
// optional headers
$headers = [];
return response()->file(storage_path('myfile.zip'), $optionalHeaders);
You can also use your own absolute file path instead of the storage_path helper.
download()
The download helper is similar to file(), but it also sets a Content-Disposition header which will result in a download-popup if you retrieve the file using your browser.
$location = storage_path('myfiles/invoice_document.pdf');
// Optional: serve the file under a different filename:
$filename = 'mycustomfilename.pdf';
// optional headers
$headers = [];
return response()->download($location, $filename, $headers);
stream()
The stream() helper is a bit more complex and results in reading and serving a file in chunks. This can be used for situations where the filesize is unknown (like passing through another incoming stream from an API). It results in a Transfer-Encoding: chunked header which indicates that the data stream is divided into a series of non-overlapping chunks:
// optional status code
$status = 200;
// optional headers
$headers = [];
// The stream helper requires a callback:
return response()->stream(function() {
// Load a file from storage.
$stream = Storage::readStream('somebigfile.zip');
fpassthru($stream);
if(is_resource($stream)) {
fclose($stream);
}
}, $status, $headers);
Note: Storage::readStream takes the default storage disk as defined in config/filesystems.php. You can change disks using Storage::disk('aws')->readStream(...).
Retrieving your served file
Say your file is served under GET example.com/file, then another application can retrieve it with curl (assuming PHP). A popular wrapper for this would be Guzzle:
$client = new \GuzzleHttp\Client();
$file_path = __DIR__ . '/received_file.pdf';
$response = $client->get('http://example.com/file', ['sink' => $file_path]);
You can derive the filename and extension from the request itself by the way.
If your frontend is javascript, then you can retrieve the file as well but this another component which I dont have one simple example for.
So if I understand correctly you have two systems: user app and api. You want to serve a pdf from user app to the actual user. The user app does a call to api, which works fine. Your issue is converting the response of the api to a response which you can serve from your user app, correct?
In that case I'd say you want to proxy the response from the api via the user app to the user. I don't know what the connection between the user app and the api is, but if you use Guzzle you could look at this answer I posted before.
Here are the steps you should follow to get the PDF:
Make an API call using AJAX ( you are probably already doing it ) from your public site ( User site ) to the API server, with file ID.
API server fetches the PDF, copy it to the public/users/ directory, generate the URL of that PDF file.
Send the URL as a response back to the User site. Using JS add a button/ link in the DOM, to that PDF file.
Example:
jQuery.post(ajaxurl, data, function(response) {
var responseData = JSON.parse(response);
var result = responseData.result;
var pdf_path = responseData.pdf_path;
$(".nametag-loader").remove();
$(".pdf-download-wrapper").append("<a class='download-link' href='"+ pdf_path +"' target='_blank'>Download</a>");
});
Image . I decoded a token using JSR223 Post Processor and able to see correct decoded token in the log viewer using "log.info(vars.get(mystring));". Now I want to get that decoded data to send in another next request. So how I can do it?
I used following code to decode token and[enter image description here][2] print in the JMeter log viewer-
enter code here String a=vars.get("tokenid");
import encrypt.TokenUpdate;
TokenUpdate obj=new TokenUpdate();
String mystring=obj.enc(a);
log.info(mystringenter image description here);
log.info(vars.get(mystring));
decoded data is showing in the JMeter log viewer. So ho can I get that data and to send into another next request?
enter image description here
You can use vars.put and reference the variable in your next subsequent request.
Example below:
String a=vars.get("tokenid");
import encrypt.TokenUpdate;
TokenUpdate obj=new TokenUpdate();
String mystring=obj.enc(a);
log.info(vars.get(mystring));
vars.put("YourVariableName",mystring);
Now in your next subsequent sampler you can refer the variable like ${YourVariableName}
You can refer my other detailed answer on same topic here