Giter Club home page Giter Club logo

stream-chat-php's Introduction

Official PHP SDK for Stream Chat

build Latest Stable Version

Official PHP API client for Stream Chat, a service for building chat applications.
Explore the docs ยป

Report Bug ยท Request Feature

๐Ÿ“ About Stream

You can sign up for a Stream account at our Get Started page.

You can use this library to access chat API endpoints server-side.

For the client-side integrations (web and mobile) have a look at the JavaScript, iOS and Android SDK libraries (docs).

โš™๏ธ Installation

$ composer require get-stream/stream-chat

โœจ Getting started

require_once "./vendor/autoload.php";

Instantiate a new client, find your API keys in the dashboard.

$client = new GetStream\StreamChat\Client("<api-key>", "<api-secret>");

Generate a token for client-side usage

$token = $client->createToken("bob-1");

// with an expiration time
$expiration = (new DateTime())->getTimestamp() + 3600;
$token = $client->createToken("bob-1", $expiration);

Update / Create users

$bob = [
    'id' => 'bob-1',
    'role' => 'admin',
    'name' => 'Robert Tables',
];

$bob = $client->upsertUser($bob);

// Batch update is also supported
$jane = ['id' => 'jane', 'role' => 'admin'];
$june = ['id' => 'june', 'role' => 'user'];
$tom = ['id' => 'tom', 'role' => 'guest'];
$users = $client->upsertUsers([$jane, $june, $tom]);

Channel types

$channelConf = [
    'name' => 'livechat',
    'automod' => 'disabled',
    'commands' => ['ban'],
    'mutes' => true
];

$channelType = $client->createChannelType($channelConf);

$allChannelTypes =  $client->listChannelTypes();

Channels and messages

$channel = $client->Channel("messaging", "bob-and-jane");
$state = $channel->create("bob-1", ['bob-1', 'jane']);
$channel->addMembers(['mike', 'joe']);

Messaging

$msg_bob = $channel->sendMessage(["text" => "Hi June!"], 'bob-1');

// Reply to a message
$reply_bob = $channel->sendMessage(["text" => "Long time no see!"], 'bob-1', $msg_bob['message']['id']);

Reactions

$channel->sendReaction($reply_bob['message']['id'], ['type' => 'like'], 'june');

Moderation

$channel->addModerators(['june']);
$channel->demoteModerators(['june']);

$channel->banUser('june', ["reason" => "Being a big jerk", "timeout" => 5, "user_id" => 'bob-1']);
$channel->unbanUser('june', ["user_id" => 'bob-1']);

Devices

$device_id = "iOS_Device_Token_123";
$client->addDevice($device_id, "apn", "june");
$devices = $client->getDevices('june');

$client->deleteDevice($device_id, 'june');

๐Ÿ™‹โ€โ™€๏ธ Frequently asked questions

  • Q: What date formats does the backend accept?
  • A: We accept RFC3339 format. So you either use raw strings as date or you implement a serializer for your DateTime object.
class MyDateTime extends \DateTime implements \JsonSerializable
{
    public function jsonSerialize()
    {
        // Note: this returns ISO8601
        // but it's compatible with 3339
       return $this->format("c");
    }
}

$createdAt = new MyDateTime();

$client->search( 
	['type' => "messaging"], 
	['created_at' => ['$lte' => $createdAt]], 
	['limit' => 10]
);

โœ๏ธ Contributing

We welcome code changes that improve this library or fix a problem, please make sure to follow all best practices and add tests if applicable before submitting a Pull Request on Github. We are very happy to merge your code in the official repository. Make sure to sign our Contributor License Agreement (CLA) first. See our license file for more details.

Head over to CONTRIBUTING.md for some development tips.

๐Ÿง‘โ€๐Ÿ’ป We are hiring!

We've recently closed a $38 million Series B funding round and we keep actively growing. Our APIs are used by more than a billion end-users, and you'll have a chance to make a huge impact on the product within a team of the strongest engineers all over the world.

Check out our current openings and apply via Stream's website.

stream-chat-php's People

Contributors

