1
0
mirror of https://github.com/danog/MadelineProto.git synced 2024-11-30 10:38:59 +01:00
MadelineProto/examples/bot.php

229 lines
8.6 KiB
PHP
Raw Normal View History

2023-01-20 19:21:13 +01:00
<?php declare(strict_types=1);
2019-10-28 22:39:23 +01:00
/**
* Example bot.
*
2020-02-17 14:13:46 +01:00
* Copyright 2016-2020 Daniil Gentili
2019-10-28 22:39:23 +01:00
* (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/>.
*
* @author Daniil Gentili <daniil@daniil.it>
2023-01-04 12:43:01 +01:00
* @copyright 2016-2023 Daniil Gentili <daniil@daniil.it>
2019-10-28 22:39:23 +01:00
* @license https://opensource.org/licenses/AGPL-3.0 AGPLv3
2019-10-31 15:07:35 +01:00
* @link https://docs.madelineproto.xyz MadelineProto documentation
2019-10-28 22:39:23 +01:00
*/
2023-05-07 21:06:34 +02:00
use danog\MadelineProto\Broadcast\Progress;
use danog\MadelineProto\Broadcast\Status;
2021-09-05 19:28:22 +02:00
use danog\MadelineProto\Db\DbArray;
use danog\MadelineProto\EventHandler;
2020-02-26 14:14:26 +01:00
use danog\MadelineProto\Logger;
use danog\MadelineProto\Settings;
2023-01-19 15:48:56 +01:00
use danog\MadelineProto\Settings\Database\Mysql;
use danog\MadelineProto\Settings\Database\Postgres;
use danog\MadelineProto\Settings\Database\Redis;
2023-05-02 18:48:02 +02:00
use danog\MadelineProto\Settings\Database\SerializerType;
// If a stable version of MadelineProto was installed via composer, load composer autoloader
2022-12-08 20:16:40 +01:00
if (file_exists('vendor/autoload.php')) {
require_once 'vendor/autoload.php';
2019-10-28 22:39:23 +01:00
} else {
// Otherwise download an alpha version of MadelineProto via madeline.php
2022-12-08 20:16:40 +01:00
if (!file_exists('madeline.php')) {
copy('https://phar.madelineproto.xyz/madeline.php', 'madeline.php');
2019-10-28 22:39:23 +01:00
}
require_once 'madeline.php';
2019-10-28 22:39:23 +01:00
}
/**
* Event handler class.
*/
2023-04-23 14:32:38 +02:00
class MyEventHandler extends EventHandler
2019-10-28 22:39:23 +01:00
{
/**
* @var int|string Username or ID of bot admin
*/
2023-05-02 17:50:48 +02:00
const ADMIN = "@me"; // !!! Change this to your username !!!
2021-09-05 19:28:22 +02:00
/**
* List of properties automatically stored in database (MySQL, Postgres, redis or memory).
2022-12-30 21:54:44 +01:00
*
2023-05-07 21:06:34 +02:00
* Note that **all** class properties will be stored in the database, regardless of whether they're specified here.
* The only difference is that properties *not* specified in this array will also always have a full copy in RAM.
*
* Also, properties specified in this array are NOT thread-safe, meaning you should also use a synchronization primitive
2023-05-07 21:06:34 +02:00
* from https://github.com/amphp/sync/ to use them in a thread-safe manner (i.e. when checking-and-setting with isset=>set, et cetera).
*
* Remember: **ALL** onUpdate... handler methods are called in separate green threads, so at the end of the day,
* unless your property is too large to be comfortably stored in memory (say >100MB), you should use normal properties to avoid race conditions.
*
2021-09-05 19:28:22 +02:00
* @see https://docs.madelineproto.xyz/docs/DATABASE.html
*/
protected static array $dbProperties = [
2023-05-02 18:48:02 +02:00
'dataStoredOnDb' => ['serializer' => SerializerType::SERIALIZE],
2021-09-05 19:28:22 +02:00
];
/**
2023-05-07 21:06:34 +02:00
* Use this *only* if the data you will store here is huge (>100MB).
2023-01-19 17:14:04 +01:00
* @var DbArray<array-key, array>
2021-09-05 19:28:22 +02:00
*/
protected DbArray $dataStoredOnDb;
2023-05-07 21:06:34 +02:00
/**
* Otherwise use this.
* This property is also saved in the db, but it's also always kept in memory, unlike $dataStoredInDb which is exclusively stored in the db.
*/
protected array $dataAlsoStoredOnDbAndInRam = [];
2023-01-19 17:14:04 +01:00
/**
2023-03-26 19:16:50 +02:00
* This property is also saved in the db, but it's also always kept in memory, unlike $dataStoredInDb which is exclusively stored in the db.
* @var array<int, bool>
2023-01-19 17:14:04 +01:00
*/
2023-03-26 19:16:50 +02:00
protected array $notifiedChats = [];
2021-09-05 19:28:22 +02:00
2023-05-07 21:06:34 +02:00
/**
* This property is also saved in the db, but it's also always kept in memory, unlike $dataStoredInDb which is exclusively stored in the db.
*/
private int $adminId;
/**
* Get peer(s) where to report errors.
*
* @return int|string|array
*/
public function getReportPeers()
{
return [self::ADMIN];
}
2022-05-01 19:59:07 +02:00
/**
* Initialization logic.
*/
2023-01-16 13:17:59 +01:00
public function onStart(): void
2022-05-01 19:59:07 +02:00
{
$this->logger("The bot was started!");
2023-01-16 13:17:59 +01:00
$this->logger($this->getFullInfo('MadelineProto'));
$this->adminId = $this->getId(self::ADMIN);
2023-04-22 20:32:39 +02:00
2023-05-07 21:06:34 +02:00
if ($this->getSelf()['bot'] && $this->getSelf()['id'] === $this->adminId) {
return;
}
2023-04-22 20:32:39 +02:00
$this->messages->sendMessage(
peer: self::ADMIN,
message: "The bot was started!"
);
2022-05-01 19:59:07 +02:00
}
2023-05-07 21:06:34 +02:00
private int $lastLog = 0;
/**
* Handles updates to an in-progress broadcast.
*/
public function onUpdateBroadcastProgress(Progress $progress): void
{
if (time() - $this->lastLog > 5 || $progress->status === Status::FINISHED) {
$this->lastLog = time();
$this->messages->sendMessage(
peer: self::ADMIN,
message: (string) $progress
);
}
}
2020-11-25 19:38:24 +01:00
/**
* Handle updates from supergroups and channels.
*
* @param array $update Update
*/
2023-01-16 13:17:59 +01:00
public function onUpdateNewChannelMessage(array $update): void
2020-11-25 19:38:24 +01:00
{
2023-01-16 13:17:59 +01:00
$this->onUpdateNewMessage($update);
2019-10-28 22:39:23 +01:00
}
2021-09-05 19:28:22 +02:00
/**
* Handle updates from users.
*
2023-04-27 15:55:10 +02:00
* 100+ other types of onUpdate... method types are available, see https://docs.madelineproto.xyz/API_docs/types/Update.html for the full list.
* You can also use onAny to catch all update types (only for debugging)
* A special onUpdateCustomEvent method can also be defined, to send messages to the event handler from an API instance, using the sendCustomEvent method.
*
* @param array $update Update
*/
2023-01-16 13:17:59 +01:00
public function onUpdateNewMessage(array $update): void
2019-10-28 22:39:23 +01:00
{
if ($update['message']['_'] === 'messageEmpty') {
2020-11-25 19:38:24 +01:00
return;
}
2023-01-19 15:48:56 +01:00
$this->logger($update);
2023-01-19 17:14:04 +01:00
// Chat ID
2023-01-19 17:14:04 +01:00
$id = $this->getId($update);
2022-08-09 19:08:24 +02:00
// Sender ID, not always present
$from_id = isset($update['message']['from_id'])
? $this->getId($update['message']['from_id'])
: null;
2023-01-27 14:20:47 +01:00
// In this example code, send the "This userbot is powered by MadelineProto!" message only once per chat.
// Ignore all further messages coming from this chat.
2023-01-19 17:14:04 +01:00
if (!isset($this->notifiedChats[$id])) {
2023-01-22 13:00:48 +01:00
$this->notifiedChats[$id] = true;
2023-01-19 17:14:04 +01:00
$this->messages->sendMessage(
peer: $update,
message: "This userbot is powered by [MadelineProto](https://t.me/MadelineProto)!",
reply_to_msg_id: $update['message']['id'] ?? null,
parse_mode: 'Markdown'
);
}
2023-01-19 17:14:04 +01:00
// If the message is a /restart command from an admin, restart to reload changes to the event handler code.
if (($update['message']['message'] ?? '') === '/restart'
&& $from_id === $this->adminId
) {
// Make sure to run in a bash while loop when running via CLI to allow self-restarts.
$this->restart();
2023-01-19 17:14:04 +01:00
}
2021-09-05 19:28:22 +02:00
2023-05-07 21:06:34 +02:00
// We can broadcast messages to all users.
if ($update['message']['message'] === '/broadcast'
&& $from_id === $this->adminId
) {
if (!isset($update['message']['reply_to']['reply_to_msg_id'])) {
$this->messages->sendMessage(
peer: $update,
message: "You should reply to the message you want to broadcast.",
reply_to_msg_id: $update['message']['id'] ?? null,
);
return;
}
$this->broadcastForwardMessages(
from_peer: $update,
2023-06-02 18:56:53 +02:00
message_ids: [$update['message']['reply_to']['reply_to_msg_id']],
2023-05-07 21:06:34 +02:00
drop_author: true,
);
return;
2021-09-05 19:28:22 +02:00
}
2023-05-07 21:06:34 +02:00
if (($update['message']['message'] ?? '') === 'ping') {
$this->messages->sendMessage(['message' => 'pong', 'peer' => $update]);
2021-09-05 19:28:22 +02:00
}
2019-10-28 22:39:23 +01:00
}
}
$settings = new Settings;
$settings->getLogger()->setLevel(Logger::LEVEL_ULTRA_VERBOSE);
2020-10-23 18:07:18 +02:00
// You can also use Redis, MySQL or PostgreSQL
2020-11-26 21:50:06 +01:00
// $settings->setDb((new Redis)->setDatabase(0)->setPassword('pony'));
2020-10-23 18:07:18 +02:00
// $settings->setDb((new Postgres)->setDatabase('MadelineProto')->setUsername('daniil')->setPassword('pony'));
// $settings->setDb((new Mysql)->setDatabase('MadelineProto')->setUsername('daniil')->setPassword('pony'));
2019-10-28 22:39:23 +01:00
// For users or bots
2023-04-23 14:32:38 +02:00
MyEventHandler::startAndLoop('bot.madeline', $settings);
// For bots only
2023-04-23 14:32:38 +02:00
// MyEventHandler::startAndLoopBot('bot.madeline', 'bot token', $settings);