Как постить несколько media в madelineproto

от admin

Как постить несколько media в madelineproto

Telegram-клиент на PHP (и получение сообщений с помощью MadelineProto)

Библиотека MadelineProto не выводит все посты

Все посты на главной странице
Не получается вывести все посты на главную страницу. Модель Post class Post <.

Как получить все посты категории
Добрый день. Я передаю через url slug категории переадресовывая на новую страницу. Получаю.

Как найти все посты без комментариев?
Добрый день. У Post есть много комментариев. Чтобы вывести их я пишу @post.comments.each do.

Код карты сайта WordPress не показывает все посты, как это поправить
Доброго времени суток, уважаемые гуру. Есть такой код карты сайта (привожу его без дизайна): .

Uploading and downloading files

MadelineProto provides fully parallelized wrapper methods to upload and download files that support bot API file ids, direct upload by URL and file renaming.

Maximum file size is of 2 GB.

Example bot: downloadRenameBot.php — download files by URL and rename Telegram files using this async parallelized bot!

Sending files

To send photos and documents to someone, use the $MadelineProto->messages->sendMedia method, click on the link for more info.

All files will be uploaded asynchronously and in parallel, 20 chunks at a time for maximum performance (this value can be tweaked in the settings).

The required message parameter is the caption: it can contain URLs, mentions, bold and italic text, thanks to the parse_mode parameter, that enables markdown or HTML parsing.

The media parameter contains the file path and other info about the file.

It can contain lots of various objects, here are the most important:

Security notice

Be careful when calling methods with user-provided parameters: the upload function may be used to access and send any file.
To disable automatic uploads by file name (disabled by default), use the appropriate setting OR upload files manually.

inputMediaUploadedPhoto

Can be used to upload photos: simply provide the photo’s file path in the file field, and optionally provide a ttl_seconds field to set the self-destruction period of the photo, even for normal chats. You can also provide a URL to the file field.

inputMediaUploadedDocument

Can be used to upload documents, videos, gifs, voice messages, round videos, round voice messages: simply provide the file’s file path in the file field, and optionally provide a ttl_seconds field to set the self-destruction period of the photo, even for normal chats.
You can also provide a URL to the file field.
To rename files, provide an Update or another already-uploaded Telegram file object to the file field. You can also (optionally) provide the file’s mime type in the mime_type field, generate it using mime_content_type($file_path); (tip: try using an unexpected mime type to make official clients crash ;).
Use the nosound_video field if the video does not have sound (gifs).
To actually set the document type, provide one or more DocumentAttribute objects to the attributes field:

Telegram-клиент на PHP (и получение сообщений с помощью MadelineProto)

Решив заняться бессовестным копипастом (а точнее его автоматизацией) постов с чужого Telegram-канала в свой, я первым делом полез в документацию по телеграм-ботам. Но как выяснилось, боты не только не имеют методов для получения сообщений, их просто-напросто нельзя добавить в чужой канал.

Решение нужно было на PHP и следующий час был потрачен на его поиск. Удивительно, как об этом мало информации (хотя нет, не удивительно… кто вообще пишет такое на PHP. ). В общем, дорога со StackOverflow привела к MadelineProto. На библиотеку довольно мало ссылок в сети.

Что такое Madeline? Это Telegram-клиент на PHP, предоставляющий методы для работы как от имени пользователя, так и от имени бота. Цель статьи — в первую очередь сократить путь поиска Madeline и привлечь к нему внимание. Также интересно узнать у хабравчан что есть подобное на других ЯП?

Ну и разумеется, опубликовать для примера кусочек кода, который решил мою задачу:

UPD от mopkob: У проекта есть активное комьюнити: рускоязычное @pwrtelegramgroupru и интернациональное @pwrtelegramgroup.

Как постить несколько media в madelineproto

Telegram-клиент на PHP (и получение сообщений с помощью MadelineProto)

Решив заняться бессовестным копипастом (а точнее его автоматизацией) постов с чужого Telegram-канала в свой, я первым делом полез в документацию по телеграм-ботам. Но как выяснилось, боты не только не имеют методов для получения сообщений, их просто-напросто нельзя добавить в чужой канал.

Решение нужно было на PHP и следующий час был потрачен на его поиск. Удивительно, как об этом мало информации (хотя нет, не удивительно… кто вообще пишет такое на PHP. ). В общем, дорога со StackOverflow привела к MadelineProto. На библиотеку довольно мало ссылок в сети.

