Skip to content

Instantly share code, notes, and snippets.

@mpijierro
Last active August 24, 2023 22:47
Show Gist options
  • Save mpijierro/55b363cf4a1e2f2305094db5ec4247c8 to your computer and use it in GitHub Desktop.
Save mpijierro/55b363cf4a1e2f2305094db5ec4247c8 to your computer and use it in GitHub Desktop.
Invite to Channel with MadelieProto (PHP (Laravel))
<?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