Telegram bot using PHP - echo doesn't work - php

I'm trying to use Google Maps API to calculate time and distance between two spots. My code is rather simple and it works (used codepad and it runs smoothly) but when I deploy the code and try to use the service the bot gives me wrong answers...
This is the code:
$details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Miami&destinations=Miami+Beach&mode=driving&sensor=false";
$json = file_get_contents($details);
$arr = json_decode($json, TRUE);
$distance = $arr[rows][0][elements][0][distance][text];
$time = $arr[rows][0][elements][0][duration][text];
$response = "You should be there in $time. Total distance you'll cover: $distance";
$parameters = array('chat_id' => $chatId, "text" => $response);
$parameters["method"] = "sendMessage";
echo json_encode($parameters);
This is what the bot answers me:
"You should be there in {. Total distance you'll cover: {";
And this is the actual json:
{
"destination_addresses" : [ "Miami Beach, Florida, Stati Uniti" ],
"origin_addresses" : [ "Miami, Florida, Stati Uniti" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "15,7 km",
"value" : 15745
},
"duration" : {
"text" : "22 min",
"value" : 1322
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
What's going on?!
UPDATE: file_get_contents returns a string. So I decoded it into a PHP array but now the bot doesn't even answer!

$details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Miami&destinations=Miami+Beach&mode=driving&sensor=false";
$json = file_get_contents($details);
$JsonObject = json_decode($json);
$distance = $JsonObject->rows[0]->elements[0]->distance->text;
$time = $JsonObject->rows[0]->elements[0]->duration->text;
$response = "You should be there in $time. Total distance you'll cover: $distance";
$chatId = "your telegram id here";
$botToken = "your bot token here";
file_get_contents("https://api.telegram.org/bot$botToken/sendMessage?chat_id=$chatId&text=$response");
This one works with file_get_contents.

Related

MongoDB / PHP / MapReduce / Reg Exp / Strings->Floats

I'm new with MapReduce, but I have a collection that I'd like to apply myself to as a chance to learn how mapreduce works.
Example Documents:
{ "filename" : "resume.doc",
"folder" : "work",
"completed": "0.5" },
{ "filename" : "spreadsheet.xls",
"folder" : "work",
"completed": "0.6" },
{ "filename" : "thesis.doc",
"folder" : "school",
"completed": "0.75" },
{ "filename" : "coverletter.doc",
"folder" : "work",
"completed": "0.6"}
So the whole idea is: I'd like to query:
{ "folder" : "work",
"completed": { $gt: 0.5 },
"filename" : new MongoRegex( "/\.[a-zA-Z]{2,}$/" ) }
And ultimately get the count of all documents by extension (.doc, .xls, etc.), as so:
{ ".doc" : 1,
".xls" : 1 }
I also realize i've got an issue because my %-completed are strings, not floats, so i think mongodb is going to need more instruction for comparing the strings.
I'm using (if it matters):
PHP extension: mongo/1.5.7
MongoDB: version 3.2.11
Seems I've stumbled upon my own answer.
Let me know if anybody comes up with a more concise/expert solution.
But this seems to work.
try {
$map = new MongoCode(
'function(){
var re = new RegExp(/(.+)\.([a-zA-Z]{2,})$/);
doctype = this.value.match(re);
if(parseFloat(this.completed)>0.5){
emit(doctype[2], parseFloat(this.completed));
}
}'
);
$reduce = new MongoCode(
'function(key, values){
var sum = 0, num = 0;
for(var i in values){
if(parseFloat(values[i])>0.5){
sum += values[i];
num += 1;
}
}
return { number_of_documents : num,
sum_of_document_completions : sum,
average_completion : (sum/num) };
}'
);
$query = array (
"folder" => "work"
);
$doctypes = $db->command(
array(
'mapReduce' => 'mydocuments',
"map" => $map,
"reduce" => $reduce,
"query" => $query,
"out" => array("inline"=>1)
)
);
print_r ( $doctypes);
}
catch(MongoCursorException $e) {
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
}

How to save multiple items from JSON post in database using Yii

What I'm trying to achieve here is to save multiple items from JSON post data into database whenever there's a new registration.
I've successfully save a single registration. But if I have multiple registrations, it won't save all data passed. It will save only the first item.
Here's the JSON post data captured:
{"id" : "1514358676612-F9RM4",
"accountId" : 128768,
"eventId" : 206218,
"timestamp" : 1514358676612,
"url" : "http://hub.mymagic.my/bizzabo/bizzaboCallback",
"details" : {
"items" : [ {
"contactEmail" : "ikram#mymagic.my",
"created" : "2017-12-27T07:09:21.000+0000",
"ticketPaid" : 0,
"contactFirstName" : "Ikram",
"contactLastName" : "Khasim",
"currency" : "USD",
"validity" : "valid",
"status" : "completed",
"ticketType" : "test",
"ticketId" : 1296403,
"invoice" : false,
"contactName" : "Ikram Khasim",
"paymentStatus" : "completed",
"registrationForm" : {
"type_of_person" : "Experienced Entrepreneur",
"firstName" : "Ikram",
"organisation__instit" : "MaGIC",
"lastName" : "Khasim",
"gender" : "Male | Lelaki",
"age_group" : "22-24",
"mobileNumber" : "0193533005",
"email" : "ikram#mymagic.my",
"how_did_you_hear_abo" : "Word of mouth"
},
"type" : "ticket"
}, {
"contactEmail" : "yasmin#mymagic.my",
"created" : "2017-12-27T07:09:21.000+0000",
"ticketPaid" : 0,
"contactFirstName" : "Ikram",
"contactLastName" : "Khasim",
"currency" : "USD",
"validity" : "valid",
"status" : "completed",
"ticketType" : "test",
"ticketId" : 1296404,
"invoice" : false,
"contactName" : "Ikram Khasim",
"paymentStatus" : "completed",
"registrationForm" : {
"type_of_person" : "Experienced Entrepreneur",
"firstName" : "Ikram",
"organisation__instit" : "MaGIC",
"lastName" : "Khasim",
"gender" : "Male | Lelaki",
"age_group" : "22-24",
"mobileNumber" : "0193533005",
"email" : "yasmin#mymagic.my",
"how_did_you_hear_abo" : "Word of mouth"
},
"type" : "ticket"
} ],
"contactEmail" : "ikram#mymagic.my",
"contactFirstName" : "Ikram",
"contactLastName" : "Khasim",
"currency" : "USD",
"action" : "charge",
"status" : "completed",
"quantity" : 2,
"invoice" : false,
"contactName" : "Ikram Khasim",
"paymentStatus" : "completed",
"amount" : 0,
"orderId" : 651560
},
"type" : "orderCreated"
}
And this is the code to save the JSON post data items into database. It successfully stored the first item into the database, however didn't save the second item.
public function actionBizzaboCallback()
{
$junk = new Junk;
$junk->code = 'bizzabo-bizzaboCallback-'.time();
$junk->content .= serialize($_POST);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// fetch RAW input
$json = file_get_contents('php://input');
// expecting valid json
if (json_last_error() !== JSON_ERROR_NONE) {
$junk = new Junk;
$junk->code = 'bizzabo-getJSONError-'.time();
$junk->content = sprintf('JSON not captured at : %s', Yii::app()->params['masterDomain']);
die(header('HTTP/1.0 415 Unsupported Media Type'));
} else {
// check if registration exist
// decode json
$objects = json_decode($json);
//create new registration
$object = new EventRegistration;
$object->event_code = $objects->eventId;
$tmps = HUB::getEventCode($object->event_code);
$object->event_id = $tmps->id;
$object->event_vendor_code = 'bizzabo';
$object->registration_code = $objects->details->items[0]->ticketId;
$object->full_name = sprintf('%s %s', $objects->details->items[0]->registrationForm->firstName, $objects->details->items[0]->registrationForm->lastName);
$object->first_name = $objects->details->items[0]->registrationForm->firstName;
$object->last_name = $objects->details->items[0]->registrationForm->lastName;
$object->email = $objects->details->items[0]->registrationForm->email;
$object->date_registered = time();
$object->date_payment = time();
$object->json_original = json_decode($json,true);
$object->date_added = time();
$object->date_modified = time();
if($object->save()){
$success = 'successfully insert data into db';
}else{
$fail = $object->errors;
$status = 'failed insert data into db';
}
//create junk
$junk = new Junk;
$junk->code = 'bizzabo-getBizzaboRegistrationIntoDB-'.time();
$junk->content = sprintf('Success(%s) or Fail(%s) with error message (%s). With first name is %s and last name is %s. JSON Captured: %s', $success, $status, $fail, $object->first_name, $object->last_name, $json);
}
}
$junk->save();
}
you should iterate over the items content for save the related values eg:
} else {
// check if registration exist
// decode json
$objects = json_decode($json);
foreach( $object->details->items as $key = $value){
//create new registration
$object = new EventRegistration;
$object->event_code = $objects->eventId;
$tmps = HUB::getEventCode($object->event_code);
$object->event_id = $tmps->id;
$object->event_vendor_code = 'bizzabo';
// apply the actual item value
$object->registration_code = $value->ticketId;
$object->full_name = sprintf('%s %s',
$value->registrationForm->firstName,
$value->registrationForm->lastName);
.......
......
}

Json to url with php

In my $output there is this:
{
"status" : "success",
"data" : {
"network" : "BTC",
"addresses" : [
{
"user_id" : 0,
"address" : "3ABR5GohqyXzf2zebYwjmLuwV7vtFZw1BZ",
"label" : "default",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
]
}
}
But now I want it to get to redirect like:
https://example.com/index.php?status=succes&network=BTC
etc. etc.
But $output can change to like:
{
"status" : "success",
"data" : {
"network" : "BTC",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
}
But then I still want it to work.
I don't know PHP enough for this, so I want to ask:
How to do this?
Simply json_decode() and access the status and network properties:
$decoded = json_decode($output);
header('Location: https://example.com/index.php?status=' . urlencode($decoded->status) . '&network=' . urlencode($decoded->data->network));
exit();
Get the data in the json as an array:
$url = 'https://example.com/index.php?status=' . $status;
foreach($data as $param->$value) {
$url += '&' . $param . '=' . $value
}
header('Location:' $url);
Been a while since i've worked in php but this should handle a varying amount of parameters.

Speeding up PHP Calls

so I have some PHP code which is displaying an email list (Name, Surname & Email) from a list I have hosted via API.
The problem I have is that in order to display the name of the subscriber, I have to separately pass the email through the API... and the only way to get the email is to use a separate function.
So, for a list of 100 people, I'm basically hitting calling their API 300 times... so it is taking forever to echo the information (and over 30ish people the server just times out).
Is there a way I can edit the blow code so that I'm not pulling their info EVERY time, and instead bring it all down at once?
Here's my code:
<?php
require('Mailin.php');
/////////Total Subscriber Count $subscribers
$mailin = new Mailin('https://api.sendinblue.com/v2.0','UNIQUEKEY');
$datacount = array( "id"=>13 );
$subscribercount = $mailin->get_list($datacount);
$subscribers = $subscribercount['data']['total_subscribers'] - 1;
/////////Get Emails of Subscribers
$dataemail = array( "listids" => array(2),
"page" => 1,
"page_limit" => 500
);
$getemails = $mailin->display_list_users($dataemail);
/////////Get Name of Subscribers
foreach (range(0, $subscribers) as $number) {
$subscriberemail = $getemails['data']['data'][$number]['email'];
echo $subscriberemail;
echo '<br/>';
$dataname = array( "email" => $subscriberemail );
$getname = $mailin->get_user($dataname);
$subscribername = $getname['data']['attributes']['NAME'];
$subscribersurname = $getname['data']['attributes']['SURNAME'];
echo $subscribername;
echo '<br/>';
echo $subscribersurname;
echo '<br/>';
}
?>
Here is the output you get calling the display_list_users:
{
"code":"success",
"message":"Retrieved details of all users for the given lists",
"data":{
"data":[
{
"blacklisted":0,
"email":"email1#domain.com",
"id":1,
"listid":[1],
"blacklisted_sms":1,
"last_modified" : "2015-05-22 15:30:00"
},
{
"blacklisted":1,
"email":"email2#domain.com",
"id":2,
"listid":[1,2],
"blacklisted_sms":0 ,
"last_modified" : "2015-05-25 19:10:30"
}
],
"page":1,
"page_limit":2,
"total_list_records":100
}
}
And the output you get calling the get_user:
{
"code":"success",
"message":"Data retrieved for email",
"data":{
"attributes":{
"EMAIL":"example#example.net",
"NAME" : "Name",
"SURNAME" : "surname"
},
"blacklisted":1,
"email":"example#example.net",
"entered":"2014-01-15",
"listid":[8],
"message_sent":[{
"camp_id" : 2,
"event_time" : "2013-12-18"
},
{ "camp_id" : 8,
"event_time" : "2014-01-03"
},
{ "camp_id" : 11,
"event_time" : "2014-01-07"
}],
"hard_bounces":[{
"camp_id" : 11,
"event_time" : "2014-01-07"
}],
"soft_bounces":[],
"spam":[{
"camp_id" : 2,
"event_time" : "2014-01-09"
}],
"unsubscription":{
"user_unsubscribe":[
{
"event_time":"2014-02-06",
"camp_id":2,
"ip":"1.2.3.4"
},
{
"event_time":"2014-03-06",
"camp_id":8,
"ip":"1.2.3.4"
}
],
"admin_unsubscribe":[
{
"event_time":"2014-04-06",
"ip":"5.6.7.8"
},
{
"event_time":"2014-04-16",
"ip":"5.6.7.8"
}
]
},
"opened":[{
"camp_id" : 8,
"event_time" : "2014-01-03",
"ip" : "1.2.3.4"
}],
"clicks":[],
"transactional_attributes":[
{
"ORDER_DATE":"2015-07-01",
"ORDER_PRICE":100000,
"ORDER_ID":"1"
},
{
"ORDER_DATE":"2015-07-05",
"ORDER_PRICE":500000,
"ORDER_ID":"2"
}
],
"blacklisted_sms":1
}
}

JSON to Database with php

So I have this JSON for example
{
"top" : [
{
"info" : {
"ID" : 0,
"TID" : 1
},
"geo" : {
"poins" : [
[
[
-5.9,
57.1
],
[
-5.99,
57.0
]
]
]
}
},
{
"info" : {
"ID" : 1,
"TID" : 2
},
"geo" : {
"points" : [
[
[
-5.4,
57.0
],
[
-5.9,
57.0
]
]
]
}
}
]
}
I need to put this information in the DataBase with php
So I have a colum in the DB called points and it need the data inside to be looking like:
[-5.4, 57.0],[-5.9, 57.0]
I have a columb with ID so all I need is to put the points from the JSON for every ID
My php should be loking like:
connection to the database
$str = file_get_contents(the JSON);
$json = json_decode($str, true);
foreach ($json['top'] as $field) {
query='UPDATE poins_table
SET points='$field['geo']['points']'
WHERE ID='$field['info']['ID']' '
}
The code seems to be not working. What I am missing ...Any siggestions will be helpfull. Thank you
You could try following:
<?php
$str = file_get_contents('the JSON URL');
$json = json_decode($str, true);
try{
$db = new PDO("dbtype:host=yourhost;dbname=yourdbname;charset=utf8","username","password");
$query = $db->prepare('UPDATE poins_table SET points=? WHERE ID=?');
foreach ($json['top'] as $field) {
$query->execute(array(json_encode($field['geo']['points']), $field['info']['ID']));
}
} catch(PDOException $e) {
echo "Error: ". $e;
}
?>

Categories