A session with a Telegram bot

This is the second part of me introducing my PHP library for the Telegram bot API. (To the first part)

When building web applications session management is one of the most important parts. When working with Telegram bots you might also need sessions. You can’t just simply use PHP’s own session management with $_SESSION – this is why my PHP Telegram library comes with a session class.

Letting the bot remember things

Setting up the database

Before your bot can remember anything you need a MySQL Database and some information to connect to that database. Then, in your index.php, uncomment the part with $DB = ... and fill out your Database Credentials in the constants above. If you have a different database port (one which is not 3306), you can add the port as an argument behind MYSQL_NAME.

Now your database is still empty, so import the file DATABASE.sql into it – done.

Using the Session Manager

Using the sessions is pretty straight forward from here on. You only need to create a new object of the session class:

$session = new Session(NAME, $request['message']['chat']['id'], $DB);

Now when you want to save a variable in the session, do
$session->set('index', 'value');

And – you guessed it – to get the value you can simply say
$session->get('index'); // will return value

That was pretty easy, right?

Good to know

Well, it’s not that easy. You might want to know, what NAME and $request['message']['chat']['id'] is all about. The name is used as a key to identify the values for this bot in the table – this allows you to use the same database table for multiple bots. The message id is – of course – basically the session id, because the values we are storing are store linked to this chat. So the next time someone from this chat sends a message to your bot – the bot remembers ;).

View Repository

Telegram Image Source: The Logo is directly from the Telegram website.