Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unfurling Discord Message Links #221

Merged
merged 8 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ services:
- SLACK_TEAM_ID
- SLACK_REDIRECT_URI
- SLACK_BOT_USER_OAUTH_TOKEN
- DISCORD_BOT_TOKEN
- SENTRY_BACKEND_DSN
- SENTRY_FRONTEND_DSN
- SENTRY_AUTH_TOKEN
Expand Down
22 changes: 11 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions potal/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,32 @@ func EventsHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params)
return
}

txn.Status = sentry.SpanStatusOK
}()
case *slackevents.LinkSharedEvent:
go event.ProcessLinkSharedEvent(r.Context(), ev)
go func() {
hub := sentry.CurrentHub().Clone()
ctx := sentry.SetHubOnContext(context.Background(), hub)

options := []sentry.SpanOption{
sentry.WithOpName("event.handler"),
sentry.WithTransactionSource(sentry.SourceTask),
sentry.ContinueFromHeaders(transaction.ToSentryTrace(), transaction.ToBaggage()),
}
txn := sentry.StartTransaction(ctx, "EVENT link_shared", options...)
defer txn.Finish()

processedEvent := event.ProcessLinkSharedEvent(txn.Context(), ev)
if processedEvent == nil {
return
}
err := potalhttp.SendRequest(txn.Context(), processedEvent)
if err != nil {
txn.Status = sentry.SpanStatusInternalError
return
}

txn.Status = sentry.SpanStatusOK
}()
}
Expand Down
1 change: 1 addition & 0 deletions potal/internal/event/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const (
appHomeOpened PotalEventType = "app_home_opened"
slashCommand PotalEventType = "slash_command"
interactionCallback PotalEventType = "interaction_callback"
linkShared PotalEventType = "link_shared"
)

func (e PotalEventType) String() string {
Expand Down
66 changes: 66 additions & 0 deletions potal/internal/event/linkshared.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package event

import (
"context"

"github.com/getsentry/sentry-go"
"github.com/slack-go/slack/slackevents"
)

type LinkSharedEvent struct {
Type PotalEventType `json:"type"`
User string `json:"user"`
TimeStamp string `json:"ts"`
Channel string `json:"channel"`
MessageTimeStamp string `json:"message_ts"`
ThreadTimeStamp string `json:"thread_ts"`
Links []Link `json:"links"`
EventTimestamp string `json:"event_ts"`
}

type Link struct {
Domain string `json:"domain"`
URL string `json:"url"`
}

func (e LinkSharedEvent) isValid() bool {
return len(e.Links) > 0
}

func ProcessLinkSharedEvent(ctx context.Context, e *slackevents.LinkSharedEvent) *LinkSharedEvent {
hub := sentry.GetHubFromContext(ctx)
txn := sentry.TransactionFromContext(ctx)

span := txn.StartChild("event.process", sentry.WithDescription("Process LinkShared Event"))
defer span.Finish()

links := make([]Link, len(e.Links))
for i, link := range e.Links {
links[i] = Link{
Domain: link.Domain,
URL: link.URL,
}
}

linkSharedEvent := LinkSharedEvent{
Type: linkShared,
User: e.User,
TimeStamp: e.TimeStamp,
Channel: e.Channel,
MessageTimeStamp: e.MessageTimeStamp,
ThreadTimeStamp: e.ThreadTimeStamp,
Links: links,
EventTimestamp: e.EventTimestamp,
}

if !linkSharedEvent.isValid() {
span.Status = sentry.SpanStatusInvalidArgument
return nil
}
span.Status = sentry.SpanStatusOK

hub.Scope().SetExtra("event", linkSharedEvent)
hub.Scope().SetTag("event_type", linkShared.String())

return &linkSharedEvent
}
4 changes: 4 additions & 0 deletions src/Event/AbstractEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace App\Event;

use App\Http\DiscordClient;
use App\Http\SlackClient;
use Cake\ORM\Locator\LocatorAwareTrait;

Expand All @@ -17,8 +18,10 @@ abstract class AbstractEvent
public const TYPE_APP_MENTION = 'app_mention';
public const TYPE_SLASH_COMMAND = 'slash_command';
public const TYPE_INTERACTIONS_CALLBACK = 'interaction_callback';
public const TYPE_LINK_SHARED = 'link_shared';

protected SlackClient $slackClient;
protected DiscordClient $discordClient;

public string $type;
public string $eventTimestamp;
Expand All @@ -29,6 +32,7 @@ abstract class AbstractEvent
public function __construct()
{
$this->slackClient = new SlackClient();
$this->discordClient = new DiscordClient();
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/Event/EventFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
return new SlashCommandEvent($data);
case AbstractEvent::TYPE_INTERACTIONS_CALLBACK:
return new InteractionsCallbackEvent($data);
case AbstractEvent::TYPE_LINK_SHARED:
return new LinkSharedEvent($data);

Check warning on line 47 in src/Event/EventFactory.php

View check run for this annotation

Codecov / codecov/patch

src/Event/EventFactory.php#L46-L47

Added lines #L46 - L47 were not covered by tests
default:
throw new Exception('Unknown event type');
}
Expand Down
85 changes: 85 additions & 0 deletions src/Event/LinkSharedEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);

namespace App\Event;

