Commit 17471725 authored by Armando Lüscher's avatar Armando Lüscher

Move examples to own repository.

Update changelog.
parent 48452981
......@@ -2,6 +2,17 @@
The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]
### Added
- Proper standalone `scrutinizer.yml` config.
- Human-readable last error date for debug command.
### Changed
- Bot username no longer required for object instantiation.
### Deprecated
### Removed
- All examples have been moved to a [dedicated repository](https://github.com/php-telegram-bot/example-bot).
### Fixed
- Format of Update content type using `$update->getUpdateContent()`.
### Security
## [0.43.0] - 2017-04-17
### Added
......
......@@ -49,6 +49,7 @@ A Telegram Bot based on the official [Telegram Bot API](https://core.telegram.or
- [Upload and Download directory path](#upload-and-download-directory-path)
- [Logging](doc/01-utils.md)
- [Documentation](#documentation)
- [Example bot](#example-bot)
- [Projects with this library](#projects-with-this-library)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
......@@ -529,6 +530,11 @@ $telegram->setUploadPath('yourpath/Upload');
Take a look at the repo [Wiki](https://github.com/php-telegram-bot/core/wiki) for further information and tutorials!
Feel free to improve!
## Example bot
We're busy working on a full A-Z example bot, to help get you started with this library and to show you how to use all its features.
You can check the progress of the [example bot repository](https://github.com/php-telegram-bot/example-bot).
## Projects with this library
Here's a list of projects that feats this library, feel free to add yours!
......
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
use Longman\TelegramBot\Request;
/**
* Callback query command
*/
class CallbackqueryCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'callbackquery';
/**
* @var string
*/
protected $description = 'Reply to callback query';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$update = $this->getUpdate();
$callback_query = $update->getCallbackQuery();
$callback_query_id = $callback_query->getId();
$callback_data = $callback_query->getData();
$data = [
'callback_query_id' => $callback_query_id,
'text' => 'Hello World!',
'show_alert' => $callback_data === 'thumb up',
'cache_time' => 5,
];
return Request::answerCallbackQuery($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Entities\Keyboard;
use Longman\TelegramBot\Request;
/**
* User "/cancel" command
*
* This command cancels the currently active conversation and
* returns a message to let the user know which conversation it was.
* If no conversation is active, the returned message says so.
*/
class CancelCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'cancel';
/**
* @var string
*/
protected $description = 'Cancel the currently active conversation';
/**
* @var string
*/
protected $usage = '/cancel';
/**
* @var string
*/
protected $version = '0.2.0';
/**
* @var bool
*/
protected $need_mysql = true;
/**
* Command execute method
*
* @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$text = 'No active conversation!';
//Cancel current conversation if any
$conversation = new Conversation(
$this->getMessage()->getFrom()->getId(),
$this->getMessage()->getChat()->getId()
);
if ($conversation_command = $conversation->getCommand()) {
$conversation->cancel();
$text = 'Conversation "' . $conversation_command . '" cancelled!';
}
return $this->removeKeyboard($text);
}
/**
* Remove the keyboard and output a text
*
* @param string $text
*
* @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
private function removeKeyboard($text)
{
return Request::sendMessage(
[
'reply_markup' => Keyboard::remove(['selective' => true]),
'chat_id' => $this->getMessage()->getChat()->getId(),
'text' => $text,
]
);
}
/**
* Execute no db
*
* @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function executeNoDb()
{
return $this->removeKeyboard('Nothing to cancel.');
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Channel chat created command
*/
class ChannelchatcreatedCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Channelchatcreated';
/**
* @var string
*/
protected $description = 'Channel chat created';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$message = $this->getMessage();
//$channel_chat_created = $message->getChannelChatCreated();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Channel post command
*/
class ChannelpostCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Channelpost';
/**
* @var string
*/
protected $description = 'Handle channel post';
/**
* @var string
*/
protected $version = '1.0.0';
/**
* Execute command
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$channel_post = $this->getUpdate()->getChannelPost();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Chosen inline result command
*/
class ChoseninlineresultCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'choseninlineresult';
/**
* @var string
*/
protected $description = 'Chosen result query';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//Information about chosen result is returned
//$update = $this->getUpdate();
//$inline_query = $update->getChosenInlineResult();
//$query = $inline_query->getQuery();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use DateTime;
use DateTimeZone;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\TelegramLog;
/**
* User "/date" command
*/
class DateCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'date';
/**
* @var string
*/
protected $description = 'Show date/time by location';
/**
* @var string
*/
protected $usage = '/date <location>';
/**
* @var string
*/
protected $version = '1.4.0';
/**
* Guzzle Client object
*
* @var \GuzzleHttp\Client
*/
private $client;
/**
* Base URI for Google Maps API
*
* @var string
*/
private $google_api_base_uri = 'https://maps.googleapis.com/maps/api/';
/**
* The Google API Key from the command config
*
* @var string
*/
private $google_api_key;
/**
* Date format
*
* @var string
*/
private $date_format = 'd-m-Y H:i:s';
/**
* Get coordinates
*
* @param string $location
*
* @return array
*/
private function getCoordinates($location)
{
$path = 'geocode/json';
$query = ['address' => urlencode($location)];
if ($this->google_api_key !== null) {
$query['key'] = $this->google_api_key;
}
try {
$response = $this->client->get($path, ['query' => $query]);
} catch (RequestException $e) {
TelegramLog::error($e->getMessage());
return [];
}
if (!($data = $this->validateResponseData($response->getBody()))) {
return [];
}
$result = $data['results'][0];
$lat = $result['geometry']['location']['lat'];
$lng = $result['geometry']['location']['lng'];
$acc = $result['geometry']['location_type'];
$types = $result['types'];
return [$lat, $lng, $acc, $types];
}
/**
* Get date
*
* @param string $lat
* @param string $lng
*
* @return array
*/
private function getDate($lat, $lng)
{
$path = 'timezone/json';
$date_utc = new \DateTime(null, new \DateTimeZone('UTC'));
$timestamp = $date_utc->format('U');
$query = [
'location' => urlencode($lat) . ',' . urlencode($lng),
'timestamp' => urlencode($timestamp),
];
if ($this->google_api_key !== null) {
$query['key'] = $this->google_api_key;
}
try {
$response = $this->client->get($path, ['query' => $query]);
} catch (RequestException $e) {
TelegramLog::error($e->getMessage());
return [];
}
if (!($data = $this->validateResponseData($response->getBody()))) {
return [];
}
$local_time = $timestamp + $data['rawOffset'] + $data['dstOffset'];
return [$local_time, $data['timeZoneId']];
}
/**
* Evaluate the response data and see if the request was successful
*
* @param string $data
*
* @return array
*/
private function validateResponseData($data)
{
if (empty($data)) {
return [];
}
$data = json_decode($data, true);
if (empty($data)) {
return [];
}
if (isset($data['status']) && $data['status'] !== 'OK') {
return [];
}
return $data;
}
/**
* Get formatted date at the passed location
*
* @param string $location
*
* @return string
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
private function getFormattedDate($location)
{
if ($location === null || $location === '') {
return 'The time in nowhere is never';
}
list($lat, $lng) = $this->getCoordinates($location);
if (empty($lat) || empty($lng)) {
return 'It seems that in "' . $location . '" they do not have a concept of time.';
}
list($local_time, $timezone_id) = $this->getDate($lat, $lng);
$date_utc = new DateTime(gmdate('Y-m-d H:i:s', $local_time), new DateTimeZone($timezone_id));
return 'The local time in ' . $timezone_id . ' is: ' . $date_utc->format($this->date_format);
}
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//First we set up the necessary member variables.
$this->client = new Client(['base_uri' => $this->google_api_base_uri]);
if (($this->google_api_key = trim($this->getConfig('google_api_key'))) === '') {
$this->google_api_key = null;
}
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$location = $message->getText(true);
$text = 'You must specify location in format: /date <city>';
if ($location !== '') {
$text = $this->getFormattedDate($location);
}
$data = [
'chat_id' => $chat_id,
'text' => $text,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Delete chat photo command
*/
class DeletechatphotoCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Deletechatphoto';
/**
* @var string
*/
protected $description = 'Delete chat photo';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$message = $this->getMessage();
//$delete_chat_photo = $message->getDeleteChatPhoto();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
/**
* User "/echo" command
*/
class EchoCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'echo';
/**
* @var string
*/
protected $description = 'Show text';
/**
* @var string
*/
protected $usage = '/echo <text>';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$text = trim($message->getText(true));
if ($text === '') {
$text = 'Command usage: ' . $this->getUsage();
}
$data = [
'chat_id' => $chat_id,
'text' => $text,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Edited channel post command
*/
class EditedchannelpostCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Editedchannelpost';
/**
* @var string
*/
protected $description = 'Handle edited channel post';
/**
* @var string
*/
protected $version = '1.0.0';
/**
* Execute command
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$edited_channel_post = $this->getUpdate()->getEditedChannelPost();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Edited message command
*/
class EditedmessageCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'editedmessage';
/**
* @var string
*/
protected $description = 'User edited message';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$update = $this->getUpdate();
//$edited_message = $update->getEditedMessage();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
/**
* User "/editmessage" command
*/
class EditmessageCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'editmessage';
protected $description = 'Edit message';
protected $usage = '/editmessage';
protected $version = '1.0.0';
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$reply_to_message = $message->getReplyToMessage();
$text = $message->getText(true);
if ($reply_to_message) {
$message_to_edit = $reply_to_message->getMessageId();
}
if (isset($message_to_edit) && $message_to_edit) {
$data_edit = [];
$data_edit['chat_id'] = $chat_id;
$data_edit['message_id'] = $message_to_edit;
if (!empty($text)) {
$data_edit['text'] = $text;
} else {
$data_edit['text'] = "Edited message";
}
return Request::editMessageText($data_edit);
} else {
$data = [];
$data['chat_id'] = $chat_id;
$data['text'] = 'Reply to any bot\'s message and use /' . $this->name . ' <your text> to edit it.';
return Request::sendMessage($data);
}
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\Keyboard;
use Longman\TelegramBot\Request;
/**
* User "/forcereply" command
*/
class ForceReplyCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'forcereply';
protected $description = 'Force reply with reply markup';
protected $usage = '/forcereply';
protected $version = '0.1.0';
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$chat_id = $this->getMessage()->getChat()->getId();
$data = [
'chat_id' => $chat_id,
'text' => 'Write something:',
'reply_markup' => Keyboard::forceReply(),
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
use Longman\TelegramBot\Request;
/**
* Generic command
*/
class GenericCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Generic';
/**
* @var string
*/
protected $description = 'Handles generic commands or is executed by default when a command is not found';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$message = $this->getMessage();
//You can use $command as param
$chat_id = $message->getChat()->getId();
$user_id = $message->getFrom()->getId();
$command = $message->getCommand();
//If the user is an admin and the command is in the format "/whoisXYZ", call the /whois command
if (stripos($command, 'whois') === 0 && $this->telegram->isAdmin($user_id)) {
return $this->telegram->executeCommand('whois');
}
$data = [
'chat_id' => $chat_id,
'text' => 'Command /' . $command . ' not found.. :(',
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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()
{
//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);
}
return Request::emptyResponse();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Group chat created command
*/
class GroupchatcreatedCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Groupchatcreated';
/**
* @var string
*/
protected $description = 'Group chat created';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$message = $this->getMessage();
//$group_chat_created = $message->getGroupChatCreated();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\Command;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
/**
* User "/help" command
*/
class HelpCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'help';
/**
* @var string
*/
protected $description = 'Show bot commands help';
/**
* @var string
*/
protected $usage = '/help or /help <command>';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$command = trim($message->getText(true));
//Only get enabled Admin and User commands
/** @var Command[] $command_objs */
$command_objs = array_filter($this->telegram->getCommandsList(), function ($command_obj) {
/** @var Command $command_obj */
return !$command_obj->isSystemCommand() && $command_obj->isEnabled();
});
//If no command parameter is passed, show the list
if ($command === '') {
$text = sprintf(
'%s v. %s' . PHP_EOL . PHP_EOL . 'Commands List:' . PHP_EOL,
$this->telegram->getBotUsername(),
$this->telegram->getVersion()
);
foreach ($command_objs as $command) {
if (!$command->showInHelp()) {
continue;
}
$text .= sprintf(
'/%s - %s' . PHP_EOL,
$command->getName(),
$command->getDescription()
);
}
$text .= PHP_EOL . 'For exact command help type: /help <command>';
} else {
$command = str_replace('/', '', $command);
if (isset($command_objs[$command])) {
/** @var Command $command_obj */
$command_obj = $command_objs[$command];
$text = sprintf(
'Command: %s v%s' . PHP_EOL .
'Description: %s' . PHP_EOL .
'Usage: %s',
$command_obj->getName(),
$command_obj->getVersion(),
$command_obj->getDescription(),
$command_obj->getUsage()
);
} else {
$text = 'No help available: Command /' . $command . ' not found';
}
}
$data = [
'chat_id' => $chat_id,
'reply_to_message_id' => $message_id,
'text' => $text,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\Keyboard;
use Longman\TelegramBot\Request;
/**
* User "/hidekeyboard" command
*/
class HidekeyboardCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'hidekeyboard';
protected $description = 'Hide the custom keyboard';
protected $usage = '/hidekeyboard';
protected $version = '0.1.0';
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$chat_id = $this->getMessage()->getChat()->getId();
$data = [
'chat_id' => $chat_id,
'text' => 'Keyboard Hidden',
'reply_markup' => Keyboard::remove(),
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Entities\ReplyKeyboardMarkup;
/**
* User "/image" command
*/
class ImageCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'image';
protected $description = 'Send Image';
protected $usage = '/image';
protected $version = '1.0.1';
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$text = $message->getText(true);
$data = [
'chat_id' => $chat_id,
'caption' => $text,
];
//Return a random picture from the telegram->getUploadPath().
return Request::sendPhoto($data, $this->ShowRandomImage($this->telegram->getUploadPath()));
}
/**
* Return the path to a random image in the passed directory.
*
* @param string $dir
*
* @return string
*/
private function ShowRandomImage($dir)
{
$image_list = scandir($dir);
return $dir . '/' . $image_list[mt_rand(2, count($image_list) - 1)];
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\InlineKeyboard;
use Longman\TelegramBot\Request;
/**
* User "/inlinekeyboard" command
*/
class InlinekeyboardCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'inlinekeyboard';
protected $description = 'Show inline keyboard';
protected $usage = '/inlinekeyboard';
protected $version = '0.1.0';
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$chat_id = $this->getMessage()->getChat()->getId();
$switch_element = mt_rand(0, 9) < 5 ? 'true' : 'false';
$inline_keyboard = new InlineKeyboard([
['text' => 'inline', 'switch_inline_query' => $switch_element],
['text' => 'inline current chat', 'switch_inline_query_current_chat' => $switch_element],
], [
['text' => 'callback', 'callback_data' => 'identifier'],
['text' => 'open url', 'url' => 'https://github.com/php-telegram-bot/core'],
]);
$data = [
'chat_id' => $chat_id,
'text' => 'inline keyboard',
'reply_markup' => $inline_keyboard,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
use Longman\TelegramBot\Entities\InlineQuery\InlineQueryResultArticle;
use Longman\TelegramBot\Entities\InputMessageContent\InputTextMessageContent;
use Longman\TelegramBot\Request;
/**
* Inline query command
*/
class InlinequeryCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'inlinequery';
/**
* @var string
*/
protected $description = 'Reply to inline query';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$update = $this->getUpdate();
$inline_query = $update->getInlineQuery();
$query = $inline_query->getQuery();
$data = ['inline_query_id' => $inline_query->getId()];
$results = [];
if ($query !== '') {
$articles = [
[
'id' => '001',
'title' => 'https://core.telegram.org/bots/api#answerinlinequery',
'description' => 'you enter: ' . $query,
'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]),
],
[
'id' => '002',
'title' => 'https://core.telegram.org/bots/api#answerinlinequery',
'description' => 'you enter: ' . $query,
'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]),
],
[
'id' => '003',
'title' => 'https://core.telegram.org/bots/api#answerinlinequery',
'description' => 'you enter: ' . $query,
'input_message_content' => new InputTextMessageContent(['message_text' => ' ' . $query]),
],
];
foreach ($articles as $article) {
$results[] = new InlineQueryResultArticle($article);
}
}
$data['results'] = '[' . implode(',', $results) . ']';
return Request::answerInlineQuery($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\Keyboard;
use Longman\TelegramBot\Request;
/**
* User "/keyboard" command
*/
class KeyboardCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'keyboard';
protected $description = 'Show a custom keyboard with reply markup';
protected $usage = '/keyboard';
protected $version = '0.2.0';
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
//Keyboard examples
/** @var Keyboard[] $keyboards */
$keyboards = [];
//Example 0
$keyboards[] = new Keyboard(
['7', '8', '9'],
['4', '5', '6'],
['1', '2', '3'],
[' ', '0', ' ']
);
//Example 1
$keyboards[] = new Keyboard(
['7', '8', '9', '+'],
['4', '5', '6', '-'],
['1', '2', '3', '*'],
[' ', '0', ' ', '/']
);
//Example 2
$keyboards[] = new Keyboard('A', 'B', 'C');
//Example 3
$keyboards[] = new Keyboard(
['text' => 'A'],
'B',
['C', 'D']
);
//Example 4 (bots version 2.0)
$keyboards[] = new Keyboard([
['text' => 'Send my contact', 'request_contact' => true],
['text' => 'Send my location', 'request_location' => true],
]);
//Return a random keyboard.
$keyboard = $keyboards[mt_rand(0, count($keyboards) - 1)]
->setResizeKeyboard(true)
->setOneTimeKeyboard(true)
->setSelective(false);
$chat_id = $this->getMessage()->getChat()->getId();
$data = [
'chat_id' => $chat_id,
'text' => 'Press a Button:',
'reply_markup' => $keyboard,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Left chat member command
*/
class LeftchatmemberCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Leftchatmember';
/**
* @var string
*/
protected $description = 'Left Chat Member';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$message = $this->getMessage();
//$member = $message->getLeftChatMember();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\Entities\ReplyKeyboardMarkup;
/**
* User "/markdown" command
*/
class MarkdownCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'markdown';
protected $description = 'Print Markdown text';
protected $usage = '/markdown';
protected $version = '1.0.1';
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$data = [
'chat_id' => $chat_id,
'parse_mode' => 'MARKDOWN',
'text' => '*bold* _italic_ `inline fixed width code`
```
preformatted code block
code block
```
[Best Telegram bot api!!](https://github.com/php-telegram-bot/core)
',
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Migrate from chat id command
*/
class MigratefromchatidCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Migratefromchatid';
/**
* @var string
*/
protected $description = 'Migrate from chat id';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$message = $this->getMessage();
//$migrate_from_chat_id = $message->getMigrateFromChatId();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Migrate to chat id command
*/
class MigratetochatidCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Migratetochatid';
/**
* @var string
*/
protected $description = 'Migrate to chat id';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$message = $this->getMessage();
//$migrate_to_chat_id = $message->getMigrateToChatId();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
use Longman\TelegramBot\Request;
/**
* New chat member command
*/
class NewchatmemberCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Newchatmember';
/**
* @var string
*/
protected $description = 'New Chat Member';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$member = $message->getNewChatMember();
$text = 'Hi there!';
if (!$message->botAddedInChat()) {
$text = 'Hi ' . $member->tryMention() . '!';
}
$data = [
'chat_id' => $chat_id,
'text' => $text,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* New chat photo command
*/
class NewchatphotoCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Newchatphoto';
/**
* @var string
*/
protected $description = 'New chat Photo';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$message = $this->getMessage();
//$new_chat_photo = $message->getNewChatPhoto();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* New chat title command
*/
class NewchattitleCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Newchattitle';
/**
* @var string
*/
protected $description = 'New chat Title';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$message = $this->getMessage();
//$new_chat_title = $message->getNewChatTitle();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Pinned message command
*/
class PinnedmessageCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Pinnedmessage';
/**
* @var string
*/
protected $description = 'Message was pinned';
/**
* @var string
*/
protected $version = '1.0.0';
/**
* Execute command
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$message = $this->getMessage();
//$pinned_message = $message->getPinnedMessage();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Botan;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
/**
* User "/shortener" command
*/
class ShortenerCommand extends UserCommand
{
/**#@+
* {@inheritdoc}
*/
protected $name = 'shortener';
protected $description = 'Botan Shortener example';
protected $usage = '/shortener';
protected $version = '1.0.0';
/**#@-*/
/**
* {@inheritdoc}
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$user_id = $message->getFrom()->getId();
$data = [];
$data['chat_id'] = $chat_id;
$text = Botan::shortenUrl('https://github.com/php-telegram-bot/core', $user_id);
$data['text'] = $text;
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
/**
* User "/slap" command
*/
class SlapCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'slap';
/**
* @var string
*/
protected $description = 'Slap someone with their username';
/**
* @var string
*/
protected $usage = '/slap <@user>';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$text = $message->getText(true);
$sender = '@' . $message->getFrom()->getUsername();
//username validation
$test = preg_match('/@[\w_]{5,}/', $text);
if ($test === 0) {
$text = $sender . ' sorry no one to slap around..';
} else {
$text = $sender . ' slaps ' . $text . ' around a bit with a large trout';
}
$data = [
'chat_id' => $chat_id,
'text' => $text,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
use Longman\TelegramBot\Request;
/**
* Start command
*/
class StartCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'start';
/**
* @var string
*/
protected $description = 'Start command';
/**
* @var string
*/
protected $usage = '/start';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$text = 'Hi there!' . PHP_EOL . 'Type /help to see all commands!';
$data = [
'chat_id' => $chat_id,
'text' => $text,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* 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\Commands\SystemCommand;
/**
* Super group chat created command
*/
class SupergroupchatcreatedCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'Supergroupchatcreated';
/**
* @var string
*/
protected $description = 'Super group chat created';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
//$message = $this->getMessage();
//$supergroup_chat_created = $message->getSuperGroupChatCreated();
return parent::execute();
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Conversation;
use Longman\TelegramBot\Entities\Keyboard;
use Longman\TelegramBot\Entities\KeyboardButton;
use Longman\TelegramBot\Entities\PhotoSize;
use Longman\TelegramBot\Request;
/**
* User "/survery" command
*/
class SurveyCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'survey';
/**
* @var string
*/
protected $description = 'Survery for bot users';
/**
* @var string
*/
protected $usage = '/survey';
/**
* @var string
*/
protected $version = '0.3.0';
/**
* @var bool
*/
protected $need_mysql = true;
/**
* Conversation Object
*
* @var \Longman\TelegramBot\Conversation
*/
protected $conversation;
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$message = $this->getMessage();
$chat = $message->getChat();
$user = $message->getFrom();
$text = trim($message->getText(true));
$chat_id = $chat->getId();
$user_id = $user->getId();
//Preparing Response
$data = [
'chat_id' => $chat_id,
];
if ($chat->isGroupChat() || $chat->isSuperGroup()) {
//reply to message id is applied by default
//Force reply is applied by default so it can work with privacy on
$data['reply_markup'] = Keyboard::forceReply(['selective' => true]);
}
//Conversation start
$this->conversation = new Conversation($user_id, $chat_id, $this->getName());
$notes = &$this->conversation->notes;
!is_array($notes) && $notes = [];
//cache data from the tracking session if any
$state = 0;
if (isset($notes['state'])) {
$state = $notes['state'];
}
$result = Request::emptyResponse();
//State machine
//Entrypoint of the machine state if given by the track
//Every time a step is achieved the track is updated
switch ($state) {
case 0:
if ($text === '') {
$notes['state'] = 0;
$this->conversation->update();
$data['text'] = 'Type your name:';
$data['reply_markup'] = Keyboard::remove(['selective' => true]);
$result = Request::sendMessage($data);
break;
}
$notes['name'] = $text;
$text = '';
// no break
case 1:
if ($text === '') {
$notes['state'] = 1;
$this->conversation->update();
$data['text'] = 'Type your surname:';
$result = Request::sendMessage($data);
break;
}
$notes['surname'] = $text;
$text = '';
// no break
case 2:
if ($text === '' || !is_numeric($text)) {
$notes['state'] = 2;
$this->conversation->update();
$data['text'] = 'Type your age:';
if ($text !== '') {
$data['text'] = 'Type your age, must be a number:';
}
$result = Request::sendMessage($data);
break;
}
$notes['age'] = $text;
$text = '';
// no break
case 3:
if ($text === '' || !in_array($text, ['M', 'F'], true)) {
$notes['state'] = 3;
$this->conversation->update();
$data['reply_markup'] = (new Keyboard(['M', 'F']))
->setResizeKeyboard(true)
->setOneTimeKeyboard(true)
->setSelective(true);
$data['text'] = 'Select your gender:';
if ($text !== '') {
$data['text'] = 'Select your gender, choose a keyboard option:';
}
$result = Request::sendMessage($data);
break;
}
$notes['gender'] = $text;
// no break
case 4:
if ($message->getLocation() === null) {
$notes['state'] = 4;
$this->conversation->update();
$data['reply_markup'] = (new Keyboard(
(new KeyboardButton('Share Location'))->setRequestLocation(true)
))
->setOneTimeKeyboard(true)
->setResizeKeyboard(true)
->setSelective(true);
$data['text'] = 'Share your location:';
$result = Request::sendMessage($data);
break;
}
$notes['longitude'] = $message->getLocation()->getLongitude();
$notes['latitude'] = $message->getLocation()->getLatitude();
// no break
case 5:
if ($message->getPhoto() === null) {
$notes['state'] = 5;
$this->conversation->update();
$data['text'] = 'Insert your picture:';
$result = Request::sendMessage($data);
break;
}
/** @var PhotoSize $photo */
$photo = $message->getPhoto()[0];
$notes['photo_id'] = $photo->getFileId();
// no break
case 6:
if ($message->getContact() === null) {
$notes['state'] = 6;
$this->conversation->update();
$data['reply_markup'] = (new Keyboard(
(new KeyboardButton('Share Contact'))->setRequestContact(true)
))
->setOneTimeKeyboard(true)
->setResizeKeyboard(true)
->setSelective(true);
$data['text'] = 'Share your contact information:';
$result = Request::sendMessage($data);
break;
}
$notes['phone_number'] = $message->getContact()->getPhoneNumber();
// no break
case 7:
$this->conversation->update();
$out_text = '/Survey result:' . PHP_EOL;
unset($notes['state']);
foreach ($notes as $k => $v) {
$out_text .= PHP_EOL . ucfirst($k) . ': ' . $v;
}
$data['photo'] = $notes['photo_id'];
$data['reply_markup'] = Keyboard::remove(['selective' => true]);
$data['caption'] = $out_text;
$this->conversation->stop();
$result = Request::sendPhoto($data);
break;
}
return $result;
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\TelegramLog;
/**
* User "/weather" command
*/
class WeatherCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'weather';
/**
* @var string
*/
protected $description = 'Show weather by location';
/**
* @var string
*/
protected $usage = '/weather <location>';
/**
* @var string
*/
protected $version = '1.2.0';
/**
* Base URI for OpenWeatherMap API
*
* @var string
*/
private $owm_api_base_uri = 'http://api.openweathermap.org/data/2.5/';
/**
* Get weather data using HTTP request
*
* @param string $location
*
* @return string
*/
private function getWeatherData($location)
{
$client = new Client(['base_uri' => $this->owm_api_base_uri]);
$path = 'weather';
$query = [
'q' => $location,
'units' => 'metric',
'APPID' => trim($this->getConfig('owm_api_key')),
];
try {
$response = $client->get($path, ['query' => $query]);
} catch (RequestException $e) {
TelegramLog::error($e->getMessage());
return '';
}
return (string) $response->getBody();
}
/**
* Get weather string from weather data
*
* @param array $data
*
* @return string
*/
private function getWeatherString(array $data)
{
try {
if (!(isset($data['cod']) && $data['cod'] === 200)) {
return '';
}
//http://openweathermap.org/weather-conditions
$conditions = [
'clear' => ' ☀️',
'clouds' => ' ☁️',
'rain' => ' ☔',
'drizzle' => ' ☔',
'thunderstorm' => ' ⚡️',
'snow' => ' ❄️',
];
$conditions_now = strtolower($data['weather'][0]['main']);
return sprintf(
'The temperature in %s (%s) is %s°C' . PHP_EOL .
'Current conditions are: %s%s',
$data['name'], //city
$data['sys']['country'], //country
$data['main']['temp'], //temperature
$data['weather'][0]['description'], //description of weather
isset($conditions[$conditions_now]) ? $conditions[$conditions_now] : ''
);
} catch (Exception $e) {
TelegramLog::error($e->getMessage());
return '';
}
}
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$text = '';
if (trim($this->getConfig('owm_api_key'))) {
$location = trim($message->getText(true));
if ($location !== '') {
if ($weather_data = json_decode($this->getWeatherData($location), true)) {
$text = $this->getWeatherString($weather_data);
}
if ($text === '') {
$text = 'Cannot find weather for location: ' . $location;
}
} else {
$text = 'You must specify location in format: /weather <city>';
}
} else {
$text = 'OpenWeatherMap API key not defined.';
}
$data = [
'chat_id' => $chat_id,
'text' => $text,
];
return Request::sendMessage($data);
}
}
<?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Written by Marco Boretto <marco.bore@gmail.com>
*/
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\File;
use Longman\TelegramBot\Entities\PhotoSize;
use Longman\TelegramBot\Entities\UserProfilePhotos;
use Longman\TelegramBot\Request;
/**
* User "/whoami" command
*/
class WhoamiCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'whoami';
/**
* @var string
*/
protected $description = 'Show your id, name and username';
/**
* @var string
*/
protected $usage = '/whoami';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$message = $this->getMessage();
$from = $message->getFrom();
$user_id = $from->getId();
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$data = [
'chat_id' => $chat_id,
'reply_to_message_id' => $message_id,
];
//Send chat action
Request::sendChatAction([
'chat_id' => $chat_id,
'action' => 'typing',
]);
$caption = sprintf(
'Your Id: %d' . PHP_EOL .
'Name: %s %s' . PHP_EOL .
'Username: %s',
$user_id,
$from->getFirstName(),
$from->getLastName(),
$from->getUsername()
);
//Fetch user profile photo
$limit = 10;
$offset = null;
$response = Request::getUserProfilePhotos(
[
'user_id' => $user_id,
'limit' => $limit,
'offset' => $offset,
]
);
if ($response->isOk()) {
/** @var UserProfilePhotos $user_profile_photos */
$user_profile_photos = $response->getResult();
if ($user_profile_photos->getTotalCount() > 0) {
$photos = $user_profile_photos->getPhotos();
/** @var PhotoSize $photo */
$photo = $photos[0][2];
$file_id = $photo->getFileId();
$data['photo'] = $file_id;
$data['caption'] = $caption;
$result = Request::sendPhoto($data);
//Download the photo after send message response to speedup response
$response2 = Request::getFile(['file_id' => $file_id]);
if ($response2->isOk()) {
/** @var File $photo_file */
$photo_file = $response2->getResult();
Request::downloadFile($photo_file);
}
return $result;
}
}
//No Photo just send text
$data['text'] = $caption;
return Request::sendMessage($data);
}
}
<?php
/**
* README
* This configuration file is intended to run your commands with crontab.
* Uncommented parameters must be filled
*/
// Load composer
require __DIR__ . '/vendor/autoload.php';
// Add you bot's API key and name
$API_KEY = 'your_bot_api_key';
$BOT_NAME = 'username_bot';
// 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',
//];
// Your command(s) to run, pass it just like in a message (arguments supported)
$commands = ['/whoami', '/echo I\'m a bot!'];
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($path . '/' . $BOT_NAME . '_error.log');
//Longman\TelegramBot\TelegramLog::initDebugLog($path . '/' . $BOT_NAME . '_debug.log');
//Longman\TelegramBot\TelegramLog::initUpdateLog($path . '/' . $BOT_NAME . '_update.log');
// Enable MySQL
//$telegram->enableMySql($mysql_credentials);
// Enable MySQL with table prefix
//$telegram->enableMySql($mysql_credentials, $BOT_NAME . '_');
// Uncomment this line to load example commands
//$telegram->addCommandsPath(BASE_PATH . '/../examples/Commands');
// Add commands path containing your commands
//$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');
// Requests Limiter (tries to prevent reaching Telegram API limits)
// First argument are options
$telegram->enableLimiter();
//$telegram->enableLimiter(['interval' => 0.5);
// Run user selected commands
$telegram->runCommands($commands);
} 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;
}
#!/usr/bin/env php
<?php
/**
* README
* This configuration file is intented to run the bot with the getUpdates method
* Uncommented parameters must be filled
*/
// Bash script
// while true; do ./getUpdatesCLI.php; done
// Load composer
require __DIR__ . '/vendor/autoload.php';
// Add you bot's API key and name
$API_KEY = 'your_bot_api_key';
$BOT_USERNAME = 'username_bot';
// 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_USERNAME);
// Error, Debug and Raw Update logging
//Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance);
//Longman\TelegramBot\TelegramLog::initErrorLog($path . '/' . $BOT_NAME . '_error.log');
//Longman\TelegramBot\TelegramLog::initDebugLog($path . '/' . $BOT_NAME . '_debug.log');
//Longman\TelegramBot\TelegramLog::initUpdateLog($path . '/' . $BOT_NAME . '_update.log');
// Enable MySQL
$telegram->enableMySql($mysql_credentials);
// Enable MySQL with table prefix
//$telegram->enableMySql($mysql_credentials, $BOT_NAME . '_');
// Uncomment this line to load example commands
//$telegram->addCommandsPath(BASE_PATH . '/../examples/Commands');
// Add commands path containing your commands
//$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
// Second argument are options
//$telegram->enableBotan('your_token');
//$telegram->enableBotan('your_token', ['timeout' => 3]);
// Requests Limiter (tries to prevent reaching Telegram API limits)
// First argument are options
$telegram->enableLimiter();
//$telegram->enableLimiter(['interval' => 0.5);
// Handle telegram getUpdates request
$serverResponse = $telegram->handleGetUpdates();
if ($serverResponse->isOk()) {
$updateCount = count($serverResponse->getResult());
echo date('Y-m-d H:i:s', time()) . ' - Processed ' . $updateCount . ' updates';
} else {
echo date('Y-m-d H:i:s', time()) . ' - Failed to fetch updates' . PHP_EOL;
echo $serverResponse->printError();
}
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
echo $e;
// Log telegram errors
Longman\TelegramBot\TelegramLog::error($e);
} catch (Longman\TelegramBot\Exception\TelegramLogException $e) {
// Catch log initilization errors
echo $e;
}
<?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 = 'your_bot_api_key';
$BOT_USERNAME = 'username_bot';
// 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_USERNAME);
// Error, Debug and Raw Update logging - Don't forget to define the $path
//Longman\TelegramBot\TelegramLog::initialize($your_external_monolog_instance);
//Longman\TelegramBot\TelegramLog::initErrorLog($path . '/' . $BOT_USERNAME . '_error.log');
//Longman\TelegramBot\TelegramLog::initDebugLog($path . '/' . $BOT_USERNAME . '_debug.log');
//Longman\TelegramBot\TelegramLog::initUpdateLog($path . '/' . $BOT_USERNAME . '_update.log');
// Enable MySQL
//$telegram->enableMySql($mysql_credentials);
// Enable MySQL with table prefix
//$telegram->enableMySql($mysql_credentials, $BOT_USERNAME . '_');
// Uncomment this line to load example commands
//$telegram->addCommandsPath(BASE_PATH . '/../examples/Commands');
// Add commands path containing your commands
//$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
// Second argument are options
//$telegram->enableBotan('your_token');
//$telegram->enableBotan('your_token', ['timeout' => 3]);
// Requests Limiter (tries to prevent reaching Telegram API limits)
// First argument are options
$telegram->enableLimiter();
//$telegram->enableLimiter(['interval' => 0.5);
// 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;
}
<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';
$API_KEY = 'your_bot_api_key';
$BOT_USERNAME = 'username_bot';
$hook_url = 'https://yourdomain/path/to/hook.php';
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_USERNAME);
// Set webhook
$result = $telegram->setWebhook($hook_url);
// Uncomment to use certificate
//$result = $telegram->setWebhook($hook_url, ['certificate' => $path_certificate]);
if ($result->isOk()) {
echo $result->getDescription();
}
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
echo $e;
}
<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';
$API_KEY = 'your_bot_api_key';
$BOT_USERNAME = 'username_bot';
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_USERNAME);
// Delete webhook
$result = $telegram->deleteWebhook();
if ($result->isOk()) {
echo $result->getDescription();
}
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
echo $e;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment