Getting messages from multiple chats madelineproto - php

I am looking for some help here.
I am trying to get messages from multiple chats in Telegram using MadelineProto using the user IDs with code:
require 'vendor\autoload.php';
$settings[ 'logger' ][ 'logger' ] = 0;
$settings[ 'serialization' ][ 'serialization_interval' ] = 30;
$MadelineProto = new API('session.madeline', $settings);
$MadelineProto->async(true);
$MadelineProto->start();
$chat_one = 1234567;
$chat_two = 3254682;
$chat_three = 154789965;
function getMessagesById($u_id, $MadelineProto){
$offset_id = 0;
$limit = 100;
do {
$messages_Messages = $MadelineProto->messages->getHistory(
['peer' =>$u_id,
'offset_id' => $offset_id,
'offset_date' => 0,
'add_offset' => 0,
'limit' => $limit,
'max_id' => 0,
'min_id' => 0,
'hash' => 0 ]
);
if (count($messages_Messages['messages']) == 0) break;
print_r($messages_Messages);
$offset_id = end($messages_Messages['messages'])['id'];
yield $MadelineProto->sleep(3);
} while (true);
}
getMessagesById($chat_one , $MadelineProto);
getMessagesById($chat_two , $MadelineProto);
getMessagesById($chat_three , $MadelineProto);
But this does not return any message. I tried it by setting async to false and I get the messages only for the first function call and not two others.
Any idea here, what I am missing?
What I am actually after is only getting messages from specifics contacts and the code above works with async set to false for only one contact. I use ajax to refresh it every 10 seconds for new messages but sometimes it returns empty, so any better idea to do this would be appreciated. I went through the docs but nothing helped on getting messages, all sendMessage.
Thanks

It is necessary to transfer the object:
$inputChannel = ['_' => 'inputPeerChat', 'chat_id' => $u_id];
['peer' => inputChannel,

Related

update_post_meta and update_field not working without any error received

I am working with a wordpress site that imports all data from API to the site automatically via cron job. However, I'm now on the part of saving the field data from the API. The problem is update_post_meta and update_fields are both not working.
I already tried interchanging between the two methods of saving but both doesn't work. No error prompts and no results as well (which is pretty weird for me). I checked the built-in plugin of the site and it uses update_post_meta.
add_action('wp_ajax_nopriv_get_properties_from_api','get_properties_from_api');
add_action('wp_ajax_get_properties_from_api','get_properties_from_api')
function get_properties_from_api(){
$file = get_stylesheet_directory() . '/report.txt';
$current_page=(! empty($_POST['current_page'])) ? $_POST['current_page'] : 1;
$properties = [];
$results = wp_remote_retrieve_body(wp_remote_get('https://www.realestateview.com.au/listing_api?rm=search&company=castlemain&code=29GKRRSgkVdQVM&CID=5813&json=1&ptr=r&con=S&portalview=residential&rn=1&pg='. $current_page));
file_put_contents($file, "Current page: ". $current_page. "\n\n", FILE_APPEND);
$results=json_decode($results, true);
if(!is_array($results['Listings']) || empty($results['Listings'])){
return false;
}
$properties[]=$results;
foreach($properties[0] as $property){
$property_slug = sanitize_title($property->TitleNoHTML, '-', $property->OrderID);
$inserted_property = wp_insert_post([
'post_name' => $property_slug,
'post_title' => $property->TitleNoHTML,
'post_type' => 'property',
'post_status' => 'publish',
]);
if(is_wp_error($inserted_property)){
continue;
}
$fillable=[
//Basic information
get_the_title($inserted_property) => 'TitleNoHTML',
'REAL_HOMES_property_price' => 'PriceText',
'REAL_HOMES_property_size' => 'LandSizeText',
'REAL_HOMES_property_bedrooms' => 'BedroomsCount',
'REAL_HOMES_property_bathrooms' => 'BathroomsCount',
'REAL_HOMES_property_garage' => 'LockUpGaragesCount',
'REAL_HOMES_featured' => 'FeaturedProperty',
//$this->REAL_HOMES_property_id =
//$this->REAL_HOMES_property_year_built =
//Location on Map
'REAL_HOMES_property_address' => 'AddressText',
'REAL_HOMES_property_location' => 'Suburb',
'REAL_HOMES_property_map' => 'DisplayTrueAddress',
//Gallery
'REAL_HOMES_property_images' => 'PhotoOriginalURL',
//Floor Plans
//$this->inspiry_floor_plan_name =
'inspiry_floor_plan_price' => 'PriceText',
//$this->inspiry_floor_plan_price_postfix =
// $this->inspiry_floor_plan_size =
// $this->inspiry_floor_plan_size_postfix =
'inspiry_floor_plan_bedrooms' => 'BedroomsCount',
'inspiry_floor_plan_bathrooms' =>'BathroomsCount',
// $this->inspiry_floor_plan_descr =
'inspiry_floor_plan_image' => 'FloorplanThumbURL',
//Property Video
'inspiry_video_group_image' => 'PhotoThumbURL',
//$this->inspiry_video_group_title =
'inspiry_video_group_url' => 'VideoURL',
//DEPRECATED FIELDS
// $this->REAL_HOMES_360_virtual_tour =
// $this->REAL_HOMES_tour_video_url_divider =
// $this->REAL_HOMES_tour_video_url =
// $this->REAL_HOMES_tour_video_image =
//Agent
//$this->REAL_HOMES_agent_display_option =
'REAL_HOMES_agents' => 'ContactAgentName',
//Energy Performance
// $this->REAL_HOMES_energy_class =
// $this->REAL_HOMES_energy_performance =
// $this->REAL_HOMES_epc_current_rating =
// $this->REAL_HOMES_epc_potential_rating =
//Misc
// $this->REAL_HOMES_sticky =
// $this->inspiry_property_label =
// $this->inspiry_property_label_color =
// $this->REAL_HOMES_attachments =
'inspiry_property_owner_name' => 'ClientName',
//$this->inspiry_property_owner_contact =
'inspiry_property_owner_address' => 'ClientAddress',
// $this->REAL_HOMES_property_private_note =
// $this->inspiry_message_to_reviewer =
//Homepage slider
// $this->REAL_HOMES_add_in_slider =
// $this->REAL_HOMES_slider_image =
// $this->REAL_HOMES_page_banner_image =
//Additional fields
'inspiry_InspectionDateandStartTime' => 'ISOInspectionStart',
'inspiry_InspectionDateandFinishTime' => 'ISOInspectionFinish',
];
foreach($fillable as $key => $TitleNoHTML){
update_post_meta($inserted_property, $key, $property->$TitleNoHTML);
}
}
$current_page = $current_page + 1;
wp_remote_post(admin_url('admin-ajax.php?action=get_properties_from_api'), [
'blocking' => false,
'sslverify' => false,
'body' => [
'current_page' => $current_page
]
]);
What I'm already expecting is it should be already save some data, if not, it should produce an error but for some weird reason, there isn't. I tried to var_dump some variables and I think it should be working. Would anyone be able to help me find out where I gone wrong?
In order to replace the Wordpress cron with a real cron job you will need to set a cron job which will fetch data from a webpage using wget. First you will need to create a Wordpress page which will contain your PHP code then fetch the content with cron using wget.
The real cron job command will look like this:
wget -q -O - http://yourdomain.com/your_cron_page >/dev/null 2>&1
-q tells wget to operate quietly (ie. to not output the usual status information)
-O /dev/null tells it to output to /dev/null
Keep in mind that everyone can access this page so you might want to set some restrictions.

Handle when api doesn't respond

I am trying to get euro, dollar and turkish liras currencies and comparing them. But sometimes api (i am using a random currency website json values) can't respond.
Cannot get any value and page loading 30 sec, after execute time was done, error appears.
What i am trying to do is: if it couldn't get any value in 1 second(or less) from api, return null. How can i do that. If anybody can help, i would glad. This is my php codes. I was tried to use if else in this, but can't worked.
ps: I have a ajax codes for that, its refreshing when the value are change. This is working most times. But 2-3 times in a day, it throws error.
$json_eur = file_get_contents('https://doviz.com/api/v1/currencies/EUR/latest');
$val_eur = json_decode($json_eur, true);
echo $val_eur['selling'];
EDIT
This is the solve. Added some codes to JRoss answer.
$ctx_dollar = stream_context_create(array(
'http' => array(
'timeout' => 1
)
)
);
$usd_url = 'https://doviz.com/api/v1/currencies/USD/latest';
if (#file_get_contents($usd_url)):
$json_usd = file_get_contents($usd_url, 0, $ctx_dollar);
$val_usd = json_decode($json_usd, true);
if (is_numeric($val_usd['selling'])) {
echo $val_usd['selling'];
}
else {
echo "loading...";
}
endif;
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1
)
)
);
file_get_contents("https://doviz.com/api/v1/currencies/EUR/latest", 0, $ctx);
http://php.net/file_get_contents
and on top of that I would catch exceptions. try {} catch (Exception $e) {}

Server keeps crashing on heavy load (facebook SDK + Laravel 5.2 + AWS)

I'm on the free tier of AWS and using the laravel framework and the facebook v.2.5 SDK (Web). I'm trying to get the latests 10 posts from facebook for approximately 600 users. Which would be 6000 posts max. Every time I run the query it runs through about 10 loops and then the app completely crashes and goes offline. Then returns after a few minutes. Laravel isn't showing me any errors.
My code is:
/**
* Get facebook users posts
* #return \SammyK\LaravelFacebookSdk\LaravelFacebookSdk;
*/
public function posts(\SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
{
// get posts
$profiles_to_get = DB::table('facebook_profiles')->distinct('username')->get();
$fb_admin_profile = DB::table('profiles')->where('social_media_type', "facebook")->first();
$admin_fb_access_token = $fb_admin_profile->oauth_token;
foreach ($profiles_to_get as $profile_to_get) {
try {
$response = $fb->get('/'.$profile_to_get->username.'?fields=posts.limit(10)', $admin_fb_access_token);
$userNode = $response->getGraphUser();
$posts = json_decode($userNode['posts']);
foreach ($posts as $post)
{
isset($post->message) ? $fb_posts[] = array('account_id' => $profile_to_get->id,
'facebook_id' => $userNode->getID(),
'message_id' => $post->id,
'message' => $post->message,
'created_time' => $post->created_time->date,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
) : null;
foreach ($fb_posts as $fb_post)
{
$postDuplicateChecker = DB::table('facebook_posts')->where('message_id', $fb_post['message_id'])->get();
if($postDuplicateChecker == !null)
{
DB::table('facebook_posts')->where('message_id', $fb_post['message_id'])->update($fb_post);
$notification = "First notification";
}
else
{
DB::table('facebook_posts')->insert( $fb_post );
$notification = "Second notification";
}
}
if ($post > 0 && $post % 10 == 0)
{
sleep(5);
}
}
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
}
return Redirect::route('someroute',[ 'notification' => $notification]);
}
I've tried setting the query timeout at 300 so it doesn't time out and also making the loop sleep after every 10 requests so that it reduces the load. Also I have other apps running on the same server but they never go offline when this app crashes.
My question is is there any way to optimize the code so that I don't have to upgrade the server or is my only choice to upgrade the server?
The answer was to batch the query using array_chunk and chunk the process into smaller pieces which could be handled easier.
array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )
Reference: http://php.net/manual/en/function.array-chunk.php

array_key_exists() expects parameter 2 to be array, string when using pushWoosh Class

I am having some trouble implementing the pushwoosh class http://astutech.github.io/PushWooshPHPLibrary/index.html. I have everything set up but i am getting an error with the array from the class.
This is the code i provied to the class:
<?php
require '../core/init.php';
//get values from the clientside
$sendID = $_POST['sendID'];
$memID = $_POST['memID'];
//get sender name
$qry = $users->userdata($memID);
$sendName = $qry['name'];
//get receiving token
$qry2 = $users->getTokenForPush($sendID);
$deviceToken = $qry2['token'];
//i have testet that $deviceToken actually returns the $deviceToken so thats not the problem
//this is the array that the php class requires.
$pushArray = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$push->createMessage($pushArray, 'now', null);
?>
And this is the actually code for the createMessage() method
public function createMessage(array $pushes, $sendDate = 'now', $link = null,
$ios_badges = 1)
{
// Get the config settings
$config = $this->config;
// Store the message data
$data = array(
'application' => $config['application'],
'username' => $config['username'],
'password' => $config['password']
);
// Loop through each push and add them to the notifications array
foreach ($pushes as $push) {
$pushData = array(
'send_date' => $sendDate,
'content' => $push['content'],
'ios_badges' => $ios_badges
);
// If a list of devices is specified, add that to the push data
if (array_key_exists('devices', $push)) {
$pushData['devices'] = $push['devices'];
}
// If a link is specified, add that to the push data
if ($link) {
$pushData['link'] = $link;
}
$data['notifications'][] = $pushData;
}
// Send the message
$response = $this->pwCall('createMessage', $data);
// Return a value
return $response;
}
}
Is there a bright mind out there that can tell me whats wrong?
If I understand, your are trying to if your are currently reading the devices sub-array. You should try this:
foreach ($pushes as $key => $push) {
...
// If a list of devices is specified, add that to the push data
if ($key == 'devices') {
$pushData['devices'] = $push['devices'];
}
You iterate over $pushes, which is array('content' => ..., 'devices' => ...). You will first have $key = content, the $key = 'devices'.
It looks like the createMessage function expects an array of messages, but you are passing in one message directly. Try this instead:
$push->createMessage(array($pushArray), 'now', null);
The class is expecting an array of arrays; you are just providing an array.
You could do something like this
//this is the array that the php class requires.
$pushArrayData = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$pushArray[] = $pushArrayData
Will you ever want to handle multiple messages? It makes a difference in how I would do it.

connection between android app and cakephp

Hi I'm making a web service in cakephp for an android app. I am getting the request and the respose is being send but the response is not visible on the client's end. My code is as shown below. Can there be some other method to send the response.
public function AndroidApp() {
if (isset($_POST["myHttpData"])) {
$coupon = trim($_POST["myHttpData"]);
$couponId = $this->Code->find('all', array(
'conditions' => array(
'Code.coupon_code' => $coupon,
'Code.status' => 'Used'
),
'fields' => array('Code.id')));
$studentAssessmentId = $this->StudentAssessment->find('all', array(
'conditions' => array(
'StudentAssessment.code_id' => $couponId[0]['Code']['id'],
'StudentAssessment.status' => 'Complete'
),
'fields' => array('StudentAssessment.id')));
$scores = $this->AssessmentScore->find('all', array(
'conditions' => array(
'AssessmentScore.student_assessment_id' => $studentAssessmentId[0]['StudentAssessment']['id']
),
'fields' => array('AssessmentScore.score')));
$json = array();
$assessment_data = array();
//debug($scores);
$i = 0;
foreach ($scores as $score) {
$assessment_data[$i] = array("score" => $score['AssessmentScore']['score']);
$i+=1;
}
header('Content-type: application/json');
$json['success'] = $assessment_data;
$android = json_encode($json);
} else {
$json['error'] = "Sorry, no score is available for this coupon code!";
$android = json_encode($json);
}
echo $android;
code smell, non-cakephp standards
First of all, as mentioned in comments by others, you're not using the CakePHP request/response objects. Because of this, you're overly complicating things. See the documentation here;
http://book.cakephp.org/2.0/en/controllers/request-response.html
http://book.cakephp.org/2.0/en/controllers/request-response.html#dealing-with-content-types
And
http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
The $scores loop to reformat the query results is probably redundant if you replace the find('all') with find('list'), using 'score' as display field. See the documentation here http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list
bugs
There also seems to be some bugs in your code;
the content-type header is only sent if $_POST["myHttpData"] is present.
you're only checking if $_POST["myHttpData"] is present, not if it actually contains any data (empty)
you're not checking if the various queries return a result. This will cause errors in your code if a query did not return anything! For example, you assume that $couponId[0]['Code']['id'] is present (but it won't be if the coupon-code was not found)
possible answer
Apart from these issues, the most probable cause for your problem is that you did not disable 'autoRender'. Therefore CakePHP will also render the view after you've output your JSON, causing a malformed JSON response.
public function AndroidApp() {
$this->autoRender = false;
// rest of your code here
}

Categories