send Message to a user by Username in telegram bot - php

I used php-telegram-bot/core to create a shopping bot in telegram.
What I want to do is when a User make an order, bot send a notification that a new Order is come to admin of Channel.
Suppose admin channel username is like #admin_username and stored in a global variable(means that may be change in a period of time). for that I wrote this :
static public function showOrderToConfirm ($order)
{
if ($order) {
Request::sendMessage([
'chat_id' => '#admin_username',
'text' => 'New Order registered',
'parse_mode' => 'HTML'
]);
}
}
But this does not work and does not anything.

Telegram bot API does not support sending messages using username because it's not a stable item and can be changed by the user. On the other hand, bots can only send messages to user that have sent at least one message to the bot before.
You know that when a user sends a message to a bot (for example the users taps on the start button) the bot can get his/her username and ChatID (As you know ChatID is different from username; ChatID is a long number) so I think the best way that you can fix this issue is storing the chat IDs and related usernames in a database and send the message to that chatID of your favorite username.
By the way, try searching online to see whether there is an API which supports sending messages to usernames or not. But as I know it's not possible.

This example works very well:
<?php
$token = 'YOUR_TOCKEN_HERE';
$website = 'https://api.telegram.org/bot' . $token;
$input = file_get_contents('php://input');
$update = json_decode($input, true);
$chatId = $update['message']['chat']['id'];
$message = $update['message']['text'];
switch ($message) {
case '/start':
$response = 'now bot is started';
sendMessage($chatId, $response);
break;
case '/info':
$response = 'Hi, i am #trecno_bot';
sendMessage($chatId, $response);
break;
default:
$response = 'Sorry, i can not understand you';
sendMessage($chatId, $response);
break;
}
function sendMessage($chatId, $response){
$url = $GLOBALS['website'] . '/sendMessage?chat_id=' . $chatId .
'&parse_mode=HTML&text=' . urlencode($response);
file_get_contents($url);
}
?>

Related

How to send custom message before, proxy session send actual message

When Customer replies to proxy service reserved number then proxy hit an OutOfSessionCallbackUrl(if a session is not active).
That URL will come to my code below.
public function response()
{
$to = $_POST['To'];
$from = $_POST['From'];
$from = substr($from, 2);
$body = $_POST['Body'];
$twilio = new Client($this->sid, $this->token);
$response=$this->db->get_where('contact_management as cm
,proxy_service as ps',
array('mobile'=>$from,'company_mobile'=>$to,'sc.sms_template_id<>'=>0))
->row_array();
$number = trim($response['country_code'].$response['mobile_number']);
//Here I'm sending a response
header("content-type:application/json");
?>
{
"uniqueName": "<?php echo rand();?>",
"ttl":"64800",
"mode": "voice-and-message",
"participantIdentifier":"<?php echo $number;?>"
}
<?php
}
This will create a session between SMS sender and returned number(company) and send the message of the sender to the company. I want to send a custom message before Twilio proxy send actual message to the company.
Thanks.
Twilio developer evangelist here.
Currently you are using the out of session callback in order to create a session, but you want to send a message before you forward on the incoming message.
To do this, you won't be able to respond with the JSON to create a session. Instead, you should create the session manually using the session API. Once you have created a session you can then send your initial message by creating an interaction on the participant you want to send the message to. You can then follow up by using the same API to forward the original message. And finally you still need to respond to the webhook. Since you handled all the message sending manually, you can return an empty TwiML <Response/> to signify that you need Twilio to take no further part.
Let me know if that helps at all.
Here Are the complete Description.
I have add Twilio number as reserved in proxy service and set the proxy service OutOfSessionCallbackUrl.When this URL reach my code then the magic happens,
public function response()
{
$to = $_POST['To'];
$from = $_POST['From'];
$twilio = new Client($this->sid, $this->token);
$response=$this->db->get_where('contact_management ,proxy_service,
array('mobile'=>$from,'company_mobile'=>$to))->row_array();
$service_sid=$response['service_sid'];
$session = $twilio->proxy->v1->services($service_sid)->sessions
->create(array("uniqueName" => rand(),"ttl"=>"64800"));
$session_sid = $session->sid;
$participant1 = $twilio->proxy->v1->services($service_sid)
->sessions($session_sid)->participants->create($_POST['From'], // identifier
array("friendlyName" => $response['f_name'],"proxyIdentifier"=>$to));
$from_id = $participant1->proxyIdentifier;
$participant2 = $twilio->proxy->v1->services($service_sid)
->sessions($session_sid)->participants
->create($response['country_code'].$response['mobile_number'], // identifier
array("friendlyName" => $response['first_name']));
$to_id = $participant2->proxyIdentifier;
$to_sid = $participant2->sid;
$body = $response['campaign_name']."\n";
$body .= $_POST['Body'];
$message_interaction = $twilio->proxy->v1->services($service_sid)
->sessions($session_sid)
->participants($to_sid)
->messageInteractions
->create(array("body" => $body));
header("content-type:text/xml");
?>
<Response />
<?php
}

Activecollab Self Hosted account API Authentication invalid response

I am using this API integration https://github.com/activecollab/activecollab-feather-sdk
I using this below code to get token:
$authenticator = new \ActiveCollab\SDK\Authenticator\SelfHosted('<COMPANY NAME>', 'My Application', '<EMAIL>', '<PASSWORD>', 'http://criticalproject.com.mx/projects');
$token = $authenticator->issueToken();
// Did we get what we asked for?
if ($token instanceof \ActiveCollab\SDK\TokenInterface) {
print $token->getUrl() . "\n";
print $token->getToken() . "\n";
} else {
print "Invalid response\n";
die();
}
But I am getting
"invalid response".
Please check attachment for the error screenshot and suggest me
Below is the screen shot.
Note: i used dummy company name , application name. But email and password were correct. will that be an issue ?
If it is then how can i get the company name and application name, please suggest

Invalid Registration error in GCM

I am getting following error I am trying to integrate Google Cloud Messaging in PHP to Android, Any solution
{"multicast_id":5864514048533725299,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration" }]}
PHP CODE
<?php
if (isset($_GET["regId"]) && isset($_GET["receiver_id"]) && isset($_GET["sender_id"])) {
$regId = $_GET["regId"];
$receiver_id = $_GET["receiver_id"];
$sender_id = $_GET["sender_id"];
include_once './db_functions.php';
include_once './GCM.php';
$db = new DB_Functions();
$gcm = new GCM();
//echo $sender_id. $receiver_id; exit;
$res = $db->storeUser($sender_id, $receiver_id);
$registatoin_ids = array($regId);
$message = array("message" => 'You have friend request');
$result = $gcm->send_notification($registatoin_ids, $sender_id, $receiver_id, $message);
echo $result;
}
?>
Check your device id is updated?
check whether API_key you have entered in web api is available at console.google.com?
check whether API_key belongs to the same project number you have used to generate device token?
Invalid Registration ID Check the formatting of the registration ID
that you pass to the server. Make sure it matches the registration ID
the phone receives in the com.google.android.c2dm.intent.REGISTRATION
intent and that you're not truncating it or adding additional
characters. Happens when error code is InvalidRegistration. Source
So basically you are making an error in sending the DeviceID received by the phone to the server.

Laravel webapp login from iOS with Facebook SDK

i have a webapp working with Laravel.
i have some users registered in my webapp.
users who dont want to create a account can use Facebook/Google+ login.
to make Facebook/Google+ connection, i used a oAuth2 connexion with :
oauth-4-laravel
on the iOS application, users can login using username and password but they can login too with Facebook/Google+ using FB/G+ SDK.
my questions is, how to login on my webapp users from iOS who are connected by Facebook/Google+.
artdarek/oauth-4-laravel require a "code" given by the social network, and i dont know how to get it on iOS.
here the code for users who want to connect to the webapp by web browser :
public function loginWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
// $message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
//echo $message. "<br/>";
//Var_dump
//display whole array().
// dd($result);
if (User::where('fb_id','=', $result['id'])->count() == 0) {
$user = new User;
$user->firstname = $result['first_name'];
$user->lastname = $result['last_name'];
$user->username = $result['email'];
$user->email = $result['email'];
$user->fb_id = $result['id'];
$user->yearofbirth = substr($result['birthday'],6,9);
$user->fk_role=3;
if ($result['gender'] == 'male') {
$user->sex = 1;
}
else{
$user->sex = 0;
}
$user->save();
}
else{
$user = User::where('fb_id','=', $result['id'])->first();
}
Auth::login($user);
Userslog::log('desktop_facebook_login');
return Redirect::to('/')->with('message', 'Logged in with Facebook');
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
}
i finally find a solution in the issues of oauth-4-laravel on github,
i just have to use iOS AccessToken and connect the user to the webapp using this token.
here the code laravel code to use the Token ;)
use OAuth\OAuth2\Token\StdOAuth2Token;
$token_interface = new StdOAuth2Token(Input::get( 'token' ));
$network = OAuth::consumer( 'Facebook' );
$network->getStorage()->storeAccessToken('Facebook', $token_interface);
$result = json_decode( $network->request( '/me' ), true );
$fb_id = $result['id'];
To Resume,
the best way is ; to login with Facebook/Google+ on iOS,
when login finish with success, get the AccessToken and send to the webapp.And then the webapp use you token to login again the user to Facebook/Google+ and finally , the user is verified and you can login it to laravel webapp.
have a nice day.
I'm quite in the same situation here.
With the solution you provide, how are you preventing other applications to send their own AccessToken and access your Laravel application?
I assume you send the token via a POST request from you iOS app to a certain endpoint of your Laravel app, therefore any developper knowing this endpoint could pretend to be logged on your mobile application, no?

Trouble getting output from API

I'm currently building a site that will offer services that customers can pay for in Dogecoin. I am using DogeAPI and these example checkout scripts to try and build my checkout pages.
The problem is I can't get the address ($new_address) to echo to the page. When I run the script all that shows up is "Please pay 1000 DOGE to to receive your item. It may take up to 10 minutes to confirm your payment." When I log into my dashboard on DogeAPI, it doesn't show that any addresses were created.
I have a feeling that I need some sort of code that will wait until file_get_ contents() is finished and then start the JSON decoding. My code is below.
NOTE: I do have the API key in my code, I just obviously removed it before posting the code here.
//set to your API_KEY
$api_key = 'MY API HERE';
//set this to your users id
//must be alphanumeric only
$user_id = 'test123';
//set this to the amount the item costs
$amount_doge = '1000';
//send a request to the API to make a new payment address
//put info about the request in
$response = file_get_contents("https://www.dogeapi.com/wow/?api_key=$api_key&a=get_new_address&address_label=$user_id");
if($response !== 'Bad Query' && $response !== '') {
$new_address = json_decode($response);
//insert the new pending payment
mysql_query("INSERT INTO `api_payments`
(`payment_label`,`payment_address`,`paid`,`amount`)
VALUES ('$user_id', '$new_address', '0', '$amount_doge')");
//give them the address or echo a widget here
//for this example we will just echo an address
echo "Please pay $amount_doge DOGE to $response to receive your item. It may take up to 10 minutes to confirm your payment.";
} else {
echo 'There was a problem processing your order.';
}

Categories