How To define command from server for telegram BOT - php

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.

Related

Loop the PHP Code Until Statement Is True

I'm using two API keys to receive the data. That's because provider have some daily quota limit. If quota exceeds the daily limit, 403 error is returned from the server.
I used $http_response_header to check the response from the server. But the problem is that when response returned isn't 200, e.g the API key used exceeds the daily limit, the code should execute again so that another API key is picked randomly. Here's the code I'm using:
$keys = array('1stkey','2ndkey');
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
if (strpos($http_response_header[0], "200")) {
echo $data;
}
else{
echo 'No';
}
You can create a function of this code, and just re-run the function when the response is not 200. Something like this maybe?
function getAPIData() {
$keys = array('1stkey','2ndkey');
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
if (strpos($http_response_header[0], "200")) {
echo $data;
}
else {
getAPIData();
}
}
Like #Jaquarh says, you might want to change max_execution_time also. Have a look here and see what works for you.
I've created perfect solution, check this:
$api = array('1st key','2nd key');
$k = array_rand($api);
$api_key_yt = $api[$k];
$total_api=count($api);
for ($loop=0;$loop<=$total_api;$loop++) {
$api_key_yt=$api[$loop];
$request2 = "https://example.com/?data&key=$api_key_yt";
$response = file_get_contents($request2);
$jsonobj = json_decode($response);
if (isset($jsonobj->items)) {break;} else {unset($jsonobj);}
}
print_r($jsonobj);
Please try this
$data = null;
do {
$keys = array('1stkey','2ndkey')
$key_r = array_rand($keys);
$yt_key = $keys[$key_r];
$data = file_get_contents("https://example.com/data&key=$yt_key");
} while ($data == null);

PHP+Apache2+Ubuntu Server: How to get all threads to work in parallel?

I usually work with web hosting companies but I decided to start learning working with servers to expand my knowledge.
I'll better give a real example to explain my question the best:
I have a web application that gathers data from a slow API that returns JSON data of products.
I have a function running every 1AM running a lot of queries on "id"s in my database.
Crontab:
0 1 * * * cd /var/www/html/tools; php index.php aso Cli_kas kas_alert
So this creates a process for the app (please correct me here if I'm wrong) and each process creates threads, and just to be more accurate, they are multi-threads since they do more than one thing: like pulling data from the DB to get the right variables and string them to the API queries, getting the data from the API, organizing it, searching the relevant data, and then inserting new data to the database.
The main PHP functions:
// MAIN: Cron Job Function
public function kas_alert() {
// 0. Deletes all the saved data from the `data` table 1 month+ ago.
// $this->kas_model->clean_old_rows();
// 1. Get 'prod' table
$data['table'] = $this->kas_model->prod_table();
// 2. Go through each row -
foreach ( $data['table'] as $row ) {
// 2.2. Gets all vars from the first query.
$last_row_query = $this->kas_model->get_last_row_of_tag($row->tag_id);
$last_row = $last_row_query[0];
$l_aaa_id = $last_row->prod_aaa_id;
$l_and_id = $last_row->prod_bbb_id;
$l_r_aaa = $last_row->dat_data1_aaa;
$l_r_and = $last_row->dat_data1_bbb;
$l_t_aaa = $last_row->dat_data2_aaa;
$l_t_and = $last_row->dat_data2_bbb;
$tagword = $last_row->tag_word;
$tag_id = $last_row->tag_id;
$country = $last_row->kay_country;
$email = $last_row->u_email;
$prod_name = $last_row->prod_name;
// For the Weekly report:
$prod_id = $last_row->prod_id;
$today = date('Y-m-d');
// 2.3. Run the tagword query again for today on each one of the tags and insert to DB.
if ( ($l_aaa_id != 0) || ( !empty($l_aaa_id) ) ) {
$aaa_data_today = $this->get_data1_aaa_by_id_and_kw($l_aaa_id, $tagword, $country);
} else{
$aaa_data_today['data1'] = 0;
$aaa_data_today['data2'] = 0;
$aaa_data_today['data3'] = 0;
}
if ( ($l_and_id != 0) || ( !empty($l_and_id) ) ) {
$bbb_data_today = $this->get_data1_bbb_by_id_and_kw($l_and_id, $tagword, $country);
} else {
$bbb_data_today['data1'] = 0;
$bbb_data_today['data2'] = 0;
$bbb_data_today['data3'] = 0;
}
// 2.4. Insert the new variables to the "data" table.
if ($this->kas_model->insert_new_tag_to_db( $tag_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $aaa_data_today['data2'], $bbb_data_today['data2'], $aaa_data_today['data3'], $bbb_data_today['data3']) ){
}
// Kas Alert Outputs ($SEND is echoed in it's original function)
echo "<h1>prod Name: $prod_id</h1>";
echo "<h2>tag id: $tag_id</h2>";
var_dump($aaa_data_today);
echo "aaa old: ";
echo $l_r_aaa;
echo "<br> aaa new: ";
echo $aaa_data_today['data1'];
var_dump($bbb_data_today);
echo "<br> bbb old: ";
echo $l_r_and;
echo "<br> bbb new: ";
echo $bbb_data_today['data1'];
// 2.5. Check if there is a need to send something
$send = $this->check_if_send($l_aaa_id, $l_and_id, $l_r_aaa, $aaa_data_today['data1'], $l_r_and, $bbb_data_today['data1']);
// 2.6. If there is a trigger, send the email!
if ($send) {
$this->send_mail($l_aaa_id, $l_and_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $l_r_aaa, $l_r_and, $tagword, $email, $prod_name);
}
}
}
For #Raptor, this is the function that get's the API data:
// aaa tag Query
// Gets aaa prod dataing by ID.
public function get_data_aaa_by_id_and_tg($id, $tag, $query_country){
$tag_for_url = rawurlencode($tag);
$found = FALSE;
$i = 0;
$data = array();
// Create a stream for Json. That's how the code knows what to expect to get.
$context_opts = array(
'http' => array(
'method' => "GET",
'header' => "Accepts: application/json\r\n"
));
$context = stream_context_create($context_opts);
while ($found == FALSE) {
// aaa Query
$json_query_aaa = "https://api.example.com:443/aaa/ajax/research_tag?app_id=$id&term=$tag_for_url&page_index=$i&country=$query_country&auth_token=666";
// Get the Json
$json_query_aaa = file_get_contents($json_query_aaa, false, $context);
// Turn Json to a PHP array
$json_query_aaa = json_decode($json_query_aaa, true);
// Get the data2
$data2 = $json_query_aaa['tag']['data2'];
if (is_null($data2)){ $data2 = 0; }
// Get data3
$data3 = $json_query_aaa['tag']['phone_prod']['data3'];
if (is_null($data3)){ $data3 = 0; }
// Finally, the main prod array.
$json_query_aaa = $json_query_aaa['tag']['phone_prod']['app_list'];
if ( count($json_query_aaa) > 2 ) {
for ( $j=0; $j<count($json_query_aaa); $j++ ) {
if ( $json_query_aaa[$j]['id'] == $id ) {
$found = TRUE;
$data = $json_query_aaa[$j]['data'] + 1;
break;
}
if ($found == TRUE){
break;
}
}
$i++;
} else {
$data = 0;
break;
}
}
$data['data1'] = $data;
$data['data2'] = $data2;
$data['data3'] = $data3;
return $data;
}
All threads are stacked one after an other, and when one thread is done, only then - the second thread can proceed, ect'.
And in technical view on this, all threads wait in the RAM until the one before them is done working "inside" the CPU. (correct me if I'm wrong again :] )
This doesn't even "tickle" the servers RAM or CPU when looking at it in the process manager (I use "htop"). RAM is at 400M/4.25G and CPU at ONLY 0.7%-1.3%.
Making me feel this isn't the best I can get from my current server, and getting slow results from my web app.
How do I get things done in a way that all threads work in parallel, but not to a point that my app crashes due to lacks of CPU or RAM?

Custom Joomla 3 Button task not executing in my controller

I am trying to upload an external list of "groups" to add to my custom Joomla 3 component. I have created a CSV file and written a few functions that I hope will do it. I have created a custom button to start the task in my "groups" view.
When I push the button I get an SQL error that has absoloutle nothing to do with the functions so I have tried debugging and when the button is pressed its not even getting to my controller task before the sql error. I am so confused as to why.
This is the code I have
view.html.php TestViewGroups
JToolBarHelper::custom('group.uploadsave', '', '', 'Upload and Save', false);
TestControllerGroup
protected function uploadsave() {
$detail_headers = array(
'agm_date',
'preferred_media'
);
$rows = array_map('str_getcsv', file('groupdata.csv'));
$header = array_shift($rows);
foreach ($rows as $row) {
$entry = array_combine($header, $row);
foreach ($entry as $key => $value) {
if(in_array($key, $detail_headers)){
$details[$key]= $value;
unset($entry[$key]);
}
}
$entry['details'] = $details;
$this->saveUploaded($entry);
}
// Redirect to the list screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . '&view=' . $this->view_list
. $this->getRedirectToListAppend(), false
)
);
}
protected function saveUploaded($dataIn = array()) {
$app = JFactory::getApplication();
$lang = JFactory::getLanguage();
$model = $this->getModel();
$table = $model->getTable();
$data = $dataIn;
$checkin = property_exists($table, 'checked_out');
// Determine the name of the primary key for the data.
if (empty($key))
{
$key = $table->getKeyName();
}
// To avoid data collisions the urlVar may be different from the primary key.
if (empty($urlVar))
{
$urlVar = $key;
}
$recordId = $this->input->getInt($urlVar);
// Populate the row id from the session.
$data[$key] = $recordId;
if (!$model->save($validData))
{
// Redirect back to the edit screen.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
}
if ($checkin && $model->checkin($validData[$key]) === false)
{
// Save the data in the session.
$app->setUserState($context . '.data', $validData);
// Check-in failed, so go back to the record and display a notice.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
}
$this->setMessage(
JText::_(
($lang->hasKey($this->text_prefix . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS')
? $this->text_prefix
: 'JLIB_APPLICATION') . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS'
)
);
}
I am not using this as a regular function, its just a once off to upload the data initially.
The SQL error I am getting is like it is trying to load a list of groups?? not anything to do with the save function at all.
The saveUploaded is a similar function to the initial save function.
Thanks :-)
**** Edit *****
I have just followed the task through with debug and its getting to the execute task methotd of JControllerLegacy and because the task is not defined in the task map its defaulting to display, hence the SQL error trying to load a group when it doesn't have an ID. Do I need to now register a task in the task map before it will pick it up?
I am officially an idiot! When I just logged back on to see if anyone had responded I saw that I had declared the function as a protected function!! dir! I just copied and pasted from another function and forgot to change its access. I also made a few other changes and now it works quite well!
public function uploadsave() {
// An array of headers that will need to be entered into a seperate array to allow entry as JSON
$detail_headers = array(
'agm_date',
'preferred_media'
);
$app = JFactory::getApplication();
$lang = JFactory::getLanguage();
$model = $this->getModel();
$path = JPATH_COMPONENT . '/controllers/groupdata.csv';
//Load the file and pass each line into an array.
$rows = array_map('str_getcsv', file($path));
//Take out the first line as it is the headers.
$header = array_shift($rows);
//turn each of the arrays into an entry
foreach ($rows as $row) {
$entry = array_combine($header, $row);
foreach ($entry as $key => $value) {
//separate each of the entries that need to be entered into an array to be stored as JSON
if(in_array($key, $detail_headers)){
$details[$key]= $value;
unset($entry[$key]);
}
}
$entry['details'] = $details;
$recordId = 'id';
// Populate the row id from the session.
$entry[$key] = $recordId;
//Save each one
if (!$model->save($entry))
{
// Redirect back to the edit screen.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
return false;
}
$this->setMessage(
JText::_(
($lang->hasKey($this->text_prefix . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS')
? $this->text_prefix
: 'JLIB_APPLICATION') . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS'
)
);
}
// Redirect to the list screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . '&view=' . $this->view_list
. $this->getRedirectToListAppend(), false
)
);
}

My iMacro script(s) doesnt run inside my PHP script. Why?

I am learning how to run iMacros from my php scripts so that PHP script calls an iMacros browser session and passes any variables that I have (url and macro name for example). The iMacros session then runs the iMacro, after the macro is done running it passes the resulting html page back to the PHP script and closes itself. In an ideal world, anyway.
Here is the iMacros calling script:
<?php
require 'src/iimfx.class.php';
$iim = new imacros();
$vars = array();
$iim->play($vars,'grab_data.iim');
?>
But when i run this script from cmd.exe [command line] on WAMP, I get this:
New imacros session started!
Using Proxy: MY_PROXY_IP:MY_PROXY_PORT
-runner -fx -fxProfile default
--------------------------------------------------------
Setting Value IP => MY_PROXY_IP
Setting Value port => MY_PROXY_PORT
Playing Macro proxy.iim
--------MACRO ERROR!-------------------
ERROR: Browser was not started. iimInit() failed?
--------------------------------------------------------
Playing Macro grab_google.iim
--------MACRO ERROR!-------------------
ERROR: Browser was not started. iimInit() failed?
P.S. MY_PROXY_IP and MY_PROXY_PORT are replaced with actual numbers both in error messages above and iimfx.class.php.
And here is code for the iimfx.class.php :
<?php
class imacros {
function __construct($proxyip = 'MY_PROXY_IP', $proxyport = 'MY_PROXY_PORT', $silent = false, $noexit = false) {
echo "--------------------------------------\nNew imacros session started!\nUsing Proxy: $proxyip:$proxyport\n";
$this->proxyip = $proxyip;
$this->proxyport = $proxyport;
if (empty ( $this->proxyip ))
echo "NO PROXY!!\n";
$this->noexit = $noexit;
$this->fso = new COM ( 'Scripting.FileSystemObject' );
$this->fso = NULL;
$this->iim = new COM ( "imacros" );
$toexec = "-runner -fx -fxProfile default";
if ($silent === true)
$toexec .= " -silent";
if ($noexit === true)
$toexec .= " -noexit";
echo $toexec . "\n";
$this->iim->iimInit ( $toexec );
if (! empty ( $this->proxyip )) {
$dvars ['IP'] = $this->proxyip;
$dvars ['port'] = $this->proxyport;
$this->play ( $dvars, 'proxy.iim' );
}
}
function __destruct() {
if ($this->noexit === false)
$this->iim->iimExit ();
}
function play($immvars = '', $macro) {
echo "--------------------------------------------------------\n";
if (is_array ( $immvars )) {
foreach ( $immvars as $key => $value ) {
echo "Setting Value $key => $value\n";
$this->iim->iimSet ( "-var_" . $key, $value );
}
}
echo "Playing Macro $macro\n";
$s = $this->iim->iimPlay ( $macro );
if($s>0){
echo "Macro successfully played!\n";
}else{
echo "--------MACRO ERROR!-------------------\n ERROR: " . $this->getLastError() . "\n";
}
return $s;
}
// This function retrieves extracts in your iMacros script if you have any.
function getLastExtract($num) {
return $this->iim->iimGetLastExtract ( $num );
}
// Returns the last error :)
function getLastError(){
return $this->iim->iimGetLastError();
}
// Enables/disables images
function setImages($images = 1) { // 1 = on 2 = off
$dvars ['images'] = $images;
$this->play ( $dvars, 'images.iim' );
}
// Enables or disables adblockplus
function enableABP($status = true){
$dvars['status'] = $status;
$this->play ( $dvars, 'abp.iim' );
}
}
?>
Is there something I am missing here?
I have iimRunner.exe running during all of this [started manually before running the script] and I have iMacros Browser V8+.
Also, my grab_data.iim and all other required .iim are in the same place as the php script that is trying to call them and execute them.
Any kind of help and/or steer towards the right direction would be greatly appreciated!!
Thanks in advance.
U must by start the immrunner, before start the script =)
http://wiki.imacros.net/iimRunner

How do I find out how many edits a user has for my MediaWiki extension?

I'm writing an extension that will allow me to add the magic words: CURRENTUSER, CURRENTUSERREALNAME, CURRENTUSERLANGABBR, CURRENTUSERGROUPS, and now I want to add CURRENTUSEREDITCOUNT and CURRENTUSEREDITCOUNTALL.
That section of my code is currently:
function wfGetCustomVariable(&$parser,&$cache,&$index,&$ret) {
switch ($index) {
case MAG_CURRENTUSER:
$parser->disableCache(); # Mark this content as uncacheable
$ret = $GLOBALS['wgUser']->getName();
break;
case MAG_CURRENTUSERREALNAME:
$parser->disableCache(); # Mark this content as uncacheable
$ret = $GLOBALS['wgUser']->getRealName();
break;
case MAG_CURRENTUSERLANGABBR
$parser->disableCache(); # Mark this content as uncacheable
$ret = $GLOBALS['wgLang']->getCode();
break;
case MAG_CURRENTUSERGROUPS
$parser->disableCache(); # Mark this content as uncacheable
$array = $GLOBALS['wgUser']->getEffectiveGroups();
$ret = implode(",", $array);
break;
}
return true;
}
However, I can't seem to find the $GLOBAL for the edit counts. I've done some research based on other extensions that use different edit counts for different reasons and have found:
For CURRENTUSEREDITCOUNT:
function wfContributionseditcount( $uid ) {
if ( $uid != 0 ) {
global $wgOut, $wgLang;
$wgOut->addWikiText( wfMsgExt( 'contributionseditcount', array( 'parsemag' ),
$wgLang->formatNum( User::edits( $uid ) ),
User::whoIs( $uid ) ) );
}
return true;
}
and for CURRENTUSEREDITCOUNTALL:
public function execute( $params ) {
global $wgOut, $wgUser;
$skin = $wgUser->getSkin();
$this->setHeaders();
$this->loadRequest( $params );
$wgOut->addHTML( $this->makeForm() );
if( $this->target ) {
if( User::isIP( $this->target ) ) {
$this->showResults( $this->countEditsReal( 0, $this->target ) );
} else {
$id = User::idFromName( $this->target );
if( $id ) {
$this->showResults( $this->countEditsReal( $id, false ), $id );
} else {
$wgOut->addHTML( '<p>' . wfMsgHtml( 'countedits-nosuchuser', htmlspecialchars( $this->target ) ) . '</p>' );
}
}
}
$this->showTopTen( $wgOut );
return true;
}
I have tried to learn PHP on my own in the past, and have struggled with it. I'm signed up for a PHP class at my local community college, but I do not start until Fall `12. Am I looking in the right place, or is there a simpler place to find the user's edit counts? Maybe as part of /trunk/phase3/includes/User.php someplace? I should mention this needs to run on a wiki running MW 1.17.1, so classUser would not work where-as it is MW 1.18+.
If what you want is to change the definition of edit count, perhaps you should directly change the code where it reduces the user's editcount after a page is deleted.

Categories