Skip to content

Instantly share code, notes, and snippets.

@Rhincodon
Created October 6, 2015 18:14
Show Gist options
  • Save Rhincodon/853cf6c1045ecfbff642 to your computer and use it in GitHub Desktop.
Save Rhincodon/853cf6c1045ecfbff642 to your computer and use it in GitHub Desktop.
<?php

namespace App\Console\Commands;

use App\Author;
use App\Message;
use GuzzleHttp\Client;
use Illuminate\Console\Command;

class GetMessages extends Command
{
    /**
     * @var string
     */
    protected $token = "TOKEN";
    /**
     * @var string
     */
    protected $chatId = "52f9b90e5e986b0712ef6b9d";
    /**
     * @var string
     */
    protected $firstMessageId = "52f9b93e74e32f4a3c0000ec";
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'gitter:room-messages';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Get gitter messages.';

    /**
     * @var
     */
    protected $messages;

    /**
     * @var
     */
    protected $bar;

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param Client $client
     */
    public function handle(Client $client)
    {
        $this->firstMessageId = Message::orderBy('id', 'DESC')->first()->gitter_id;
        $this->messages = $this->getMessages($client);

        while($this->messages->count() > 0) {
            $bar = $this->output->createProgressBar($this->messages->count());

            $this->messages->each(function($message) use ($client, $bar) {
                $author = Author::firstOrCreate([
                    "gitter_id" => $message->fromUser->id,
                ]);

                $author->update([
                    "username" => $message->fromUser->username,
                    "avatar" => $message->fromUser->avatarUrlSmall
                ]);

                $author->messages()->save(new Message([
                    "gitter_id" => $message->id,
                    "text" => $message->text,
                    "sent" => $message->sent,
                    "readers" => $message->readBy
                ]));

                $bar->advance();
            });

            $bar->finish();
            $this->firstMessageId = $this->messages->last()->id;
            $this->messages = null;
            $this->messages = $this->getMessages($client);
        }
    }

    /**
     * @param Client $client
     * @return \Illuminate\Support\Collection
     */
    private function getMessages(Client $client)
    {
        $response = $client->get("https://api.gitter.im/v1/rooms/{$this->chatId}/chatMessages?access_token={$this->token}&limit=50000&afterId={$this->firstMessageId}");

        return collect(json_decode($response->getBody()->getContents()));
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment