Added single-threaded and multi-threaded example

This commit is contained in:
Netkas 2023-02-20 21:27:43 -05:00
parent da6abceed2
commit 040426a63c
9 changed files with 110 additions and 15 deletions

10
tests/autoload.php Normal file
View file

@ -0,0 +1,10 @@
<?php
// Import ncc
require 'ncc';
import('net.nosial.tgbotlib');
// Require commands & event handlers
require 'commands' . DIRECTORY_SEPARATOR . 'StartCommand.php';
require 'commands' . DIRECTORY_SEPARATOR . 'HashCommand.php';

View file

@ -0,0 +1,26 @@
<?php
namespace commands;
use TgBotLib\Bot;
use TgBotLib\Exceptions\TelegramException;
use TgBotLib\Interfaces\CommandInterface;
use TgBotLib\Objects\Telegram\Update;
class HashCommand implements CommandInterface
{
/**
* @param Bot $bot
* @param Update $update
* @return void
* @throws TelegramException
*/
public function handle(Bot $bot, Update $update): void
{
// Usage: /hash <text>
$data = str_replace('/hash ', '', $update->getMessage()->getText());
$bot->sendMessage(
$update->getMessage()->getChat()->getId(), md5($data)
);
}
}

View file

@ -1,14 +0,0 @@
<?php
require 'ncc';
import('net.nosial.tgbotlib');
require 'commands/StartCommand.php';
$bot = new TgBotLib\Bot('865804194:AAHTo9aIFP5X47dMYLJ6eoldHJnM6sc3LBc');
$bot->setCommandHandler('start', new \commands\StartCommand());
print_r(json_encode($bot->getMe()->toArray()) . PHP_EOL);
$bot->sendMessage(570787098, 'Hello, world!');
$bot->handleGetUpdates();
unset($bot);

19
tests/multi_threaded.php Normal file
View file

@ -0,0 +1,19 @@
<?php
require __DIR__ . DIRECTORY_SEPARATOR . 'autoload.php';
import('net.nosial.tamerlib');
$bot = new TgBotLib\Bot(getenv('BOT_TOKEN'));
TamerLib\Tamer::init(\TamerLib\Abstracts\ProtocolType::Gearman, ['127.0.0.1:4730']);
TamerLib\Tamer::addWorker(__DIR__ . DIRECTORY_SEPARATOR . 'worker.php', 10);
var_dump('Starting workers');
TamerLib\Tamer::startWorkers();
while(true)
{
foreach($bot->getUpdates() as $update)
{
TamerLib\Tamer::do(TamerLib\Objects\Task::create('handle_update', json_encode($update->toArray())));
}
}

10
tests/single_threaded.php Normal file
View file

@ -0,0 +1,10 @@
<?php
require __DIR__ . DIRECTORY_SEPARATOR . 'autoload.php';
$bot = new TgBotLib\Bot(getenv('BOT_TOKEN'));
$bot->setCommandHandler('start', new \commands\StartCommand());
$bot->setCommandHandler('hash', new \commands\HashCommand());
$bot->handleGetUpdates(true);

18
tests/worker.php Normal file
View file

@ -0,0 +1,18 @@
<?php
require __DIR__ . DIRECTORY_SEPARATOR . 'autoload.php';
import('net.nosial.tamerlib');
$bot = new TgBotLib\Bot('865804194:AAHTo9aIFP5X47dMYLJ6eoldHJnM6sc3LBc');
$bot->setCommandHandler('start', new \commands\StartCommand());
$bot->setCommandHandler('hash', new \commands\HashCommand());
TamerLib\Tamer::initWorker();
TamerLib\Tamer::addFunction('handle_update', function (\TamerLib\Objects\Job $job) use ($bot)
{
$bot->handleUpdate(\TgBotLib\Objects\Telegram\Update::fromArray(json_decode($job->getData(), true)));
});
TamerLib\Tamer::work();