I've got a basic bot set up that will send text back to the user, now I also want to send the user an audio message. But that I cannot do, here is the code.
I'm also using this https://github.com/Eleirbag89/TelegramBotPHP to send the audio
include("Telegram.php);
define('BOT_TOKEN', 'tokentoken');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
$telegram = new Telegram(BOT_TOKEN);
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
$reply = sendMessage($message);
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply;
file_get_contents($sendto);
function sendMessage(&$string) {
switch ($string) {
case "Hi":
$message = "Hi Back";
sendAudio();
break;
case "Bye":
$message = "Bye Bye";
break;
default:
$message = "Default";
}
return $message
}
func sendAudio() {
$sound = curl_file_create('sampleAudio.mp3', 'audio/mp3');
$newContent = array('chat_id' => $chatID, 'audio' => $sound);
$telegram->sendAudio($newContent);
}
Calling the code outside of the functions works, but than the user gets the file each time they type something. I experimenting so a bit of explanation would be great.
You have some errors:
First line " is unclosed
Last function, you've typed "func" instead of "function"
In sendAudio() you've used $chatID but you've to pass it as a parameter of sendAudio() or to set is as global.
Related
In Wordpress (PHP) i'm using Contact Form 7 (CF7) as the UI and sending the data via an API with the function on_submit below. Would like to have the success or fail response data logged to make sure everything is working so thought i'd write that to a simple text file using the function custom_logs. It does write to the text file but then the process never continues on to the CF7 plugin to indicate the POST was a success or fail, it just hangs after hitting submit on the UI side. I believe something about writing to the file is interrupting the flow and then is just stops from CF7's POV. I rarely write anything in PHP so not 100% sure what the issue is? Anyone have an idea how to solve it, I can't find anything. Thanks
function on_submit( $form, &$abort, $submission )
{
$data = $submission->get_posted_data();
$firstname = sanitize_text_field($data['first-name']);
$response = wp_safe_remote_post("https://www.api.com", [
'body' => json_encode([
'firstname' => $firstname,
]),
]);
if ( is_wp_error($response) ) {
$abort = TRUE;
$body = wp_remote_retrieve_body($response);
$result = json_decode($body);
$submission->set_response($result->error);
$submission->set_status('api_failed');
} else {
$abort = FALSE;
$body_success = wp_remote_retrieve_body($response);
$result_success = json_decode($body_success);
custom_logs("WP API: " . $result_success);
}
}
add_action('wpcf7_before_send_mail', 'on_submit', 10, 3);
function custom_logs($message) {
if(is_array($message)) {
$message = json_encode($message);
}
$file = fopen("custom_logs.log","a");
echo fwrite($file, "\n" . date('Y-m-d h:i:s') . " :: " . $message);
fclose($file);
}
I'm trying to create a php that sends via email all possible information about the request. Currently I'm using something like:
Email request php:
<?php
$remoteIp = $_SERVER['REMOTE_ADDR'];
$remoteHost = $_SERVER['HTTP_HOST'];
$remoteRef = $_SERVER['HTTP_REFERER'];
$remoteUrl = $_SERVER['REQUEST_URI'];
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$yourEmailAddress = "user#mail.com";
$emailSubject = "New request from: ".$remoteIp;
$emailContent = "The URL Request was made to: $remoteUrl
The request REFERER was: $remoteRef
The IP was $remoteIp
The User Agent was: $userAgent";
// send the message
mail($yourEmailAddress, $emailSubject, $emailContent);
?>
I like to add the Entire http request (GET OR POST) to the email been send so $emailContent it look like this:
$emailContent = "The URL Request was made to: $remoteUrl
The request REFERER was: $remoteRef
The IP was $remoteIp
The User Agent was: $userAgent"
The Full request was:
$fullrequest";
Looking around I found this https://gist.github.com/magnetikonline/650e30e485c0f91f2f40 which allows you to create file but I'm not sure on how to put it together with my PHP so it sends me an email with the request. (Creating the file is not necessary)
This PHP I like to integrate to my Email request php
<?php
// https://gist.github.com/magnetikonline/650e30e485c0f91f2f40
class DumpHTTPRequestToFile {
public function execute($targetFile) {
$data = sprintf(
"%s %s %s\n\nHTTP headers:\n",
$_SERVER['REQUEST_METHOD'],
$_SERVER['REQUEST_URI'],
$_SERVER['SERVER_PROTOCOL']
);
foreach ($this->getHeaderList() as $name => $value) {
$data .= $name . ': ' . $value . "\n";
}
$data .= "\nRequest body:\n";
file_put_contents(
$targetFile,
$data . file_get_contents('php://input') . "\n"
);
echo("Done!\n\n");
}
private function getHeaderList() {
$headerList = [];
foreach ($_SERVER as $name => $value) {
if (preg_match('/^HTTP_/',$name)) {
// convert HTTP_HEADER_NAME to Header-Name
$name = strtr(substr($name,5),'_',' ');
$name = ucwords(strtolower($name));
$name = strtr($name,' ','-');
// add to list
$headerList[$name] = $value;
}
}
return $headerList;
}
}
(new DumpHTTPRequestToFile)->execute('./dumprequest.txt');
Can any one help me to add class DumpHTTPRequestToFile to $fullrequest?
Something like
<?php
$message="The following request was made:\n";
foreach($_REQUEST as $k=>$v){
$message.=$k." : ".$v."\n\n";
}
mail($to_address, $subject, $message, $headers);
?>
Replace $_REQUEST with the super global of your choice. Or run similar loops across multiple superglobals ($_SERVER, etc) if $_REQUEST doesn't have all you want in it.
I made this code in my .php file where I set webHook that works good.
$token = "my token";
$website = "https://api.telegram.org/bot" . $token . "/";
$updates = file_get_contents("php://input");
$updates = json_decode($updates, true);
$text = $updates["message"]["text"];
$chatID = $updates["message"]["chat"]["id"];
switch($text){
case "/prova_gratuita":
if(check($chatID)){
sendMessage($chatID, "Are you sure? Demo is available only one time. Write confirm to continue");
switch($text){
case "confirm":
...
break;
}
}
Second switch() does not work. Why? What can I do?
I know I should update value of $text, but I don't know how I can do it
I think that the error is how you set up the problem.
Each bot input is a call to that WebHook. Then $ text can not be aggornato that way.
You should also include in the first switch of the "case" of the second.
$token = "my token";
$website = "https://api.telegram.org/bot" . $token . "/";
$updates = file_get_contents("php://input");
$updates = json_decode($updates, true);
$text = $updates["message"]["text"];
$chatID = $updates["message"]["chat"]["id"];
switch($text){
case "/prova_gratuita":
if(check($chatID)) sendMessage($chatID, "Are you sure? Demo is available only one time. Write confirm to continue");
case "confirm":
...
}
Every time you send a message to the bot, he makes a call to the WebHook. So to change the state of $updates, so even the $text the script should restart
I'm trying to send a json object as a POST command using the following:
$uri = "http://amore-luce.com/product_create";
$product = $observer->getEvent()->getProduct();
$json = Mage::helper('core')->jsonEncode($product);
Mage::log(" Json={$json}", null,'product-updates.txt');
// new HTTP request to some HTTP address
$client = new Zend_Http_Client('http://amore-luce.com/product_create');
// set some parameters
$client->setParameterPost('product', $json);
// POST request
$response = $client->request(Zend_Http_Client::POST);
When I view the $json the data is there and all looks good - however the POST is not sending the json data. I'm capturing it using a simple email form that should send me the response:
<?php
$webhookContent = "";
$ref = "";
$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhookContent .= fread($webhook, 4096);
}
fclose($webhook);
$headers = array();
foreach($_SERVER as $key => $value) {
if (substr($key, 0, 5) <> 'HTTP_') {
continue;
}
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
foreach ($headers as $header => $value) {
$ref .= "$header: $value <br />\n";
}
$post = file_get_contents('php://input');
$to = "address#my-email.com"; //the address the email is being sent to
$subject = "This is the subject"; //the subject of the message
$msg = "This is the message - Webhook content: ".$webhookContent." This is url: ".$ref; //the message of the email
mail($to, $subject, $msg, 'From: PHP Scriptv2 <noreply#domain.com>'); //send the email.
echo ($_SERVER['HTTP_REFERER']."<br>".$_SERVER['REQUEST_URI']);
?>
This page works with other json POST requests I've sent to it. I'm fairly new at sending POST requests so any help would be greatly appreciated.
Try change :
$client->setParameterPost('product', $json);
to :
$client->setHeaders('Content-type','application/json');
$client->setParameterPost('product', $json);
or use:
$client->setRawData($json, 'application/json');
So Update / Answer changing how I did it to these lines of code:
$uri = "http://requestb.in/p6p4syp6";
$product = $observer->getEvent()->getProduct();
$json = Mage::helper('core')->jsonEncode($product);
Mage::log(" Json={$json}", null,'product-updates.txt');
$client = new Zend_Http_Client($uri);
$client->setRawData($json, null)->request('POST');
Changing the SetRawData($json, null) was the bit - using SetRawDate($json, 'application/json') caused it to fail.
Thanks Voodoo417 - I'll also try your suggestion and see if that lets me set the correct type
I'm writing a help desk pipe handler to pipe incoming e-mails as helpdesk ticket replies. Some e-mails are coming in perfectly fine, others are coming in as a jumble of the text and =3D's all munged into one giant string. Does anyone have an idea on how to decode that into plain text.
For reference, this is my mail parser function:
public function parseEmailMessage(Zend_Mail_Message $msg)
{
if ($msg->isMultiPart()) {
$arrAttachments = array();
$body = '';
// Multipart Mime Message
foreach (new RecursiveIteratorIterator($msg) as $part) {
try {
$mimeType = strtok($part->contentType, ';');
// Parse file name
preg_match('/name="(?<filename>[a-zA-Z0-9.\-_]+)"/is', $part->contentType, $attachmentName);
// Append plaintext results to $body
// All other content parts will be treated as attachments
switch ($mimeType) {
case 'text/plain':
$body .= trim($part->getContent()) . "\n";
break;
case 'text/html':
$body .= trim(strip_tags($part->getContent));
break;
default:
$arrAttachments[] = array(
'attachment_mime' => $mimeType,
'attachment_name' => $this->filterFileName($attachmentName['filename']),
'base64data' => trim($part->getContent())
);
}
} catch (Zend_Mail_Exception $e) {
// ignore
}
}
return array($body, $arrAttachments);
} else {
// Plain text message
return array(trim($msg->getContent()), array());
}
}
I'll take a guess that somehow the content type is not correctly specified and Zend doesn't know how to decode it. I know I've seen this before, but I can't remember where or how it was 'solved'.
It looks like quoted-printable being treated like plain text.