/
similarArtists.php
46 lines (37 loc) · 1.78 KB
/
similarArtists.php
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
<?php
//Get parameters proivded by the slack request
$command = $_POST['command'];
$text = $_POST['text'];
$token = $_POST['token'];
$channel_name = $_POST['channel_name'];
$username = "Music bot bleep bloop";
//We'll use the last.fm API to return some similar artists. This URL string will provide a JSON result to iterate over
$lastFmUrl = 'http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist=' . $text . '&api_key=9ddaab7dc99dbcfb3f2ed8204ef965ce&limit=10&format=json';
$content = file_get_contents($lastFmUrl);
$json = json_decode($content, true);
//The URL of the webhook generated by slack on setting one up. Follow readme instructions if not sure
$webhookUrl = "https://hooks.slack.com/services/this-will-be-unique-to-your-webhook";
//Initialize and set up a new cURL session
$curl = curl_init($webhookUrl);
curl_setopt($curl, CURLOPT_POST, true);
$response = '';
//Loop over the JSON response from the last.fm similar artist request
foreach($json['similarartists']['artist'] as $item)
{
//Append the artists to a variable to be later used in our JSON slack response. Include a line break for formatting
$response .= $item['name'];
$response .= '\n';
}
//Create an array with optional elements that slack recognises
$payload = array(
'text' => rawurlencode($response), //The main body of the slack message
'username' => $username, //The username of the bot
'channel' => "#".$channel_name //Which channel it came from, and then needs to post back to. This stops it defualting to the one set up in the webhook
);
//Encode the response ready to send back to slack
$jsonPayload = "payload=".json_encode($payload);
curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonPayload);
$return = curl_exec($curl);
//Close the cURL session
curl_close($curl);
?>