Last active
May 13, 2022 21:23
-
-
Save WhiteGrouse/061c9e50b3096aec911548188bca09df to your computer and use it in GitHub Desktop.
DiscordPHPは神だった
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace delion\discord; | |
| use React\EventLoop\Factory as LoopFactory; | |
| use Discord\Discord; | |
| use Discord\Parts\Channel\Channel; | |
| define('BOT_TOKEN', ''); | |
| define('BOT_CHANNEL', ''); | |
| class DiscordThread extends \Thread { | |
| protected $D2P_Queue; | |
| protected $P2D_Queue; | |
| protected $shutdownRequested; | |
| public function __construct() { | |
| $this->D2P_Queue = new \Threaded; | |
| $this->P2D_Queue = new \Threaded; | |
| $this->shutdownRequested = false; | |
| } | |
| public function fetchMessages() { | |
| $messages = []; | |
| while(count($this->D2P_Queue) > 0) { | |
| $messages[] = unserialize($this->D2P_Queue->shift()); | |
| } | |
| return $messages; | |
| } | |
| public function sendMessage($message) { | |
| $this->P2D_Queue[] = serialize($message); | |
| } | |
| public function shutdown() { | |
| $this->shutdownRequested = true; | |
| $this->join(); | |
| } | |
| public function run() { | |
| require __DIR__ . '/vendor/autoload.php'; | |
| $discord = new Discord([ | |
| 'token' => BOT_TOKEN, | |
| 'logging' => false | |
| ]); | |
| $discord->on('ready', function($discord) { | |
| $channel = $discord->factory(Channel::class, ['id' => BOT_CHANNEL]); | |
| $discord->loop->addPeriodicTimer(1, function($timer) use ($discord, $channel) { | |
| if($this->shutdownRequested) { | |
| $discord->loop->cancelTimer($timer); | |
| $discord->close(); | |
| $discord->loop->stop(); | |
| return; | |
| } | |
| while(count($this->P2D_Queue) > 0) { | |
| $message = unserialize($this->P2D_Queue->shift()); | |
| $channel->sendMessage($message); | |
| } | |
| }); | |
| $discord->on('message', function($message) use ($discord) { | |
| $this->D2P_Queue[] = serialize([ | |
| 'username' => $message->author->username, | |
| 'content' => $message->content | |
| ]); | |
| }); | |
| }); | |
| $discord->run(); | |
| echo "shutdown...\n"; | |
| } | |
| } | |
| $discordThread = new DiscordThread(); | |
| $discordThread->start(); | |
| $i = 3; | |
| while(true) { | |
| sleep(1); | |
| foreach($discordThread->fetchMessages() as $message) { | |
| printf("%s: %s\n", $message['username'], $message['content']); | |
| } | |
| if($i-- > 0) { | |
| $discordThread->sendMessage("ちんちん"); | |
| } | |
| else { | |
| $discordThread->shutdown(); | |
| break; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment