LaraGram API Server
- Introduction
- Installation
- Running the Server
- WebSocket Subscriptions
- Using the Server With LaraGram
- Storage
- Statistics
- Logging
- Running in Production
Introduction
LaraGram API Server is a Telegram Bot API server written in PHP and built on top of LaraGram MTProto. It is a drop-in replacement for the official telegram-bot-api server: it accepts the same command-line options, serves the same HTTP API, and returns the same responses and error descriptions. Every Bot API method is supported, and file_id values are interchangeable with the ones issued by api.telegram.org.
Since the server speaks the plain Bot API over HTTP, it is not tied to LaraGram. Any Telegram bot library in any language may use it by pointing its API URL at the server instead of https://api.telegram.org.
Running your own Bot API server gives you the same benefits as the official local server, such as uploading files up to 2000 MB, downloading files without a size limit, and receiving updates through webhooks on any IP address and port.
On top of the official API, the server offers a third way of receiving updates next to long polling and webhooks: WebSocket subscriptions, which push the updates to your bot over a connection it opens and also carry its method calls.
Installation
Server Prerequisites
The API Server requires PHP 8.3 or greater along with the following PHP extensions:
- Swoole
- JSON
- Mbstring
- OpenSSL
- Zlib
Typically, the Swoole extension can be installed via PECL:
pecl install swooleAPI Credentials
Like the official server, the API Server logs in to Telegram with an application identifier. Sign in at my.telegram.org, open API development tools, and create an application. Telegram will give you an api_id (a number) and an api_hash (a 32 character string). You will pass both of these values to the server when starting it.
WARNING
Your api_hash is a secret. Never commit it to source control or share it publicly.
Global Installation
The most convenient way to install the API Server is as a global Composer package, which makes the laragram-server command available everywhere:
composer global require laraxgram/apiserverMake sure Composer's global bin directory is in your system's $PATH. You may find the location of this directory by running:
composer global config bin-dir --absoluteThen, verify the installation:
laragram-server --versionProject Installation
Alternatively, you may install the API Server as a dependency of a single project. In that case, the server binary is available at vendor/bin/laragram-server:
composer require laraxgram/apiserver
vendor/bin/laragram-server --versionNOTE
On its first start, the server compiles the MTProto TL schema into the laraxgram/mtproto package directory of your Composer installation. The user running the server must have write access to that directory the first time it starts. Later starts reuse the compiled classes.
Running the Server
Start the server by passing your API credentials. The --local option enables local mode, which is what you will want in most cases:
laragram-server --api-id=123456 --api-hash=0123456789abcdef0123456789abcdef --localInstead of passing the credentials as options, you may define the API_ID and API_HASH environment variables:
export API_ID=123456
export API_HASH=0123456789abcdef0123456789abcdef
laragram-server --localBy default, the server listens on port 8081 of every local IPv4 address and stores its data in the current directory. You may change these with the --http-port, --http-ip-address, and --dir options:
laragram-server --local --http-ip-address=127.0.0.1 --http-port=8081 --dir=/var/lib/laragram-serverPress Ctrl+C to stop the server.
Sending Requests
Requests are sent exactly like they are sent to api.telegram.org, using the server's address as the base URL:
curl http://127.0.0.1:8081/bot<token>/getMeThe first request for a bot token logs that bot in. Later requests reuse the same connection, and the bot stays logged in across server restarts. Bots on Telegram's test environment may be used by adding /test after the token:
curl http://127.0.0.1:8081/bot<token>/test/getMeAvailable Options
The server accepts the same options as the official telegram-bot-api binary. You may display them at any time using the --help option:
| Option | Description |
|---|---|
-h, --help | Display the help text and exit. |
--version | Display the supported Bot API version and exit. |
--local | Enable local mode. |
--api-id | The application identifier. Defaults to the API_ID environment variable. |
--api-hash | The application identifier hash. Defaults to the API_HASH environment variable. |
-p, --http-port | The HTTP listening port. Defaults to 8081. |
-s, --http-stat-port | The HTTP statistics port. Disabled by default. |
-d, --dir | The server working directory. Defaults to the current directory. |
-f, --files-dir | The directory for storing downloaded files. Defaults to the working directory. |
-t, --temp-dir | The directory for storing temporary files of uploads. Defaults to the system temporary directory. |
--filter | <remainder>/<modulo>: serve only the bots whose bot_user_id % modulo == remainder. |
--max-webhook-connections | The default maximum number of webhook connections per bot. Defaults to 100 in local mode and 40 otherwise. |
--http-ip-address | The local IP address to accept HTTP connections on. Defaults to every local IPv4 address. |
--http-stat-ip-address | The local IP address to accept statistics connections on. Defaults to every local IPv4 address. |
-l, --log | The path of the log file. Defaults to the standard error stream. |
-v, --verbosity | The log verbosity level. |
--memory-verbosity | The memory log verbosity level. Defaults to 3. |
--log-max-file-size | The maximum size of the log file in bytes. |
-u, --username | The effective user name to switch to after start-up. |
-g, --groupname | The effective group name to switch to after start-up. |
-c, --max-connections | The maximum number of open connections. |
--cpu-affinity | The CPU affinity, as a 64-bit mask. |
--main-thread-affinity | The CPU affinity of the main thread, as a 64-bit mask. |
--proxy | An HTTP proxy for outgoing webhook requests, in the http://host:port format. |
--stream-files | Serve files at their /file/ URLs, streaming them from Telegram. |
--stream-read-ahead | The number of 1 MB chunks of a streamed file fetched ahead of the one being sent. Defaults to 4. |
--no-file-storage | Never write files to disk, see running without file storage. Requires --stream-files. |
--no-storage-cleanup | Never delete downloaded files automatically. |
--storage-* | The limits and filters of the automatic clean-up. |
The --stream-files, --stream-read-ahead, and --no-file-storage options are specific to the LaraGram API Server; the official server doesn't have them.
NOTE
Some options, such as --memory-verbosity, --log-max-file-size, and the CPU affinity options, are accepted for compatibility with scripts written for the official server.
Local Mode
When the server is started with the --local option, it behaves like the official server in local mode. In this mode, the server is able to:
- Download files without a size limit.
- Upload files up to 2000 MB.
- Upload files using their local path and the
file://URI scheme. - Use an HTTP URL for the webhook.
- Use any local IP address for the webhook.
- Use any port for the webhook.
- Set
max_webhook_connectionsup to100000. - Return the absolute local path as the
file_pathof agetFilerequest, so the file may be read directly from disk without downloading it.
Without --local, the server applies the same limits as api.telegram.org.
Switching From the Cloud Bot API
Before a bot can be used with your own server, it must be logged out of the cloud Bot API. Call the logOut method on api.telegram.org once:
curl https://api.telegram.org/bot<token>/logOutAfter that, every request of the bot should go to your server. Likewise, to move a bot to a different server, call logOut on the current one first. Use the close method instead when you only want to restart the bot on the same server.
WebSocket Subscriptions
Besides long polling and webhooks, the server offers a third way to receive updates: a WebSocket connection opened by the bot. While the connection is open, the server pushes every update over it the moment it arrives, and the bot may call any Bot API method over the same connection. The bot needs no public address, as with long polling, and gets its updates without any request, as with a webhook. This is a feature of the LaraGram API Server; the official server doesn't have it.
The updates are the official Update objects, and the methods take the same parameters and return the same results as over HTTP, so an existing library only needs a small transport to use it. LaraGram applications use it with a single setting, API_MODE=websocket; see receiving updates over WebSocket.
Subscribing
Open a WebSocket connection to the subscribeWebsocket method of your bot, using the ws:// scheme, or wss:// behind a TLS proxy:
ws://127.0.0.1:8081/bot<token>/subscribeWebsocketBots on Telegram's test environment add /test after the token, as for HTTP requests. The connection accepts the following optional query parameters:
| Parameter | Description |
|---|---|
allowed_updates | A JSON-serialized list of the update types to receive, as for setWebhook and getUpdates. |
drop_pending_updates | true to drop the updates waiting to be delivered. |
When the subscription can't start, the server answers the handshake with an ordinary HTTP error, whose body is the usual JSON error object: 401 for an invalid token, 409 while a webhook is set, and 429 with a Retry-After header when there are too many attempts. A request to subscribeWebsocket that isn't a WebSocket handshake is answered with 400 Bad Request: subscribeWebsocket requires a WebSocket connection.
Receiving Updates
Every message the server sends is a JSON text message with a type and a data field. Updates have the update type, and their data is the update itself:
{"type": "update", "data": {"update_id": 123456789, "message": {...}}}The updates waiting to be delivered are sent first, in order, followed by new updates as they arrive. The bot doesn't have to confirm them: after sending updates, the server sends a WebSocket ping, and the pong that every WebSocket client answers with on its own confirms everything sent before it, as the next getUpdates call confirms the previous updates. Updates that were sent but not confirmed when the connection dropped are sent again to the next subscription, so an update may occasionally arrive twice; compare update_ids if that matters to your bot.
Calling Methods
To call a method over the connection, send a text message with the method's name, its parameters in a body object, and an id of your choice:
{"id": "a1", "method": "sendMessage", "body": {"chat_id": 123456789, "text": "Hello!"}}The body holds exactly what the JSON body of an HTTP request would. The response comes back as a response message with the same id; its data holds the result of the method, or the fields of the usual error object:
{"type": "response", "data": {"id": "a1", "result": {"message_id": 42, ...}}}
{"type": "response", "data": {"id": "a2", "error_code": 400, "description": "Bad Request: chat not found"}}Requests are executed concurrently, so responses may arrive in any order; match them by their id. A request without an id is executed without a response. A message that isn't valid JSON is ignored, and a request without a method gets a 400 error. At most 1,000 requests may be in progress on a connection at the same time. Every method may be called over the connection, except getUpdates and setWebhook, which conflict with the subscription.
Of course, the bot may keep calling methods over HTTP instead; the subscription only changes how the updates arrive.
Uploading Files
As over HTTP, a request may pass a file_id, or an HTTP URL for Telegram to download, in its body. To upload files, send the request as a single binary message made of a 4-byte big-endian header length, a JSON header, and the contents of the files, one after another:
uint32 (big-endian) header length | header (JSON) | contents of file 1 | contents of file 2 | …The header is the request, with a files list describing the contents that follow, in order:
{
"id": "u1",
"method": "sendDocument",
"body": {"chat_id": 123456789, "document": "attach://report", "caption": "Monthly report"},
"files": [
{"name": "report", "filename": "report.pdf", "size": 48213}
]
}The body refers to each file with attach://<name>, as a multipart/form-data request does, so sendMediaGroup, thumbnails, and every other place accepting attach:// work the same way. Each entry of files holds the name used in attach://, the filename, the size in bytes, and, optionally, a mime_type; the MIME type is otherwise guessed from the file name. Up to 50 files may be sent in one request. The files are written to disk as they arrive, or sent to Telegram as they arrive when the server runs without file storage, so large uploads are never held in memory.
Files are downloaded over HTTP as usual: call getFile, over the connection or over HTTP, and download the file from its /file/bot<token>/<file_path> URL.
Conflicts
A subscription, a webhook, and getUpdates are three ways of receiving the same updates, so only one of them may be in use at a time:
| Request | While a webhook is set | While a subscription is open |
|---|---|---|
subscribeWebsocket | 409 Conflict: can't use subscribeWebsocket method while webhook is active; use deleteWebhook to delete the webhook first | The new subscription replaces the open one, which is closed with code 4409. |
setWebhook | Allowed. | 409 Conflict: can't use setWebhook method while a subscription is active; use unsubscribeWebsocket first |
getUpdates | 409, as always. | 409 Conflict: can't use getUpdates method while a subscription is active; use unsubscribeWebsocket first |
A getUpdates request waiting for updates when the bot subscribes is answered with 409 Conflict: terminated by subscription. A subscription isn't stored: it lasts as long as its connection, and the updates that arrive while no subscription is open wait in the queue for the next one.
Unsubscribing
A subscription ends when its connection is closed, by either side, or when the unsubscribeWebsocket method is called. The method may be called over the subscription itself, or over HTTP, which lets another process free the bot for a webhook or getUpdates, as deleteWebhook does for a webhook:
curl http://127.0.0.1:8081/bot<token>/unsubscribeWebsocketIt accepts the optional drop_pending_updates parameter and returns true, with the description Subscription was closed, or Subscription is not active when there was no subscription. The requests still running on the connection are answered first, then the connection is closed with code 1000.
Subscription Information
The getWebsocketInfo method, the counterpart of getWebhookInfo, may be called over HTTP or over the subscription. It returns a WebsocketInfo object:
| Field | Type | Description |
|---|---|---|
is_active | Boolean | true while a subscription is open. |
pending_update_count | Integer | The number of updates waiting to be delivered. |
ip_address | String | Optional. The IP address the open subscription connected from. |
start_date | Integer | Optional. The Unix time the open subscription started. |
allowed_updates | Array of String | Optional. The update types the subscription receives, when not the default ones. |
active_request_count | Integer | Optional. The number of requests of the open subscription being executed. |
last_close_date | Integer | Optional. The Unix time the last subscription ended. |
last_close_code | Integer | Optional. The close code the last subscription ended with. |
last_close_reason | String | Optional. The reason the last subscription ended. |
While a subscription is open, getWebhookInfo returns an empty url, as when getUpdates is used.
Keep-Alive and Closing
The server pings the client every 30 seconds while the connection is idle, and closes a connection that hasn't answered anything for 75 seconds. When the server ends a subscription because of an error, it first sends the error in an error message, then closes the connection with the code 4000 plus the error code:
{"type": "error", "data": {"error_code": 409, "description": "Conflict: terminated by other subscription"}}| Code | Meaning | What the client should do |
|---|---|---|
1000 | unsubscribeWebsocket, close, or logOut was called. | Stop. |
4409 | A newer subscription replaced this one. | Stop: another instance of the bot is running. |
4401, 4400 | The token is no longer valid, or the bot logged out. | Stop. |
4429 | Too many requests; the error message holds the delay. | Reconnect after the delay. |
4500 | The server is restarting. | Reconnect. |
1001 | The client didn't answer pings. | Reconnect. |
1002, 1007, 1009 | The client broke the protocol, sent text that isn't UTF-8, or sent a text message larger than 1 MB. | Fix the client. |
When the connection drops without a close code, reconnect with a growing delay, for example 1, 2, 4… up to 30 seconds.
Implementing a Client
Any WebSocket library following RFC 6455 may be used; the server uses no subprotocol and no extension. A client comes down to the following steps:
connect to ws://server/bot<token>/subscribeWebsocket
on an HTTP error: stop on 401 and 409, otherwise wait and retry
for each text message:
message = parse JSON
if message.type == "update": handle(message.data) // the library's update handler
if message.type == "response": resolve the request with the id message.data.id
to call a method:
send {"id": <a new unique id>, "method": <name>, "body": <parameters>}
wait for the response with that id
when the connection closes:
stop on 1000, 4400, 4401, and 4409; otherwise reconnect with a growing delayFor example, using the WebSocket client built into browsers and Node.js:
const socket = new WebSocket('ws://127.0.0.1:8081/bot<token>/subscribeWebsocket');
const pending = new Map();
function call(method, body) {
const id = crypto.randomUUID();
socket.send(JSON.stringify({id, method, body}));
return new Promise((resolve) => pending.set(id, resolve));
}
socket.onmessage = async (event) => {
const {type, data} = JSON.parse(event.data);
if (type === 'update' && data.message?.text) {
await call('sendMessage', {chat_id: data.message.chat.id, text: 'You said: ' + data.message.text});
} else if (type === 'response') {
pending.get(data.id)?.(data);
pending.delete(data.id);
}
};Behind a Reverse Proxy
When the server sits behind a reverse proxy, such as Nginx terminating TLS, the proxy has to pass the WebSocket handshake through and keep idle connections open longer than the ping interval of 30 seconds:
location / {
proxy_pass http://127.0.0.1:8081;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 120s;
}Using the Server With LaraGram
Configuration
The Bot API server used by your LaraGram application is configured in the api_server section of the config/bot.php configuration file:
'api_server' => [
'binary' => env("API_BINARY", "telegram-bot-api"),
'endpoint' => env("API_ENDPOINT", "https://api.telegram.org"),
'dir' => env("API_DIR", storage_path('app/api-server')),
'log_dir' => '',
'ip' => '127.0.0.1',
'port' => 8081,
'stat' => [
'ip' => '',
'port' => ''
],
'api_id' => env("API_ID", ''),
'api_hash' => env("API_HASH", ''),
'stream_files' => env('API_STREAM_FILES', false),
'stream_read_ahead' => env('API_STREAM_READ_AHEAD', 4),
'file_storage' => env('API_FILE_STORAGE', true),
],The binary option determines which server program the start:apiserver command runs. It defaults to the official telegram-bot-api binary. To use the LaraGram API Server instead, set the API_BINARY environment variable to laragram-server, along with your API credentials and the address of the server:
API_BINARY=laragram-server
API_ENDPOINT=http://127.0.0.1:8081
API_ID=123456
API_HASH=0123456789abcdef0123456789abcdefIf the server is installed in your project rather than globally, use the path to the binary instead:
API_BINARY=vendor/bin/laragram-serverThe endpoint option is the base URL that your application sends its Bot API requests to, so once it points at your server, every request of your bot goes through it. Remember to log the bot out of the cloud Bot API first.
NOTE
When you create your application using the LaraGram installer, you may select Local Bot API server and choose the LaraGram API Server. The installer requires the package in your project and writes all of these environment variables for you.
| Key | Description |
|---|---|
binary | The Bot API server program started by start:apiserver. Any binary accepting the telegram-bot-api options may be used. |
endpoint | The base URL of the Bot API server your application sends requests to. |
dir | The working directory of the server. |
log_dir | The path of the server's log file. Logs go to the console when empty. |
ip | The local IP address the server listens on. |
port | The port the server listens on. |
stream_files | Stream files at their /file/ URLs. LaraGram API Server only. |
stream_read_ahead | The number of 1 MB chunks of a streamed file fetched in advance. |
file_storage | Write files to disk. Set it to false to run without file storage, which requires stream_files. |
stat | The IP address and port of the statistics page. Disabled when empty. |
api_id | Your Telegram application identifier. |
api_hash | Your Telegram application identifier hash. |
Starting the Server
Once configured, you may start the server using the start:apiserver Commander command. The server always starts in local mode:
php laragram start:apiserverThe --binary, --host, --port, and --dir options may be used to override the configured values for a single run:
php laragram start:apiserver --binary=laragram-server --host=127.0.0.1 --port=8082The output of the server is shown in your console, and pressing Ctrl+C stops it.
During development, the dev command starts the server together with the rest of your application whenever API_ENDPOINT points to localhost and your API credentials are set, so you rarely need to start it yourself.
Storage
The Working Directory
The server keeps all of its state in the working directory given by the --dir option. Every bot receives a directory of its own, named after its token, that holds its MTProto session, its settings, and the updates that have not been delivered yet. Bots on the test environment use the token followed by :T. The registered webhooks are stored in the webhooks_db.json file, so they are restored automatically when the server restarts.
working-directory/
├── webhooks_db.json
├── storage_gc.json
└── 123456789:AAE.../
├── bot.binlog
├── tqueue.binlog
└── bot.lockThe bot.binlog file holds the bot's MTProto session, its settings, and the users and chats it knows, and tqueue.binlog holds the updates that have not been delivered yet. Both are append-only logs that are compacted as they grow, so a bot keeps the same few files however many chats it has. Downloaded files are stored next to them, in directories named after their type. Bot directories created by earlier versions of the server are converted to this layout the first time the bot starts.
A bot's directory is deleted when the bot logs out, either through the logOut method or because Telegram rejected its token. Therefore, the working directory should be persistent and writable by the user running the server, and it should never be shared between two running servers.
WARNING
The working directory contains the session of every bot served by the server. Anyone who can read it can act as your bots, so restrict its permissions accordingly.
Serving Files
Files fetched by the getFile method are stored in the bot's directory, or in the directory given by --files-dir. In local mode, getFile returns the absolute path of the file, so an application on the same machine can read it directly from disk.
Like the official server, the API Server does not serve the downloaded files over HTTP by default. Outside of local mode, or when your application runs on another machine, you may let the server stream them, or serve the files directory with a web server such as Nginx. The following configuration serves files at the same URLs as api.telegram.org, which are /file/bot<token>/<file_path>:
location ~ ^/file/bot([^/]+)/(.*)$ {
alias /var/lib/laragram-server/$1/$2;
}
location / {
proxy_pass http://127.0.0.1:8081;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}Streaming Files
When the server is started with the --stream-files option, it serves files itself, at the same URLs as api.telegram.org:
laragram-server --stream-files --api-id=123456 --api-hash=0123456789abcdef0123456789abcdefThe getFile method then answers right away, without downloading the file first. The file_path it returns names the file, and requesting it streams the file from Telegram while it is being downloaded:
curl -O http://127.0.0.1:8081/file/bot<token>/<file_path>Streamed files support byte ranges, so video and audio players can seek, and interrupted downloads can be resumed with a Range header. While one chunk of the file is being sent, the following chunks are already being downloaded; the --stream-read-ahead option sets how many, and defaults to 4 chunks of 1 MB each.
A file that is already on disk is sent from there. When a file is streamed from its first byte to its last, it is also stored like a downloaded file, so the next request is answered from disk and the automatic clean-up removes it in time.
NOTE
Without --local, the limits of api.telegram.org still apply: files over 20 MB can't be streamed. In local mode, getFile returns the absolute path of a file that is already on disk, and the file_path of a streamed file otherwise.
Running Without File Storage
By default, the server writes files to disk twice: getFile stores the files it downloads, and uploads are saved to temporary files until they are sent to Telegram. The --no-file-storage option turns both off, which suits containers with a read-only or small disk:
laragram-server --stream-files --no-file-storage --api-id=123456 --api-hash=0123456789abcdef0123456789abcdefWithout file storage, every file is streamed, so the option requires --stream-files. Uploads are sent to Telegram while the request is being received: a file of up to 10 MB is kept in memory until the request is handled, and a bigger file is sent in parts as they arrive, so the memory used by an upload stays the same whatever its size. Webhook certificates are still saved, since they are part of the bot's settings.
LaraGram's file helpers download files from their /file/ URLs, so they work with both options without any change.
Cleaning Up Downloaded Files
Downloaded files are only a cache of what Telegram stores: a file that has been deleted is simply downloaded again by the next getFile request. Like the official server, the API Server removes old downloads on its own. Every limit applies to each bot separately:
| Limit | Option | Default |
|---|---|---|
| Number of files | --storage-max-files | 40000 |
| Total size | --storage-max-size | 100M |
| Time since the last use | --storage-max-age | 23h |
Each of these limits may be raised, or turned off by setting it to 0. To turn the automatic clean-up off entirely, start the server with --no-storage-cleanup:
laragram-server --local --storage-max-size=20G --storage-max-age=7d --storage-max-files=0WARNING
In local mode, an application that keeps using the absolute file_path returned by getFile should copy the file or call getFile again later, since the file may have been cleaned up in the meantime.
The server checks the limits once a day, and also as soon as downloads push a bot over its file count or size limit. Files past the age limit are deleted first. After that, the least recently used files are deleted until the bot fits its limits. Files downloaded within the last hour are never deleted, but they do count towards the limits. Calling getFile for a file counts as using it.
The following options refine the automatic clean-up:
| Option | Description |
|---|---|
--storage-age-from | Measure the age from the last access (the default) or from the download. |
--storage-immunity | How long a new file is protected from deletion. Defaults to 1h. |
--storage-interval | The time between two scheduled clean-ups. Defaults to 1d. |
--storage-scope | Apply the limits to each bot (the default) or to the whole server. |
--storage-types, --storage-exclude-types | A comma-separated list of file types to clean or to protect. |
--storage-extensions, --storage-exclude-extensions | A comma-separated list of file extensions to clean or to protect. |
--storage-min-file-size, --storage-max-file-size | Only clean files within this size range. |
--storage-bots, --storage-exclude-bots | A comma-separated list of bot identifiers to clean or to protect. |
Sizes accept a K, M, G, or T suffix, and durations accept s, m, h, d, or w, such as 90m or 1d12h. Files outside a filter neither count towards the limits nor get deleted, so --storage-types=videos --storage-max-size=5G keeps the videos of each bot under 5 GB and leaves every other file alone.
The file types are the directories of the downloaded files: animations, documents, music, notification_sounds, passport, photos, profile_photos, secret, secret_thumbnails, stickers, stories, temp, thumbnails, video_notes, videos, voice, and wallpapers.
The storage:clean Command
The storage:clean command runs a single clean-up, which is useful from cron or a scheduler. It accepts the same limits and filters without the storage- prefix, and it is safe to run next to a running server. Unlike the automatic clean-up, it has no default limits, so you must state what to delete:
laragram-server storage:clean --dir=/var/lib/laragram-server --max-age=7d --max-size=50G
# Delete every video and document older than the immunity delay...
laragram-server storage:clean --dir=/var/lib/laragram-server --all --types=videos,documentsThe --dry-run option reports what would be deleted without deleting it, --list prints each deleted file, and --json prints the report as JSON. If the downloaded files are stored elsewhere, pass the same --files-dir as the server.
To run the command from your LaraGram application's scheduler:
use LaraGram\Support\Facades\Schedule;
Schedule::exec('laragram-server storage:clean --dir=/var/lib/laragram-server --max-age=7d')->daily();Statistics
The server can publish a statistics page with the number of bots, requests and updates per second, memory and CPU usage, and per-bot details such as webhooks and pending updates. To enable it, pass a port to the --http-stat-port option:
laragram-server --local --http-stat-port=8082 --http-stat-ip-address=127.0.0.1The statistics are then available at http://127.0.0.1:8082, along with storage_* lines describing the automatic clean-up. You may append ?id=<bot_id> to the URL to view the statistics of a single bot. When starting the server through start:apiserver, the statistics address is taken from the stat option of the api_server configuration.
WARNING
The statistics page lists the tokens of your bots. Bind it to a private address and never expose it publicly.
Sentinel reads this page for you: its API Server page shows the live figures with masked tokens, and sentinel:check records them so traffic, CPU and memory can be charted over time. This works with the official telegram-bot-api server too.
Logging
By default, the server writes its log to the standard error stream. The --log option writes it to a file instead; a relative path is resolved against the files directory:
laragram-server --local --log=/var/log/laragram-server.log --verbosity=3The --verbosity option controls how much is logged:
| Level | Logged Messages |
|---|---|
0 | Fatal errors only. This is the default. |
1 | Errors. |
2 | Warnings, such as bots logging in and out. |
3 | Informational messages. |
4 and higher | Debug messages. |
When a bot fails to log in, the reason is logged at the warning level, so starting the server with --verbosity=2 or higher is a good first step when a bot does not respond as expected. The verbosity level may also be changed while the server is running by opening the statistics page with the v query parameter, for example http://127.0.0.1:8082/?v=3.
Running in Production
NOTE
To run this server, or Telegram's official server, in Docker next to your application, see LaraGram Armada.
In production, you should use a process monitor to keep the server running and restart it if it stops. For example, on Linux distributions using systemd, you may create a /etc/systemd/system/laragram-server.service unit file:
[Unit]
Description=LaraGram API Server
After=network-online.target
Wants=network-online.target
[Service]
User=laragram
Group=laragram
Environment=API_ID=123456
Environment=API_HASH=0123456789abcdef0123456789abcdef
ExecStart=/home/laragram/.config/composer/vendor/bin/laragram-server --local --http-ip-address=127.0.0.1 --http-port=8081 --dir=/var/lib/laragram-server --log=/var/log/laragram-server/server.log --verbosity=2
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.targetAdjust the ExecStart path to the location of your laragram-server binary, create the working and log directories with the correct owner, and then enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable --now laragram-serverThe server responds to SIGTERM by closing every bot gracefully, so systemctl stop and systemctl restart are safe to use.