browser.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Example Bot with Discord-PHP and ReactPHP HTTP Browser
  4. *
  5. * When an User says "discordstatus", the Bot will reply Discord service status
  6. *
  7. * @see https://reactphp.org/http/#browser
  8. *
  9. * Run this example bot from main directory using command:
  10. * php examples/browser.php
  11. */
  12. include __DIR__.'/../vendor/autoload.php';
  13. // Import classes, install a LSP such as Intelephense to auto complete imports
  14. use Discord\Discord;
  15. use Discord\Parts\Channel\Message;
  16. use Psr\Http\Message\ResponseInterface;
  17. use React\Http\Browser;
  18. // Create a $discord BOT
  19. $discord = new Discord([
  20. 'token' => '', // Put your Bot token here from https://discord.com/developers/applications/
  21. ]);
  22. // Create a $browser with same loop as $discord
  23. $browser = new Browser(null, $discord->getLoop());
  24. // When the Bot is ready
  25. $discord->on('ready', function (Discord $discord) {
  26. // Listen for messages
  27. $discord->on('message', function (Message $message, Discord $discord) {
  28. // Ignore messages from any Bots
  29. if ($message->author->bot) return;
  30. // If message is "discordstatus"
  31. if ($message->content == 'discordstatus') {
  32. // Get the $browser from global scope
  33. global $browser;
  34. // Make GET request to API of discordstatus.com
  35. $browser->get('https://discordstatus.com/api/v2/status.json')->then(
  36. function (ResponseInterface $response) use ($message) { // Request success
  37. // Get response body
  38. $result = (string) $response->getBody();
  39. // Uncomment to debug result
  40. //var_dump($result);
  41. // Parse JSON
  42. $discordstatus = json_decode($result);
  43. // Send reply about the discord status
  44. $message->reply('Discord status: ' . $discordstatus->status->description);
  45. },
  46. function (Exception $e) use ($message) { // Request failed
  47. // Uncomment to debug exceptions
  48. //var_dump($e);
  49. // Send reply about the discord status
  50. $message->reply('Unable to acesss the Discord status API :(');
  51. }
  52. );
  53. }
  54. });
  55. });
  56. // Start the Bot (must be at the bottom)
  57. $discord->run();