Merge pull request #2 from danog/master

Huge improvements
This commit is contained in:
bruninoit 2018-03-28 10:56:16 +02:00 committed by GitHub
commit 131ff5f1b2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 264 additions and 505 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
bot.lock
madeline.phar*
*.madeline*
phar.php
madeline.php

View File

@ -1,153 +0,0 @@
<?php
/*
Copyright 2016-2017 Daniil Gentili
(https://daniil.it)
This file is part of MadelineProto.
MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License along with MadelineProto.
If not, see <http://www.gnu.org/licenses/>.
*/
class HttpProxy implements \danog\MadelineProto\Proxy
{
private $domain;
private $type;
private $protocol;
private $extra;
private $sock;
public function __construct($domain, $type, $protocol) {
if (!in_array($domain, [AF_INET, AF_INET6])) {
throw new \danog\MadelineProto\Exception('Wrong protocol family provided');
}
if (!in_array($type, [SOCK_STREAM])) {
throw new \danog\MadelineProto\Exception('Wrong connection type provided');
}
if (!in_array($protocol, [getprotobyname('tcp')])) {
throw new \danog\MadelineProto\Exception('Wrong protocol provided');
}
$this->domain = $domain;
$this->type = $type;
$this->protocol = $protocol;
}
public function setExtra($extra) {
$this->extra = $extra;
$this->sock = new \Socket(strlen(@inet_pton($this->extra['address'])) !== 4 ? \AF_INET6 : \AF_INET, \SOCK_STREAM, getprotobyname('tcp'));
}
public function setOption($level, $name, $value) {
return $this->sock->setOption($level, $name, $value);
}
public function getOption($level, $name) {
return $this->sock->getOption($level, $name);
}
public function setBlocking($blocking) {
return $this->sock->setBlocking($blocking);
}
public function bind($address, $port = 0) {
throw new \danog\MadelineProto\Exception('Not Implemented');
}
public function listen($backlog = 0) {
throw new \danog\MadelineProto\Exception('Not Implemented');
}
public function accept() {
throw new \danog\MadelineProto\Exception('Not Implemented');
}
public function select(array &$read, array &$write, array &$except, $tv_sec, $tv_usec = 0) {
throw new \danog\MadelineProto\Exception('Not Implemented');
}
public function connect($address, $port = 0) {
$this->sock->connect($this->extra['address'], $this->extra['port']);
try {
if (strlen(inet_pton($address)) !== 4) {
$address = '['.$address.']';
}
} catch (\danog\MadelineProto\Exception $e) {
}
$this->sock->write("CONNECT $address:$port HTTP/1.1\r\n\r\n");
$response = $this->read_http_payload();
if ($response['code'] !== 200) {
\danog\MadelineProto\Logger::log([$response['body']]);
throw new \danog\MadelineProto\Exception($response['description'], $response['code']);
}
\danog\MadelineProto\Logger::log(['Connected to '.$address.':'.$port.' via http']);
return true;
}
private function http_read($length) {
$packet = '';
while (strlen($packet) < $length) {
$packet .= $this->sock->read($length - strlen($packet));
if ($packet === false || strlen($packet) === 0) {
throw new \danog\MadelineProto\NothingInTheSocketException(\danog\MadelineProto\Lang::$current_lang['nothing_in_socket']);
}
}
return $packet;
}
public function read_http_line()
{
$line = '';
while (($curchar = $this->http_read(1)) !== "\n") {
$line .= $curchar;
}
return rtrim($line);
}
public function read_http_payload()
{
$header = explode(' ', $this->read_http_line(), 3);
$protocol = $header[0];
$code = (int) $header[1];
$description = $header[2];
$headers = [];
while (strlen($current_header = $this->read_http_line())) {
$current_header = explode(':', $current_header, 2);
$headers[strtolower($current_header[0])] = trim($current_header[1]);
}
$read = '';
if (isset($headers['content-length'])) {
$read = $this->http_read((int) $headers['content-length']);
}/* elseif (isset($headers['transfer-encoding']) && $headers['transfer-encoding'] === 'chunked') {
do {
$length = hexdec($this->read_http_line());
$read .= $this->http_read($length);
$this->read_http_line();
} while ($length);
}*/
return ['protocol' => $protocol, 'code' => $code, 'description' => $description, 'body' => $read, 'headers' => $headers];
}
public function read($length, $flags = 0) {
return $this->sock->read($length, $flags);
}
public function write($buffer, $length = -1) {
return $this->sock->write($buffer, $length);
}
public function send($data, $length, $flags) {
throw new \danog\MadelineProto\Exception('Not Implemented');
}
public function close() {
$this->sock->close();
}
public function getPeerName($port = true) {
throw new \danog\MadelineProto\Exception('Not Implemented');
}
public function getSockName($port = true) {
throw new \danog\MadelineProto\Exception('Not Implemented');
}
}

View File

@ -6,12 +6,9 @@ Per sapere come utilizzare questo codice, leggere la guida, oppure seguire quest
1. Creare spazio web altervista
2. Attivare cloudflare, https, s2s
3. Caricare file in sottocartella
4. Prendere api_id e api_hash da my.telegram.org
5. Settare le varie cose in \_config.php
6. Lanciare login.php e seguire le varie istruzioni (il caricamento è lento)
7. Lanciare updates.php e chiudere la pagina al termine del caricamento (che darà probabilmente errore 502)
3. Caricare bot.php
4. Lanciare bot.php e seguire le varie istruzioni (il primo caricamento è lento)
Per fare un nuovo login, usare una cartella diversa o cancellare il file check.log
Per fare un nuovo login, usare una cartella diversa o eliminare la sessione dalle impostazioni telegram.
Per supporto entrare nel gruppo Telegram.

View File

@ -1,61 +1,46 @@
<?php
/*
QUESTO FILE SERVE PER AVERE SEPARATI I COMANDI DELL'USERBOT
DAI FILE BASE DI FUNZIONAMENTO DELLO STESSO
*/
if(isset($userID) && in_array($userID, $lista_admin)) $isadmin = true;
else $isadmin = false;
if(isset($msg) && isset($chatID))
{
if($isadmin)
{
if($msg == "!on")
{
sm($chatID, "Hello world, I'm alive.");
}
if(stripos($msg, "!say ")===0)
{
sm($chatID, explode(" ", $msg, 2)[1]);
}
if($msg == "!off" and (time() - $lastser) > 5)
{
sm($chatID, "Mi spengo.");
exit;
}
if(stripos($msg, "!join ")===0)
{
joinChat(explode(" ", $msg, 2)[1], $chatID);
}
if($msg == "!leave" && stripos($chatID, "-100")===0)
{
abbandonaChat($chatID);
}
//ALTRI COMANDI RISERVATI AGLI ADMIN
}
//COMANDI DESTINATI AL PUBBLICO
}
<?php
include '_config.php';
/*
QUESTO FILE SERVE PER AVERE SEPARATI I COMANDI DELL'USERBOT
DAI FILE BASE DI FUNZIONAMENTO DELLO STESSO
*/
if (isset($userID) && in_array($userID, $lista_admin)) {
$isadmin = true;
} else {
$isadmin = false;
}
if (isset($msg) && isset($chatID)) {
if ($isadmin) {
if ($msg == '!on') {
sm($chatID, "Hello world, I'm alive.");
}
if ($msg == '!pony') {
sm($chatID, "This bot is powered by altervistabot & MadelineProto.\n\nCreated by a pony and a bruno.");
}
if (stripos($msg, '!say ') === 0) {
sm($chatID, explode(' ', $msg, 2)[1]);
}
if ($msg == '!off' and (time() - $started) > 5) {
sm($chatID, 'Mi spengo.');
exit;
}
if (stripos($msg, '!join ') === 0) {
joinChat(explode(' ', $msg, 2)[1], $chatID);
}
if ($msg == '!leave' && stripos($chatID, '-100') === 0) {
abbandonaChat($chatID);
}
//ALTRI COMANDI RISERVATI AGLI ADMIN
}
//COMANDI DESTINATI AL PUBBLICO
}

View File

@ -1,41 +1,9 @@
<?php
//li ottieni da my.telegram.org
$api_id = 12345;
$api_hash = 'ksdjfsdkjvksjvbdksvjdsv';
$numero_di_telefono = '123456789'; //devi inserire anche il prefisso nazionale senza +
$leggi_messaggi_in_uscita = false;
$lista_admin = [
40955937, //id di Bruno :D
12344567, //un id probabilmente inesistente
];
//header("Content-Type: text/plain");
ini_set('display_errors', TRUE);
error_reporting(E_ALL);
if (!file_exists('bot.lock')) {
touch('bot.lock');
}
$lock = fopen('bot.lock', 'r+');
flock($lock, LOCK_EX);
require __DIR__ . '/phar.php';
require __DIR__ . '/HttpProxy.php';
require __DIR__ . '/functions.php';
<?php
$leggi_messaggi_in_uscita = true;
$lista_admin = [
40955937, //id di Bruno :D
101374607, //id del creatore di MadelineProto :D
12344567, //un id probabilmente inesistente
];

1
av.version Normal file
View File

@ -0,0 +1 @@
2.0.11

2
basefiles Normal file
View File

@ -0,0 +1,2 @@
_comandi.php
_config.php

122
bot.php Normal file
View File

@ -0,0 +1,122 @@
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
chdir(__DIR__);
if (!file_exists(__DIR__.'/madeline.php') || !filesize(__DIR__.'/madeline.php')) {
copy('https://phar.madelineproto.xyz/madeline.php', __DIR__.'/madeline.php');
}
$remote = 'danog/AltervistaUserbot';
$branch = 'master';
$url = "https://raw.githubusercontent.com/$remote/$branch";
$version = file_get_contents("$url/av.version?v=new");
if (!file_exists(__DIR__.'/av.version') || file_get_contents(__DIR__.'/av.version') !== $version) {
foreach (explode("\n", file_get_contents("$url/files?v=new")) as $file) {
if ($file) {
copy("$url/$file?v=new", __DIR__."/$file");
}
}
foreach (explode("\n", file_get_contents("$url/basefiles?v=new")) as $file) {
if ($file && !file_exists(__DIR__."/$file")) {
copy("$url/$file?v=new", __DIR__."/$file");
}
}
}
if (!file_exists('bot.lock')) {
touch('bot.lock');
}
$lock = fopen('bot.lock', 'r+');
$try = 1;
$locked = false;
while (!$locked) {
$locked = flock($lock, LOCK_EX | LOCK_NB);
if (!$locked) {
closeConnection();
if ($try++ >= 30) {
exit;
}
sleep(1);
}
}
require __DIR__.'/madeline.php';
require __DIR__.'/functions.php';
require __DIR__.'/_config.php';
$MadelineProto = new \danog\MadelineProto\API('session.madeline', ['logger' => ['logger_level' => 5]]);
$MadelineProto->start();
register_shutdown_function('shutdown_function', $lock);
closeConnection();
$running = true;
$offset = 0;
$started = time();
try {
while ($running) {
$updates = $MadelineProto->get_updates(['offset' => $offset]);
foreach ($updates as $update) {
$offset = $update['update_id'] + 1;
if (isset($update['update']['message']['out']) && $update['update']['message']['out'] && !$leggi_messaggi_in_uscita) {
continue;
}
$up = $update['update']['_'];
if ($up == 'updateNewMessage' or $up == 'updateNewChannelMessage') {
if (isset($update['update']['message']['message'])) {
$msg = $update['update']['message']['message'];
}
try {
$chatID = $MadelineProto->get_info($update['update']);
$type = $chatID['type'];
$chatID = $chatID['bot_api_id'];
} catch (Exception $e) {
}
if (isset($update['update']['message']['from_id'])) {
$userID = $update['update']['message']['from_id'];
}
try {
require '_comandi.php';
} catch (Exception $e) {
if (isset($chatID)) {
try {
//sm($chatID, '<code>'.$e.'</code>');
} catch (Exception $e) {
}
}
}
}
if (isset($msg)) {
unset($msg);
}
if (isset($chatID)) {
unset($chatID);
}
if (isset($userID)) {
unset($userID);
}
if (isset($up)) {
unset($up);
}
}
}
} catch (\danog\MadelineProto\RPCErrorException $e) {
\danog\MadelineProto\Logger::log((string) $e);
if (in_array($e->rpc, ['SESSION_REVOKED', 'AUTH_KEY_UNREGISTERED'])) {
foreach (glob('session.madeline*') as $path) {
unlink($path);
}
}
}

4
files Normal file
View File

@ -0,0 +1,4 @@
functions.php
bot.php
LICENSE
av.version

View File