class LinkSharedEvent extends AbstractEvent
{
public string $user;
public string $timestamp;
public string $channel;
public string $messageTimeStamp;
public string $threadTimeStamp;
public array $links;
public string $eventTimestamp;

/**
* Constructor
*
* @param array $event Event data.
*/
public function __construct(array $event)

Check warning on line 21 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L21

Added line #L21 was not covered by tests
{
parent::__construct();

Check warning on line 23 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L23

Added line #L23 was not covered by tests

$this->type = self::TYPE_LINK_SHARED;
$this->user = $event['user'];
$this->timestamp = $event['ts'];
$this->channel = $event['channel'];
$this->messageTimeStamp = $event['message_ts'];
$this->threadTimeStamp = $event['thread_ts'];
$this->eventTimestamp = $event['event_ts'];
$this->links = $event['links'];

Check warning on line 32 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L25-L32

Added lines #L25 - L32 were not covered by tests
}

/**
* @inheritDoc
*/
public function process(): void

Check warning on line 38 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L38

Added line #L38 was not covered by tests
{
foreach ($this->links as $link) {

Check warning on line 40 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L40

Added line #L40 was not covered by tests
// if Discord link, unfurl and fetch the message and return it
if (str_starts_with($link['url'], 'https://discord.com/')) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@HazAT As Slack only emits events for configured domains, do we need this check?

$message = $this->fetchDiscordMessage($link['url']);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Message might be empty

$this->slackClient->unfurl(
channel: $this->channel,
timestamp: $this->messageTimeStamp,
unfurls: [
$link['url'] => [
'blocks' => [
[
'type' => 'section',
'text' => [
'type' => 'mrkdwn',
'text' => $message,
],
],
],
],
],
);

Check warning on line 60 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L42-L60

Added lines #L42 - L60 were not covered by tests
}
}
}

/**
* Fetch a Discord message
*
* @param string $url The Discord message URL
* @return string The message content
*/
private function fetchDiscordMessage(string $url): string

Check warning on line 71 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L71

Added line #L71 was not covered by tests
{
if (!preg_match('#^https://discord\.com/channels/\d+/\d+/\d+$#', $url)) {
return $url;

Check warning on line 74 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L73-L74

Added lines #L73 - L74 were not covered by tests
}

$parts = explode('/', $url);
$channelId = $parts[5];
$messageId = $parts[6];

Check warning on line 79 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L77-L79

Added lines #L77 - L79 were not covered by tests

$message = $this->discordClient->getMessage($channelId, $messageId);

Check warning on line 81 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L81

Added line #L81 was not covered by tests

return $message;

Check warning on line 83 in src/Event/LinkSharedEvent.php

View check run for this annotation

Codecov / codecov/patch

src/Event/LinkSharedEvent.php#L83

Added line #L83 was not covered by tests
}
}
59 changes: 59 additions & 0 deletions src/Http/DiscordClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);

namespace App\Http;

use function Cake\Core\env;
use function Sentry\captureMessage;
use function Sentry\withScope;

class DiscordClient
{
protected const DISCORD_API_URL = 'discord.com/api/v10';

protected Client $client;

/**
* Constructor.
*/
public function __construct()
{
$this->client = new Client([
'host' => self::DISCORD_API_URL,
'scheme' => 'https',
'headers' => [
'Authorization' => 'Bot ' . env('DISCORD_BOT_TOKEN'),
'Content-Type' => 'application/json',
],
]);
}

/**
* Get a message from a channel
*
* @param string $channelId The channel ID
* @param string $messageId The message ID
* @return string The message content
*/
public function getMessage(string $channelId, string $messageId): string

Check warning on line 38 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L38

Added line #L38 was not covered by tests
{
$response = $this->client->get("channels/{$channelId}/messages/{$messageId}");

Check warning on line 40 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L40

Added line #L40 was not covered by tests

if ($response->isSuccess()) {
$json = $response->getJson();

Check warning on line 43 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L42-L43

Added lines #L42 - L43 were not covered by tests

return $json['content'] ?? '';

Check warning on line 45 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L45

Added line #L45 was not covered by tests
}

withScope(function ($scope) use ($response, $channelId, $messageId): void {
$scope->setContext('Discord API', [
'channel_id' => $channelId,
'message_id' => $messageId,
'discord_response' => $response->getJson(),
]);
captureMessage('Discord API error: Failed to fetch message');
});

Check warning on line 55 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L48-L55

Added lines #L48 - L55 were not covered by tests

return '';

Check warning on line 57 in src/Http/DiscordClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/DiscordClient.php#L57

Added line #L57 was not covered by tests
}
}
30 changes: 30 additions & 0 deletions src/Http/SlackClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,4 +207,34 @@

return [];
}

/**
* @param string $channel The channel to unfurl the links in.
* @param string $timestamp The timestamp of the message to unfurl the links in.
* @param array $unfurls The unfurls to send.
* @return void
* @see https://api.slack.com/methods/chat.unfurl
*/
public function unfurl(string $channel, string $timestamp, array $unfurls): void

Check warning on line 218 in src/Http/SlackClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/SlackClient.php#L218

Added line #L218 was not covered by tests
{
$response = $this->client->post('chat.unfurl', [
'channel' => $channel,
'ts' => $timestamp,
'unfurls' => json_encode($unfurls),
]);
if ($response->isSuccess()) {
$json = $response->getJson();
if ($json['ok'] === false) {
withScope(function ($scope) use ($json, $channel, $timestamp, $unfurls): void {
$scope->setContext('Slack API', [
'channel' => $channel,
'timestamp' => $timestamp,
'unfurls' => $unfurls,
'slack_response' => $json,
]);
captureMessage('Slack API error: https://api.slack.com/methods/chat.unfurl');
});

Check warning on line 236 in src/Http/SlackClient.php

View check run for this annotation

Codecov / codecov/patch

src/Http/SlackClient.php#L220-L236

Added lines #L220 - L236 were not covered by tests
}
}
}
}
Loading