Skip to content

Instantly share code, notes, and snippets.

@ammarfaizi2
Created October 5, 2018 06:03
Show Gist options
  • Save ammarfaizi2/2e24036d59844c7b79f9eaca1de7e4dc to your computer and use it in GitHub Desktop.
Save ammarfaizi2/2e24036d59844c7b79f9eaca1de7e4dc to your computer and use it in GitHub Desktop.
#!/usr/bin/env php
<?php
if (! isset($argv[1])) {
printf("Please provide \$argv[1] for session identifier!\n");
exit(1);
}
use danog\MadelineProto\API;
use TelegramDaemon\EventHandler;
require __DIR__."/../config/init.php";
require __DIR__."/../config/telegramd.php";
require __DIR__."/../vendor/autoload.php";
class PidDesctructor {
/**
* @var string
*/
private $pidFile;
/**
* @param string $pidFile
*
* Constructor.
*/
public function __construct(string $pidFile)
{
$this->pidFile = $pidFile;
}
/**
* Destructor.
*/
public function __destruct()
{
$myPid = getmypid();
if (file_exists($this->pidFile)) {
$pidList = json_decode(file_get_contents($this->pidFile), true);
if (is_array($pidList) && in_array($myPid, $pidList)) {
print "Deleting pid file {$this->pidFile}...\n";
unlink($this->pidFile);
}
}
exit(0);
}
}
$pidData = [];
$pidFile = STORAGE_PATH."/pid/{$argv[1]}.pid";
if (file_exists($pidFile)) {
$pidData = json_decode(file_get_contents($pidFile), true);
$pidData = is_array($pidData) ? $pidData : [];
}
$pidData[] = getmypid();
file_put_contents($pidFile, json_encode($pidData));
$pidDesctructor = new PidDesctructor($pidFile);
$pidClosure = function () {
global $pidDesctructor;
unset($pidDesctructor);
exit;
};
// Prevent defunct.
pcntl_signal(SIGCHLD, SIG_IGN);
// Delete pid file.
pcntl_signal(SIGINT, $pidClosure);
pcntl_signal(SIGTERM, $pidClosure);
pcntl_signal(SIGPIPE, $pidClosure);
chdir(STORAGE_PATH."/tmp");
set_include_path(STORAGE_PATH."/tmp");
if (!file_exists(STORAGE_PATH."/tmp/madeline.php")) {
copy("https://phar.madelineproto.xyz/madeline.php", STORAGE_PATH."/tmp/madeline.php");
}
if (!defined("DEBUG_MODE")) {
define("DEBUG_MODE", true);
}
require STORAGE_PATH."/tmp/madeline.php";
DEBUG_MODE or ob_start();
$madelineProto = new API(STORAGE_PATH."/telegram_sessions/".$argv[1]);
$madelineProto->start();
$madelineProto->setEventHandler(
EventHandler::class
);
DEBUG_MODE or ob_get_clean();
$madelineProto->loop(-1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment