Giter Club home page Giter Club logo

telegram's Introduction

Telegram Bot API

PHP Telegram Bot API, Supports Laravel.

Installation

composer require tje3d/telegram

Laravel Only

Service Provider

Tje3d\Telegram\Laravel\TelegramServiceProvider::class

Facade

'Bot' => Tje3d\Telegram\Laravel\Facades\Bot::class

Publish Assets

artisan vendor:publish --tag=telegram

Will make a config file named telegram (config/telegram.php)

Examples

✔️ Initialize a Bot

$bot = new \Tje3d\Telegram\Bot($token);
$info = $bot->getMe();
print_r($info);

✔️ Set Web Hook

$bot->setWebhook('https://sld.tld');

✔️ Get Updates

$response = $bot->getUpdates();
...
$response = $bot->getUpdates($offset=0, $limit=100, $timeout=10); // Long pull

✔️ Send text message (known as sendMessage)

$bot->sendMethod(
	(new \Tje3d\Telegram\Methods\Text())
	    ->text('test')
	    ->chat_id($chatId)
);

⭐️ Or pass configuration as array

$bot->sendMethod(
    (new Tje3d\Telegram\Methods\Text(['text' => 'hi', 'chat_id' => $chatId]))
);

✔️ Keyboard

⭐️ Reply Keyboard

$bot->sendMethod(
	(new Tje3d\Telegram\Methods\Text)
		->text('My Sample Text')
		->chat_id($chatId)
		->reply_markup(
			(new Tje3d\Telegram\Markups\ReplayKeyboardMarkup)
    			->row(function($handler){
    				$handler->addButton(['text' => 'btn1']);
    				$handler->addButton(['text' => 'my special button ⭐️']);
    			})
    			->row(function($handler){
    				$handler->addButton(['text' => 'WOW']);
    			})
    			->row(function($handler){
    				$handler->addButton(['text' => 'Hey this is third line!']);
    			})
    			->row(function($handler){
    				$handler->addButton(['text' => '1']);
    				$handler->addButton(['text' => '2']);
    				$handler->addButton(['text' => '3']);
    				$handler->addButton(['text' => '4']);
    			})
		)
);

image

⭐️ Inline Keyboard

$bot->sendMethod(
	(new Tje3d\Telegram\Methods\Text)
		->text('My Sample Text')
		->chat_id($testChatId)
		->reply_markup(
			(new Tje3d\Telegram\Markups\InlineKeyboardMarkup)
    			->row(function($handler){
    				$handler->addButton(['text' => 'btn1', 'url' => 'http://sld.tld']);
    				$handler->addButton(['text' => 'my special button ⭐️', 'url' => 'http://sld.tld']);
    			})
    			->row(function($handler){
    				$handler->addButton(['text' => 'WOW', 'callback_data' => 'doSomethingSpecial']);
    			})
		)
);

image

✔️ Photo, Audio, Video, Document ...

$bot->sendMethod(
	(new \Tje3d\Telegram\Methods\Photo)
		->chat_id($chatId)
		->photo(realpath('pic.png'))
);

...

$bot->sendMethod(
	(new \Tje3d\Telegram\Methods\Video)
		->chat_id($chatId)
		->video(realpath('video.mp4'))
		->duration(10) // optional
		->width(320) // optional
		->height(320) // optional
);

...

$bot->sendMethod(
	(new \Tje3d\Telegram\Methods\Audio)
		->chat_id($chatId)
		->audio(realpath('video.mp3'))
		->duration(30) // optional
		->performer('tje3d') // optional
		->title('Great music') // optional
);
...

✔️ ChatAction

$bot->sendMethod(
	(new \Tje3d\Telegram\Methods\ChatAction)
		->chat_id($testChatId)
		->typing() // Could be: upload_photo, record_video, upload_video, record_audio, upload_audio, upload_document, find_location
);

Exceptions

Throw's Tje3d\Telegram\Exceptions\TelegramResponseException if sendMethod failed.

try {
	$bot = new \Tje3d\Telegram\Bot($token);
	$response = $bot->sendMethod(
		(new \Tje3d\Telegram\Methods\Text())
		    ->text($text)
		    ->chat_id($chatId)
	);
} catch (TelegramResponseException $e) {
	print_r($e->response());
}

Contact me

You can contact me via Telegram or Email.

telegram's People

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

qa1 gunesahmet

telegram's Issues

How can I use data when webhook is setted?

I can give webhook data in a laravel POST route and saving them into a file. every time a hook is sent to my server the bot gime me a message that a hook is recieved.
but when I want to use this data I have some problem with them.
I used this forms but all of them have not respond to my bot:

public function postWebhook(Request $request)
	{
		$alldata = $request->all();
		$telegram = new Telegram('mytoken');
		$result = $telegram->requestBuilder()
			    ->text(json_encode($alldata->message->text))
			    ->chat_id(163267482)
			    ->sendMessage();
	}
public function postWebhook(Request $request)
	{
		$alldata = $request->all();
		$telegram = new Telegram('mytoken');
		$result = $telegram->requestBuilder()
			    ->text($alldata->message->text)
			    ->chat_id(163267482)
			    ->sendMessage();
	}
public function postWebhook(Request $request)
	{
		$alldata = $request->all();
		$telegram = new Telegram('mytoken');
		$result = $telegram->requestBuilder()
			    ->text($request->message->text)
			    ->chat_id(163267482)
			    ->sendMessage();
	}

but it works just when I use a static message like this:

public function postWebhook(Request $request)
	{
		$alldata = $request->all();
		$telegram = new Telegram('mytoken');
		$result = $telegram->requestBuilder()
			    ->text('وبهوک رسید')
			    ->chat_id(163267482)
			    ->sendMessage();
	}

how can I use $request text?

how to forgot a non answered request?

I have a serious problem with my bot.
when a request is not answered , bot sticked into the request and even user can not /start or...
how can I catch errors and say to telegram bot api to neglect that request and run next request?

there are many causes of errors in bot, user can stop and block it, my code maybe have bugs or even the webservice I am using can not respond in that time.
how can I catch them and avoid bot to stick in this error.

Call to a member function getBody() on null

I used composer to install the package.
here is my simple code:

<?php
require_once('vendor/autoload.php');

$token='488810564:AAHzxaSk_zS9FSEO4ZWTC3Gh87kv28VYFWY';
$bot = new \Tje3d\Telegram\Bot($token);
$info = $bot->getMe();
print_r($info);

and the output is:

marn@mint18 ~/c/bot> php alibot.php 
PHP Fatal error:  Uncaught Error: Call to a member function getBody() on null in /home/marn/code/bot/vendor/tje3d/telegram/src/Request.php:125
Stack trace:
#0 /home/marn/code/bot/vendor/tje3d/telegram/src/Request.php(97): Tje3d\Telegram\Request->send()
#1 /home/marn/code/bot/vendor/tje3d/telegram/src/Bot.php(67): Tje3d\Telegram\Request->sendMethod(Object(Tje3d\Telegram\Methods\GetMe))
#2 /home/marn/code/bot/vendor/tje3d/telegram/src/Bot.php(49): Tje3d\Telegram\Bot->sendMethod(Object(Tje3d\Telegram\Methods\GetMe))
#3 /home/marn/code/bot/alibot.php(6): Tje3d\Telegram\Bot->getMe()
#4 {main}
  thrown in /home/marn/code/bot/vendor/tje3d/telegram/src/Request.php on line 125

how to share users contact with the bot using this package?

I want users share their contact with my bot.
How can I implement such method in my bot using this package?
for example I have this code:

$result = $telegram->requestBuilder()
			    ->text('برای ورود به  باید شماره تلفن خود را در اختیار روبات قرار دهید. در صورت تمایل روی کلید ورود به تی‌چارتر کلیک کنید.👇.'."\n".'☎ خرید تلفنی: +')
			    ->chat_id($chatid)
			    ->reply_markup(
			        [	'resize_keyboard' => true,
			        	'request_contact' => true,
			           "keyboard"=>
			           [
			           		['🔑ورود ','بازگشت👆']
			           ],
			        ]
			    )
			    ->sendMessage(); 

I want to edit it as https://core.telegram.org/bots/api#keyboardbutton and give the share contact property to ورود button.
thanks.

I can not install the package on laravel 5.4

I want to install the package on laravel 5.4 but It gaves me:
composer require tje3d/telegram

  [InvalidArgumentException]                                                   
  Could not find package tje3d/telegram at any version for your minimum-stabi  
  lity (stable). Check the package spelling or your minimum-stability          

how to set webhook correctly?

I created a route like this: Route::get('/setwebhook', 'BotController@handle'); and the methos is this:

   public function handle()
  {		
    	$telegram = new Telegram('306779470:AAHKlLEbwnzv-2t2OjUr2hBynhAqkG2owTY');
	$result = $telegram->requestBuilder()
	    ->setWebhook('https://x.y.ir/');
	    return 'webhook is set';
   }

and https://x.y.ir/ is the route of my project. so I used this url : Route::post('/', 'BotController@postWebhook');
the method is:

public function postWebhook($request)
   {
   	$alldata=\Request::all();
   	dd($request);
   }

I think what I did is right but it gave me this error in laravel:
MethodNotAllowedHttpException in RouteCollection.php line 251

How to check if a bot member is a channel member?

I want to get information about a member of a channel, so I used this method:

$result = $telegram->requestBuilder()
	    ->user_id(163267482)
	    ->chat_id(@karmoon)
	    ->getChatMember();
dd($result);

and the user is registerred in the channel.
but it gave me 400 error:

+"ok": false
  +"error_code": 400
  +"description": "Bad Request: chat not found"

am I using the method correctly?

how to catch any kind of error in a telegram bot code?

Hi.
how can I send ok to telegram api against any errors or mistake?
thanks.
or in other word when I using this package how can I use try catch like this

public function getInline()
{  
     try
     {
       600 lines of code
       if (haserror)
       {
                 throw new Exception('An ERROR.');
       }
       catch(Exception $ex)                                                   
    {                                                                      
             echo 'Error : '.$ex -> getMessage();                               
        }
  }
}

what should I do for if (haserror) part?

I cannot publish vendor in laravel 5.2 !

after installing the package and modifying app/config.php I have this error:

reka@marn ~/b/projectname> php artisan vendor:publish --tag=telegram
PHP Fatal error:  Class Tje3d\Telegram\Laravel\TelegramServiceProvider contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Illuminate\Support\ServiceProvider::register) in /home/reka/bot/projectname/vendor/tje3d/telegram/src/Laravel/TelegramServiceProvider.php on line 35


I think we need a register method!
                                                                                                                                                                                            
 [Symfony\Component\Debug\Exception\FatalErrorException]                                                                                                                                    
 Class Tje3d\Telegram\Laravel\TelegramServiceProvider contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Illuminate\Support\ServicePro  
 vider::register)            

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.