Inheritance: use trait Telegram\Bot\Events\EmitsEvents
Example #1
0
 /**
  * App constructor.
  */
 public function __construct()
 {
     parent::__construct();
     $this->match('/', function () {
         return '/';
     });
     /**
      * process messages
      */
     $this->match('update', function () {
         $telegram = new Client(BOT_TOKEN);
         $handler = new Handler($telegram);
         return $handler->handle();
     });
     /**
      * update hook settings/api
      */
     $this->match('hook', function () {
         $telegram = new Api(BOT_TOKEN);
         $telegram->removeWebhook();
         if (USE_WEBHOOK) {
             $telegram->setWebhook(WEBHOOK, '../server-setup/files/cert/nginx.crt');
             return 'hook set';
         }
         return 'hook-removed';
     });
 }
 /**
  * Initialize Telegram Bot SDK Library with Default Config.
  */
 public function registerTelegram()
 {
     $this->app->singleton('telegram', function ($app) {
         $config = $app['config'];
         $telegram = new Api($config->get('telegram.bot_token', false), $config->get('telegram.async_requests', false), $config->get('telegram.http_client_handler', null));
         // Register Commands
         $telegram->addCommands($config->get('telegram.commands', []));
         return $telegram;
     });
 }
 /**
  * Initialize Telegram Bot SDK Library with Default Config.
  *
  * @param Application $app
  */
 protected function registerTelegram(Application $app)
 {
     $app->singleton(Api::class, function ($app) {
         $config = $app['config'];
         $telegram = new Api($config->get('telegram.bot_token', false), $config->get('telegram.async_requests', false), $config->get('telegram.http_client_handler', null));
         // Register Commands
         $telegram->addCommands($config->get('telegram.commands', []));
         return $telegram;
     });
     $app->alias(Api::class, 'telegram');
 }
 /**
  * @param TelegramMessageRequest $request
  *
  * @return JsonResponse
  */
 public function store(TelegramMessageRequest $request)
 {
     $content = ['chat_id' => StaffTelegramGroup::id(), 'text' => sprintf('(%s) %s', App::environment(), $request->text())];
     try {
         $message = $this->telegram->sendMessage($content);
         $this->webUi->successMessage("Sent message `{$message->getMessageId()}` to staff");
     } catch (\Exception $e) {
         $this->webUi->errorMessage(sprintf('Failed to send message to staff: %s (%s)', $e->getMessage(), json_encode($content)));
     }
     return $this->webUi->redirect('telegram.index');
 }
 /**
  * Initialize Telegram Bot SDK Library with Default Config.
  *
  * @param Application $app
  */
 protected function registerTelegram(Application $app)
 {
     $app->singleton(Api::class, function ($app) {
         $config = $app['config'];
         $telegram = new Api($config->get('telegram.bot_token', false), $config->get('telegram.async_requests', false), $config->get('telegram.http_client_handler', null));
         // Register Commands
         $telegram->addCommands($config->get('telegram.commands', []));
         // Check if DI needs to be enabled for Commands
         if ($config->get('telegram.inject_command_dependencies', false)) {
             $telegram->setContainer($app);
         }
         return $telegram;
     });
     $app->alias(Api::class, 'telegram');
 }
 /**
  * @param string $name
  * @param array $args
  *
  * @return bool
  * @throws DialogException
  */
 public function __call($name, array $args)
 {
     if (count($args) === 0) {
         return false;
     }
     $step = $args[0];
     if (!is_array($step)) {
         throw new DialogException('For string steps method must be defined.');
     }
     // @todo Add logging
     if (isset($step['response'])) {
         $params = ['chat_id' => $this->getChat()->getId(), 'text' => $step['response']];
         if (isset($step['markdown']) && $step['markdown']) {
             $params['parse_mode'] = 'Markdown';
         }
         $this->telegram->sendMessage($params);
     }
     if (!empty($step['jump'])) {
         $this->jump($step['jump']);
     }
     if (isset($step['end']) && $step['end']) {
         $this->end();
     }
     return true;
 }
Example #7
0
 /**
  * Use PHP Reflection and Laravel Container to instantiate the answer with type hinted dependencies.
  *
  * @param $answerClass
  *
  * @return object
  */
 protected function buildDependencyInjectedAnswer($answerClass)
 {
     // check if the command has a constructor
     if (!method_exists($answerClass, '__construct')) {
         return new $answerClass();
     }
     // get constructor params
     $constructorReflector = new \ReflectionMethod($answerClass, '__construct');
     $params = $constructorReflector->getParameters();
     // if no params are needed proceed with normal instantiation
     if (empty($params)) {
         return new $answerClass();
     }
     // otherwise fetch each dependency out of the container
     $container = $this->telegram->getContainer();
     $dependencies = [];
     foreach ($params as $param) {
         $dependencies[] = $container->make($param->getClass()->name);
     }
     // and instantiate the object with dependencies through ReflectionClass
     $classReflector = new \ReflectionClass($answerClass);
     return $classReflector->newInstanceArgs($dependencies);
 }
Example #8
0
 /**
  * Client constructor.
  */
 public function __construct($token)
 {
     parent::__construct($token);
     $container = new Container();
     self::setContainer($container);
     $this->addCommand(StartCommand::class);
     $this->addCommand(RouteCommand::class);
     $this->addCommand(StopCommand::class);
     $this->addCommand(GetCommand::class);
     $this->addCommand(EnableUpdatesCommand::class);
     $this->addCommand(StopUpdatesCommand::class);
     $this->addCommand(ResetCommand::class);
     $this->addCommand(SaveFavCommand::class);
     $this->addCommand(LoadFavCommand::class);
     $this->addCommand(FavsCommand::class);
     $this->addCommand(DelFavCommand::class);
     $this->addCommand(GetLinkCommand::class);
     $this->addCommand(RoutesCommand::class);
     $this->addCommand(CreditsCommand::class);
 }
<?php

use Telegram\Bot\Api;
require 'vendor/autoload.php';
require 'config.php';
if (isset($_GET['url'])) {
    $url = $_GET['url'];
} else {
    $url = $_SERVER['HTTP_HOST'];
}
if (filter_var('https://' . $url, FILTER_VALIDATE_URL) == false) {
    echo 'Invalid url for get certificate: ' . $url;
    die;
}
$g = stream_context_create(array("ssl" => array("capture_peer_cert" => true, "verify_peer" => false, "verify_peer_name" => false)));
$r = stream_socket_client("ssl://{$url}:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $g);
if (!$r) {
    echo 'Domain dont exists or dont is over ssl';
    die;
}
$cont = stream_context_get_params($r);
openssl_x509_export($cont["options"]["ssl"]["peer_certificate"], $certificate);
$certificate = trim($certificate, "\n");
echo '<pre>';
echo $certificate;
echo '</pre>';
$telegram = new Api($config['token']);
$response = $telegram->setWebhook('https://' . $url, $certificate);
var_dump(['url' => 'https://' . $url, 'response' => $response]);
Example #10
0
 /**
  * Make the bot instance.
  *
  * @param string $name
  *
  * @return Api
  */
 protected function makeBot($name)
 {
     $config = $this->getBotConfig($name);
     $token = array_get($config, 'token');
     $commands = array_get($config, 'commands', []);
     $telegram = new Api($token, $this->getConfig('async_requests', false), $this->getConfig('http_client_handler', null));
     // Check if DI needs to be enabled for Commands
     if ($this->getConfig('resolve_command_dependencies', true)) {
         $telegram->setContainer($this->app);
     }
     $commands = $this->parseBotCommands($commands);
     // Register Commands
     $telegram->addCommands($commands);
     return $telegram;
 }
<?php

use Telegram\Bot\Api;
use Commands;
require 'vendor/autoload.php';
require 'config.php';
if (getenv('MODE_ENV') == 'develop') {
    class mockApi extends Api
    {
        public function getWebhookUpdates()
        {
            $json = '{}';
            return new Telegram\Bot\Objects\Update(json_decode($json, true));
        }
    }
    $telegram = new mockApi($config['token']);
} else {
    error_log(file_get_contents('php://input'));
    $telegram = new Api($config['token']);
}
// Standalone
$telegram->addCommands([Telegram\Bot\Commands\HelpCommand::class, Commands\StartCommand::class, Commands\RegisterCommand::class, Commands\RemoveCommand::class, Commands\RankingCommand::class, Commands\ListUsersCommand::class]);
$telegram->commandsHandler(true);
Example #12
0
<?php

$token = getenv('TELEGRAM_BOT_TOKEN');
if (empty($token)) {
    die('No token');
}
require 'src/bootstrap.php';
use Telegram\Bot\Api;
use WeightLog\WeightLog;
use WeightLog\Db;
$db = Db::getInstance();
$telegram = new Api($token);
$weightLog = new WeightLog($db);
$telegram->addCommand(\WeightLog\TelegramCommands\OutputCommand::class);
$telegram->addCommand(\WeightLog\TelegramCommands\ApiCommand::class);
$telegram->addCommand(\WeightLog\TelegramCommands\HelpCommand::class);
$run = true;
$lastUpdateId = 0;
while ($run) {
    sleep(1);
    $updates = $telegram->commandsHandler(false);
    if (empty($updates)) {
        continue;
    }
    foreach ($updates as $update) {
        $lastUpdateId = $update['update_id'];
        if (substr(trim($update['message']['text']), 0, 1) == '/') {
            continue;
        }
        $weightGiven = preg_replace('/[^0-9\\.]/', '', $update['message']['text']);
        $person = $weightLog->getPersonFromUpdate($update);
Example #13
0
<?php

use Telegram\Bot\Api;
require 'vendor/autoload.php';
$telegram = new Api('897587587658:AAFbUUXEbKEPT9Bkjalksdjfklashjdflkjasdklf');
$telegram->sendMessage(['chat_id' => '-43054748', 'text' => print_r(['name' => 'José das Couves', 'email' => '*****@*****.**'], true)]);
Example #14
0
<?php

require_once 'EDITME/config.php';
require_once 'boot.php';
use Telegram\Bot\Api;
$telegram = new Api($BOTTOKEN);
$updates = $telegram->getWebhookUpdates();
$arup = json_decode($updates, true);
//syslog(LOG_INFO, $updates);
$acheck = $arup;
unset($acheck['message']['message_id']);
unset($acheck['message']['from']);
unset($acheck['message']['chat']);
unset($acheck['message']['date']);
foreach ($commands as $command) {
    $command = substr_replace($command, '', 0, 7);
    $command = substr_replace($command, '', -4);
    $telegram->addCommand('Commands\\' . $command);
}
foreach ($acheck['message'] as $vc => $avalue) {
    switch ($vc) {
        case "text":
            if ($arup['message']['text'][0] != "/") {
                $telegram->sendMessage($arup['message']['chat']['id'], $lang['error_command']);
            } else {
                $telegram->commandsHandler(true);
            }
            break;
        case "photo":
            $telegram->sendMessage($arup['message']['chat']['id'], $lang['recv_photo']);
            break;
Example #15
0
<?php

require_once "../bootstrap.php";
use Symfony\Component\Yaml\Yaml;
use Telegram\Bot\Api as TelegramApi;
$config = Yaml::parse(file_get_contents('../config.yml'));
$telegram = new TelegramApi($config['telegram_api_key']);
$app = new \Slim\App();
$app->get('/telegram/webhook/{key}', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) {
    $key = $request->getAttribute('key');
    error_log($request->getBody());
    $response->getBody()->write("Hello telegram!");
    return $response;
});
$app->get('/hello/{name}', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) {
    $name = $request->getAttribute('name');
    $response->getBody()->write("Hello, {$name}");
    return $response;
})->setName('hello');
$app->get('telegram/setup', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) {
    global $config, $telegram;
    $telegramCallbackAuth = $telegram->setWebhook("https://kickbot.telegram.thru.io/telegram/webhook/{$config['telegram_api_key']}");
    \Kint::dump($telegramCallbackAuth);
    exit;
});
$app->get('.well-known/acme-challenge/El1K2GOuLyDvjk9-uM8P-Fge_oDMeYHYBL_VVvdvT4s', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) {
    $response->getBody()->write("El1K2GOuLyDvjk9-uM8P-Fge_oDMeYHYBL_VVvdvT4s.BjQMlU5nwgsexb_DdA7zyb5OWcbghyA_u5G5PCeY610");
    return $response;
});
$app->run();
Example #16
0
<?php

require_once 'EDITME/config.php';
require_once 'boot.php';
use Telegram\Bot\Api;
$telegram = new Api($BOTTOKEN);
$response = $telegram->setWebhook($BASEURL . "webhook");
echo "<pre>";
print_r($response);
echo "</pre>";
Example #17
0
File: midna.php Project: e0th/Midna
<?php

namespace Midna;

use RedBeanPHP\R;
use Telegram\Bot\Api;
require_once __DIR__ . '/../../vendor/autoload.php';
define('MIDNA_TOKEN', 'xxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('MIDNA_HOOK', 'https://example.com/path/to/this/file.php');
define('MIDNA_CERT', '/path/to/your/ssl/certificate.pem');
$telegram = new Api(MIDNA_TOKEN);
R::setup('sqlite:' . __DIR__ . '/../../database/database.db');
$telegram->addCommand(new Commands\Start());
$telegram->addCommand(new Commands\Help());
$telegram->commandsHandler(true);
if (php_sapi_name() == 'cli') {
    if ($argv[1] == 'start') {
        print "Starting Midna" . PHP_EOL;
        $bean = R::dispense('messages');
        $bean->message_id = 0;
        $bean->message_date = 0;
        R::store($bean);
        $telegram->setWebhook(['url' => MIDNA_HOOK, 'certificate' => MIDNA_CERT]);
    } else {
        if ($argv[1] == 'stop') {
            print "Stopping Midna" . PHP_EOL;
            $telegram->removeWebhook();
        }
    }
    exit;
}
Example #18
0
<?php

define('API_KEY', '123456789:ABCDEFGHIJKLMNO_PQRSTUVWXYZ1234_5-6');
define('LOG_FILE', 'bot.log');
define('BOT_USER_AGENT', 'FreeWiFi_Bot/1.0');
define('HELP', "Вы можете использовать следующие комманды:\n\n/help [cmd] - Справка по коммандам бота\n/find [key] - Поиск в базе\n/ping [msg] - Проверить бота");
define('START_MESSAGE', "Пользуясь этим ботом Вы принимаете с Соглашение http://3wifi.stascorp.com/rules. \nАдминистрация не несет ответственности за Ваши действия с полученной информацией!\n\n" . HELP);
define('HELP_FIND', "Найти информацию о WiFi точке в базе.\n/find [key]\n\nВ кчестве параметра key укажите имя интересующей сети (ESSID).\n\nВозвращает информацию в формате:\nДата_Комментарий\nДиапазон IP\nBSSID|ESSID\n(Тип шифрования)Пароль[WPS]\nШирота Долгота");
define('HELP_PING', "Проверить что бот работает.\n/ping [msg]\nНеобязательный параметр msg будет возвращен в ответном сообщении.\n\nФормат ответа:\nPONG msg");
define('HELP_HELP', "Cправка по командам бота.\n/help [cmd]\nБез параметров возвращает список доступных команд.\nС параметром cmd отображает детальную справку по команде.");
define('HELP_UNKNOWN', "Я таким командам не обучен!");
require 'vendor/autoload.php';
use Telegram\Bot\Api;
$telegram = new Api(API_KEY);
$bot = $telegram->getMe();
$botId = $bot->getId();
$botUserName = $bot->getUserName();
$botFirstName = $bot->getFirstName();
function logs($msg)
{
    file_put_contents(LOG_FILE, $msg . "\n", FILE_APPEND);
}
function logs_var($name, $var)
{
    logs($name . " = " . var_export($var, TRUE));
}
function checkToken()
{
    if (API_KEY != (isset($_GET["token"]) ? $_GET["token"] : false)) {
        logs("ERROR TOKEN!");
        logs_var("_GET", $_GET);
Example #19
0
<?php

require_once 'EDITME/config.php';
require_once 'boot.php';
use Telegram\Bot\Api;
$telegram = new Api($BOTTOKEN);
$response = $telegram->removeWebhook();
echo "<pre>";
print_r($response);
echo "</pre>";
Example #20
0
<?php

require_once 'EDITME/config.php';
require_once 'boot.php';
use Telegram\Bot\Api;
$telegram = new Api($BOTTOKEN);
$response = $telegram->getMe($BASEURL . "webhook");
echo "<pre>";
print_r($response);
echo "</pre>";
<?php

use Telegram\Bot\Api;
use Commands;
require 'vendor/autoload.php';
require 'config.php';
$telegram = new Api($config['token']);
// Standalone
$telegram->addCommands([Telegram\Bot\Commands\HelpCommand::class]);
$telegram->commandsHandler(true);
Example #22
0
<?php

require 'vendor/autoload.php';
use Telegram\Bot\Api;
$telegram = new Api('153172554:AAGrcXguYssXQAwsM2M-YIvBL2RJS1fdgrk');
$updates = $telegram->getUpdates();
return $updates;
<?php

require 'vendor/autoload.php';
use Telegram\Bot\Api;
$api = new Api('146785038:AAHwk3zAWaYh_LJbowIepSkv5EMngXMriN4');
$chat = $api->getUpdates()[0]->getMessage()->getChat();
// while(1) {
// 	$api->sendMessage(array('text' => 'oi', 'chat_id' => 149378523));
// 	sleep(5);
// }