Парсинг телеграмм каналов php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

PHP Telegram Forum Parser Bot

corsairdnb/telegram_forum_parser_bot

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A Telegram Bot based on the official Telegram Bot API

  • Introduction
  • Instructions
    • Create your first bot
    • Require this package with Composer
    • Choose how to retrieve Telegram updates
    • Webhook installation
    • Self Signed Certificate
    • Unset Webhook
    • getUpdates installation
    • Types
    • Inline Query
    • Methods
    • Send Message
    • Send Photo
    • Send Chat Action
    • getUserProfilePhoto
    • getFile and dowloadFile
    • Send message to all active chats
    • MySQL storage (Recommended)
    • Channels Support
    • Botan.io integration (Optional)
    • Predefined Commands
    • Custom Commands
    • Commands Configuration
    • Set Admins
    • Channel Administration

    This is a pure PHP Telegram Bot, fully extensible via plugins. Telegram recently announced official support for a Bot API allowing integrators of all sorts to bring automated interactions to the mobile platform. This Bot aims to provide a platform where one can simply write a plugin and have interactions in a matter of minutes.

    • retrieve updates with webhook and getUpdates methods.
    • supports all types and methods according to Telegram API (25 May 2016).
    • supports supergroups.
    • handle commands in chat with other bots.
    • manage Channel from the bot admin interface.
    • full support for inline bots.
    • inline keyboard.
    • Messages, InlineQuery and ChosenInlineQuery are stored in the Database.
    • Botan.io integration and database cache system. (new!)
    • Conversation feature

    This code is available on Github. Pull requests are welcome.

    botfather initial conversation

    1. Message @botfather https://telegram.me/botfather with the following text: /newbot If you don’t know how to message by username, click the search field on your Telegram app and type @botfather , where you should be able to initiate a conversation. Be careful not to send it to the wrong contact, because some users has similar usernames to botfather .
    2. @botfather replies with Alright, a new bot. How are we going to call it? Please choose a name for your bot.
    3. Type whatever name you want for your bot.
    4. @botfather replies with Good. Now let’s choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
    5. Type whatever username you want for your bot, minimum 5 characters, and must end with bot . For example: telesample_bot
    6. @botfather replies with:
    Done! Congratulations on your new bot. You will find it at telegram.me/telesample_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. Use this token to access the HTTP API: 123456789:AAG90e14-0f8-40183D-18491dDE For a description of the Bot API, see this page: https://core.telegram.org/bots/api 

    botfather later conversation

  • Note down the ‘token’ mentioned above.
  • Type /setprivacy to @botfather.
  • @botfather replies with Choose a bot to change group messages settings.
  • Type (or select) @telesample_bot (change to the username you set at step 5 above, but start it with @ )
  • @botfather replies with
    'Enable' - your bot will only receive messages that either start with the '/' symbol or mention the bot by username. 'Disable' - your bot will receive all messages that people send to groups. Current status is: ENABLED 

    Require this package with Composer

    Install this package through Composer. Edit your project’s composer.json file to require longman/telegram-bot .

    < "name": "yourproject/yourproject", "type": "project", "require": < "php": ">=5.5", "longman/telegram-bot": "*" > >

    run this command in your command line:

    composer require longman/telegram-bot

    Choose how to retrieve Telegram updates

    The bot can handle updates with Webhook or getUpdates method:

    Webhook getUpdates
    Description Telegram sends the updates directly to your host You have to fetch Telegram updates manually
    Host with https Required Not required
    MySQL Not required Required

    Note: For a more detailed explanation, head over to the example-bot repository and follow the instructions there.

    In order to set a Webhook you need a server with HTTPS and composer support. (For a self signed certificate you need to add some extra code)

    Create set.php with the following contents:

     // Load composer require __DIR__ . '/vendor/autoload.php'; $bot_api_key = 'your:bot_api_key'; $bot_username = 'username_bot'; $hook_url = 'https://your-domain/path/to/hook.php'; try < // Create Telegram API object $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); // Set webhook $result = $telegram->setWebhook($hook_url); if ($result->isOk()) < echo $result->getDescription(); > > catch (Longman\TelegramBot\Exception\TelegramException $e) < // log telegram errors // echo $e->getMessage(); >

    Open your set.php via the browser to register the webhook with Telegram. You should see Webhook was set .

    Now, create hook.php with the following contents:

     // Load composer require __DIR__ . '/vendor/autoload.php'; $bot_api_key = 'your:bot_api_key'; $bot_username = 'username_bot'; try < // Create Telegram API object $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); // Handle telegram webhook request $telegram->handle(); > catch (Longman\TelegramBot\Exception\TelegramException $e) < // Silence is golden! // log telegram errors // echo $e->getMessage(); >

    To upload the certificate, add the certificate path as a parameter in set.php:

    $result = $telegram->setWebhook($hook_url, ['certificate' => '/path/to/certificate']);

    Edit unset.php with your bot credentials and execute it.

    The MySQL database must be enabled for the getUpdates method!

    Create getUpdatesCLI.php with the following contents:

    #!/usr/bin/env php  require __DIR__ . '/vendor/autoload.php'; $bot_api_key = 'your:bot_api_key'; $bot_username = 'username_bot'; $mysql_credentials = [ 'host' => 'localhost', 'user' => 'dbuser', 'password' => 'dbpass', 'database' => 'dbname', ]; try < // Create Telegram API object $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); // Enable MySQL $telegram->enableMySql($mysql_credentials); // Handle telegram getUpdates request $telegram->handleGetUpdates(); > catch (Longman\TelegramBot\Exception\TelegramException $e) < // log telegram errors // echo $e->getMessage(); >

    Next, give the file permission to execute:

    Источник

    Как парсить Telegram канал при помощи PHP 37

    Когда-то на Хабре была опубликована статья как спарсить Телеграм канал при помощи PHP, как показала практика после прочтения материала появляется ещё больше вопросов, или в процессе тестирования «ни чего не работает».

    Нам понадобится:

    1. Действующая учётная запись в Телеграм
    2. Tor браузер под рукой (если вы из РФ и у вас заблокирован доступ к сайту Телеграм)
    3. Обычный хостинг, например Бегет
    4. Знания php и умение использовать composer
    5. PHP 7.2
    6. Умение пользоваться консолью сервера. (Некоторые операции будут выполняться в консоли)

    Итак, нужно перейти на сайте Телеграм https://my.telegram.org:

    1. Вводим свой номер телефона
    2. Указываем код подтверждения пришедший в ваше клиентское приложение Телеграм
    3. Переходим в меню API development tools

    На этой странице нам нужно заполнить данные о нашем создаваемом приложении (на один номер — одно приложение).

    Нам понадобится два параметра: App api_id и App api_hash, далее мы их будем использовать в коде вызова для получения постоянных ключей авторизации.

    Следующее что нам надо, это скачать проект https://github.com/danog/MadelineProto к себе в отдельную папку на хостинге и при помощи composer установить все зависимости.

    PS: в коде будет использоваться PHP функция «readline» — предварительно установите её на ваш хостинг и проверьте её доступность в консольном режиме PHP.

    Для работы с Телеграм из PHP нам потребуются специальные ключи доступа. Для этого воспользуемся «одноразовым» классом, для создания таких ключей:

    Источник

    Читайте также:  Line drawing in javascript
Оцените статью