how to get filename by file_id in telegram - file

for my new bot i need to get real file name.
when i get the file_id and requesting for generate download link with "get file" commend, the file name is look like "file_370.mp3" but the real file name is:"michaeljackson.mp3".
i tried this code:
$mp3name = $result['message']['audio']['title'];
$mp3fileid = $result['message']['audio']['file_id'];
file_get_contents( $url."/sendaudio?chat_id=118718802&audio=$mp3fileid&performer=awaperformer&title=awatitle");
$bot_url = "https://api.telegram.org/bot".$botToken;
$file_path_gen_url = $bot_url."/getfile?file_id=".$mp3fileid;
// file_get_contents( $url."/sendmessage?chat_id=118718802&text=lastfileid:filegen:$file_path_gen_url");
$file_path_result = file_get_contents($file_path_gen_url);
// echo "last file id: $last_file_id <br>";
$file_path_result = json_decode($file_path_result, TRUE);
$file_path = $file_path_result['result']['file_path'];
// echo "file_path: $file_path <br>";
$file_url = "https://api.telegram.org/file/bot".$botToken."/".$file_path;
how can i get real file name?

You can't get original file name for audio object.
here avaliable attributes : https://core.telegram.org/bots/api#audio
You can get original file name for document object.

Related

PHP Download File Script (doesn't work)

I have never written an PHP Download File Script neither have any experience with it and I am really not a pro. I got the snippet of code you can see below from another website and tried to make use of it. I understand what is written in the script but I just don't get the message of the errors or rather said, I don't know how to prevent these.
Here is the download.php script - I have put it into the /download/ folder below my main domain:
<?php
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
$path = "/downloads/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
Now in the /download/ folder, which contains the download.php I have a folder /downloads, which contains the .pdf that should be downloaded.
The link I use on my webpage is:
PHP download file (why isn't it displayed, included the 4 white spaces :
Now I get the following errors when I click on the link:
Warning: Cannot set max_execution_time above master value of 30 (tried to set unlimited) in /var/www/xxx/html/download/download.php on line 4
Warning: fopen(/downloads/test.pdf): failed to open stream: No such file or directory in /var/www/xxx/html/download/download.php on line 12
Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/xxx/html/download/download.php on line 34
If I use an absolute path (https://www.my-domain.de/downloads/) for the $path variable, I get these errors:
Warning: Cannot set max_execution_time above master value of 30 (tried to set unlimited) in /var/www/xxx/html/download/download.php on line 4
Warning: fopen(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /var/www/xxx/html/download/download.php on line 12
Warning: fopen(https://www.my-domain.de/downloads/test.pdf): failed to open stream: no suitable wrapper could be found in /var/www/xxx/html/download/download.php on line 12
Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/xxx/html/download/download.php on line 34
I am thankful for any advices!
<?php
ignore_user_abort(true);
//set_time_limit(0); disable the time limit for this script
$path = "downloads/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
?>
Try this code
Your server is probably not allowing you for a maximum execution time limit for infinite seconds. Check it in php.ini file
Also the relative path was wrong, and "https://www.my-domain.de/downloads/" is not a path, it's a url for the server

Handling Hebrew files and folders with Python 3.4

I used Python 3.4 to create a programm that goes through E-mails and saves specific attachments to a file server.
Each file is saved to a specific destination depending on the sender's E-mail's address.
My problem is that the destination folders and the attachments are both in Hebrew and for a few attachments I get an error that the path does not exsist.
Now that's not possible because It can fail for one attachment but not for the others on the same Mail (the destination folder is decided by the sender's address).
I want to debug the issue but I cannot get python to display the file path it is trying to save correctly. (it's mixed hebrew and english and it always displays the path in a big mess, although it works correctly 95% of the time when the file is being saved to the file server)
So my questions are:
what should I add to this code so that it will proccess Hewbrew correctly?
Should I encode or decode somthing?
Are there characters I should avoid when proccessing the files?
here's the main piece of code that fails:
try:
found_attachments = False
for att in msg.Attachments:
_, extension = split_filename(str(att))
# check if attachment is not inline
if str(att) not in msg.HTMLBody:
if extension in database[sender][TYPES]:
file = create_file(str(att), database[sender][PATH], database[sender][FORMAT], time_stamp)
# This is where the program fails:
att.SaveAsFile(file)
print("Created:", file)
found_attachments = True
if found_attachments:
items_processed.append(msg)
else:
items_no_att.append(msg)
except:
print("Error with attachment: " + str(att) + " , in: " + str(msg))
and the create file function:
def create_file(att, location, format, timestamp):
"""
process an attachment to make it a file
:param att: the name of the attachment
:param location: the path to the file
:param format: the format of the file
:param timestamp: the time and date the attachment was created
:return: return the file created
"""
# create the file by the given format
if format == "":
output_file = location + "\\" + att
else:
# split file to name and type
filename, extension = split_filename(att)
# extract and format the time sent on
time = str(timestamp.time()).replace(":", ".")[:-3]
# extract and format the date sent on
day = str(timestamp.date())
day = day[-2:] + day[4:-2] + day[:4]
# initiate the output file
output_file = format
# add the original file name where needed
output_file = output_file.replace(FILENAME, filename)
# add the sent date where needed
output_file = output_file.replace(DATE, day)
# add the time sent where needed
output_file = output_file.replace(TIME, time)
# add the path and type
output_file = location + "\\" + output_file + "." + extension
print(output_file)
# add an index to the file if necessary and return it
index = get_file_index(output_file)
if index:
filename, extension = split_filename(output_file)
return filename + "(" + str(index) + ")." + extension
else:
return output_file
Thanks in advance, I would be happy to explain more or supply more code if needed.
I found out that the promlem was not using Hebrew. I found that there's a limit on the number of chars that the (path + filename) can hold (255 chars).
The files that failed excided that limit and that caused the problem

Find string in log files and return extra characters

How can I get Python to loop through a directory and find a specific string in each file located within that directory, then output a summary of what it found?
I want to search the long files for the following string:
FIRMWARE_VERSION = "2.15"
Only, the firmware version can be different in each file. So I want the log file to report back with whatever version it finds.
import glob
import os
print("The following list contains the firmware version of each server.\n")
os.chdir( "LOGS\\" )
for file in glob.glob('*.log'):
with open(file) as f:
contents = f.read()
if 'FIRMWARE_VERSION = "' in contents:
print (file + " = ???)
I was thinking I could use something like the following to return the extra characters but it's not working.
file[:+5]
I want the output to look something like this:
server1.web.com = FIRMWARE_VERSION = "2.16"
server2.web.com = FIRMWARE_VERSION = "3.01"
server3.web.com = FIRMWARE_VERSION = "1.26"
server4.web.com = FIRMWARE_VERSION = "4.1"
server5.web.com = FIRMWARE_VERSION = "3.50"
Any suggestions on how I can do this?
You can use regex for grub the text :
import re
for file in glob.glob('*.log'):
with open(file) as f:
contents = f.read()
if 'FIRMWARE_VERSION = "' in contents:
print (file + '='+ re.search(r'FIRMWARE_VERSION ="([\d.]+)"',contents).group(1))
In this case re.search will do the job! with searching the file content based on the following pattern :
r'FIRMWARE_VERSION ="([\d.]+)"'
that find a float number between two double quote!also you can use the following that match anything right after FIRMWARE_VERSIONbetween two double quote.
r'FIRMWARE_VERSION =(".*")'

Corona lua: How do I attach a .txt data file saved to system.DocumentsDirectory to an email?

Corona lua: How do I attach a data file that is saved to the system directory to an email? An image of the data.txt file shows up in the email pop up on an iPad after I build, but doesn't get attached although the email is sent. Images go fine. I used "text", "plain", and "text/plain" as the mime type. If you can help with this, I would greatly appreciate it!
Try this:
-----------------------------------------------------------------------------------
-- Creating the text file --
-----------------------------------------------------------------------------------
local filePath_Type = system.pathForFile( "myTextFile.txt", system.DocumentsDirectory )
local file = io.open( filePath_Type, "r" )
if file then
io.close( file )
else
--Create an empty file--
local path_Type = system.pathForFile( "myTextFile.txt", system.DocumentsDirectory )
local file = io.open( path_Type, "w+b" )
file:write("My data inside file")
io.close( file )
end
-----------------------------------------------------------------------------------
-- Now, to email this file --
-----------------------------------------------------------------------------------
function showMailPicker()
-- Create mail options --
local options =
{
to = { "me#me.com",},
subject = "Subject Text",
body = "Email Body",
attachment =
{
{ baseDir=system.DocumentsDirectory, filename="myTextFile.txt", type="text" },
},
}
-- Send mail --
native.showPopup("mail", options)
end
submitButton = display.newImageRect("myButton.png",100,40)
submitButton.x = 160
submitButton.y = 240
submitButton:addEventListener("tap",showMailPicker)
Keep Coding.............. :)

Groovy - create file issue: The filename, directory name or volume label syntax is incorrect

I'm running a script made in Groovy from Soap UI and the script needs to generate lots of files.
Those files have also in the name two numbers from a list (all the combinations in that list are different), and there are 1303 combinations
available and the script generates just 1235 files.
A part of the code is:
filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile();
where $file is actually that part of the file name which include those 2 combinations from that list:
file = "abc" + "-$firstNumer"+"_$secondNumber"
For those file which are not created is a message returned:"The filename, directory name or volume label syntax is incorrect".
I've tried puting another path:
filename = "D:\\rez\\" + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile();
and also:
File parentFolder = new File("D:\\rez\\");
File targetFile = new File(parentFolder, "$file"+"_OK.txt");
targetFile.createNewFile();
(which I've found here: What are possible reasons for java.io.IOException: "The filename, directory name, or volume label syntax is incorrect")
but nothing worked.
I have no ideea where the problem is. Is strange that 1235 files are created ok, and the rest of them, 68 aren't created at all.
Thanks,
My guess is that some of the files have illegal characters in their paths. Exactly which characters are illegal is platform specific, e.g. on Windows they are
\ / : * ? " < > |
Why don't you log the full path of the file before targetFile.createNewFile(); is called and also log whether this method succeeded or not, e.g.
filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
println "attempting to create file: $targetFile"
if (targetFile.createNewFile()) {
println "Successfully created file $targetFile"
} else {
println "Failed to create file $targetFile"
}
When the process is finished, check the logs and I suspect you'll see a common pattern in the ""Failed to create file...." messages
File.createNewFile() returns false when a file or directory with that name already exists. In all other failure cases (security, I/O) it throws an exception.
Evaluate createNewFile()'s return value or, additionally, use the File.exists() method:
File file = new File("foo")
// works the first time
createNewFile(file)
// prints an error message
createNewFile(file)
void createNewFile(File file) {
if (!file.createNewFile()) {
assert file.exists()
println file.getPath() + " already exists."
}
}

Resources