定制 httd1/telegramphp 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

httd1/telegramphp

Composer 安装命令:

composer require httd1/telegramphp

包简介

This is a PHP package for using Telegram Bot API

README 文档

README

GitHub license Packagist Downloads GitHub commit activity GitHub stars

👌 Read this documentation in Portuguese here

This is a package for the Telegram Bots API.
This package was made exclusively for use with Webhook.
Before using this package, please read the entire Telegram Bot API documentation: https://core.telegram.org/bots/api

Requirements

  • PHP >= 7.0
    • cURL
    • JSON

Installation

composer require httd1/TelegramPhp

Usage:

<?php

include __DIR__.'/vendor/autoload.php';

use \TelegramPhp\TelegramPhp;
use \TelegramPhp\Methods;
use \TelegramPhp\Buttons;

// set bot token
\TelegramPhp\Config\Token::setToken ('110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw');

$tlg = new TelegramPhp;

$tlg->command ('/start', function ($bot){

  // send message
  Methods::sendMessage ([
    'chat_id' => $bot->getChatId (),
    'text' => 'Hello 👋'
  ]);

});

// Passing parameters to a command with {{info}}
$tlg->command ('/get {{info}}', function ($bot, $data){

  switch ($data ['info']){
    case 'id':
      $user_info = $bot->getUserId ();
      break;
    case 'username':
      $user_info = $bot->getUsername ();
      break;
    case 'name':
      $user_info = $bot->getFullName ();
      break;
    default:
      $user_info = "Use <code>/get id or username or name</code>";
  }

  Methods::sendMessage ([
    'chat_id' => $bot->getChatId (),
    'text' => "User Info: <b>{$user_info}</b>",
    'parse_mode' => 'html',
    'reply_markup' => Buttons::inlineKeyBoard ([
      [Buttons::inlineKeyBoardUrl ("Link My Profile", "tg://user?id=".$bot->getUserId ())],
      [Buttons::inlineKeyBoardCallbackData ("Ok, Thanks 👍", "/ok")]
    ])
  ]);

});

// match pattern
$tlg->commandMatch ('/^\/ok$/', function ($bot){

  Methods::answerCallbackQuery ([
    'callback_query_id' => $bot->getCallbackQueryId (),
    'text' => '💪 Bro'
  ]);

});

// commandDefault aways in the end of code!
$tlg->commandDefault (function ($bot){

  Methods::sendMessage ([
    'chat_id' => $bot->getChatId (),
    'text' => 'Chose a command /start, /info with id, name or username'
  ]);

});

🔒 Secure

Telegram provides ways to verify if a request actually comes from its servers (read more here).
You can set a secret_token in your webhook, and Telegram will include this token in the X-Telegram-Bot-Api-Secret-Token header. This package allows you to validate your secret_token.

$secret_token = 'wubbalubbadub_dub';

// set secret_token in webhook
// Methods::setWebhook ([
//   'url' => 'https://url.com/mybot/',
//   'secret_token' => $secret_token
// ]);

// my secret token
$tlg->setSecretToken ($secret_token);

if ($tlg->checkSecretToken () == false){
    http_response_code (401);
}

Handling Commands

Use the methods command (), commandMatch () or commandDefault to catch and handle commands sent to your bot. Each method receives a callback or class method.

  • command () - Use for standard Telegram commands like /comando or simple inputs that you consider a command, such as '👍'. You can use {{param}} to define expected parameters.
$tlg->command ('👍', function ($bot){

  // process command...

});

$tlg->command ('/colors {{color_1}} {{color_2}} {{color_3}}', function ($bot, $data){

  // $data ['color_1']...
  // process command...

});

// run the colors method of ClassBot class
// $tlg->command ('/colors {{color_1}} {{color_2}} {{color_3}}', 'ClassBot:methodColors');

// for namespace use '\MyNamespace\ClassBot:colors'
// $tlg->command ('/colors {{color_1}} {{color_2}} {{color_3}}', '\MyNamespace\ClassBot:colors');
  • commandMatch () - For some kind of commands, you can build you own pattern using regular expression such as telegram urls for example!
// telegram urls https://t.me/botfather, https://t.me/TelegramBR
$tlg->commandMatch ('/^https?:\/\/t\.me\/\w{5,}$/', function ($bot, $data){

  // $data [0]
  // process command...

});

// run the executeLinks method of TelegramBot class
// $tlg->commandMatch ('/^https?:\/\/t\.me\/\w{5,}$/', 'TelegramBot:executeLinks');

// for namespace use '\MyNamespace\ClassBot:colors'
// $tlg->commandMatch ('/^https?:\/\/t\.me\/\w{5,}$/', '\MyNamespace\TelegramBot:executeLinks');
  • commandDefault () - Fallback handler when no command matches.
// ...command
// ...commandMatch

// in the end of code!
$tlg->commandDefault (function ($bot){
  
  // send default message

});

// $tlg->commandDefault ('ControllerBot:default');

Some methods available:

getText (), getUpdateType (), getContent (), getUserId (), getUsername (), getFirstName (), getLastName (), getFullName () - User full name; getLanguageCode () - List of languages ID; getMessageId (), getChatId (), getMediaType () - Media type, photo, animation, audio, document, sticker, story, video, video_note, voice, contact, dice, game, poll, venue, location, invoice; getCallbackQueryId (), getChatType () - Chat type, private, group, supergroup, channel; saveFile () - Download a file, receive with paramether a return of getFile () and the file destination; setSecretToken () - Set a token used in Webhook(secret_token) updates; checkSecretToken () - Checks the secret_token set on the the webhook.

Buttons:

Use the static Buttons class to create inline or reply keyboards.

Methods::sendMessage ([
  'chat_id' => $bot->getUserId (),
  'text' => '(☞゚ヮ゚)☞',
  'reply_markup' => Buttons::inlineKeyBoard ([
    [Buttons::inlineKeyBoardCallbackData ('Hello', '/hello')],
    // [Buttons::inlineKeyBoardUrl ('Open Link', 'https://google.com')]
  ])
]);

inlineKeyBoardUrl (), inlineKeyBoardCallbackData (), inlineKeyBoardWebApp (), inlineKeyBoardLoginUrl (), inlineKeyBoardSwitchInlineQuery (),inlineKeyBoardSwitchInlineQueryCurrentChat (), inlineKeyBoardPay (), inlineKeyBoardCopyText, inlineKeyBoardSwitchInlineQueryChosenChat

Methods::sendMessage ([
  'chat_id' => $bot->getUserId (),
  'text' => 'Hello 👋',
  'reply_markup' => Buttons::replyKeyBoardMarkup ([
    [Buttons::keyBoardButtonText ('Hello')],
    // [Buttons::keyBoardButtonRequestContact ('share your contact')]
  ])
]);

keyBoardButtonText (), keyBoardButtonRequestContact (), keyBoardButtonRequestLocation (), keyBoardButtonRequestPoll (), keyBoardButtonWebApp ()

Methods::sendMessage ([
  'chat_id' => $bot->getChatId (),
  'text' => '😍🤔👌🔥🤦',
  'reply_markup' => Buttons::forceReply ()
]);
Methods::sendMessage([
  'chat_id' => $bot->getChatId(),
  'text' => 'Message with force reply',
  'reply_markup' => Buttons::forceReply()
]);
  • replyKeyboardRemove () - Removes the Telegram keyboard buttons and displays the device keyboard, documentation
Methods::sendMessage([
  'chat_id' => $bot->getChatId(),
  'text' => 'Keyboard removed',
  'reply_markup' => Buttons::replyKeyboardRemove()
]);

Message reactions

Telegram Bots can react to messages using simple emojis such as 👍, 👌, 🔥, 😍... or custom emojis.
You can see the all available reaction emoji here We have Reaction, an static class for reacting to messages.

  • Reaction with ❤
    Reacting with ❤
Methods::setMessageReaction ([
  'chat_id' => $bot->getChatId (),
  'message_id' => $bot->getMessageId (),
  'reaction' => Reaction::reactionType ([
      Reaction::reactionTypeEmoji (''),
  ])
]);
  • Reacting with custom emojis5445284980978621387
    Reacting with custom emojis
Methods::setMessageReaction ([
  'chat_id' => $bot->getChatId (),
  'message_id' => $bot->getMessageId (),
  'reaction' => Reaction::reactionType ([
      Reaction::reactionTypeCustomEmoji ('5445284980978621387'),
  ])
]);

Send files:

  • Send audio
Methods::sendAudio ([
  'chat_id' => $bot->getChatId (),
  'audio' => curl_file_create (__DIR__.'/music.mp3'),
  'caption' => 'Description music'
]);
  • Send photo
Methods::sendPhoto ([
  'chat_id' => $bot->getChatId (),
  'photo' => curl_file_create (__DIR__.'/photo.jpg'),
  'caption' => 'Description photo'
]);
  • Send video
Methods::sendVideo ([
  'chat_id' => $bot->getChatId (),
  'video' => curl_file_create (__DIR__.'/video.mp4'),
  'caption' => 'Description video'
]);
  • Send file
Methods::sendDocument ([
  'chat_id' => $bot->getChatId (),
  'document' => curl_file_create (__DIR__.'/application.apk'),
  'caption' => 'Description file'
]);

Download files

$file = Methods::getFile ([
  'file_id' => 'CQACAgEAAxkBAAIBRGMFiJ_7zH2y9lJZxnn-XesvrBIhAALrAgACBcf5R68w-Z9ZMsgUKQQ'
]);

var_dump ($bot->saveFile ($file, __DIR__.'/music.mp3'));

Logs

You can capture bot logs using \TelegramPhp\Config\Logs, symple set one or more classes to catch all user logs.

  • Class to catch and process all user logs.
class LogCommands {
  // method log is required
  public function log ($telegramPhp, $action, $route, $data){
    // process data
  }
}
  • Setting class LogCommands on the \TelegramPhp\Config\Logs
\TelegramPhp\Config\Logs::catchLogs ([
  LogCommands::class,
  // LogStatistics::class
]);

Updates types

It's possible to execute a callback for a specific type of Updates sent by the Telegram API, for example, executing a callback to 'my_chat_member' or 'chat_member'.

  • Handling 'my_chat_member' updates
$tlg->on ('my_chat_member', function ($bot){
  // code here
});
// $tlg->on (['message_reaction', 'message'], function ($bot){
  // code here
// });
  • Handling 'chat_member' updates
$tlg->on ('chat_member', 'TelegramBot:myChatMember');

🔥 Share your project made with this class, your project could be featured here!

• J.M

httd1/telegramphp 适用场景与选型建议

httd1/telegramphp 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 227 次下载、GitHub Stars 达 11, 最近一次更新时间为 2022 年 09 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 httd1/telegramphp 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 httd1/telegramphp 我们能提供哪些服务?
定制开发 / 二次开发

基于 httd1/telegramphp 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 227
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 11
  • 点击次数: 4
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 11
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2022-09-24