Core: How i can preg_match message and execute command?

Created on 16 Jan 2017  路  15Comments  路  Source: php-telegram-bot/core

Required Information

  • PHP version: 7.0
  • PHP Telegram Bot version:
  • Using MySQL database: no
  • Update Method: Webhook
  • Self-signed certificate: no
  • RAW update (if available):

Hello. How i can preg_match message - example:
馃帴 Today in Cinema

Code:

preg_match("馃帴", $text , $matches);

and execute command or simple my code?

I do KinoCommand.php - but button's not beaty if set command (/kinotoday, /kinotomorrow and etc).

I set privacy off.

Most helpful comment

When not using DB you must place the code in executeNoDb() function, not execute() in GenericmessageCommand.

All 15 comments

If I understand correctly you want to execute a command when someone message contains this emoji?

preg_match expects regex.

$message = $this->getMessage();

if (strpos($message, "馃帴") !== false) {
    return $this->getTelegram()->executeCommand("kino");
}

Is this what you want?

Yes - i correct ')' in preg_match, but no work:

```

namespace Longman\TelegramBot\Commands\SystemCommands;

use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Commands\SystemCommand;

/**

  • Generic message command
    /
    class GenericmessageCommand extends SystemCommand
    {
    /
    *

    • @var string

      */

      protected $name = 'Genericmessage';

/**
 * @var string
 */
protected $description = 'Handle generic message';

/**
 * @var string
 */
protected $version = '1.1.0';

/**
 * @var bool
 */
protected $need_mysql = true;

/**
 * Execution if MySQL is required but not available
 *
 * @return \Longman\TelegramBot\Entities\ServerResponse
 */
public function executeNoDb()
{
    //Do nothing
    return Request::emptyResponse();
}

/**
 * Execute command
 *
 * @return \Longman\TelegramBot\Entities\ServerResponse
 * @throws \Longman\TelegramBot\Exception\TelegramException
 */
public function execute()
{
    //If a conversation is busy, execute the conversation command after handling the message
    $conversation = new Conversation(
        $this->getMessage()->getFrom()->getId(),
        $this->getMessage()->getChat()->getId()
    );
    //Fetch conversation command if it exists and execute it
    if ($conversation->exists() && ($command = $conversation->getCommand())) {
        return $this->telegram->executeCommand($command);
    }

    $message = $this->getMessage();

    if (preg_match("test", $message)) {
      return $this->getTelegram()->executeCommand("help");
    }

    return Request::emptyResponse();
}

}
```

if (preg_match("test", $message)) {
          return $this->getTelegram()->executeCommand("help");
        }

and I tested - not work:

 $message = $this->getMessage();

        if ($message == 'test') {
          return $this->getTelegram()->executeCommand("help");
        }

if (preg_match("馃帴", $message) {

It could be that php doesn't check the charset. its utf8mb4 as far as i remember from my chat script.
http://stackoverflow.com/questions/16496554/can-php-detect-4-byte-encoded-utf8-chars
EDIT: yes, i know its related to mysql and you dont use it, but it could be a point still

Another EDIT;
could you please tell us what
$message = $this->getMessage(); var_dump($message); if ($message == 'test') { return $this->getTelegram()->executeCommand("help"); }
says?

Absolutely go for strpos, nothing with regex for something this simple.

Have you tried it?

Also, to get the actual text of the message, you need to do:

$text = trim($this->getMessage()->getText(true));

I try your code, but not work it :sob:

GenericmessageCommand.php

I tested this - not work:

    public function execute()
    {
        //If a conversation is busy, execute the conversation command after handling the message
        $conversation = new Conversation(
            $this->getMessage()->getFrom()->getId(),
            $this->getMessage()->getChat()->getId()
        );
        //Fetch conversation command if it exists and execute it
        if ($conversation->exists() && ($command = $conversation->getCommand())) {
            return $this->telegram->executeCommand($command);
        }

        $text = trim($this->getMessage->getText(true));
        $chat_id = $this->getMessage()->getChat()->getId();

        if (strpos($text, "test") !== false) {

            $text = PHP_EOL . 'TEST MESSAGE TEST';
            $data = [
                'chat_id' => $chat_id,
                'text'    => $text,
            ];

            return Request::sendMessage($data);

        }

        return Request::emptyResponse();
    }

}

Try this - not work for me:

        $text = trim($this->getMessage->getText(true));

        if ($text == "test") {
            return $this->getTelegram()->executeCommand("help");

        }

And this - not work:

    public function execute()
    {
        //If a conversation is busy, execute the conversation command after handling the message
        $conversation = new Conversation(
            $this->getMessage()->getFrom()->getId(),
            $this->getMessage()->getChat()->getId()
        );
        //Fetch conversation command if it exists and execute it
        if ($conversation->exists() && ($command = $conversation->getCommand())) {
            return $this->telegram->executeCommand($command);
        }

$message = $this->getMessage();

if (strpos($message, "馃帴") !== false) {
    return $this->getTelegram()->executeCommand("kino");
}

        return Request::emptyResponse();

    }

Privacy mode - off. What I can do? please :sad:

My mistake, it should be:

$text = trim($this->getMessage()->getText(true));
if ($text == "test") {
    return $this->getTelegram()->executeCommand("help");
}

Forgot the () after getMessage.

Try again please.

I try:

    public function execute()
    {
        //If a conversation is busy, execute the conversation command after handling the message
        $conversation = new Conversation(
            $this->getMessage()->getFrom()->getId(),
            $this->getMessage()->getChat()->getId()
        );
        //Fetch conversation command if it exists and execute it
        if ($conversation->exists() && ($command = $conversation->getCommand())) {
            return $this->telegram->executeCommand($command);
        }

$text = trim($this->getMessage()->getText(true));
if ($text == "test") {
    return $this->getTelegram()->executeCommand("help");
}

        return Request::emptyResponse();

    }

}

but, not work :-1: I sad :smile_cat: It's real do this?

Do you get any output?

Instead of just returning an empty response, try this at the end:

      return Request::sendMessage([
          'chat_id' => $this->getMessage()->getChat()->getId(),
          'text'    => $text,
      ]);

That should simply echo any input. Does this work?

Also, do you have the error log enabled? If so, check if there is something of interest there.

Nothing.

I set:

    // Error, Debug and Raw Update logging
    Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance);
    Longman\TelegramBot\TelegramLog::initErrorLog(__DIR__ . '/' . $BOT_NAME . '_error.log');
    Longman\TelegramBot\TelegramLog::initDebugLog(__DIR__ . '/' . $BOT_NAME . '_debug.log');
    Longman\TelegramBot\TelegramLog::initUpdateLog(__DIR__ . '/' . $BOT_NAME . '_update.log');

In the file cinema_park_bot._update.log:
Fine all message:

{"update_id":5506789, "message":{"message_id":1793,"from":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA"},"chat":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA","type":"private"},"date":1484681117,"text":"/Kino \u0421\u0435\u0433\u043e\u0434\u043d\u044f \ud83c\udfa5","entities":[{"type":"bot_command","offset":0,"length":5}]}}
{"update_id":5506790, "message":{"message_id":1795,"from":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA"},"chat":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA","type":"private"},"date":1484681119,"text":"/Kino \u0421\u0432\u043e\u0434\u043a\u0430 \ud83d\udcc5","entities":[{"type":"bot_command","offset":0,"length":5}]}}
{"update_id":5506791, "message":{"message_id":1797,"from":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA"},"chat":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA","type":"private"},"date":1484681143,"text":"test"}}
{"update_id":5506792, "message":{"message_id":1798,"from":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA"},"chat":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA","type":"private"},"date":1484681146,"text":"test"}}
{"update_id":5506793, "message":{"message_id":1799,"from":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA"},"chat":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA","type":"private"},"date":1484681152,"text":"test"}}
{"update_id":5506794, "message":{"message_id":1800,"from":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA"},"chat":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA","type":"private"},"date":1484681170,"text":"text"}}
{"update_id":5506795, "message":{"message_id":1801,"from":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA"},"chat":{"id":163457759,"first_name":"\u0415\u0432\u0433\u0435\u043d\u0438\u0439","last_name":"\u041a\u043e\u043f\u044b\u043b\u043e\u0432","username":"CB9TOIIIA","type":"private"},"date":1484681171,"text":"test"}}

Full file GenericmessageCommand.php:

<?php
/**
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Longman\TelegramBot\Commands\SystemCommands;

use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Commands\SystemCommand;

/**
 * Generic message command
 */
class GenericmessageCommand extends SystemCommand
{
    /**
     * @var string
     */
    protected $name = 'Genericmessage';

    /**
     * @var string
     */
    protected $description = 'Handle generic message';

    /**
     * @var string
     */
    protected $version = '1.1.0';

    /**
     * @var bool
     */
    protected $need_mysql = true;

    /**
     * Execution if MySQL is required but not available
     *
     * @return \Longman\TelegramBot\Entities\ServerResponse
     */
    public function executeNoDb()
    {
        //Do nothing
        return Request::emptyResponse();
    }

    /**
     * Execute command
     *
     * @return \Longman\TelegramBot\Entities\ServerResponse
     * @throws \Longman\TelegramBot\Exception\TelegramException
     */
    public function execute()
    {

$text == "test";
    return Request::sendMessage([
          'chat_id' => $this->getMessage()->getChat()->getId(),
          'text'    => $text,
      ]);

    }

}

Noting sent.

First of all, remove this line:

Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance);

Could you post your hook.php file please?
Remember to remove your API key and bot name!

<?php
/**
 * README
 * This configuration file is intended to run the bot with the webhook method.
 * Uncommented parameters must be filled
 *
 * Please note that if you open this file with your browser you'll get the "Input is empty!" Exception.
 * This is a normal behaviour because this address has to be reached only by Telegram server.
 */

// Load composer
require __DIR__ . '/vendor/autoload.php';

// Add you bot's API key and name
$API_KEY = 'MY_KEY';
$BOT_NAME = 'MY_BOT_NAME.';

// Define a path for your custom commands
//$commands_path = __DIR__ . '/Commands/';

// Enter your MySQL database credentials
//$mysql_credentials = [
//    'host'     => 'localhost',
//    'user'     => 'dbuser',
//    'password' => 'dbpass',
//    'database' => 'dbname',
//];

try {
    // Create Telegram API object
    $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);

    // Error, Debug and Raw Update logging
    // Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance);
    Longman\TelegramBot\TelegramLog::initErrorLog(__DIR__ . '/' . $BOT_NAME . '_error.log');
    Longman\TelegramBot\TelegramLog::initDebugLog(__DIR__ . '/' . $BOT_NAME . '_debug.log');
    Longman\TelegramBot\TelegramLog::initUpdateLog(__DIR__ . '/' . $BOT_NAME . '_update.log');

    // Enable MySQL
    //$telegram->enableMySql($mysql_credentials);

    // Enable MySQL with table prefix
    //$telegram->enableMySql($mysql_credentials, $BOT_NAME . '_');

    // Add an additional commands path
    //$telegram->addCommandsPath($commands_path);

    // Enable admin user(s)
    //$telegram->enableAdmin(your_telegram_id);
    //$telegram->enableAdmins([your_telegram_id, other_telegram_id]);

    // Add the channel you want to manage
    //$telegram->setCommandConfig('sendtochannel', ['your_channel' => '@type_here_your_channel']);

    // Here you can set some command specific parameters,
    // for example, google geocode/timezone api key for /date command:
    //$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']);

    // Set custom Upload and Download path
    //$telegram->setDownloadPath('../Download');
    //$telegram->setUploadPath('../Upload');

    // Botan.io integration
    $telegram->enableBotan('MY_KEY');

    // Handle telegram webhook request
    $telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // Silence is golden!
    echo $e;
    // Log telegram errors
    Longman\TelegramBot\TelegramLog::error($e);
} catch (Longman\TelegramBot\Exception\TelegramLogException $e) {
    // Silence is golden!
    // Uncomment this to catch log initilization errors
    echo $e;
}

When not using DB you must place the code in executeNoDb() function, not execute() in GenericmessageCommand.

Also, it seems you're editing the GenericmessageCommand.php file directly in the library, which is a bad idea, as it gets overwritten with updates.
Instead, create a new directory somewhere in your project and put the file in there, then add that folder as a commands path with $telegram->addCommandsPath($commands_path);, which you can find commented out in your hook.php file.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Recouse picture Recouse  路  3Comments

sayjeyhi picture sayjeyhi  路  3Comments

ttvd94 picture ttvd94  路  4Comments

NabiKAZ picture NabiKAZ  路  4Comments

mohsenshahab picture mohsenshahab  路  4Comments