Telegram Send image from external server - php

I'm using PHP to config a webhook for a BOT.
I'd like to send picture from another server.
I've tried this way
function bot1($chatID,$sentText) {
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$this->sendPhoto($botUrl,$chatID,$img);
}
function sendPhoto($botUrl,$chatID, $img){
$this->sendMessage($botUrl,$chatID,'This is the pic'.$chatID);
$this->sendPost($botUrl,"sendPhoto",$chatID,"photo",$img);
}
function sendMessage($botUrl,$chatID, $text){
$inserimento = file_get_contents($botUrl."/sendMessage?chat_id=".$chatID."&text=".$text."&reply_markup=".json_encode(array("hide_keyboard"=>true)));
}
function sendPost($botUrl,$function,$chatID,$type,$doc){
$response = $botUrl. "/".$function;
$post_fields = array('chat_id' => $chatID,
$type => new CURLFile(realpath($doc))
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $response);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);
}
But I receive only the message.
What is the problem?
I've tried to change in http but the problem persists

Well, I've done a workaround because my cUrl version seems to have a bug in uploading file.
Now I use Zend FW
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$realpath = realpath($doc);
$url = $botUrl . "/sendPhoto?chat_id=" . $chatID;
$client = new Zend_Http_Client();
$client->setUri($url);
$client->setFileUpload($realpath, "photo");
$client->setMethod('POST');
$response = $client->request();

You have to send a file, not a URL.
So:
function bot1( $chatID,$sentText )
{
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$data = file_get_contents( $img ); # <---
$filePath = "/Your/Local/FilePath/Here"; # <---
file_put_contents( $data, $filePath ); # <---
$this->sendPhoto( $botUrl, $chatID, $filePath ); # <---
}
This is as raw example, without checking success of file_get_contents().
In my bot I use this schema, and it works fine.

Related

How to get json for soundcloud without type

I get JSON from the Soundcloud API by using code in section【A】.
But I want to get it without using $type, like in code【B】.
In other words, I want to get that information by only giving $target.
What should I do?
$r = soundcloud_responce();
var_dump( $r );
function soundcloud_responce(){
$client_id = 'xxx';
$type = 'tracks';
$q = 'words';
// code【A】
// If I have $type, So this process ok.
$url = "https://api.soundcloud.com/";
$url .= $type;
$url .= "?client_id=$client_id";
$url .= "&q=$q";
// code【B】
// I want to do same process with $target but without $type
$target = "https://soundcloud.com/accountname/trackname";
$target = str_replace('https://soundcloud.com/', '', $target);
$url = "https://api.soundcloud.com/";
$url .= $target;
$url .= "?client_id=$client_id";
// curl
$ch = curl_init();
$headers = [
'Accept: application/json',
'Content-Type: application/json',
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
$json = json_decode($res);
curl_close($ch);
return $json;
}
(Add 2020-02-21-09:38 #Tokyo)
I tried this code【C】but this also failed.
// code【C】
// I tried with oembed but this also failed.
$target = "https://soundcloud.com/accountname/trackname";
$url = 'http://soundcloud.com/oembed?format=json&url='.$target;
(Add 2020-02-21-10:12 #Tokyo)
I tried this code【D】but this also failed.
// code【D】
// I tried with resolve but this also failed.
$target = "https://soundcloud.com/accountname/trackname";
$url = "https://api.soundcloud.com/resolve?url=$target&client_id=$client_id";
I tried this code【E】this is successful!
Thank you for giving me good advice, #showdev.
// code【E】
// this is successful!
$target = "https://soundcloud.com/accountname/trackname";
$target = urlencode($target);
$url = "https://api.soundcloud.com/resolve.json?url=$target&client_id=$client_id";

Sending an image to aws via php

The main problem that i've to do is sending an image from another server to AWS after some process. For that i've done the database processes in the first server. It works very well, i tested it. After that i've to send this image directly to AWS to start another .php file. I try it via cURL function:
server1.php the php file that's found in the first server:
$url = 'http://myawsurl.com/server/test.php';
$imageData = file_get_contents($_FILES['fileToUpload']['tmp_name']);
$post_data = array(
'tmp' => $_FILES["fileToUpload"]["tmp_name"],
'type' => $_FILES["fileToUpload"]["type"],
'name' => $_FILES["fileToUpload"]["name"],
'data' => $imageData
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
test.php the php file that's found in aws:
if ($_POST["tmp"] && $_POST["name"] && $_POST["type"] && $_POST["data"]) {
$target_dir_requests = "/requests/";
create_folder_if_not_exist(ABSPATH . $target_dir_requests);
$dir_for_req_server = ABSPATH . $target_dir_requests . basename($_FILES["fileToUpload"]["name"]);
$dir_for_req_server = base64_to_jpeg($_POST["data"],$dir_for_req_server);
// After some requests that i've to do and i've done
} else {
echo "data sending error";
}
i tried something for todo but they did not work. Could you please help me for find a solution ? Thanks.
You are checking if the variable is true or not with the if($_POST[])
What you actually want is to check if the variable isset
Try this and see if you get any result:
if(isset($_POST['tmp'])){
echo 'test';
}
Or
$tmp = isset($_POST['tmp']) ? trim($_POST['tmp']) : null;
if(!empty($tmp)){
echo 'test';
}
The curl itself should be working

PHP Upload PDF to Google Drive API

I have website created in PHP. Basically it is a send document kind of project. It uses a document store in Azure I will call and send it into Azure. Now I want to send in email as well as store in Google drive.
So it should be stored to drive with public access. I have create following code. It works properly I don't want any input from user.
$client->setAccessToken($_SESSION['accessToken']);
$service = new Google_DriveService($client);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = new Google_DriveFile();
foreach ($files as $file_name) {
$file_path = 'files/'.$file_name;
$mime_type = finfo_file($finfo, $file_path);
$file->setTitle($file_name);
$file->setDescription('This is a '.$mime_type.' document');
$file->setMimeType($mime_type);
$service->files->insert(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => $mime_type
)
);
}
finfo_close($finfo);
I want upload from Azure URL using cURL or using API. When mail send it is automatically uploaded to drive at the same time.
Question Update
I have function to send a mail this is work perfectly. I would like to store an attachment to google drive and retrieve path store that path in to database.
This all work will be based on API no user interaction required. That file is PDF in formate and not specific bytes its different as per data of file.
Issue :
When I upload a file to Drive original file name is rename to untitled. Here is code.
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS, array("title" =>"newfile.txt"));
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : text/plain', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
==========================================
Updated code (Issue with Added code but still getting issue with Untitle.pdf in drive)
==========================================
<?php
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$CLIENT_ID = '709846732498-xxxxxxxx';
$CLIENT_SECRET = 'XXXXXXXXXXXXXX';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : application/pdf', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
function getStoredCredentials($path)
{
$credentials = json_decode(file_get_contents($path), true);
if (isset($credentials['refresh_token']))
return $credentials;
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
{
$credentials = null;
unlink($path);
}
return $credentials;
}
function storeCredentials($path, $credentials)
{
$credentials['created'] = (new DateTime())->getTimestamp();
file_put_contents($path, json_encode($credentials));
return $credentials;
}
function requestAuthCode()
{
global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
$url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
);
header('Location:' . $url);
}
function requestAccessToken($access_code)
{
global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$url = $GOAUTH . 'token';
$post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
. '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
function getAccessToken($credentials)
{
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
return $credentials['refresh_token'];
else
return $credentials['access_token'];
}
function authenticate()
{
global $STORE_PATH;
if (file_exists($STORE_PATH))
$credentials = getStoredCredentials($STORE_PATH);
else
$credentials = null;
if (!(isset($_GET['code']) || isset($credentials)))
requestAuthCode();
if (!isset($credentials))
$credentials = requestAccessToken($_GET['code']);
if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
$credentials = storeCredentials($STORE_PATH, $credentials);
return $credentials;
}
$credentials = authenticate();
$result = uploadFile($credentials, 'example.pdf', '');
if (!isset($result['id']))
throw new Exception(print_r($result));
else
echo 'File copied successfuly (file Id: ' . $result['id'] . ')';
echo '<pre>'; print_r($result);
going by https://developers.google.com/drive/api/v3/simple-upload , this should work:
<?php
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
CURLOPT_HTTPHEADER => array (
'Content-Type: application/pdf', // todo: runtime detection?
'Authorization: Bearer [YOUR_AUTH_TOKEN]'
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents ( '/path/to/file.pdf' ),
CURLOPT_RETURNTRANSFER => 1
) );
try {
if (false === ($resp = curl_exec ( $ch ))) {
throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
}
$parsed = json_decode ( $resp, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $resp );
}
} finally{
curl_close ( $ch );
}
var_dump($resp);
I am still not completely sure i understand your question. Assuming you just want to upload a file in php or curl here are two options.
Uploading to Google drive is in two parts the first part you create the meta data that being the file name and basic information about your fine. The second part is where you upload the actual data of your file.
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'My Report',
'mimeType' => 'application/vnd.google-apps.spreadsheet'));
$content = file_get_contents('files/report.csv');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'text/csv',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
Code ripped from media upload
If you want to do this in curl inserting the meta data shouldnt be an issue your issue will be uploading the file itself. You will need to POST the metadata to create the empty file and capture its file-id. Then use the file-id for a content upload. You can find more information on the requests you will nee dot make here simple upload request.
The code will probably look something like this but again your going to have to pass the file id.
curl
--silent
--request POST
--data-binary "#c:\temp\myfile.jpg"
-OL MyFolder\myfile2.jpeg
-H "Slug: myfile3.jpg"
-H "Authorization: Bearer [your access token here]"
-H "Content-Type: image/jpeg {"fileid":"1234"}"
"https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
Note i have not tested the upload in curl this is just a guess.
You can use Logic Apps to send the file from Azure Blob storage to Google Drive as well as an email attachment.
https://learn.microsoft.com/en-us/azure/connectors/connectors-create-api-azureblobstorage
Alternatively files stored in Azure Blobs can be addresses with a public URL assuming you have the right permissions set on the container and/or blob.

