ifhub-telegram/bot.php

162 lines
5.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require_once ("vendor/autoload.php");
use Symfony\Component\Yaml\Yaml;
use Mremi\UrlShortener\Model\Link;
use Mremi\UrlShortener\Provider\Bitly\BitlyProvider;
use Mremi\UrlShortener\Provider\Bitly\GenericAccessTokenAuthenticator;
use Revolution\Mastodon\MastodonClient;
use GuzzleHttp\Client;
$config = Yaml::parse(file_get_contents('config.yml'));
$lastrun = 0;
if (file_exists('.lastrun') && !$config['DRY_RUN']) {
$lastrun = file_get_contents('.lastrun');
}
function get_text($url) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
));
$resp = curl_exec($curl);
curl_close($curl);
return $resp;
}
function ellipse($str,$n_chars,$crop_str='[...]')
{
$buff = $str;
if(strlen($buff) > $n_chars)
{
$cut_index=strpos($buff,' ',$n_chars);
$buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
// then cut for last newline or dot
$cut_index_a=strpos($buff,'.',$n_chars);
$cut_index_b=strpos($buff,PHP_EOL,$n_chars);
$cut_index = max((int) $cut_index_a, (int) $cut_index_b);
$buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
}
return trim($buff);
}
function formatdsc($description) {
global $pandoc;
$description = strip_tags($description, 'img');
$description = $pandoc->runWith($description, [
'from' => 'html',
'to' => 'plain',
'wrap' => 'none'
]);
$description = str_replace('Читать дальше', '', $description);
$description = trim($description);
return $description;
}
function download($url, $outFile) {
$options = array(
CURLOPT_FILE => fopen($outFile, 'w'),
CURLOPT_TIMEOUT => 28800, // set this to 8 hours so we dont timeout on big files
CURLOPT_URL => $url
);
$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);
}
$string = get_text('https://ifhub.club/rss/full/');
$service = new \Sabre\Xml\Service();
$service->elementMap = [
'{}item' => function(\Sabre\Xml\Reader $reader) {
return \Sabre\Xml\Deserializer\keyValue($reader, '');
},
'{}channel' => function(\Sabre\Xml\Reader $reader) {
return \Sabre\Xml\Deserializer\repeatingElements($reader, '{}item');
},
];
$articles = $service->parse($string)[0]['value'];
unset($string);
$pandoc = new \Pandoc\Pandoc();
/*
$bitlyProvider = new BitlyProvider(
new GenericAccessTokenAuthenticator($config['BITLY_TOKEN'])
);
*/
$telegram = new Longman\TelegramBot\Telegram(
$config['TELEGRAM_API_KEY'],
$config['TELEGRAM_BOT_NAME']
);
$mastodon = new MastodonClient(new Client);
foreach ($articles as $article) {
if (strtotime($article['pubDate']) <= $lastrun) {
continue;
}
$title = $article['title'];
$link_mastodon = $article['link'];
$link_telegram = 'https://t.me/iv?url='.urlencode($article['link']).'&rhash=2db6db1261cc57';
$description = $article['description'];
$image = NULL;
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $description, $image);
if (isset($image[1])) {
$image = $image[1];
}
$long_description = $description;
$description = substr( $description, 0, strpos($description, '<a name="cut"'));
$description = formatdsc($description);
/*
if (strlen($description) < 50) { // description is too small
$description = $long_description;
$description = formatdsc($description);
}
*/
$limit = 500 - strlen($link_telegram) - strlen($title) - 20;
$description = "$title\n\n".ellipse($description, $limit);
$description_mastodon = $description."\nСсылка на статью и голосование за рейтинг: $link_mastodon";
$description_telegram = $description."\n$link_telegram\nСсылка на статью и голосование за рейтинг: $link_mastodon";
if (!$config['DRY_RUN']) {
if ($config['TELEGRAM'] === true) {
try {
$result = \Longman\TelegramBot\Request::sendMessage([
'chat_id' => $config['TELEGRAM_CHAT_ID'],
'text' => $description_telegram,
'parse_mode' => 'Markdown'
]);
unset($tdescription);
if (!$config['DRY_RUN']) {
file_put_contents('.lastrun', time());
}
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
echo $e;
}
}
if ($config['MASTODON'] === true) {
$mastodon->domain($config['MASTODON_SERVER'])->token($config['MASTODON_ACCESS_TOKEN']);
/*
if ($image) {
download('https://ifhub.club'.$image, './'.basename($image));
$attachment = $mastodon->post('/media', [
'file' => file_get_contents('./'.basename($image))
]);
var_dump($attachment);
unlink('./'.basename($image));
$mdescription .= $attachment->url;
}*/
$mastodon->createStatus($description_mastodon, [
'language' => 'ru'
]);
if (!$config['DRY_RUN']) {
file_put_contents('.lastrun', time());
}
}
if (!empty($config['INDEXNOW'])) {
$client = new \GuzzleHttp\Client();
$client->request('GET', 'https://www.bing.com/indexnow?url='.$link.'&key='.$config['INDEXNOW']);
}
} else {
echo $description."\n";
}
}