bdandy avatar bogdan-d avatar carldemic avatar ferhatelmas avatar github-actions[bot] avatar gumuz avatar jimmypettersson85 avatar jmnorman avatar marco-ulge avatar miagilepner avatar muzucode avatar nikola-jovanovic-php avatar peterdeme avatar prondubuisi avatar pterk avatar ruggi avatar tbarbugli avatar thesyncim avatar totalimmersion avatar vishalnarkhede avatar yaziine avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stream-chat-php's Issues

Don't require created_by in get of getOrCreateChannel

I am facing below error while adding members in channel:

"{"code":4,"message":"GetOrCreateChannel failed with error: "either data.created_by or data.created_by_id must be provided when using server side auth."","StatusCode":400,"duration":"0.00ms"}"

I don't know why this issue is displaying

verifyWebhook seems not to work properly

Hi, as shown here we want to validate the incoming content from the webhook.

This is the code that we are using:

class GetStreamValidator implements SignatureValidator
{
    public function __construct(
        protected GetStreamService $getStreamService,
    ) {}

    public function isValid(Request $request, WebhookConfig $config): bool
    {
        $signature = $request->header('X-Signature');

        $body = json_encode($request->all());

        return $this->getStreamService->verifyWebhook($body, $signature);
    }
}

With our getStreamService->verifyWebhook just passing the parameters through to your method :

class GetStreamService
{
    public function __construct(
        protected Client $client,
    ) {}

    // ...

  public function verifyWebhook(string $requestBody, string $signature): bool
    {
        return $this->client->verifyWebhook($requestBody, $signature);
    }
}

The odd thing is now, that this function always returns false even though we're using the actual request that we receive after we wrote something in our chat. This is the actual request that we receive to the url that we configured here:
actual request

I don't know if this is important but we enabled teams for our application. We're using version 3.3.0 of this package in a laravel application.

We don't know what we're doing wrong. I tripple checked our key and secret, to ensure that they are correct. But the given signature in the request from above seems not to match with the given body.

Can you help us on this one please?

After channel creation. Is there a way to change ownership of channel?

$data = [
'image' => 'https://path/to/image2',
'roles' => ['elon'=> 'moderator', 'gwynne'=> 'moderator']
];

$update = $channel->update($data);

The method here shows how to change the roles of the user server-side. But it's not changing roles And if possible this way do I have any method to change ownership of the channel

Fix typo with Replying message example

I think there is a typo in the reply message example

$msg_bob = $channel->sendMessage(["text" => "Hi June!"], 'bob-1');

// Reply to a message
$reply_bob = $channel->sendMessage(["text" => "Long time no see!"], 'bob-1', $msg_june['message']['id']);

The third parameter for sendMessage should be $msg_bob['message']['id'] not $msg_june['message']['id'], as $msg_june is not declared anywhere within the snippet.

I am making a PR for this

Regex Pattern For Searching Message Substring

Currently, we need to add the full word so we can get the search result for our message. Can't we get messages which contain the substring of the word we are typing?

E.g
$response = $client->search(
$filters,
'Hey',
['limit' => 2, 'offset' => 0]
);

This will list all messages which contain the word hey.

is there a way where we could just enter 'ey' keyword & it will give all messages containing that string?

Setting timeout when initialising the SDK

Currently, when initializing the SDK with a timeout value, you have to do something like:

        // Initialize Stream Chat SDK
        $client = new StreamClient(
            getenv("STREAM_API_KEY"), 
            getenv("STREAM_API_SECRET"),
            '',
            '',
            9 // timeout
        );

This way the apiVersion and location will be overwriten with empty string unless the users sets it when initialzing the SDK.

Would it be better to make it an array instead and the keys are then merged?

something like:

        // Initialize Stream Chat SDK
        $client = new StreamClient(
            getenv("STREAM_API_KEY"), 
            getenv("STREAM_API_SECRET"),
            ['timeout' => 9]
        );

I am facing error while adding members to any already created channel

I am facing below error while i have channel already created, but I am adding new members in it:

"{"code":4,"message":"UpdateChannel failed with error: "could not find user 972214ab-3df2-42c5-9983-f95fe3221379 from add_members"","StatusCode":400,"duration":"0.00ms"}"

Should I call createToken method first or any newly adding user in existing channel???

Permissions for channel type do not work as expected

I have a list of permissions where the user can only read messages from this type of channel

[
	{
		"action": "Allow",
		"name": "admin can do almost anything",
		"resources": [
			"CreateChannel",
			"ReadChannel",
			"UpdateChannelMembers",
			"UpdateChannel",
			"DeleteChannel",
			"CreateMessage",
			"UpdateMessage",
			"DeleteMessage",
			"BanUser",
			"UploadAttachment",
			"DeleteAttachment",
			"UseCommands",
			"AddLinks",
			"EditUser",
			"RunMessageAction",
			"CreateReaction",
			"DeleteReaction",
			"SendCustomEvent",
			"RemoveOwnChannelMembership"
		],
		"roles": [
			"admin"
		],
		"owner": false,
		"priority": 999
	},
	{
		"action": "Deny",
		"name": "No guests or anonymous access",
		"resources": [
			"*"
		],
		"roles": [
			"anonymous",
			"guest"
		],
		"owner": false,
		"priority": 90
	},
	{
		"action": "Allow",
		"name": "Owner permissions",
		"resources": [
			"ReadChannel",
			"UpdateChannelMembers",
			"UpdateChannel",
			"DeleteChannel",
			"UpdateMessage",
			"DeleteMessage",
			"EditUser",
			"DeleteAttachment",
			"DeleteReaction"
		],
		"roles": [],
		"owner": true,
		"priority": 80
	},
	{
		"action": "Allow",
		"name": "Channel member permissions",
		"resources": [
			"ReadChannel",
			"RunMessageAction"
		],
		"roles": [
			"channel_member",
			"channel_moderator"
		],
		"owner": false,
		"priority": 70
	},
	{
		"action": "Allow",
		"name": "Users can read channels",
		"resources": [
			"ReadChannel"
		],
		"roles": [
			"user"
		],
		"owner": false,
		"priority": 60
	},
	{
		"action": "Allow",
		"name": "Moderator only features",
		"resources": [
			"UpdateChannelMembers",
			"UpdateChannel",
			"UpdateMessage",
			"DeleteMessage",
			"BanUser",
			"DeleteAttachment",
			"UploadAttachment"
		],
		"roles": [
			"channel_moderator"
		],
		"owner": false,
		"priority": 50
	},
	{
		"action": "Deny",
		"name": "deny all policy",
		"resources": [
			"*"
		],
		"roles": [
			"*"
		],
		"owner": false,
		"priority": 1
	}
]

but user still can send a message to this channel

{
    "message": {
        "id": "4617-ba99a8a0-5926-4ea9-9710-ee7dc7def8e1",
        "text": "sdsd",
        "html": "<p>sdsd</p>\n",
        "type": "regular",
        "user": {
            "id": "4617",
            "role": "user",
            "created_at": "2020-12-23T13:29:49.643007Z",
            "updated_at": "2020-12-28T14:00:04.951443Z",
            "last_active": "2020-12-28T14:00:04.951443Z",
            "banned": false,
            "online": true,
            "image": "",
            "name": "Borro "
        },
        "attachments": [],
        "latest_reactions": [],
        "own_reactions": [],
        "reaction_counts": null,
        "reaction_scores": {},
        "reply_count": 0,
        "created_at": "2020-12-28T14:11:31.173896Z",
        "updated_at": "2020-12-28T14:11:31.173896Z",
        "shadowed": false,
        "mentioned_users": [],
        "silent": false
    },
    "duration": "14.06ms"
}

gz#8269

Query all channels without any conditions(filters)

$client->queryChannels(); - returns me error

Too few arguments to function GetStream\StreamChat\Client::queryChannels()

$client->queryChannels([]); - returns me error

QueryChannels failed with error: \"expected object for field \"filter_conditions\" but got array

$client->queryChannels([]); - returns me error

"syntax error, unexpected '{'",

Can you please update this method as you did with #27 ?