Что такое Madeline? Это Telegram-клиент на PHP, предоставляющий методы для работы как от имени пользователя, так и от имени бота. Цель статьи — в первую очередь сократить путь поиска Madeline и привлечь к нему внимание. Также интересно узнать у хабравчан что есть подобное на других ЯП?

Ну и разумеется, опубликовать для примера кусочек кода, который решил мою задачу:

UPD от mopkob: У проекта есть активное комьюнити: рускоязычное @pwrtelegramgroupru и интернациональное @pwrtelegramgroup.

Uploading and downloading files

MadelineProto provides fully parallelized wrapper methods to upload and download files that support bot API file ids, direct upload by URL and file renaming.

Maximum file size is of 2 GB.

Example bot: downloadRenameBot.php — download files by URL and rename Telegram files using this async parallelized bot!

Sending files

To send photos and documents to someone, use the $MadelineProto->messages->sendMedia method, click on the link for more info.

All files will be uploaded asynchronously and in parallel, 20 chunks at a time for maximum performance (this value can be tweaked in the settings).

The required message parameter is the caption: it can contain URLs, mentions, bold and italic text, thanks to the parse_mode parameter, that enables markdown or HTML parsing.

The media parameter contains the file path and other info about the file.

It can contain lots of various objects, here are the most important:

Security notice

Be careful when calling methods with user-provided parameters: the upload function may be used to access and send any file.
To disable automatic uploads by file name (disabled by default), use the appropriate setting OR upload files manually.

inputMediaUploadedPhoto

Can be used to upload photos: simply provide the photo’s file path in the file field, and optionally provide a ttl_seconds field to set the self-destruction period of the photo, even for normal chats. You can also provide a URL to the file field.

inputMediaUploadedDocument

Can be used to upload documents, videos, gifs, voice messages, round videos, round voice messages: simply provide the file’s file path in the file field, and optionally provide a ttl_seconds field to set the self-destruction period of the photo, even for normal chats.
You can also provide a URL to the file field.
To rename files, provide an Update or another already-uploaded Telegram file object to the file field. You can also (optionally) provide the file’s mime type in the mime_type field, generate it using mime_content_type($file_path); (tip: try using an unexpected mime type to make official clients crash ;).
Use the nosound_video field if the video does not have sound (gifs).
To actually set the document type, provide one or more DocumentAttribute objects to the attributes field:

MadelineProto Присоединяйтесь к нескольким группам/каналам одновременно

Я использую MadelineProtoDocs для создания пользовательского бота, который выполняет нужные мне задачи. Что я хочу сделать, так это то, что я хочу присоединиться к более чем одной группе одновременно! я использовал $MadelineProto->messages->importChatInvite([‘hash’ => ‘HASH_CODE’]);

Это работает, когда я помещаю хэш-код для одной группы, но когда я добавляю более одного, например:

Это не работает

Я также пробовал:

$MadelineProto->channels->joinChannel([‘channel’ => [InputChannel, InputChannel], ]);

Тоже не работает!

1 ответ

Я нашел решение. Это легко сделать. Итак, когда вы присоединяетесь к каналу или группе, вы делаете следующее:

При этом вы присоединитесь только к одному каналу/группе, так как же добавить еще один канал/группу в том же коде? Это просто:

Общение ботов телеграм, или авторизация через PHP

Для одного проекта мне понадобилось получать данные от одного бота в автоматическом режиме. То есть при получении сообщений от бота необходимо было их обрабатывать или как-то пересылать дальше. Осложнялось дело тем, что этот бот – чужой, не мой, у меня нет к нему доступов. Что ж, тогда давайте создадим обычный аккаунт и научимся им управлять удаленно.

Для решения данной задачи мы воспользуемся клиентом MadelineProto для телеграм на PHP. Первым делом необходим хостинг с разрешенными исходящими соединениями (любой платный) иди впс/вдс. Создайте папку, разрешите юзеру писать в ней и закиньте файл index.php в неё с таким содержимым:

И перейдите к этому файлу в браузере. Первоначально вам необходимо будет зарегистрировать клиент – в автоматическом или ручном режиме. Обратите внимание, что лучше использовать такой аккаунт в телеграм, который не жалко потерять – мало ли куда могут уйти данные!

Также вам надо будет выбрать, для чего вы будете использовать данный клиент – для магазина, для разработки, для обучения – буквально можно пару слов написать. Все на английском. Выбираем ручной режим, вводим свой номер телефона телеграм, затем вводим код, который получим в сообщении, немного ждем, получаем сообщение о входе с нового устройства и можно начинать работать.

В вашей папке появится несколько новых файлов — session.madeline.ipcState.php, madeline-74.phar и тд – не переживайте, это так и должно быть.

Итак, после успешной регистрации клиента можно уже начинать работу. Давайте попробуем получить данные какого-нибудь канала (или переписку с пользователем, это неважно). Например, добавимся к каналу «@phpdigest» (из интерфейса пользователя) для простоты, а в файл index.php добавим следующий код:

Здесь мы получаем последние 20 сообщений данного канала. Как видите, все довольно просто. В MadelineProto есть разные методы – добавления в канал, писать самим и тд. Для моей задачи необходимо было просто получать сообщения – для этого периодически запрашивал принятые сообщения от необходимого контакта, сравнивал с имеющимися в базе данных и если были более новые писал их и отправлял другому боту.

Читать:
Как переименовать слои в фотошопе

Таким образом, с помощью клиента telegram на PHP и хостинга можно создавать довольно сложные, многоуровневые системы с ботами и настоящими людьми. Все ограничивается вашей фантазией, временем и, конечно, бюджетом.


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегизаметки, php, telegram

Name already in use

MadelineProtoDocs / docs / docs / FILES.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Uploading and downloading files

MadelineProto provides fully parallelized wrapper methods to upload and download files that support bot API file ids, direct upload by URL and file renaming.

Maximum file size is of 2 GB.

Example bot: downloadRenameBot.php — download files by URL and rename Telegram files using this async parallelized bot!

To send photos and documents to someone, use the $MadelineProto->messages->sendMedia method, click on the link for more info.

All files will be uploaded asynchronously and in parallel, 20 chunks at a time for maximum performance (this value can be tweaked in the settings).

The required message parameter is the caption: it can contain URLs, mentions, bold and italic text, thanks to the parse_mode parameter, that enables markdown or HTML parsing.

The media parameter contains the file path and other info about the file.

It can contain lots of various objects, here are the most important:

Be careful when calling methods with user-provided parameters: the upload function may be used to access and send any file.
To disable automatic uploads by file name (disabled by default), use the appropriate setting OR upload files manually.

Can be used to upload photos: simply provide the photo’s file path in the file field, and optionally provide a ttl_seconds field to set the self-destruction period of the photo, even for normal chats. You can also provide a URL to the file field.

Can be used to upload documents, videos, gifs, voice messages, round videos, round voice messages: simply provide the file’s file path in the file field, and optionally provide a ttl_seconds field to set the self-destruction period of the photo, even for normal chats.
You can also provide a URL to the file field.
To rename files, provide an Update or another already-uploaded Telegram file object to the file field. You can also (optionally) provide the file’s mime type in the mime_type field, generate it using mime_content_type($file_path); (tip: try using an unexpected mime type to make official clients crash ;).
Use the nosound_video field if the video does not have sound (gifs).
To actually set the document type, provide one or more DocumentAttribute objects to the attributes field:

Set round_message to true to send a round message.
You might want to manually provide square w (width) and h (height) parameters to send round videos.

Set the voice parameter to true to send a voice message.

The file can be a file name, a URL, or a file uploaded by someone else (can be used to rename files).

You can also only upload a file, without actually sending it to anyone, storing only the file ID for later usage.

All files will be uploaded asynchronously and in parallel, 20 chunks at a time for maximum performance (this value can be tweaked in the settings).

The $MadelineProto->messages->uploadMedia function is a reduced version of the $MadelineProto->messages->sendMedia, that requires only a media parameter, with the media to upload (on normal users, the peer field should be populated with @me or another value).

The returned MessageMedia object can then be reused to resend the document using sendMedia.

$MessageMedia can also be a Message (the media contained in the message will be sent), an Update (the media contained in the message contained in the update will be sent).

Reusing uploaded files

$MadelineProto->messages->uploadMedia and bot API file IDs do not allow you to modify the type of the file to send: however, MadelineProto provides methods that can generate a file object that can be resent with multiple file types.

The file name can also be a URL.
More optional parameters are available, check the PHPDOC of the method in your IDE.
You can also upload a file from a stream (this is especially useful, for example, when downloading YouTube videos using youtube-dl with ffmpeg and async AMPHP CLI streams):

$stream — PHP resource or async AMPHP stream.
$size — Size of file to upload
$mime — MIME type of file to upload

More optional parameters are available, check the PHPDOC of the method in your IDE.
You can also upload files from a callable:

$callable :
The callable must accept two parameters: int $offset, int $size
The callable must return a string with the contest of the file at the specified offset and size.
$size — Size of file to upload
$mime — MIME type of file to upload

More optional parameters are available, check the PHPDOC of the method in your IDE.

The generated $inputFile can later be reused thusly:

In this case, we’re reusing the same InputFile to send both a document and a video, without uploading the file twice.

The concept is easy: where you would usually provide a file path, simply provide $inputFile .

Files can be renamed by simply providing the $Update with the file to the sendMedia method thusly:

There are multiple download methods that allow you to download a file to a directory, to a file or to a stream.

Extracting download info

$MessageMedia can be a MessageMedia object or a bot API file ID.

  • $info[‘ext’] — The file extension
  • $info[‘name’] — The file name, without the extension
  • $info[‘mime’] — The file mime type
  • $info[‘size’] — The file size

Downloading profile pictures

$Update can be a Message object, an Update, or any value supported by getInfo.
The result (which is in the same format as getDownloadInfo ) should the be passed to the download functions in order to download the profile picture.

  • $info[‘ext’] — The file extension
  • $info[‘name’] — The file name, without the extension
  • $info[‘mime’] — The file mime type
  • $info[‘size’] — The file size

Download to directory

This downloads the given file to /tmp , and returns the full generated file path.

$MessageMedia can be either a Message, an Update, a MessageMedia object, or a bot API file ID.

Download to file

This downloads the given file to /tmp/myname.mp4 , and returns the full file path.

$MessageMedia can be either a Message, an Update, a MessageMedia object, or a bot API file ID.

Download to stream

This downloads the given file to the given resource or async AMPHP stream, the latter is especially useful for building an async HTTP file server with http-server.

$MessageMedia can be either a Message, an Update, a MessageMedia object, or a bot API file ID.

Download to callback

This downloads the given file to the callable. The callable must accept two parameters: string $payload, int $offset The callable will be called (possibly out of order, depending on the value of the $seekable (see PHPDOC)). The callable should return the number of written bytes.

$MessageMedia can be either a Message, an Update, a MessageMedia object, or a bot API file ID.

Download to http-server

This downloads the given file, replying to the specified async http-server request.
Automatically supports HEAD requests and content-ranges for parallel and resumed downloads.

$MessageMedia can be either a Message, an Update, a MessageMedia object, or a bot API file ID.

$request is the Request object returned by http-server.

$cb is an optional parameter can be a callback for download progress, but it shouldn’t be used, the new FileCallback should be used instead

Download to browser

This downloads the given file to the browser, sending also information about the file’s type and size. Automatically supports HEAD requests and content-ranges for parallel and resumed downloads.

$MessageMedia can be either a Message, an Update, a MessageMedia object, or a bot API file ID.

$cb is an optional parameter can be a callback for download progress, but it shouldn’t be used, the new FileCallback should be used instead

To get the upload/download progress in real-time, use the \danog\MadelineProto\FileCallback class:

This will send the file video.mp4 to @danogentili: while uploading, he will receive progress messages Upload progress: 24% until the upload is complete; while downloading, he will receive progress messages Download progress: 34% until the download is complete.

You can also add two more parameters $speed, $time to the signature of the method to get a partial upload speed in mbps, along with the time elapsed since the start of the download.

A FileCallback object can be provided to uploadMedia , sendMedia , uploadProfilePicture , upload , upload_encrypted , download_to_* : the first parameter to its constructor must be the file path/object that is usually accepted by the function, the second must be a callable function or object.

You can also write your own callback class, just implement \danog\MadelineProto\FileCallbackInterface :

Bot API file IDs

$MessageMedia can even be a bot API file ID, generated by the bot API, or by MadelineProto:

Actual MessageMedia objects can also be converted to bot API file IDs like this:

$botAPI_file now contains a bot API message, to extract the file ID from it use the following code:

Похожие статьи