Moved code to under the src/ directory (to keep the directory structure tidy); created a separate instance of the EventLoop to have a periodic YouTube check
This commit is contained in:
53
src/pigeon.php
Normal file
53
src/pigeon.php
Normal file
@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
include __DIR__ . '/../vendor/autoload.php';
|
||||
|
||||
use Discord\Discord;
|
||||
use Discord\Parts\Channel\Message;
|
||||
use Discord\WebSockets\Intents;
|
||||
use Madcoda\Youtube\Youtube;
|
||||
use Noodlehaus\Config;
|
||||
|
||||
// load config file
|
||||
$config = new Config('config/config.yaml');
|
||||
|
||||
// create YouTube API object
|
||||
$youtube = new Youtube(array('key' => $config->get('youtube.api_key')));
|
||||
// get channel
|
||||
$yt_res = $youtube->getChannelById($config->get('youtube.channel_id'));
|
||||
// get channel info
|
||||
$config->set('youtube.channel_name', $yt_res->snippet->title);
|
||||
$config->set('youtube.uploads_id', $yt_res->contentDetails->relatedPlaylists->uploads);
|
||||
|
||||
// create our event loop
|
||||
$loop = React\EventLoop\Factory::create();
|
||||
|
||||
// instantiate Discord API object
|
||||
$discord = new Discord([
|
||||
'token' => $config->get('discord.api_key'),
|
||||
'intents' => Intents::getDefaultIntents() | Intents::GUILDS,
|
||||
'loop' => $loop,
|
||||
]);
|
||||
|
||||
// periodic youtube uploads check
|
||||
$loop->addPeriodicTimer($config->get('pigeon.check_interval') * 60, function () use ($config, $discord, $youtube) {
|
||||
// get latest video from uploads playlist
|
||||
$uploads = $youtube->getPlaylistItemsByPlaylistId($config->get('youtube.uploads_id'));
|
||||
$latest_video_id = $uploads[0]->contentDetails->videoId;
|
||||
$latest_url = "https://youtu.be/$latest_video_id";
|
||||
|
||||
$message_text = str_replace('{link}', $latest_url, $config->get('discord.message_template'));
|
||||
|
||||
$discord->guilds->first()->channels->find(function ($channel) use ($config) {
|
||||
return $channel->name === $config->get('discord.announcement_channel');
|
||||
})->sendMessage($message_text)->done(function ($message) use ($discord) {
|
||||
echo 'Message sent!', PHP_EOL;
|
||||
});
|
||||
});
|
||||
|
||||
// run tasks when Discord is ready
|
||||
$discord->on('ready', function (Discord $discord) use ($conf, $latest_url) {
|
||||
echo "Bot is ready!", PHP_EOL;
|
||||
});
|
||||
|
||||
$discord->run();
|
Reference in New Issue
Block a user