Come creare un bot telegram in PHP GRATIS [Parte 2]

In questa guida composta da 3 parti andremo a vedere:

  • Come creare un bot telegram, e ottenere accesso all’API di Telegram [CLICCA QUA]
  • Come scrivere il nostro bot in PHP, e fargli gestire i messaggi e i file [QUESTA LEZIONE]
  • Dove hostare il nostro bot gratis. [CLICCA QUA]

Siamo arrivati alla fase principale, la seconda, ovvero la stesura del codice.

Ci sono tanti strumenti da usare per creare un bot Telegram in PHP. Possiamo gestire da soli la comunicazione con l’API di telegram seguendo questo lunghissima guida e questa documentazione, ma ritemo che sia eccessivamente complicato. Infatti, basta usare una libreria come NovaGram, MadelineProto, oppure PHP-Telegram-Bot.

Per questa guida useremo MadelineProto.

Bot d’esempio

Questo bot ripetera ogni cosa che gli inviate. In gergo tecnico si chiama Echobot.

<?php
use Amp\Loop;
use danog\MadelineProto\Db\DbArray;
use danog\MadelineProto\EventHandler;
use danog\MadelineProto\Logger;
use danog\MadelineProto\Settings;
use danog\MadelineProto\Settings\Database\Mysql;
use danog\MadelineProto\Settings\Database\Postgres;
use danog\MadelineProto\Settings\Database\Redis;
use danog\MadelineProto\Settings\Database\Sqlite;

if (!\file_exists('madeline.php')) {
    \copy('https://phar.madelineproto.xyz/madeline.php', 'madeline.php');
}
include 'madeline.php';

class MyEventHandler extends EventHandler
{
    const ADMIN = "VOSTRO USERNAME"; // Change this
    public function getReportPeers(){ return [self::ADMIN]; }
    public function onUpdateNewChannelMessage(array $update): \Generator
    {
        return $this->onUpdateNewMessage($update);
    }

    public function onUpdateNewMessage(array $update): \Generator
    {
        if (!isset($update["message"]["message"]) || $update['message']['_'] === 'messageEmpty' || $update['message']['out'] ?? false) {
            return;
        }

        yield $this->messages->sendMessage(['peer' => $update, 'message' => $update["message"]["message"], 'reply_to_msg_id' => isset($update['message']['id']) ? $update['message']['id'] : null]);
    }
}

$settings = new Settings;
$settings->getLogger()->setLevel(Logger::WARNING);
MyEventHandler::startAndLoop('bot.madeline', $settings);

Ora che abbiamo il progetto del bot in locale dobbiamo capire come metterlo su un server e lasciarlo 24/7. Basta seguirmi nella terza lezione!