gz#8192

Unflag message not working.

I'm using the queryMessageFlags call to get a list of flagged messages, but if I then try to use the unFlagMessage call to unflag the message that was just returned it fails with the error 'Unflag failed with error: "message xxxxxxx is not flagged"'

gz#12408

How to get all banned users per channel?

I have a channel that's using livestream default channel type

  1. I have successfully banned a user from the channel X โœ…
  2. Banned user can't send messages SendMessage failed with error: "Sorry, you do not have access to this feature. Your account is currently suspended from chat." โœ…

After a live stream is done I'd like to revisit my bans and unban some users if needed. I've tried using queryChannels API endpoint but:

  1. queryChannels shows only current members, is there a way to get past members?
  2. queryChannel response doesn't reflect the current banned state for a member. Banned user who can't send messages is having banned => false inside channel's members key

What would be the best way to get all banned users for a channel?

Thanks!

Invalid phpdoc type on devices methodes

The type of user_id in : addDevice, deleteDevice & getDevices shouldn't be array but string.

`
/**
* @param string $deviceId
* @param string $pushProvider // apn or firebase
* @param array $userId
* @return mixed
* @throws StreamException
*/
public function addDevice($deviceId, $pushProvider, $userId) {

and

/**
* @param string $deviceId
* @param array $userId
* @return mixed
* @throws StreamException
*/
public function deleteDevice($deviceId, $userId) {

and

/**
* @param array $userId
* @return mixed
* @throws StreamException
*/
public function getDevices($userId) {
`

Get Flagged Message History

I've gone through the docs but haven't seemed to have found it. Is there a way to get a list of the flagged messages and the history of who has reviewed them, outside of the Get Stream dashboard? The flagged attribute doesn't even seem to show up on the messages when watched in a channel.

gz#9988

cannot set skip_push, in sendMessage method payload

cannot set skip_push, in sendMessage method payload

public function sendMessage(array $message, string $userId, string $parentId = null): StreamResponse
{
if ($parentId !== null) {
$message['parent_id'] = $parentId;
}
$payload = [
"message" => Channel::addUser($message, $userId)
];
return $this->client->post($this->getUrl() . "/message", $payload);
}

Refer Payload in REST API https://getstream.io/chat/docs/rest/#messages-sendmessage

Cannot Retrieve All Messages For A Specific Channel

I am having an issue on retrieving all messages for a channel;

"{"code":4,"message":"GetOrCreateChannel failed with error: \"expected object for field \"data\" but got array\"","StatusCode":400,"duration":"0.00ms","more_info":"https://getstream.io/chat/docs/api_errors_response","details":[]}",

On using this;

` private static function updateChannelMessagesFlag(int $spaceId, string $spaceType, string $channelType)
{
$client = new Client(env("STREAM_CHAT_ACCESS_KEY"), env("STREAM_CHAT_SECRET_ACCESS_KEY"));

    $channelId = self::getChannelId($spaceType, $spaceId, $channelType);

    \Log::info('$channelId is '. $channelId);


    $channel = $client->Channel(
        'team',
        $channelId
    );

    $queryResponse = $channel->query([
        'messages' => [
            'limit' => 300,
            'offset' => 0,
            ]
        ]
    );

    \Log::info('$queryResponse is '. json_encode($queryResponse));

`

I am simply following the quide from here; https://getstream.io/chat/docs/php/channel_pagination/?language=php

My library version is 3.3.0.

How to get full response with `getChannel` method?

Hi guys,
return $client->getChannel('one_to_one', $channelId);
returns me only channel ID
{ "success": true, "data": { "id": "28434226" } }

How I can get full response data of this channel(what method)?

By the way,
code -
return $oldChannel->query(['state' => true]);
returns -

    "name": "Exception",
  "message": "{\"code\":4,\"message\":\"GetOrCreateChannel failed with error: \\\"expected object for field \\\"data\\\" but got array\\\"\",\"StatusCode\":400,\"duration\":\"0.00ms\",\"more_info\":\"https://getstream.io/chat/docs/api_errors_response\"}",

gz#8093

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.