Commit 16feb519 authored by LONGMAN's avatar LONGMAN

Initial commit

parent 73d12c2a
# Telegram Api
\ No newline at end of file
# PHP Telegram Bot
======================
A Telegram Bot based on the official [Telegram Bot API](https://core.telegram.org/bots/api)
## introduction
This is a pure php Telegram Bot, fully extensible via plugins. Telegram recently announced official support for a [Bot API](https://telegram.org/blog/bot-revolution) allowing integrators of all sorts to bring automated interactions to the mobile platform. This Bot aims to provide a platform where one could simply write a plugin and have interactions in a matter of minutes.
Instructions
============
1. Message @botfather https://telegram.me/botfather with the following text: `/newbot`
If you don't know how to message by username, click the search field on your Telegram app and type `@botfather`, you should be able to initiate a conversation. Be careful not to send it to the wrong contact, because some users has similar usernames to `botfather`.
![botfather initial conversation](http://imgur.com/aI26ixR)
2. @botfather replies with `Alright, a new bot. How are we going to call it? Please choose a name for your bot.`
3. Type whatever name you want for your bot.
4. @botfather replies with `Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.`
5. Type whatever username you want for your bot, minimum 5 characters, and must end with `bot`. For example: `telesample_bot`
6. @botfather replies with:
Done! Congratulations on your new bot. You will find it at telegram.me/telesample_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands.
Use this token to access the HTTP API:
<b>123456789:AAG90e14-0f8-40183D-18491dDE</b>
For a description of the Bot API, see this page: https://core.telegram.org/bots/api
7. Note down the 'token' mentioned above.
8. Type `/setprivacy` to @botfather.
![botfather later conversation](http://imgur.com/tWDVvh4)
9. @botfather replies with `Choose a bot to change group messages settings.`
10. Type `@telesample_bot` (change to the username you set at step 5 above, but start it with `@`)
11. @botfather replies with
'Enable' - your bot will only receive messages that either start with the '/' symbol or mention the bot by username.
'Disable' - your bot will receive all messages that people send to groups.
Current status is: ENABLED
12. Type `Disable` to let your bot receive all messages sent to a group. This step is up to you actually.
13. @botfather replies with `Success! The new status is: DISABLED. /help`
## Installation
You need server with https and composer support.
Create composer.json filde:
```js
{
"name": "yourproject/yourproject",
"type": "project",
"require": {
"php": ">=5.3.0",
"longman/telegram-bot": "*"
}
}
```
And run composer update
###### bot token
You will notice that the Telegram Bot wants a value for `API_KEY`. This token may be obtained via a telegram client for your bot. See [this](https://core.telegram.org/bots#botfather) link if you are unsure of how to so this.
## Usage
You must set [WebHook](https://core.telegram.org/bots/api#setwebhook)
Create set.php and put:
```php
<?php
$loader = require __DIR__.'/vendor/autoload.php';
$API_KEY = 'your_bot_api_key';
// create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY);
// set webhook
$telegram->setWebHook('https://yourdomain/yourpath_to_hook.php');
```
After c reate hook.php and put:
```php
<?php
$loader = require __DIR__.'/vendor/autoload.php';
$API_KEY = 'your_bot_api_key';
// create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY);
// handle telegram webhook request
$telegram->handle();
```
This code is available on [Github][0]. Pull requests are welcome.
Troubleshooting
---------------
If you like living on the edge, please report any bugs you find on the [PHP Telegram Bot issues](https://github.com/akalongman/php-telegram-bot/issues) page.
## Credits
Created by [Avtandil Kikabidze][1].
[0]: https://github.com/akalongman/php-telegram-bot
[1]: mailto:akalongman@gmail.com
\ No newline at end of file
{
"name": "longman/telegram-api",
"name": "longman/telegram-bot",
"type": "library",
"description": "PHP library",
"keywords": ["string", "utilities", "translit"],
"description": "PHP telegram bot",
"keywords": ["telegram", "bot", "api"],
"license": "MIT",
"homepage": "https://github.com/akalongman/telegram-api",
"homepage": "https://github.com/akalongman/php-telegram-bot",
"support": {
"issues": "https://github.com/akalongman/telegram-api/issues",
"source": "https://github.com/akalongman/telegram-api"
"issues": "https://github.com/akalongman/php-telegram-bot/issues",
"source": "https://github.com/akalongman/php-telegram-bot"
},
"authors": [
{
......@@ -22,7 +22,7 @@
},
"autoload": {
"psr-4": {
"Longman\\TelegramApi\\": "src/"
"Longman\\TelegramBot\\": "src/"
}
},
"autoload-dev": {
......
<?php
/*
* This file is part of the TelegramApi 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\TelegramApi\Commands;
use Longman\TelegramApi\Request;
use Longman\TelegramApi\Command;
use Longman\TelegramApi\Entities\Update;
class DateCommand extends Command
{
private $google_api_key = '';
private $base_url = 'https://maps.googleapis.com/maps/api';
private $date_format = 'd-m-Y H:i:s';
private function getCoordinates($location) {
$url = $this->base_url.'/geocode/json?';
$params = 'address='.urlencode($location);
if (!empty($this->google_api_key)) {
$params .= '&key='.$this->google_api_key;
}
$data = $this->request($url.$params);
if (empty($data)) {
return false;
}
$data = json_decode($data, true);
if (empty($data)) {
return false;
}
if ($data['status'] !== 'OK') {
return false;
}
$lat = $data['results'][0]['geometry']['location']['lat'];
$lng = $data['results'][0]['geometry']['location']['lng'];
$acc = $data['results'][0]['geometry']['location_type'];
$types = $data['results'][0]['types'];
return array($lat, $lng, $acc, $types);
}
private function getDate($lat, $lng) {
$url = $this->base_url.'/timezone/json?';
$timestamp = time();
$params = 'location='.urlencode($lat).','.urlencode($lng).'&timestamp='.urlencode($timestamp);
if (!empty($this->google_api_key)) {
$params .= '&key='.$this->google_api_key;
}
$data = $this->request($url.$params);
if (empty($data)) {
return false;
}
$data = json_decode($data, true);
if (empty($data)) {
return false;
}
if ($data['status'] !== 'OK') {
return false;
}
$local_time = $timestamp + $data['rawOffset'] + $data['dstOffset'];
return array($local_time, $data['timeZoneId']);
}
private function getFormattedDate($location) {
if (empty($location)) {
return 'The time in nowhere is never';
}
list($lat, $lng, $acc, $types) = $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(date('Y-m-d H:i:s', $local_time), new \DateTimeZone($timezone_id));
//$timestamp = $date_utc->format($this->date_format);
$return = 'The local time in '.$timezone_id.' is: '.date($this->date_format, $local_time).'';
return $return;
}
private function request($url) {
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array($ch, $curlConfig);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code !== 200) {
throw new Exception('Error receiving data from url');
}
curl_close($ch);
return $response;
}
public function execute() {
$update = $this->getUpdate();
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$text = $message->getText(true);
if (empty($text)) {
$text = 'You must specify location in format: /date <city>';
} else {
$date = $this->getformattedDate($text);
if (empty($date)) {
$text = 'Can not find date for location: '.$text;
} else {
$text = $date;
}
}
$data = array();
$data['chat_id'] = $chat_id;
$data['reply_to_message_id'] = $message_id;
$data['text'] = $text;
$result = Request::sendMessage($data);
}
}
......@@ -33,9 +33,6 @@ class EchoCommand extends Command
$result = Request::sendMessage($data);
var_dump($result);
die;
}
......
<?php
/*
* This file is part of the TelegramApi 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\TelegramApi\Commands;
use Longman\TelegramApi\Request;
use Longman\TelegramApi\Command;
use Longman\TelegramApi\Entities\Update;
class HelpCommand extends Command
{
public function execute() {
$update = $this->getUpdate();
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$text = $message->getText(true);
$data = array();
$data['chat_id'] = $chat_id;
$data['text'] = 'GeoBot v. '.VERSION;
$result = Request::sendMessage($data);
}
}
<?php
/*
* This file is part of the TelegramApi 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\TelegramApi\Commands;
use Longman\TelegramApi\Request;
use Longman\TelegramApi\Command;
use Longman\TelegramApi\Entities\Update;
class WeatherCommand extends Command
{
private function getWeather($location) {
$url = 'http://api.openweathermap.org/data/2.5/weather?q='.$location.'&units=metric';
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => $url,
//CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
//CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
//CURLOPT_POSTFIELDS => $data
//CURLOPT_VERBOSE => true,
//CURLOPT_HEADER => true,
);
curl_setopt_array($ch, $curlConfig);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code !== 200) {
throw new Exception('Error receiving data from url');
}
curl_close($ch);
return $response;
}
private function getWeatherString($location) {
if (empty($location)) {
return false;
}
// try/catch
$data = $this->getWeather($location);
$decode = json_decode($data, true);
if (empty($decode) || $decode['cod'] != 200) {
return false;
}
$city = $decode['name'];
$country = $decode['sys']['country'];
$temp = 'The temperature in '.$city .' (' .$country.') is '.$decode['main']['temp'].'°C';
$conditions = 'Current conditions are: '.$decode['weather'][0]['description'];
switch(strtolower($decode['weather'][0]['main'])) {
case 'clear':
$conditions .= ' ☀';
break;
case 'clouds':
$conditions .= ' ☁☁';
break;
case 'rain':
$conditions .= ' ☔';
break;
case 'thunderstorm':
$conditions .= ' ☔☔☔☔';
break;
}
return $temp."\n".$conditions;
}
public function execute() {
$update = $this->getUpdate();
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$text = $message->getText(true);
if (empty($text)) {
$text = 'You must specify location in format: /weather <city>';
} else {
$weather = $this->getWeatherString($text);
if (empty($weather)) {
$text = 'Can not find weather for location: '.$text;
} else {
$text = $weather;
}
}
$data = array();
$data['chat_id'] = $chat_id;
$data['reply_to_message_id'] = $message_id;
$data['text'] = $text;
$result = Request::sendMessage($data);
}
}
......@@ -12,7 +12,8 @@ namespace Longman\TelegramApi;
class Request
{
private static $api_key = '';
private static $telegram;
private static $input;
private static $methods = array(
'getMe',
......@@ -32,31 +33,55 @@ class Request
public static function setApiKey($api_key) {
self::$api_key = $api_key;
if (empty(self::$api_key)) {
throw new Exception('API KEY not defined!');
}
public static function initialize(Telegram $telegram) {
self::$telegram = $telegram;
}
public static function getInput() {
$input = file_get_contents('php://input');
return $input;
if ($update = self::$telegram->getCustomUpdate()) {
self::$input = $update;
} else {
self::$input = file_get_contents('php://input');
}
self::log();
return self::$input;
}
private static function log() {
if (!self::$telegram->getLogRequests()) {
return false;
}
$path = self::$telegram->getLogPath();
if (!$path) {
return false;
}
$status = file_put_contents($path, self::$input."\n", FILE_APPEND);
return $status;
}
public static function send($action, array $data = null) {
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => 'https://api.telegram.org/bot'.self::$api_key.'/'.$action,
CURLOPT_URL => 'https://api.telegram.org/bot'.self::$telegram->getApiKey().'/'.$action,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
//CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'),
//CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
//CURLOPT_POSTFIELDS => $data
);
if (!empty($data)) {
if (substr($data['text'], 0, 1) === '@') {
$data['text'] = ' '.$data['text'];
}
//$data = array_map('urlencode', $data);
$curlConfig[CURLOPT_POSTFIELDS] = $data;
}
......
......@@ -13,6 +13,11 @@ namespace Longman\TelegramApi;
ini_set('max_execution_time', 0);
ini_set('memory_limit', -1);
date_default_timezone_set('UTC');
define('VERSION', '0.0.1');
use Longman\TelegramApi\Entities\Update;
......@@ -53,6 +58,21 @@ class Telegram
*/
protected $update;
/**
* Log Requests
*
* @var bool
*/
protected $log_requests;
/**
* Log path
*
* @var string
*/
protected $log_path;
/**
* Constructor
*
......@@ -60,7 +80,7 @@ class Telegram
*/
public function __construct($api_key) {
$this->api_key = $api_key;
Request::setApiKey($this->api_key);
Request::initialize($this);
}
......@@ -76,6 +96,61 @@ class Telegram
return $this;
}
/**
* Get custom update string for debug purposes
*
* @return string $update
*/
public function getCustomUpdate() {
return $this->update;
}
/**
* Set log requests
*
* @param bool $log_requests
*
* @return \Longman\TelegramApi\Telegram
*/
public function setLogRequests($log_requests) {
$this->log_requests = $log_requests;
return $this;
}
/**
* Get log requests
*
* @return bool
*/
public function getLogRequests() {
return $this->log_requests;
}
/**
* Set log path
*
* @param string $log_path
*
* @return \Longman\TelegramApi\Telegram
*/
public function setLogPath($log_path) {
$this->log_path = $log_path;
return $this;
}
/**
* Get log path
*
* @param string $log_path
*
* @return string
*/
public function getLogPath() {
return $this->log_path;
}
/**
* Handle bot request
*
......@@ -85,9 +160,6 @@ class Telegram
$this->input = Request::getInput();
if (!empty($this->update)) {
$this->input = $this->update;
}
if (empty($this->input)) {
......@@ -163,4 +235,15 @@ class Telegram
$this->commands_dir[] = $folder;
}
/**
* Get API KEY
*
* @return string
*/
public function getApiKey() {
return $this->api_key;
}
}
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