Skip to content

Commit fee6caf

Browse files
Merge pull request #38 from CodeForPhilly/features/discourse-temp-webhooks
feat(discourse): port ad-hoc webhook handlers
2 parents 4acbffd + a1fb0ed commit fee6caf

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

site-root/discourse-webhook.php

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
<?php
2+
3+
/**
4+
* TODO: create an emergence-discourse repo, move the Discourse connector there,
5+
* merge this into the connector class and have it publish events
6+
*
7+
* Also, this was built against the discourse webhook plugin. Discourse has webhooks
8+
* built in now that may be slightly different and include signature validation. We
9+
* should switch to using that and drop the plugin
10+
*/
11+
12+
// settings
13+
$discourseHost = Emergence\Connectors\Discourse::$host;
14+
15+
16+
// only handle post_created for now
17+
$eventName = array_shift(Site::$pathStack);
18+
if ($eventName != 'post_created') {
19+
die('Ignoring request, only handling /post_created');
20+
}
21+
22+
23+
// decode webhook payload
24+
list($post, $topic, $user) = json_decode(file_get_contents('php://input'), true);
25+
26+
27+
// log to tmp file
28+
file_put_contents('/tmp/last-discourse-webhook-payload', var_export([
29+
'$post' => $post,
30+
'$topic' => $topic,
31+
'$user' => $user
32+
], true));
33+
34+
35+
// skip empty events that seem to get fired when topics get edited:
36+
if (empty($topic['title'])) {
37+
die('Ignoring request, no topic title');
38+
}
39+
40+
41+
// skip private messages
42+
if ($topic['archetype'] == 'private_message') {
43+
die('Ignoring request, private message');
44+
}
45+
46+
47+
// compose message for Slack
48+
$messageText = "New topic on $discourseHost";
49+
50+
#// This doesn't work because the category is a number... we'll need to map them on our own to category names or slack rooms
51+
#if (!empty($topic['category'])) {
52+
# $messageText .= " in $topic[category]";
53+
#}
54+
55+
$messageText .= ": <http://$discourseHost/t/$post[topic_id]|$topic[title]>";
56+
$messageText .= "\n\n> " . str_replace("\n", "\n> ", $post['raw']);
57+
58+
#// post full event payload to Slack
59+
#$messageText .= "\n\n\n" . json_encode(['post' => $post, 'topic' => $topic, 'user' => $user], JSON_PRETTY_PRINT);
60+
61+
62+
// post to slack
63+
$response = Emergence\Slack\API::request('chat.postMessage', [
64+
'post' => [
65+
'channel' => Emergence\Slack\API::getChannelId('general'),
66+
'username' => "$user[username]@$discourseHost",
67+
'icon_url' => str_replace('{size}', 100, "http://$discourseHost/$user[avatar_template]"),
68+
'text' => $messageText,
69+
]
70+
]);
71+
72+
73+
// write slack response to output
74+
print_r($response);

0 commit comments

Comments
 (0)