forked from Talishar/Talishar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetDiscordReleaseNotes.php
More file actions
223 lines (189 loc) · 8.26 KB
/
GetDiscordReleaseNotes.php
File metadata and controls
223 lines (189 loc) · 8.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
<?php
/**
* GetDiscordReleaseNotes.php
*
* Fetches the latest messages from the Discord #release-notes channel
* Uses APCu caching (10 minute TTL) to reduce Discord API calls
*
* Requires:
* - DISCORD_BOT_TOKEN environment variable
* - DISCORD_CHANNEL_ID environment variable
*
* Usage: GET /GetDiscordReleaseNotes.php?maxMessages=5
*/
include 'Libraries/APCuCache.php';
header('Content-Type: application/json');
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$allowedDomains = ['localhost', 'talishar.net', 'legacy.talishar.net', 'preview.talishar.net'];
$isAllowed = false;
foreach ($allowedDomains as $domain) {
if (strpos($origin, $domain) !== false) {
$isAllowed = true;
break;
}
}
if ($isAllowed) {
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
}
// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
try {
// Check cache first
$cacheKey = 'discord_release_notes';
$cachedResult = APCuCache::get($cacheKey);
if ($cachedResult !== null) {
http_response_code(200);
echo json_encode($cachedResult);
exit;
}
$maxMessages = isset($_GET['maxMessages']) ? (int)$_GET['maxMessages'] : 5;
$maxMessages = min($maxMessages, 100); // Cap at 100 messages (Discord API max per request)
// Try to get from environment, then from $_ENV, then from direct file
$botToken = getenv('DISCORD_BOT_TOKEN') ?: ($_ENV['DISCORD_BOT_TOKEN'] ?? null);
$channelId = getenv('DISCORD_CHANNEL_ID') ?: ($_ENV['DISCORD_CHANNEL_ID'] ?? null);
// Fallback: check if there's a config file
if (!$botToken || !$channelId) {
// Try multiple .env file locations
$configPaths = [
__DIR__ . '/.env',
dirname(__DIR__) . '/.env',
'/opt/lampp/htdocs/game/.env',
'/opt/lampp/htdocs/.env',
];
foreach ($configPaths as $configFile) {
if (file_exists($configFile) && is_readable($configFile)) {
$lines = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos($line, 'DISCORD_BOT_TOKEN=') === 0) {
$botToken = trim(str_replace('DISCORD_BOT_TOKEN=', '', $line), '"\'');
}
if (strpos($line, 'DISCORD_CHANNEL_ID=') === 0) {
$channelId = trim(str_replace('DISCORD_CHANNEL_ID=', '', $line), '"\'');
}
}
if ($botToken && $channelId) {
break; // Found both values, stop searching
}
}
}
}
if (!$botToken || !$channelId) {
// Return empty response if not configured
http_response_code(200);
echo json_encode(['messages' => []]);
exit;
}
// Fetch channel info to get the channel name
$channelInfo = null;
$channelUrl = "https://discord.com/api/v10/channels/{$channelId}";
$ch = curl_init($channelUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bot {$botToken}",
"User-Agent: Talishar-Discord-Bot"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$channelResponse = curl_exec($ch);
$channelHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($channelHttpCode === 200) {
$channelInfo = json_decode($channelResponse, true);
}
// Fetch messages from Discord API
$url = "https://discord.com/api/v10/channels/{$channelId}/messages?limit={$maxMessages}";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bot {$botToken}",
"User-Agent: Talishar-Discord-Bot"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
// If Discord API fails, return empty
http_response_code(200);
echo json_encode(['messages' => []]);
exit;
}
$messages = json_decode($response, true);
if (!is_array($messages)) {
http_response_code(200);
echo json_encode(['messages' => []]);
exit;
}
$data = [];
foreach ($messages as $msg) {
// Include messages with content OR messages with embeds
$hasContent = !empty($msg['content']);
$hasEmbeds = isset($msg['embeds']) && !empty($msg['embeds']);
if ($hasContent || $hasEmbeds) {
// Get author display name (prefer global_name, then username)
$authorName = $msg['author']['global_name'] ?? $msg['author']['username'];
// Get attachments (images, files, etc.)
$attachments = isset($msg['attachments']) ? $msg['attachments'] : [];
// Get reactions
$reactions = isset($msg['reactions']) ? $msg['reactions'] : [];
// Replace channel mentions in content
$content = $msg['content'] ?? '';
$content = str_replace('<#868488473378684938>', '#release-notes', $content);
$content = str_replace('<#1014193064736194691>', '#talishar-content', $content);
$content = str_replace('<#865423689976774656>', '#bug-reports', $content);
$content = str_replace('<#971928581267664936>', '#feature-requests', $content);
$content = str_replace('<#865412150125789217>', '#general', $content);
$content = str_replace('<#1363088144139812935>', '#mobile-ui-bug-reports', $content);
// Replace user mentions with usernames
$content = str_replace('<@387720067640459275>', '@THESPIRITOFLIFE', $content);
$content = str_replace('<@256263154915475456>', '@Aegisworn', $content);
$content = str_replace('<@478621285786845196>', '@PvtVoid', $content);
$content = str_replace('<@695767191022338070>', '@hoodwill', $content);
$content = str_replace('<@214191542292840448>', '@looseleaftea', $content);
$content = str_replace('<@242811065878970368>', '@Zandrenel', $content);
$content = str_replace('<@405057789002776578>', '@Buford (Dan)', $content);
// Preserve line breaks - normalize to \n first, then convert to HTML
$content = preg_replace('/\r\n|\r/', "\n", $content);
// Remove Discord hyperlink markdown (< and >) - handle both < and < variants
$content = preg_replace('/<(https?:\/\/[^>]+)>/i', '$1', $content);
$content = preg_replace('/<(https?:\/\/[^&]+)>/i', '$1', $content);
$content = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
// Convert URLs to clickable links
$content = preg_replace(
'/(https?:\/\/[^\s<>"{}|\\^`\[\]]*)/i',
'<a href="$1" target="_blank">$1</a>',
$content
);
$content = nl2br($content, false);
$data[] = [
'id' => $msg['id'],
'content' => $content,
'author' => $authorName,
'timestamp' => $msg['timestamp'],
'embeds' => $msg['embeds'] ?? [],
'attachments' => $attachments,
'reactions' => $reactions
];
}
}
// Sort by newest first (Discord returns newest first already, but ensure it)
usort($data, function($a, $b) {
return strtotime($b['timestamp']) - strtotime($a['timestamp']);
});
$result = [
'messages' => array_slice($data, 0, $maxMessages),
'channelName' => $channelInfo ? '#' . $channelInfo['name'] : '#release-notes'
];
// Cache the result for 10 minutes
APCuCache::set($cacheKey, $result, 600);
http_response_code(200);
echo json_encode($result);
} catch (Exception $e) {
error_log("Discord fetch error: " . $e->getMessage());
http_response_code(200);
echo json_encode(['messages' => [], 'channelName' => '#release-notes']);
}