Skip to content

Instantly share code, notes, and snippets.

@Deifinger
Last active May 30, 2017 23:49
Show Gist options
  • Save Deifinger/52ccfafcfb019f31480d316c4ba439d6 to your computer and use it in GitHub Desktop.
Save Deifinger/52ccfafcfb019f31480d316c4ba439d6 to your computer and use it in GitHub Desktop.
First Telegram bot
{
"require": {
"telegram-bot/api": "^2.2"
}
}
<?php
require_once 'vendor/autoload.php';
define('BOT_TOKEN', 'TOKEN');
define('BOT_USERNAME', 'BotName');
$timestampFilename = './last_timestamp';
$startMessage = 'С Днем Рождения, здоровяк! Пиши команду /get_task и получай задание';
$questMessage = 'Поковыряйся пальцем в носу, там ты найдешь записку';
$timestampFile = fopen($timestampFilename, 'r') or die('Unable to open file!');
$lastTimestamp = fread($timestampFile, filesize($timestampFilename));
fclose($timestampFile);
try {
$bot = new \TelegramBot\Api\BotApi(BOT_TOKEN);
$updates = $bot->getUpdates();
$count = sizeof($updates);
for($i = 0; $i < $count; $i++) {
$message = $updates[$i]->getMessage();
$chatId = $message->getChat()->getId();
$text = $message->getText();
$date = $message->getDate();
if($lastTimestamp >= $date) continue;
if($text == '/start') {
$bot->sendMessage($chatId, $startMessage);
} else if($text == '/get_task') {
$bot->sendMessage($chatId, $questMessage);
}
}
// PHP specific code, because $date variable is not nulled after cycle
$timestampFile = fopen($timestampFilename, 'w');
fwrite($timestampFile, $date);
fclose($timestampFile);
} catch (\TelegramBot\Api\Exception $e) {
echo $e->getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment