I wanted to made a telegram bot so I started coding and this is what I have so far:
<?php
$string = json_decode(file_get_contents('php://input'));
function objectToArray( $object )
{
if($text == 'Hi')
$text_reply = 'Hi';
if($text == 'What is you'r name?)
$text_reply = 'testbot';
if($text == 'How are you ?')
$text_reply = 'Fine,Thanks';
}
$token = '';
$url = 'https://api.telegram.org/bot'.$token.'/sendMessage?chat_id='.$user_id;
$url .= '&text=' .$text_reply;
$res = file_get_contents($url);
?>
I didn't try it before but it's very simple and I think it will work.
How can I reply a photo from a URL ( someone ask it before but i want it in php) ?
How can I count users or save their ID in a database ? ( ex : when a user send /statics command if id=x reply members number ( when anyone send /start +1 to members number . else reply x )
Related
So, I have this code, which is from a plug-in that I want to create:
<?php
declare(strict_types = 1);
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use Ubnt\UcrmPluginSdk\Service\UcrmSecurity;
use Ubnt\UcrmPluginSdk\Security\PermissionNames;
chdir(__DIR__);
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/main.php';
$fullAddress = isset($_GET['fullAddress']) ? $_GET['fullAddress'] : '';
$firstName = isset($_GET['firstName']) ? $_GET['firstName'] : '';
$lastName = isset($_GET['lastName']) ? $_GET['lastName'] : '';
// GET collection of clients
$clients = UCRMAPIAccess::doRequest('clients') ?: [];
//echo sprintf('Found %d clients.', count($clients)) . PHP_EOL;
// GET the client data that access the 'Contract' page
foreach($clients as $client) {
$response = UCRMAPIAccess::doRequest(
sprintf('clients/%d', $client['id']),
'GET',
[
'fullAddress' => $fullAddress,
'firstName' => $firstName,
'lastName' => $lastName,
]
);
if($response !== null) {
echo sprintf('The following details are for client number: <b>%d</b>', $client['id']);
echo '<ul>';
echo sprintf('<li>%d</li>', $client['id']);
echo sprintf('<li>%s</li>', $client['fullAddress']);
echo sprintf('<li>%s</li>', $client['firstName'] . ' ' . $client['lastName']);
echo '</ul>';
} else {
echo sprintf('There was an error retrieving data from client: %d.', $client['id']) . PHP_EOL;
}
}
echo 'Done.' . PHP_EOL;
For now, if I run this code and I click on the plug-in's page I get this:
What I am trying to is: I want to recieve only the client's information that access the page.
So, I am logged as a client (each client have access to that page named Contract) and when I click on Contract page I want to get my client information, not of all clients.
I've tried to modify :
$clients = UCRMAPIAccess::doRequest('clients') ?: []; > UCRMAPIAccess::doRequest(sprintf('clients/%d', $client['id']) and remove the foreach, but then I got an error that $client is not defined.
Since the $clients variable is an array that contains a list of all the clients that have accessed that page, as you're getting the collection here:
$clients = UCRMAPIAccess::doRequest('clients') ?: [];
And I believe you're trying to get the one client that just accessed the page, since you said:
"when I click on Contract page I want to get my client information, not of all clients"
Then I believe you can filter the $clients array for a single client that matches an id, ONLY if you know the id of the client you're looking for.
For example:
$clients = UCRMAPIAccess::doRequest('clients') ?: [];
$you = (object) array('firstName' => 'foo', 'lastName' => 'bar', 'id' => 1);
$meInClients = array_filter($clients, function($k) {
// filter by key
}, ARRAY_FILTER_USE_KEY)
$clients[meInClients]
But in this case it seems your program doesn't know what user to look for, so a filter or search might not work here. What you want to do is get the last user who JUST visited that page, naturally that user would be the last in the array.
So:
$clients = UCRMAPIAccess::doRequest('clients') ?: [];
$whoJustVisitedPage = $clients[count($clients) - 1]
So this might work.
UPDATE:
When you access the page as John Doe and go to that page, ( the $clientsWhoVisitedPage array now becomes $clientsWhoVisitedPage + YOU (currently authenticated user a.k.a the last person who viewed the page) What you can do in this case is first to filter the $client array so it doesn't contain the currently authenticated user. Then get the last user in the new array.
Like so:
$me = $security->getUser();
$clientsExceptMe = array_filter($clients, function($client, $x) {
return $client->id != $me->id;
}, ARRAY_FILTER_USE_BOTH));
$lastPageVisitor = $clientsExceptMe[count($clientsExceptMe) - 1]
lastPageVisitor should now give you the last person that visited that page that isn't the currently authenticated user.
I don't know the code of UCRMAPIAccess::doRequest, so I can not help you with this aproach although is the rigth one. (Search Doc about this Class/Method)
As a really shit solution, you can do something like this ...
$fullAddress = isset($_GET['fullAddress']) ? $_GET['fullAddress'] : '';
$firstName = isset($_GET['firstName']) ? $_GET['firstName'] : '';
$lastName = isset($_GET['lastName']) ? $_GET['lastName'] : '';
// GET collection of clients
$clients = UCRMAPIAccess::doRequest('clients') ?: [];
//echo sprintf('Found %d clients.', count($clients)) . PHP_EOL;
// GET the client data that access the 'Contract' page
foreach($clients as $client) {
$response = UCRMAPIAccess::doRequest(
sprintf('clients/%d', $client['id']),
'GET',
[
'fullAddress' => $fullAddress,
'firstName' => $firstName,
'lastName' => $lastName,
]
);
if($response !== null
&& $firstName == $client['firstName']
&& $lastName == $client['lastName']
&& $fullAddress == $client['fullAddress']
) {
echo sprintf('The following details are for client number: <b>%d</b>', $client['id']);
echo '<ul>';
echo sprintf('<li>%d</li>', $client['id']);
echo sprintf('<li>%s</li>', $client['fullAddress']);
echo sprintf('<li>%s</li>', $client['firstName'] . ' ' . $client['lastName']);
echo '</ul>';
}
}
echo 'Done.' . PHP_EOL;
Is there a way to check the number likes and comments on my page album? i have make request with this code:
$fields="id,name,description,link,cover_photo,count,likes.limit(0).summary(1),comments.limit(0).summary(1)";
$fb_page_id = "my page id";
$access_token="my access token";
$json_link = "https://graph.facebook.com/v2.7/{$fb_page_id}/albums?fields={$fields}&access_token={$access_token}";
$json = file_get_contents($json_link);
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
for($x=0; $x<$album_count; $x++){
$id = isset($obj['data'][$x]['id']) ? $obj['data'][$x]['id'] : "";
$name = isset($obj['data'][$x]['name']) ? $obj['data'][$x]['name'] : "";
$url_name=urlencode($name);
$description = isset($obj['data'][$x]['description']) ? $obj['data'][$x]['description'] : "";
$link = isset($obj['data'][$x]['link']) ? $obj['data'][$x]['link'] : "";
$cover_photo = isset($obj['data'][$x]['cover_photo']['id']) ? $obj['data'][$x]['cover_photo']['id'] : "";
$count = isset($obj['data'][$x]['count']) ? $obj['data'][$x]['count'] : "";
$likes = count($obj['data'][$x]['likes']) ? $obj['data'][$x]['likes'] : "";
$comments = count($obj['data'][$x]['comments']) ? $obj['data'][$x]['comments'] : "";
But i cant get the data how many likes and comment on my specific album page facebook.
Please does anybody know how to get Facebook album like and comment counts? Many thanks in advance!
I've created a bot with #botfather and it's all okay . Now i want to set command from my host to telegram . i created a Bot.php in my root directory .
Bot.php
$string = json_decode(file_get_contents('php://input'));
function objectToArray( $object )
{
if( !is_object( $object ) && !is_array( $object ) )
{
return $object;
}
if( is_object( $object ) )
{
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
$result = objectToArray($string);
$user_id = $result['message']['from']['id'];
$text = $result['message']['text'];
if($text == 'Hi')
$text_reply = 'Hi';
if($text == 'Your name')
$text_reply = 'jJoe';
$token = '';
$text_reply = 'Got you Buddy.';
$url = 'https://api.telegram.org/bot'.tokenNumber.'/sendMessage?chat_id='.$user_id;
$url .= '&text=' .$text_reply;
$res = file_get_contents($url);
Now when i browse this :https://api.telegram.org/bot112186325:tokenNumber/setWebhook?url=https://partamsms.ir/bot.php
I get this : {"ok":true,"result":true,"description":"Webhook was set"}
But i can't run these commands in my telegram account .
How can i Run commands from my server ?
Thanks a million
According to your comment, you want something that will respond differently based on the message the user typed. So using your example code, you can change it to be something like this:
// NOTE: you can pass 'true' as the second argument to decode as array
$result= json_decode(file_get_contents('php://input'), true);
error_log(print_r($result, 1), 3, '/path/to/logfile.log');
$user_id = $result['message']['from']['id'];
$text = $result['message']['text'];
// TODO: use something like strpos() or strcmp() for more flexibility
switch (true)
{
case $text == '/hi':
$text_reply = 'Hello';
break;
case $text == '/yourname':
// TODO: use the getMe API call to get the bot information
$text_reply = 'jJoe';
break;
default:
$text_reply = 'not sure what you want?';
break;
}
$token = '';
$url = 'https://api.telegram.org/bot'.tokenNumber.'/sendMessage?chat_id='.$user_id;
$url .= '&text=' .$text_reply;
$res = file_get_contents($url);
So, this is pretty much a slight refactor of what you already had...if the issue is that your Bot.php script is not triggering, it is possibly because the page is not public. The webhook you specify to Telegram must be a publicly accessible URL. I tried to hit https://partamsms.ir/bot.php and I can't get to it.
An alternative is to use the getUpdates method instead and to cron the script to run every 5 seconds or so.
Are there any APIs that can extract moods from a string (for use in PHP but can be implemented in any language)?
If one doesn't exist, how would I go about building a classifier, presumably something related to machine learning, where I extract words with known positive/negativity.
I would suggest AlchemyAPI. They have pretty simple APIs ( which shouldn't be difficult to use. For your specific case, look into here
Using the above suggestion of AlchemyapI, here is a really simple system based on Facebook statuses'
$id = CURRENT USER ID;
$message = array(); //the users posts with scores
$status = $fb->fql("SELECT status_id, message FROM status WHERE uid=$id LIMIT 10");
foreach($status as $stat) {
$message = file_get_contents("http://access.alchemyapi.com/calls/text/TextGetTextSentiment"
."?outputMode=json&apikey=MYAPIKEY"
."&text=".urlencode($stat['message']));
$data = json_decode($message); //get reply
$messages[] = array("status"=>$stat['message'], "score"=>($data->docSentiment->type!="neutral") ? $data->docSentiment->score : 0); //save reply
}
$user = $fb->api("/".$id); //query the user
$content .= "<h3>".$user['name']."</h3>";
$total = 0;
$count = 0;
foreach($messages as $message) {
$total += $message['score'];
if($message['score']!=0) $count++;
}
$content .= 'Has an average rating of '.$total/$count.' <meter min="-1" max="1" value="'.$total/$count.'"></meter><br /><br />';
foreach($messages as $message) {
$content .= '<b>'.$message['status'].'</b> '.$message['score'].'</br>'
.'<meter ' //class="'.($message['score'] == 0 ? "yellow" : $message['score'] < 0 ? "red" : "green").'" '
.'value="'.$message['score'].'" min="-0.5" max="0.5" optimum="0">'.$message['score'].' out of -1 to 1</meter><br /><br />';
}
I have a problem with a facebook app. I want to know if the user likes a page to show one content or another. The problem is that some users click on like button but the app dont read it from facebook graph API. Here is the code I'm using to check if a user likes the page:
$appID = '171296629176';
$resp = file_get_contents("https://graph.facebook.com/".$user."/likes?access_token=".$facebook->getAccessToken()."&limit=9999");
$data = json_decode($resp,true);
$liked = 0;
$likes_array = $data['data'];
$likes_next = '';
if(($data != null) && (array_key_exists('paging',$data)) && (array_key_exists('next',$data['paging']))){
$likes_next = $data['paging']['next'];
}
foreach($likes_array as $like)
{
if($appID == $like['id']){
$liked = 1;
}
}
while(strlen($likes_next) > 0){
$resp = file_get_contents($likes_next);
$data = json_decode($resp,true);
$likes_array = $data['data'];
$likes_next = '';
if(($data != null) && (array_key_exists('paging',$data)) && (array_key_exists('next',$data['paging']))){
$likes_next = $data['paging']['next'];
}
foreach($likes_array as $like)
{
if($appID == $like['id']){
$liked = 1;
}
}
}
In some cases it isn't working. I don't know if facebook API returns an empty list of likes or if it returns an incomplete list. With my account and others it works ok and I can't contact the users that are experiencing the issue to test the app.
Thanks in advance.
Alfonso.