php telegram sendAudio

I have a problem with sendAudio() function in php telegram bot.
if (strtoupper($text) == "MUSIC") {
$voice = curl_file_create('audio.ogg');
$content = array('chat_id' => $chat_id, 'audio' => $voice);
$telegram->sendAudio($content);
}
This don't work with an audio lenghtof 9 or more seconds. I also tried with .mp3 but nothing. Same function with an audio lenght of 6 or less seconds works. I looked in the documentation and it says only 50MB files are restricted. Help pls.
Here's my $telegram.
include("Telegram.php");
$bot_id = "xxxxxxx:yyyyyyyy_mytoken";
$telegram = new Telegram($bot_id);
And here Telegram.php:
class Telegram {
private $bot_id = "mytoken";
private $data = array();
private $updates = array();
public function __construct($bot_id) {
$this->bot_id = $bot_id;
$this->data = $this->getData();
}
public function endpoint($api, array $content, $post = true) {
$url = 'https://api.telegram.org/bot' . $this->bot_id . '/' . $api;
if ($post)
$reply = $this->sendAPIRequest($url, $content);
else
$reply = $this->sendAPIRequest($url, array(), false);
return json_decode($reply, true);
}
public function sendAudio(array $content) {
return $this->endpoint("sendAudio", $content);
}
I am using this code to send mp3 audio file to telegram from my php application and It's working fine for me.
$BOT_TOKEN = 'yourBotToken';
$chat_id = '#yourChannel';
$filePath = 'your/path/file';
define('BOTAPI', 'https://api.telegram.org/bot' . $BOT_TOKEN . '/');
$cfile = new CURLFile(realpath($filePath));
$data = [
'chat_id' => $chat_id,
'audio' => $cfile,
'caption' => $message
];
$ch = curl_init(BOTAPI . 'sendAudio');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_exec($ch);
curl_close($ch);
Have you tried to use sendVoice for ogg file instead of sendAudio?
Next code did work for me well:
<?php
exec( "curl -i -F 'chat_id=1234567890' -F 'voice=#audio.ogg' 'https://api.telegram.org/bot1234567890:AABBCCDDEEFFGGHH/sendVoice' 2>&1", $output , $return );
print_r( json_decode( end( $output ) ) );
you can use this code to send your audio file
function sendmessage($url, $post_params) {
$cu = curl_init();
curl_setopt($cu, CURLOPT_URL, $url);
curl_setopt($cu, CURLOPT_POSTFIELDS, $post_params);
curl_setopt($cu, CURLOPT_RETURNTRANSFER, true); //get result
$result = curl_exec($cu);
curl_close($cu);
return $result;
}
$telsite = "https://api.telegram.org/bot"."$your_token_id";
$sendAudio_url = $telsite."sendAudio";
$post_parameters = array('chat_id' => $chat_user_id , 'audio' => $dir_of_audio);
sendmessage($sendAudio_url , $post_parameters);
Example using westacks/telebot library:
<?php
use WeStacks\TeleBot\TeleBot;
require 'vendor/autoload.php';
$bot = new TeleBot('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11');
$bot->sendAudio([
'chat_id' => 1111111111,
'audio' => 'https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3'
]);
$bot->sendAudio([
'chat_id' => 1111111111,
'audio' => './path/to/local/file.mp3'
]);

How to post an image to Twitter with PHP?

I'm trying to post a message with an image to Twitter through PHP and cURL. It's working for the message but I don't know how to add the image to it.
From the documentation:
Unlike POST statuses/update, this method
expects raw multipart data. Your POST request's Content-Type should be
set to multipart/form-data with the media[] parameter
This is the PHP:
<?php
class Tweet {
public $url = 'https://api.twitter.com/1.1/statuses/update_with_media.json';
function the_nonce(){
$nonce = base64_encode(uniqid());
$nonce = preg_replace('~[\W]~','',$nonce);
return $nonce;
}
function get_DST($status){
$url = $this->url;
$consumer_key = "[removed]";
$nonce = $this->the_nonce();
$sig_method = 'HMAC-SHA1';
$timestamp = time();
$version = "1.0";
$token = "[removed]";
$access_secret = "[removed]";
$consumer_secret = "[removed]";
$param_string = 'oauth_consumer_key='.$consumer_key.
'&oauth_nonce='.$nonce.
'&oauth_signature_method='.$sig_method.
'&oauth_timestamp='.$timestamp.
'&oauth_token='.$token.
'&oauth_version='.$version.
'&status='.rawurlencode($status);
$sig_base_string = 'POST&'.rawurlencode($url).'&'.rawurlencode($param_string);
$sig_key = rawurlencode($consumer_secret).'&'.rawurlencode($access_secret);
$tweet_sig = base64_encode(hash_hmac('sha1', $sig_base_string, $sig_key, true));
$DST = 'OAuth oauth_consumer_key="'.rawurlencode($consumer_key).'",'.
'oauth_nonce="'.rawurlencode($nonce).'",'.
'oauth_signature="'.rawurlencode($tweet_sig).'",'.
'oauth_signature_method="HMAC-SHA1",'.
'oauth_timestamp="'.rawurlencode($timestamp).'",'.
'oauth_token="'.rawurlencode($token).'",'.
'oauth_version="1.0"';
return $DST;
}
function set($status){
$url = $this->url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: ' . $this->get_DST($status)));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.rawurlencode($status));
curl_setopt($ch, CURLOPT_URL, $url);
$result = json_decode(curl_exec($ch));
$resultString = print_r($result,true);;
curl_close($ch);
}
$status->set("hello");
?>
How to add the media[] part to it?
not sure if Matt Harris' library would do for you, but the code is rather simple
require_once ('your_app_tokens.php');
require_once ('tmhOAuth.php');
$connection = new tmhOAuth(array(
'consumer_key' => $consumer_key,
'consumer_secret' => $consumer_secret,
'user_token' => $user_token, //stored in session or whatever else
'user_secret' => $User_secret
));
$message ="test";
$image = "image.jpg"; // must be in the same directory
$extension = "jpg";
$post = $connection->request(
'POST',
'https://api.twitter.com/1.1/statuses/update_with_media.json',
array(
'media[]' => "#{$image};type=image/{$extension};filename={$image}",
'status' => $message
),
true,
true
);
$code = $connection->response;
//if the code is 200 it's all fine
i've created a script that allows you to post a tweet with image. I'm using the php fonction that used an url to upload the image to your server. After that, it upload from your server to the twitter one. You got an image ID that you can use to send a tweet with a picture.
Here is my github projet. Everything is inside, easy to used and install.
https://github.com/florianchapon/twitter-poster

Categories