@ -1,89 +1,72 @@
<?php
function failLogin()
{
echo "<h1>LOGIN FALLITO</h1>";
}
function failUpdates()
{
echo "<h1>USERBOT NON AVVIATO. RIAVVIO.</h1>";
file_get_contents($_SERVER['SCRIPT_URI']);
}
function finePagina(){
return true;
}
function endUpdates()
{
file_get_contents($_SERVER['SCRIPT_URI']);
echo "Timeout, lanciato nuovo script.";
}
function sm($chatID, $text, $parsemode = 'HTML', $reply = 0) {
global $MadelineProto;
if ($reply) $MadelineProto->messages->sendMessage(['peer' => $chatID, 'message' => $text, 'parse_mode' => $parsemode, 'reply_to_msg_id' => $reply]);
else $MadelineProto->messages->sendMessage(['peer' => $chatID, 'message' => $text, 'parse_mode' => $parsemode]);
}
function setProfilo($nome, $cognome = '')
{
global $MadelineProto;
$MadelineProto->account->updateProfile(['first_name' => $nome, 'last_name' => $cognome]);
}
function joinChat($chatLink, $chatLOG)
{
//ACCETTA SOLO https://t.me/joinchat/ksjdvbdskvhbsdk o @usernameChat in questo formato
global $MadelineProto;
try{
if(stripos($chatLink, "joinchat"))
{
$MadelineProto->messages->importChatInvite([
'hash' => str_replace("https://t.me/joinchat/", "", $chatLink)
]);
}else{
$MadelineProto->channels->joinChannel([
'channel' => "@" . str_replace("@", "", $chatLink)
]);
}
sm($chatLOG, "Sono entrato nel canale/gruppo");
} catch (\danog\MadelineProto\RPCErrorException $e) {
sm($chatLOG, "NON sono entrato nel canale/gruppo.");
} catch (\danog\MadelineProto\Exception $e2) {
sm($chatLOG, "NON sono entrato nel canale/gruppo.");
}
}
function abbandonaChat($chatID)
{
//USARE SOLO SU SUPERGRUPPI o CRASH
global $MadelineProto;
$MadelineProto->channels->leaveChannel(['channel' => $chatID]);
}
?>
<?php
function closeConnection($message = 'OK!')
{
if (php_sapi_name() === 'cli') {
return;
}
ob_end_clean();
header('Connection: close');
ignore_user_abort(true);
ob_start();
echo '<html><body><h1>'.$message.'</h1></body</html>';
$size = ob_get_length();
header("Content-Length: $size");
header('Content-Type: text/html');
ob_end_flush();
flush();
}
function shutdown_function($lock)
{
$a = fsockopen((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] ? 'tls' : 'tcp').'://'.$_SERVER['SERVER_NAME'], $_SERVER['SERVER_PORT']);
fwrite($a, $_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL']."\r\n".'Host: '.$_SERVER['SERVER_NAME']."\r\n\r\n");
flock($lock, LOCK_UN);
fclose($lock);
}
function sm($chatID, $text, $parsemode = 'HTML', $reply = 0)
{
global $MadelineProto;
if ($reply) {
$MadelineProto->messages->sendMessage(['peer' => $chatID, 'message' => $text, 'parse_mode' => $parsemode, 'reply_to_msg_id' => $reply]);
} else {
$MadelineProto->messages->sendMessage(['peer' => $chatID, 'message' => $text, 'parse_mode' => $parsemode]);
}
}
function setProfilo($nome, $cognome = '')
{
global $MadelineProto;
$MadelineProto->account->updateProfile(['first_name' => $nome, 'last_name' => $cognome]);
}
function joinChat($chatLink, $chatLOG)
{
//ACCETTA SOLO https://t.me/joinchat/ksjdvbdskvhbsdk o @usernameChat in questo formato
global $MadelineProto;
try {
if (stripos($chatLink, 'joinchat')) {
$MadelineProto->messages->importChatInvite([
'hash' => str_replace('https://t.me/joinchat/', '', $chatLink),
]);
} else {
$MadelineProto->channels->joinChannel([
'channel' => '@'.str_replace('@', '', $chatLink),
]);
}
sm($chatLOG, 'Sono entrato nel canale/gruppo');
} catch (\danog\MadelineProto\RPCErrorException $e) {
sm($chatLOG, 'NON sono entrato nel canale/gruppo.');
} catch (\danog\MadelineProto\Exception $e2) {
sm($chatLOG, 'NON sono entrato nel canale/gruppo.');
}
}
function abbandonaChat($chatID)
{
//USARE SOLO SU SUPERGRUPPI/CANALI o CRASH
global $MadelineProto;
$MadelineProto->channels->leaveChannel(['channel' => $chatID]);
}

View File

