Last active
August 24, 2023 22:47
-
-
Save mpijierro/55b363cf4a1e2f2305094db5ec4247c8 to your computer and use it in GitHub Desktop.
Invite to Channel with MadelieProto (PHP (Laravel))
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use Illuminate\Http\Request | |
use danog\MadelineProto\API; | |
class InviteParticipantsController extends Controller | |
{ | |
private $madelineProto; | |
/* | |
We assume that we are with Laravel and we have received an array of participants in a var 'participants' in a POST request. | |
Participants has: phone, first and second name. | |
*/ | |
public function __invoke(Request $request, int $channelId) | |
$settings = []; | |
$this->madelineProto = new API('session.madeline', $settings); | |
$this->madelineProto->async(true); | |
return $this->madelineProto->loop(function () use ($request, $channelId) { | |
try{ | |
//get my own id | |
$me = yield $this->madelineProto->getSelf(); | |
//obtain contacts known or anonymous | |
$inputContacts = []; | |
$participants = $request->get('participants'); | |
foreach ($participants as $participant){ | |
$inputContacts[] = [ | |
'_' => 'inputPhoneContact', | |
'client_id' => $me['id'], | |
'phone' => $participant['phone'], | |
'first_name' => $participant['first_name'], | |
'second_name' => $participant['second_name'] | |
]; | |
} | |
//get contacts | |
$contacts = yield $this->madelineProto->contacts->importContacts(['contacts' => $inputContacts]); | |
//create array with contacts id | |
$keyUsers = []; | |
foreach ($contacts['users'] as $contact) { | |
$keyUsers[] = 'user#'.$contact['id']; | |
} | |
//config channel | |
$channelKey = 'channel#'.$channelId; | |
//...and invite to channel ..¡welcome! | |
$responseInvite = yield $this->madelineProto->channels->inviteToChannel(['channel' => $channelKey, 'users' => $keyUsers]); | |
//this code belongs to an API. The response is coverted automatically to json string. | |
//The answer is automatically converted into json format. We return information from the invitation response and imported users. | |
return array_merge($responseInvite, $contacts['users']); | |
} | |
catch (\Exception $exception){ | |
return response()->json(['message'=> $exception->getMessage()], 500); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment