Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
<?php
declare(strict_types=1);
use App\Enums\SocialAccount\Platform;
use App\Events\TelegramChannelConnected;
use App\Events\TelegramConnectFailed;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\TokenExpiredException;
use App\Jobs\PostHog\TrackSocialAccountConnected;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Social\ConnectionVerifier;
use App\Services\Social\Telegram\TelegramConnectCode;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
beforeEach(function () {
config([
'trypost.platforms.telegram.bot_token' => 'TESTTOKEN',
'trypost.platforms.telegram.bot_username' => 'TryPostBot',
'trypost.platforms.telegram.webhook_secret' => 'shh-secret',
]);
$this->workspace = Workspace::factory()->create();
$this->user = User::factory()->create([
'current_workspace_id' => $this->workspace->id,
'account_id' => $this->workspace->account_id,
]);
$this->workspace->members()->attach($this->user->id, membershipPivot('admin'));
$this->user->refresh();
});
function telegramUpdate(string $code, array $chat = []): array
{
return [
'channel_post' => [
'message_id' => 5,
'chat' => array_merge([
'id' => -1001234567890,
'title' => 'My Channel',
'username' => 'mychannel',
'type' => 'channel',
], $chat),
'text' => "/connect {$code}",
],
];
}
it('issues a signed connect code carrying the workspace', function () {
$response = $this->actingAs($this->user)
->postJson(route('app.social.telegram.connect'))
->assertOk()
->assertJsonStructure(['code', 'nonce', 'bot_username', 'bot_url', 'expires_at']);
expect($response->json('bot_username'))->toBe('TryPostBot')
->and($response->json('bot_url'))->toBe(config('trypost.platforms.telegram.deep_link').'/TryPostBot');
expect(data_get(TelegramConnectCode::decode($response->json('code')), 'workspace_id'))
->toBe($this->workspace->id);
expect($response->json('nonce'))
->toBe(data_get(TelegramConnectCode::decode($response->json('code')), 'nonce'));
});
it('links the channel when the webhook receives a matching /connect', function () {
Http::fake();
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
$account = SocialAccount::where('workspace_id', $this->workspace->id)
->where('platform', Platform::Telegram)
->first();
expect($account)->not->toBeNull();
expect($account->platform_user_id)->toBe('-1001234567890');
expect($account->display_name)->toBe('My Channel');
expect($account->username)->toBe('mychannel');
expect(data_get($account->meta, 'chat_id'))->toBe('-1001234567890');
expect(data_get($account->meta, 'connect_nonce'))
->toBe(data_get(TelegramConnectCode::decode($code), 'nonce'));
});
it('stores the channel photo as the account avatar on connect', function () {
Storage::fake();
Http::fake([
'*/botTESTTOKEN/getChat*' => Http::response(['ok' => true, 'result' => ['photo' => ['big_file_id' => 'BIGFILE']]], 200),
'*/botTESTTOKEN/getFile*' => Http::response(['ok' => true, 'result' => ['file_path' => 'photos/file_1.jpg']], 200),
'*/file/botTESTTOKEN/photos/file_1.jpg' => Http::response('image-bytes', 200, ['Content-Type' => 'image/jpeg']),
]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
$account = SocialAccount::where('platform', Platform::Telegram)->first();
expect($account->getRawOriginal('avatar_url'))->not->toBeNull();
});
it('links a private channel that has no username', function () {
Http::fake();
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code, ['username' => null]))
->assertNoContent();
$account = SocialAccount::where('platform', Platform::Telegram)->first();
expect($account->username)->toBeNull();
expect($account->display_name)->toBe('My Channel');
expect(data_get($account->meta, 'username'))->toBeNull();
});
it('connects a second telegram channel alongside the first', function () {
Http::fake();
SocialAccount::factory()->telegram()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => '-1009999999999',
]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
expect($this->workspace->socialAccounts()->count())->toBe(2);
expect(
SocialAccount::where('platform', Platform::Telegram)->where('platform_user_id', '-1001234567890')->exists()
)->toBeTrue();
});
it('reconnects an existing telegram channel', function () {
Http::fake();
SocialAccount::factory()->telegram()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => '-1001234567890',
]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
expect($this->workspace->socialAccounts()->count())->toBe(1);
expect(
SocialAccount::where('platform', Platform::Telegram)->where('platform_user_id', '-1001234567890')->count()
)->toBe(1);
});
it('issues a connect code that carries the reconnect card', function () {
$account = SocialAccount::factory()->telegram()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => '-1009999999999',
]);
$response = $this->actingAs($this->user)
->postJson(route('app.social.telegram.connect', ['reconnect' => $account->id]))
->assertOk();
expect(data_get(TelegramConnectCode::decode($response->json('code')), 'reconnect_id'))->toBe($account->id);
});
it('keeps the reconnect card on its own chat when a different channel posts the code', function () {
Http::fake();
Event::fake([TelegramConnectFailed::class]);
$account = SocialAccount::factory()->telegram()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => '-1009999999999',
]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15), $account->id);
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
Event::assertDispatched(
TelegramConnectFailed::class,
fn (TelegramConnectFailed $event): bool => $event->reason === 'wrong_chat'
);
expect($this->workspace->socialAccounts()->count())->toBe(1)
->and($account->fresh()->platform_user_id)->toBe('-1009999999999')
->and(Cache::has("telegram:connect:{$code}"))->toBeFalse();
});
it('lets the user retry in the right chat with the same code', function () {
Http::fake();
$account = SocialAccount::factory()->telegram()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => '-1001234567890',
'username' => 'stale',
]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15), $account->id);
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code, ['id' => -1009999999999]))
->assertNoContent();
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
expect($account->fresh()->platform_user_id)->toBe('-1001234567890')
->and($this->workspace->socialAccounts()->count())->toBe(1);
});
it('reconnects the card when its own chat posts the code', function () {
Http::fake();
$account = SocialAccount::factory()->telegram()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => '-1001234567890',
'username' => 'stale',
]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15), $account->id);
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
expect($this->workspace->socialAccounts()->count())->toBe(1)
->and($account->fresh()->platform_user_id)->toBe('-1001234567890')
->and($account->fresh()->id)->toBe($account->id);
});
it('consumes the code once so it cannot be replayed for another chat', function () {
Http::fake();
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code, ['id' => -1001111111111]))
->assertNoContent();
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code, ['id' => -1002222222222]))
->assertNoContent();
expect(SocialAccount::where('platform', Platform::Telegram)->count())->toBe(1);
expect(
SocialAccount::where('platform', Platform::Telegram)->where('platform_user_id', '-1001111111111')->exists()
)->toBeTrue();
});
it('stores reaction counts on the matching post from a reaction update', function () {
$account = SocialAccount::factory()->telegram()->create(['workspace_id' => $this->workspace->id]);
$post = Post::factory()->forAccount($account)->published()->create([
'user_id' => $this->user->id,
'platform_post_id' => '42',
]);
$update = [
'message_reaction_count' => [
'chat' => ['id' => -1001234567890],
'message_id' => 42,
'reactions' => [
['type' => ['type' => 'emoji', 'emoji' => '👍'], 'total_count' => 12],
['type' => ['type' => 'emoji', 'emoji' => '❤️'], 'total_count' => 5],
],
],
];
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), $update)
->assertNoContent();
expect(data_get($post->fresh()->meta, 'reactions'))
->toBe([['type' => '👍', 'count' => 12], ['type' => '❤️', 'count' => 5]]);
});
it('does not store reactions on a post from a different channel with the same message id', function () {
$otherAccount = SocialAccount::factory()->telegram()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => '-1009999999999',
'meta' => ['chat_id' => '-1009999999999', 'username' => 'other', 'type' => 'channel'],
]);
$post = Post::factory()->forAccount($otherAccount)->published()->create([
'user_id' => $this->user->id,
'platform_post_id' => '42',
]);
$update = [
'message_reaction_count' => [
'chat' => ['id' => -1001234567890],
'message_id' => 42,
'reactions' => [['type' => ['type' => 'emoji', 'emoji' => '👍'], 'total_count' => 9]],
],
];
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), $update)
->assertNoContent();
expect(data_get($post->fresh()->meta, 'reactions'))->toBeNull();
});
it('labels custom emoji reactions with a fallback', function () {
$account = SocialAccount::factory()->telegram()->create(['workspace_id' => $this->workspace->id]);
$post = Post::factory()->forAccount($account)->published()->create([
'user_id' => $this->user->id,
'platform_post_id' => '77',
]);
$update = [
'message_reaction_count' => [
'chat' => ['id' => -1001234567890],
'message_id' => 77,
'reactions' => [['type' => ['type' => 'custom_emoji', 'custom_emoji_id' => '555'], 'total_count' => 3]],
],
];
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), $update)
->assertNoContent();
expect(data_get($post->fresh()->meta, 'reactions'))
->toBe([['type' => 'Custom', 'count' => 3]]);
});
it('connects without an avatar when the channel has no photo', function () {
Http::fake([
'*/botTESTTOKEN/getChat*' => Http::response(['ok' => true, 'result' => []], 200),
]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
$account = SocialAccount::where('platform', Platform::Telegram)->first();
expect($account)->not->toBeNull();
expect($account->getRawOriginal('avatar_url'))->toBeNull();
});
it('rejects the webhook without the secret token', function () {
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$this->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertForbidden();
});
it('ignores the webhook for a tampered or expired code', function () {
$expired = TelegramConnectCode::issue($this->workspace->id, now()->subMinute());
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($expired))
->assertNoContent();
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate('not-a-valid-code'))
->assertNoContent();
expect(SocialAccount::where('platform', Platform::Telegram)->count())->toBe(0);
});
it('broadcasts to the workspace with the nonce when a channel connects', function () {
Event::fake([TelegramChannelConnected::class]);
Http::fake();
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$nonce = data_get(TelegramConnectCode::decode($code), 'nonce');
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
Event::assertDispatched(
TelegramChannelConnected::class,
fn (TelegramChannelConnected $event) => $event->workspaceId === $this->workspace->id
&& $event->nonce === $nonce
&& $event->created === true
&& $event->accountId === SocialAccount::where('platform', Platform::Telegram)->value('id'),
);
});
it('does not broadcast when the code is tampered or already used', function () {
Event::fake([TelegramChannelConnected::class]);
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate('not-a-valid-code'))
->assertNoContent();
Event::assertNotDispatched(TelegramChannelConnected::class);
});
it('verifies a connected telegram account via getChat', function () {
config(['trypost.platforms.telegram.bot_token' => 'TESTTOKEN']);
$account = SocialAccount::factory()->telegram()->create(['workspace_id' => $this->workspace->id]);
Http::fake([
'*/botTESTTOKEN/getChat*' => Http::response(['ok' => true, 'result' => ['id' => -1001234567890]], 200),
]);
expect(app(ConnectionVerifier::class)->verify($account))->toBeTrue();
});
it('throws TokenExpiredException when getChat reports the chat is no longer reachable', function () {
config(['trypost.platforms.telegram.bot_token' => 'TESTTOKEN']);
$account = SocialAccount::factory()->telegram()->create(['workspace_id' => $this->workspace->id]);
Http::fake([
'*/botTESTTOKEN/getChat*' => Http::response(['ok' => false, 'description' => 'chat not found'], 400),
]);
expect(fn () => app(ConnectionVerifier::class)->verify($account))
->toThrow(TokenExpiredException::class);
// Telegram has no per-account refresh flow (one bot token shared across
// every connected account) — a confirmed rejection must not trigger a
// second, identical getChat call against that shared budget.
Http::assertSentCount(1);
});
it('throws PlatformUnavailableException when getChat fails transiently', function () {
config(['trypost.platforms.telegram.bot_token' => 'TESTTOKEN']);
$account = SocialAccount::factory()->telegram()->create(['workspace_id' => $this->workspace->id]);
Http::fake([
'*/botTESTTOKEN/getChat*' => Http::response(['ok' => false, 'description' => 'Internal Server Error'], 500),
]);
expect(fn () => app(ConnectionVerifier::class)->verify($account))
->toThrow(PlatformUnavailableException::class);
});
it('throws PlatformUnavailableException, not TokenExpiredException, when the shared bot token is rejected', function () {
config(['trypost.platforms.telegram.bot_token' => 'TESTTOKEN']);
$account = SocialAccount::factory()->telegram()->create(['workspace_id' => $this->workspace->id]);
// 401 means the app-wide TELEGRAM_BOT_TOKEN is misconfigured — every
// Telegram-connected account would fail identically. It is not evidence
// that THIS account's connection is broken, so it must not disconnect it.
Http::fake([
'*/botTESTTOKEN/getChat*' => Http::response(['ok' => false, 'description' => 'Unauthorized'], 401),
]);
expect(fn () => app(ConnectionVerifier::class)->verify($account))
->toThrow(PlatformUnavailableException::class);
});
it('registers the webhook via the artisan command', function () {
Http::fake([
'*/botTESTTOKEN/setWebhook' => Http::response(['ok' => true, 'result' => true], 200),
]);
$this->artisan('telegram:set-webhook')->assertSuccessful();
Http::assertSent(function ($request) {
return str_contains($request->url(), '/setWebhook')
&& $request['secret_token'] === 'shh-secret'
&& str_contains($request['url'], 'telegram/webhook');
});
});
it('reports a busy connect instead of letting the webhook fail', function () {
Http::fake();
Event::fake([TelegramConnectFailed::class]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$lock = Cache::lock("social_connect:{$this->workspace->id}:telegram", 10);
expect($lock->get())->toBeTrue();
try {
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
} finally {
$lock->release();
}
Event::assertDispatched(
TelegramConnectFailed::class,
fn (TelegramConnectFailed $event): bool => $event->reason === 'busy'
);
expect($this->workspace->socialAccounts()->count())->toBe(0);
});
it('telegram connection uses source telegram', function () {
enablePostHog();
Http::fake();
Bus::fake([TrackSocialAccountConnected::class]);
$owner = User::factory()->create(['account_id' => $this->workspace->account_id]);
$this->workspace->account->update(['owner_id' => $owner->id]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
$account = SocialAccount::where('platform', Platform::Telegram)->firstOrFail();
Bus::assertDispatchedOnce(TrackSocialAccountConnected::class);
Bus::assertDispatched(TrackSocialAccountConnected::class, fn (TrackSocialAccountConnected $job): bool => $job->socialAccountId === (string) $account->id
&& $job->userId === null
&& $job->source === TrackSocialAccountConnected::SOURCE_TELEGRAM);
});
it('a telegram reconnect does not dispatch connected', function () {
enablePostHog();
Http::fake();
Bus::fake([TrackSocialAccountConnected::class]);
$account = SocialAccount::factory()->telegram()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => '-1001234567890',
]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15), $account->id);
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
Bus::assertNotDispatched(TrackSocialAccountConnected::class);
});
it('a telegram connection still succeeds when tracking it fails', function () {
enablePostHog();
Http::fake();
failDispatchOf(TrackSocialAccountConnected::class);
$owner = User::factory()->create(['account_id' => $this->workspace->account_id]);
$this->workspace->account->update(['owner_id' => $owner->id]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
expect(SocialAccount::where('platform', Platform::Telegram)->exists())->toBeTrue();
});
it('a telegram connection does not dispatch connected when PostHog is disabled', function () {
config(['services.posthog.enabled' => false]);
Http::fake();
Bus::fake([TrackSocialAccountConnected::class]);
$code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));
$this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')
->postJson(route('telegram.webhook'), telegramUpdate($code))
->assertNoContent();
expect(SocialAccount::where('platform', Platform::Telegram)->exists())->toBeTrue();
Bus::assertNotDispatched(TrackSocialAccountConnected::class);
});