@ -1,70 +0,0 @@
<?php
$check = file_get_contents("check.log");
if($check)
{
echo "<h1>Gi&agrave; loggato. Per nuovo login, elimina il file check.log e aggiorna questa pagina.</h1>";
exit;
}
register_shutdown_function('failLogin');
require '_config.php';
if(isset($_POST["code"])){
$MadelineProto = new \danog\MadelineProto\API("session.madeline");
$MadelineProto->complete_phone_login($_POST["code"]);
if(isset($_POST["pwd2fa"]) && $_POST["pwd2fa"])
{
sleep(1);
$MadelineProto->complete_2fa_login($_POST["pwd2fa"]);
}
echo "<center><h1><br /><br />LOGIN EFFETTUATO</h1><br /><br /><h2><a href='updates.php'>AVVIA USERBOT</a></h2></center>";
file_put_contents("check.log", "ok");
$MadelineProto->serialize();
register_shutdown_function('finePagina');
exit;
}else{
$MadelineProto = new \danog\MadelineProto\API([
'app_info' => [
'api_id' => $api_id,
'api_hash' => $api_hash
],
'connection_settings' => [
'all' => [
'protocol' => 'http',
'pfs' => false,
'proxy' => '\\HttpProxy',
'proxy_extra' => [
'address' => 'localhost',
'port' => 80
]
]
],
'logger' => [
'logger' => 2,
'logger_param' => __DIR__.'/Madeline.log',
'logger_level' => 5
]
]);
$MadelineProto->session = __DIR__.'/session.madeline';
$MadelineProto->phone_login($numero_di_telefono);
$MadelineProto->serialize();
register_shutdown_function('finePagina');
?>
<center>
<h1>Ok stai facendo il login dell'account con numero +<?=$numero_di_telefono; ?></h1>
<form action="#" method="post">
<b>CODICE SMS/TELEGRAM RICEVUTO</b><br />
<input type="number" name="code" />
<br /><br /><b>EVENTUALE PASSWORD 2FA (lasciare vuoto se non impostata)</b><br />
<input type="password" name="pwd2fa" />
<br />
<input type="submit" name="submit" value="LOGIN!" />
</form>
</center>
<?php
exit;
}

View File

@ -1,10 +0,0 @@
<?php
if (!file_exists('madeline.phar')) {
file_put_contents('madeline.phar', file_get_contents('https://phar.madelineproto.xyz/madeline.phar?v=new'));
}
require 'madeline.phar';
if (trim(file_get_contents('phar://madeline.phar/.git/refs/heads/master')) !== trim(file_get_contents('https://phar.madelineproto.xyz/release?v=new'))) {
file_put_contents('madeline.phar', file_get_contents('https://phar.madelineproto.xyz/madeline.phar?v=new'));
}

View File

@ -1,75 +0,0 @@
<?php
file_put_contents("check.log", "ok");
require '_config.php';
register_shutdown_function('failUpdates');
$MadelineProto = new \danog\MadelineProto\API("session.madeline");
$MadelineProto->session = __DIR__.'/session.madeline';
register_shutdown_function('endUpdates');
echo "<h1>USERBOT PARTITO</h1>";
$running = true;
$offset = 0;
$lastser = time();
while($running)
{
$updates = $MadelineProto->get_updates(['offset' => $offset]);
foreach($updates as $update)
{
$offset = $update['update_id'] + 1;
if (isset($update['update']['message']['out']) && $update['update']['message']['out'] && !$leggi_messaggi_in_uscita) {
continue;
}
$up = $update['update']['_'];
if($up == 'updateNewMessage' or $up == 'updateNewChannelMessage')
{
if (isset($update['update']['message']['message'])){
$msg = $update["update"]["message"]["message"];
}
if (isset($update['update']['message']['to_id']['channel_id'])) {
$chatID = $update['update']['message']['to_id']['channel_id'];
$chatID = '-100'.$chatID;
$type = "supergruppo";
}
if (isset($update['update']['message']['to_id']['chat_id'])) {
$chatID = $update['update']['message']['to_id']['chat_id'];
$chatID = '-'.$chatID;
$type = "gruppo";
}
if (isset($update['update']['message']['from_id'])) $userID = $update['update']['message']['from_id'];
if (isset($update['update']['message']['to_id']['user_id'])) {
$chatID = $update['update']['message']['from_id'];
$type = "privato";
}
try {
require "_comandi.php";
} catch(Exception $e) {
if (isset($chatID)) {
try {
sm($chatID,'<code>'.$e.'</code>');
} catch(Exception $e) { }
}
}
}
if(isset($msg)) unset($msg);
if(isset($chatID)) unset($chatID);
if(isset($userID)) unset($userID);
if(isset($up)) unset($up);
}
}