This article will guide you through setting up a Telegram channel and integrating it with a Laravel-based bot. We'll cover essential steps like creating a Telegram bot, establishing a webhook, and developing basic bot functionalities using the Laravel framework.
To start your own Telegram channel, navigate to the "New Message" menu within the Telegram app and select "New Channel." By default, newly created channels have private visibility. However, you can easily adjust their privacy settings in the channel profile to make them public. Public channels offer greater accessibility: their content can be viewed on the web even without a Telegram account and are also discoverable through search engines.
Start by accessing @BotFather. Type the command '/mybots' and then send a new command along with a short description. As a result, you will receive a Token for working with Telegram API.
Add the channel name and token to the settings file
...
TELEGRAM_BOT_TOKEN=YOUR_TEGERAM_TOKEN
TELEGRAM_CHANNEL_NAME=@newtelegramchanelname
TELEGRAM_ENDPOINT=https://api.telegram.org
...
<?php
return [
'token' => env('TELEGRAM_BOT_TOKEN', null),
'channel' => env('TELEGRAM_CHANNEL_NAME', null),
'endpoint' => env('TELEGRAM_ENDPOINT', null),
];
Create a TelegramHelper to send messages to our new Telegram channel using our bot.
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\Http;
class TelegramHelper
{
/**
* @var string
*/
private $token;
/**
* @var string
*/
private $channel;
/**
* @var string
*/
private $endpoint;
/**
*
*/
public function __construct()
{
$this->token = config('telegram.token');
$this->channel = config('telegram.channel');
$this->endpoint = config('telegram.endpoint');
}
/**
* @param $message
* @return void
*/
public function sendMessage($message)
{
$query = http_build_query([
'chat_id' => $this->channel,
'text' => $message,
]);
$url = $this->endpoint . "/bot" . $this->token . "/sendMessage?" . $query;
try {
Http::get($url);
} catch (\Exception $e) {
echo $e->getMessage();
}
}
}
Create a Console Command to test sending messages to the Telegram channel
<?php
namespace App\Console\Commands;
use App\Helpers\TelegramHelper;
use Illuminate\Console\Command;
class TelegramTest extends Command
{
/**
* @var string
*/
protected $signature = 'telegram:test';
/**
* @var string
*/
protected $description = '';
/**
* @param TelegramHelper $telegramHelper
* @return void
*/
public function handle(TelegramHelper $telegramHelper): void
{
$telegramHelper->sendMessage("Lorem Ipsum");
}
}
If you are using Laravel 11
create a tinker.php
configuration file and add your class with the console command.
<?php
return [
'commands' => [
\App\Console\Commands\TelegramTest::class,
],
];