add option to choose different chat id for telegram bot - php

I made a simple telegram bot with PHP to copy and send any messages that receives to another group
but how can I give the option to user in the bot to choose different groups to send
for example to group A or B
$msgID = $updates["message"]["message_id"];
file_get_contents($link."/copyMessage?chat_id=GroupA&from_chat_id=999999&message_id=$msgID&disable_notification=true");
file_get_contents($link."/copyMessage?chat_id=GroupB&from_chat_id=999999&message_id=$msgID&disable_notification=true");

I think sending message with buttons it's better way to that.
It'll be like this:
User sends /start command
User sends any message
Bot reply user's message with buttons
User chooses a button
Bot copies message to selected chat
Bot answers user with success or fail
Use this code:
# Configuration that you need to fill
# Bot token obtained from #BotFather
define('BOT_TOKEN', 'Put your bot token here');
# Chat IDs Or Usernames that messages will be copied to
$chats =
[
# Username/ID => 'Chat title'
'#MyOwnGroup' => 'The bot creator group',
'1265170068' => 'My own account'
];
# Function to call any Bot API method
function bot(string $method, array $data = [])
{
$api_url = 'https://api.telegram.org/bot' . BOT_TOKEN . "/$method";
if (count(data) > 0)
{
$api_url .= '?'.http_build_url($data, '', '&');
}
return file_get_contents($api_url);
}
# The update data, Received from Telegram
$update = json_decode(file_get_contents('php://input'));
# Handle if new message received
if (property_exists($update, 'message') && $update->message->text !== '/start')
{
$message = $update->message;
$buttons = ['inline_keyboard' => []];
foreach ($chats as $chat_id => $chat_title)
{
array_push($buttons['inline_keyboard'], [['text' => $chat_title, 'callback_query' => $chat_id]]);
}
# Sending message with buttons to get which group the user wants
bot('sendMessage', [
'chat_id' => $message->chat->id,
'text' => 'Select which group you want to send the message..',
'reply_to_message_id' => $message->message_id,
'reply_markup' => json_encode($buttons)
]);
}
# Handle if one of buttons was pressed
if (property_exists($update, 'callback_query'))
{
$callback_query = $update->callback_query;
# Copy the message
$result = bot('copyMessage', [
'from_chat_id' => $callback_query->message->chat->id,
'message_id' => $callback_query->message->message_id,
'chat_id' => $callback_query->data
]);
if ($result->ok == true)
{
bot('answerCallbackQuery', [
'callback_query_id' => $callback_query->id,
'text' => 'Message was sent successfully!'
]);
}
else
{
bot('answerCallbackQuery', [
'callback_query_id' => $callback_query->id,
'text' => 'Message sending failed!',
'show_alert' => true
]);
}
}

Related

how to use callback data in telegram bot

i'm using this library https://github.com/Eleirbag89/TelegramBotPHP to create telegram bot
i want to get user tweeter username like:#username
how to use callback data and then use callback_data value
ex:
bot: username
user: #alex
bot: password
user: 985468
if($text == '🚀 Submit your Detalis'){
$option = array(
array($telegram->buildInlineKeyBoardButton('✅ Done', $url, $callback_data = 'checkIsMember')) );
$keyb = $telegram->buildInlineKeyBoard($option);
$content = array('chat_id' => $chat_id, 'reply_markup' => $keyb, 'text' => '
Join Our Telegram Channel
<b> Click "✅ Done" to continue </b>
');
$telegram->sendMessage($content);
}
if($text == 'checkIsMember'){
$content = array('chat_id' => $chat_id, 'text' => '
👉 Submit your Twitter username below (Included #)
Ex : #username
');
$telegram->sendMessage($content);
}
Set webhook on file where bot is placed Site must have SSL (https).
https://api.telegram.org/bot(your token)/setWebhook?url=https://example.com/bot_directory/bot.php
Than process data and write bot
$update = json_decode(file_get_contents('php://input'), TRUE);
$botToken = "(your token)";
$botAPI = "https://api.telegram.org/bot" . $botToken;
$msg = $update['message']['text'];
$user_id = $update['message']['from']['id'];
//Simple send button when user send message
$data = http_build_query([
'text' => 'Hi it is my bot',
'chat_id' => $update['message']['from']['id'],
]);
$keyboard = json_encode([
"inline_keyboard" => [
[
[
"text" => "say Hi",
"callback_data" => "say_h"
],
]
],
"resize_keyboard" => true
]);
file_get_contents($botAPI . "/sendMessage?{$data}&reply_markup={$keyboard}");
if (isset($update['callback_query'])) {
if ($update['callback_query']['data'] == 'say_h'){
// your code here when button pressed
}
}

Error SHARED_VIEW_USER_LACKS_PERMISSION on DocuSign\eSign\Model\RecipientViewRequest

My scenario would be this flow in my application: Register > Sign Document > Return to Finish Page.
The user register on my application and he need to sign a document to finish his registration. He is not a DocuSign user. At the moment all my tests are at the Sandbox environment.
The envelope creation works great. If I don't use the client_user_id it sends the email for signing. But I need to use the client_user_id to use the embedded signing and get the URL for next step.
When I try to to get the URL of the envelope, I receive the following error:
errorCode: SHARED_VIEW_USER_LACKS_PERMISSION
message: User lacks shared permission to envelope. Only a user with shared access to the envelope may perform the requested operation.
Here is the code I'm using on my PHP application to try to get the URL of the recent created envelope:
$envelope = $this->docusignlib->create_document_for_signing($user, $file);
$result = $this->docusignlib->get_url_document($user, $envelope['envelope_id'], $return_url);
public function create_document_for_signing($user, $file)
{
# Document
$document = new DocuSign\eSign\Model\Document([
'document_base64' => base64_encode(file_get_contents($file)),
'name' => 'Document name',
'file_extension' => 'pdf',
'document_id' => '1'
]);
# Sign Here Position
$signHere = new DocuSign\eSign\Model\SignHere([
'document_id' => '1', 'page_number' => '2', 'recipient_id' => '1',
'tab_label' => 'Sign here', 'x_position' => '100', 'y_position' => '720'
]);
# The signer object
$signer = new DocuSign\eSign\Model\Signer([
'email' => $user->user_email,
'name' => $user->user_name,
'recipient_id' => "1",
'client_user_id' => $user->user_id,
'tabs' => new DocuSign\eSign\Model\Tabs([
'sign_here_tabs' => [$signHere]
])
]);
# Next, create the top level envelope definition and populate it.
$envelopeDefinition = new DocuSign\eSign\Model\EnvelopeDefinition([
'email_subject' => "Email subject",
'documents' => [$document],
'recipients' => new DocuSign\eSign\Model\Recipients(['signers' => [$signer]]),
'status' => "sent"
]);
$config = new DocuSign\eSign\Configuration();
$config->setHost($this->api);
$config->addDefaultHeader("Authorization", "Bearer " . $this->accessToken);
$apiClient = new DocuSign\eSign\Client\ApiClient($config);
$envelopeApi = new DocuSign\eSign\Api\EnvelopesApi($apiClient);
return $envelopeApi->createEnvelope($this->accountId, $envelopeDefinition);
}
public function get_url_document($user, $envelopeId, $returnUrl)
{
$recipientViewRequest = new DocuSign\eSign\Model\RecipientViewRequest([
'user_name' => $user->user_name,
'email' => $user->user_email,
"recipient_id" => "1",
"client_user_id" => $user->user_id,
"authentication_method" => "email",
"return_url" => $returnUrl
]);
$config = new DocuSign\eSign\Configuration();
$config->setHost($this->api);
$config->addDefaultHeader("Authorization", "Bearer " . $this->accessToken);
$apiClient = new DocuSign\eSign\Client\ApiClient($config);
$envelopeApi = new DocuSign\eSign\Api\EnvelopesApi($apiClient);
return $envelopeApi->createEnvelopeRecipientSharedView($this->accountId, $envelopeId, $recipientViewRequest);
}
I couldn't find ANYTHING related to this error on the documentation and I checked all the permissions and everything seems ok. I'm using the admin user of my demoaccount. Any ideas what I'm doing wrong here?
Thanks!
SHARED_VIEW_USER_LACKS_PERMISSION is about the user and the account. You may want to try a different account and/or a new envelope. I would also ensure that you are making API call to demo.docusign.net URL and not www.docusign.net since you are still in demo/sandbox.
The accessToken should match the account and if you're using the token generator, it's the account that you used when token generator prompted you to log in.

Wepay integration

I'm trying to create a simple checkout page with wepay and my checkout code (taken from the SDK sample) works great for the owner (me) when I'm signed in, but when logged in as a different user who hasn't created the account (under theirs?) it says the account is invalid or does not belong to the user.
So how are new logged in users supposed to pay to the account (mine), in other words make payments?
Here is the code for reference. The account_id doesn't work for new logged in users because they haven't created it.
$wepay = new WePay($_SESSION['wepay_access_token']);
$checkout = $wepay->request('checkout/create', array(
'account_id' => 501999810,
'amount' => 1.00,
'currency'=> 'USD',
'short_description'=> 'Selling 42 Pens',
'type'=> 'goods'
));
Maybe I have something completely off, but that account_id is where I want to receive payments?
Any help would be appreciated!
Once you register the user, you have to create an actual merchant account by calling /account/create.
Once you have the user's access token, you can call /account/create with the user's access token and the relevant info to actually attach an account to the user. The /account/create call will return an account_id. That account_id is the one you use in the /checkout/create call.
So until you create an account via /account/create the user cannot accept payments.
$productData['data']['seller_data']['wepay_access_token']="STAGE_ea6cd2dffa3dfa23bd4817f210936fadada9fa91e906f353e15813c6cf920fb8";
$productData['data']['seller_data'}['wepay_account_id']="287443494";
$wepay = new WePay($productData['data']['seller_data']['wepay_access_token']);
$checkOutData = array(
//"account_id" => 12345678,
"account_id" => $productData['data']['seller_data'}['wepay_account_id'],
"amount" => 500,
"type" => "goods",
"currency" => "USD",
"short_description" => "Purchase made at test site",
"long_description" => "The charges made in this payment are of the order placed in test",
"delivery_type" => "point_of_sale",
"fee" => array(
"app_fee" => 15,
//'fee_payer' => 'payer_from_app'
'fee_payer' => 'payee_from_app'
),
//"auto_release"=>false,
"payment_method" => array(
"type" => "credit_card",
"credit_card" => array(
"id" => 2178689241,
"auto_capture" => false
)
)
);
try {
$checkoutResult = $wepay->request('checkout/create', $checkOutData);
} catch (Exception $e) {
$data['status'] = '0';
$data['message'] = 'We could not complete checkout!';
return $this->SetOutput();
}
You can get seller access token and account id using
$user_id=20;
$access_token="STAGE_ea6cd2dffa3dfa23bd4817f210936fadada9fa91e906f353e15813c6cf920fb8":
$userName="test user";
$description="sell products";
try {
$wepay = new WePay($access_token);
if (empty($userName)) {
try {
$uresponse = $wepay->request('/user');
$userName = $uresponse->user_name;
} catch (WePayException $e) {
$uresponse['status'] = '0';
$uresponse['message'] = $e->getMessage();
return $uresponse;
}
}
$response = $wepay->request('account/create/', array(
'name' => $userName,
'description' => $description,
'reference_id' => '"' . $user_id . '"'
));
} catch (WePayException $e) {
$response['status'] = '0';
$response['message'] = $e->getMessage();
return $response;
}

Telegram API, get the sender's phone number?

I realize it is not possible to use a Bot to receive a sender's phone number.
I do, however, need to implement a bot-like client, that responds to anyone who is messaging it. I am using PHP on apache.
It is not a Bot, as it does not take commands, but rather responds to sent text from anyone who has that phone number. So you add the user as a contact (using a phone number), and then send text to it.
My goal is to realise the sender's phone number as I receive it, I saw on the Telegram API that there's a peer ID, but I can't find how to get the phone number if that's even possible...
try this lib from github https://github.com/irazasyed/telegram-bot-sdk
and code to create 'visit card' button in private chat:
$keyboard = array(
array(
array(
'text'=>"Send your visit card",
'request_contact'=>true
)
)
); //user button under keyboard.
$reply_markup = $telegram->replyKeyboardMarkup([ 'keyboard' => $auth_keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => false ]);
$telegram->sendMessage([ 'chat_id' => $chat_id, 'text' => $reply, 'reply_markup' => $reply_markup ]);
and code to get unic user phone from 'visit card' after user push the button
$user_phone = $result["message"]["contact"]["phone_number"];
if ($user_phone) {
$reply = $user_phone;
$telegram->sendMessage([ 'chat_id' => $chat_id, 'text' => $reply, 'reply_markup' => $reply_markup ]);
}
finally i found how to get the phone number.
I use package https://github.com/irazasyed/telegram-bot-sdk for Laravel 8.
The code below is command to send button and when user press the button, it'll catch the phone number from user after the user click on "share".
PhoneNumberCommand.php
public function handle()
{
$response = $this->getUpdate();
$chat_id = $response->getChat()->getId();
$btn = Keyboard::button([
'text' => 'Varify',
'request_contact' => true,
]);
$keyboard = Keyboard::make([
'keyboard' => [[$btn]],
'resize_keyboard' => true,
'one_time_keyboard' => true
]);
return $this->telegram->sendMessage([
'chat_id' => $chat_id,
'text' => 'Please click on Verify and Share.',
'reply_markup' => $keyboard
]);
}
ControllerWebhook.php
public function commandHandlerWebHook()
{
$updates = Telegram::commandsHandler(true);
$chat_id = $updates->getChat()->getId();
// Catch Phone Number
$user_phone = array_key_exists('contact', $updates['message']) ?
$updates['message']['contact']['phone_number'] : null;
$text = 'Phone number : ' . $user_phone;
if($user_phone) return Telegram::sendMessage(['chat_id' => $chat_id, 'text' => $text]);
return 'ok';
}
It's work for me! hope you can implement too.

Laravel: How to Queue mails to send later

Im trying to use the Mail::queue to send and email, but when I call this function it simple sends the mail, and the response is delayed ... I thought that the point of using Mail::queue was to queue ....
I want the response to came instantly, not having to wait for the email to be sent
for eg
Mail::queue('emails.template', $data, function($message) {
$message->to('somemail#gmail.com');
$message->subject('Notificacion');
});
return Response::json(array('error' => 0, 'message' => 'Ok'));
I want to receive the response without waiting for the mail to be sent.
How can I do that???
What queue driver (app/config/queue.php - 'default' param) are you using? If you're using sync, and haven't set up one of the others, then you're using the synchronous driver, which does exactly what the name says: Runs your queued task as soon as the task is created.
You need to configure an MQ server for Laravel to talk to. You can get a free iron.io account for this, and then you need to configure it, for instance:
'iron' => array(
'driver' => 'iron',
'project' => 'iron-io-project-id',
'token' => 'iron-io-queue-token',
'queue' => 'queue-name',
),
Then when you use Mail::queue() it will push the instruction to iron.io. You'll then have to have another thread listening on the queue - just run php artisan queue:listen and leave it running while messages are pushed to the queue.
/**
* Get all email recipients and include their user details for Mailgun's
* template tags - %recipient.userToken%
*/
private function getRecipients()
{
foreach (User::get() as $user)
{
$this->recipients[$user->email] = [
'id' => $user->id,
'userToken' => $user->user_token,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email
];
}
}
private function sendEmail()
{
$subject = 'Demo Subject';
/**
* Data for the Blade template
*/
$data = [
'foo' => 'bar'
];
// Inline the CSS for the email
$inliner = new InlineEmail('emails.some-email', $data);
$content = $inliner->convert();
// Create Emails table entry for this email. Used for Mailgun webhooks
$email = Email::create(['user_id' => $this->userId, 'subject' => $subject, 'email_id' => str_random()]);
// Prepare the email addresses
$emailAddresses = array_column($this->recipients, 'email');
$this->mailgun->sendMessage('demo.org', [
"from" => 'support#demo.org',
"to" => implode(',', $emailAddresses), // Comma separated list of email addresses
"subject" => $subject,
"html" => $content, // Inlined CSS HTML from Blade
"text" => "Plain text message here",
"recipient-variables" => json_encode($this->recipients), // Required for batch sending, matches to recipient details
"v:messageId" => $email->id, // Custom variable used for webhooks
]);
}

Categories