alish / telegram

此包已弃用且不再维护。未建议替代包。

用于Telegram机器人的laravel包

1.1.3 2018-01-17 00:00 UTC

This package is auto-updated.

Last update: 2022-07-28 15:01:07 UTC


README

使用此包与Telegram API机器人进行交互,此包专为与Laravel兼容而开发,但通过一些小的修改,您也可以用原始PHP使用它

安装

composer require alish/telegram

Laravel 5至5.4的额外设置

您需要手动将服务提供者和外观添加到config/app.php

'providers' => [
    //
    Alish\Telegram\TelegramServiceProvider::class
  
 ],
 
 'aliases' => [
    //
    'Telegram' => Alish\Telegram\Facades\Telegram::class
    
 ]
 
 

对于Laravel 5.5及以上版本,您不需要这样做

配置文件

发布配置文件

  php artisan vendor:publish --provider="Alish\Telegram\TelegramServiceProvider"

然后您可以在config/telegram.php中看到配置文件

配置文件如下

'defaults' => [
            'token_bot' => '',
            'webhook' => '',
        ],

        'commands' => [
            'active' => false,
            'list' => [
                'start' => 'App\Class'
            ]
        ],

        'handlers' => [
            'CallbackQuery'      => null,
            'ChannelPost'        => null,
            'ChosenInlineResult' => null,
            'EditedChannelPost'  => null,
            'EditedMessage'      => null,
            'InlineQuery'        => null,
            'Message'            => null,
            'ShippingQuery'      => null,
            'PreCheckoutQuery'   => null
        ],

        'loaders' => [
            
        ]

默认设置

在token_bot中填写您从机器人父亲获得的令牌,并将webhook设置为您的所需URL(相对URL)

命令

如果您想处理从Telegram API机器人接收到的特定类的命令,您可以在这里声明它,首先将'active'设置为true,然后在'list'数组中列出与相关类处理程序相关的命令。在此文件中指定的类应该继承自Alish\Telegram\TelegramCommand,然后在处理程序函数中放入您的逻辑(**示例**)

use Alish\Telegram\TelegramCommand;
use App\Http\Bot\State;

class StartCommand extends TelegramCommand
{

    public function handler()
    {
        // put your logic here
    }
}

您可以通过 $this->message 访问 Message 对象(查看Message类注意 ***如果您激活了命令处理程序,则您在处理程序部分将不会收到消息

处理程序

在本节中,我们将从Telegram接收到的消息类型分割到单独的类处理程序中,然后为了处理每个类型,您需要声明相关的类。已经定义的处理程序类应该继承自 TelegramUpdateHandler __**示例**__

use Alish\Telegram\TelegramUpdateHandler;

class CallbackQueryHandler extends TelegramUpdateHandler
{

    public function handler()
    {
        // put your logic here
    }
}

您可以通过 $this->update 访问更新对象(查看更新文档

加载器

如果您想在处理消息之前执行某些操作,您可以定义加载器类。此类接收从Telegram API接收到的更新对象,已定义的加载器类应该继承自 TelegramLoader **示例**:

use Alish\Telegram\TelegramLoader;

class StageHandler extends TelegramLoader
{

    public function process()
    {
         // put your logic here
    }
}

这些加载器不会阻止您定义的处理程序接收更新,因此请小心使用这些

Telegram外观

通过这个外观,您可以执行Telegram API机器人中定义的所有操作(查看可用方法)[https://core.telegram.org/bots/api#available-methods]

如何使用此功能

您只需要使用Telegram API中的相同方法 **示例**:

  // sending Message:
  // you must provide required filed, optional field is still optional
  Telegram::sendMessage(['chat_id' => 'user chat id', 'text' => 'Welcome to my bot']);
  
  // forward message
  Telegram::forwardMessage(['chat_id' => 'user chat id', 'from_chat_id' => 'from chat id']);
  

由于除了1或2之外的所有操作都需要chat_id,您可以使用

  Telegram::chatId('user chat id')->sendMessage(['text' => 'Welcome to my bot']);
  
  // instead of 
  // Telegram::sendMessage(['chat_id' => 'user chat id', 'text' => 'Welcome to my bot']);

发送按钮

发送按钮时,您需要使用json_encode函数对按钮数组进行编码 示例:


 
  $buttons = [
    [
      ['text' => 'some text'],
      ['text' => 'some text']
    ],
    [
      ['text' => 'some text']
    ]
  ];
  
  $replyMarkup = json_encode(['keyboard' => $buttons])
  
  Telegram::chatId('user chat id')->sendMessage(['text' => 'Welcome to my bot', 'reply_markup' => $replyMarkup]);

发送文件

发送文件时,您需要使用InputFile类中的getFile方法 示例:

  use Alish\Telegram\Template\InputFile;
  
  Telegram::chatId($chatId)->sendVideo(['caption' => $text, 'video' => InputFile::getFile($pathToFile), 'reply_markup' => $buttons, 'reply_to_message_id' => 'message id']);

getUser

您可以使用以下命令在接收到的更新中获取Telegram用户:要查看用户对象中包含哪些信息,请参阅(用户对象)[https://core.telegram.org/bots/api#user]

  $telegramUser = Telegram::getUser();

此包的工作原理

所有Telegram对象都映射到其对应的类中,这意味着当从Telegram API接收到更新时,它会映射到Update类,Update类包含


  /**
     * @var integer $update_id
     * The update‘s unique identifier. Update identifiers start from a certain positive number and increase sequentially.
     * This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
     */
    protected $update_id;

    /**
     * @var Message|null $message
     * Optional. New incoming message of any kind — text, photo, sticker, etc.
     */
    protected $message;

    /**
     * @var Message|null $edited_message
     * Optional. New version of a message that is known to the bot and was edited
     */
    protected $edited_message;

    /**
     * @var Message|null $channel_post
     * Optional. New incoming channel post of any kind — text, photo, sticker, etc.
     */
    protected $channel_post;

    /**
     * @var Message $edited_channel_post
     * Optional. New version of a channel post that is known to the bot and was edited
     */
    protected $edited_channel_post;

    /**
     * @var InlineQuery|null $inline_query
     * Optional. New incoming inline query
     */
    protected $inline_query;

    /**
     * @var ChosenInlineResult|null $chosen_inline_result
     * Optional. The result of an inline query that was chosen by a user and sent to their chat partner.
     * Please see our documentation on the feedback collecting for details on how to enable these updates for your bot.
     */
    protected $chosen_inline_result;

    /**
     * @var CallbackQuery|null $callback_query
     * Optional. New incoming callback query
     */
    protected $callback_query;

    /**
     * @var ShippingQuery|null $shipping_query
     * Optional. New incoming shipping query. Only for invoices with flexible price
     */
    protected $shipping_query;

    /**
     * @var PreCheckoutQuery|null $pre_checkout_query
     * Optional. New incoming pre-checkout query. Contains full information about checkout
     */
    protected $pre_checkout_query;

您无法直接访问这些属性,因为这些属性应该从从Telegram API接收到的信息中初始化,如果您想访问每个属性,请使用带'get'前缀的动态方法,例如,要获取update_id,请使用getUpdateId()方法;如果您想操作接收到的消息,请使用set方法来更改属性,$update->setUpdateId(' whatever');