MadelineProto, a PHP MTProto telegram client
Created by Daniil Gentili
#StandWithUkraine 🇺🇦
Do join the official channel, @MadelineProto and the support groups!
What's this?
This library can be used to easily interact with Telegram without the bot API, just like the official apps.
It can login with a phone number (MTProto API), or with a bot token (MTProto API, no bot API involved!).
Getting started (now fully async!)
<?php
// PHP 8.2+ is required.
if (!file_exists('madeline.php')) {
copy('https://phar.madelineproto.xyz/madeline.php', 'madeline.php');
}
include 'madeline.php';
$MadelineProto = new \danog\MadelineProto\API('session.madeline');
$MadelineProto->start();
$me = $MadelineProto->getSelf();
$MadelineProto->logger($me);
if (!$me['bot']) {
$MadelineProto->messages->sendMessage(peer: '@stickeroptimizerbot', message: "/start");
$MadelineProto->channels->joinChannel(channel: '@MadelineProto');
try {
$MadelineProto->messages->importChatInvite(hash: 'https://t.me/+Por5orOjwgccnt2w');
} catch (\danog\MadelineProto\RPCErrorException $e) {
$MadelineProto->logger($e);
}
}
$MadelineProto->echo('OK, done!');
Try running this code in a browser or in a console!
Tip: if you receive an error (or nothing), send us the error message and the MadelineProto.log file that was created in the same directory (if running from a browser).
Made with MadelineProto
The following open source projects were created using MadelineProto: you can directly install them, or explore the source code as direct examples on how to use MadelineProto's many features!
- magnaluna webradio - Multifeatured Telegram VoIP webradio
simpleBot.php- Extremely basic exampletgstories_dl_bot.php- Source code of @tgstories_dl_bot - Bot to download any Telegram Story!downloadRenameBot.php- Download files by URL and rename Telegram files using this async parallelized bot!secret_bot.php- Secret chat bot!pipesbot.php- Creating inline bots and using other inline bots via a userbot!bot.php- Examples for how to use filters, updates, get download links for any file, Telegram Stories and much more!
Want to add your own open-source project to this list? Click here!
Some of MadelineProto's core components are also available as separate, standalone libraries:
- danog/async-orm - Async ORM based on AMPHP v3 and fibers.
- danog/telegram-entities - A library to work with Telegram UTF-16 styled text entities.
- danog/tg-file-decoder - A library to work with Telegram bot API file IDs.
- danog/tg-dialog-id - A library to work with Telegram bot API dialog IDs.
- danog/loop - Loop/actor model abstraction for AMPHP.
- danog/better-prometheus - A better Prometheus library for PHP applications.
- danog/ipc - Async IPC component for AMPHP.
- danog/dns-over-https - Async DNS-over-HTTPS resolution for AMPHP.
Documentation
- Creating a client - This page explains how to create a MadelineProto instance.
- Login - There are many ways you can login with MadelineProto.
- Features - MadelineProto can do everything official clients can do, and more!
- Requirements - MadelineProto requires the mbstring, xml, json, fileinfo, gmp, openssl, iconv, gd extensions to function properly.
- MadelineProto on Docker - MadelineProto offers an official MadelineProto docker image for the linux/amd64, linux/arm64 and linux/riscv64 platforms @ hub.madelineproto.xyz/danog/madelineproto.
- Metrics - MadelineProto can expose many useful metrics, that can be visualized using the official MadelineProto Grafana dashboard.
- Installation - There are various ways to install MadelineProto:
- Broadcasting messages to all users - MadelineProto can be used to broadcast messages to all users, chats and channels of a bot or userbot.
- Handling updates (new messages & other events) - Update handling can be done in different ways:
- Async Event driven
- Webhook (for HTTP APIs)
- getUpdates (only for Javascript APIs)
- Noop (default)
- danog\MadelineProto\Broadcast\Progress » - Broadcast progress.
- danog\MadelineProto\EventHandler\AbstractMessage » - Represents an incoming or outgoing message.
- danog\MadelineProto\EventHandler\AbstractPrivateMessage » - Represents a private or secret chat message.
- danog\MadelineProto\EventHandler\AbstractStory » - Represents a Telegram Story.
- danog\MadelineProto\EventHandler\BotCommands » - The command set of a certain bot in a certain chat has changed.
- danog\MadelineProto\EventHandler\CallbackQuery » - Represents a query sent by the user by clicking on a button.
- danog\MadelineProto\EventHandler\Channel\ChannelParticipant » - A participant has left, joined, was banned or admin'd in a channel or supergroup.
- danog\MadelineProto\EventHandler\Channel\MessageForwards » - Indicates that the forward counter of a message in a channel has changed.
- danog\MadelineProto\EventHandler\Channel\MessageViewsChanged » - Indicates that the view counter of a message in a channel has changed.
- danog\MadelineProto\EventHandler\Channel\UpdateChannel » - A new channel is available, or info about an existing channel was changed.
- danog\MadelineProto\EventHandler\ChatInviteRequester » - Indicates someone has requested to join a chat or channel.
- danog\MadelineProto\EventHandler\ChatInviteRequester\BotChatInviteRequest » - Indicates someone has requested to join a chat or channel (bots only).
- danog\MadelineProto\EventHandler\ChatInviteRequester\PendingJoinRequests » - Someone has requested to join a chat or channel.
- danog\MadelineProto\EventHandler\Delete » - Indicates that some messages were deleted.
- danog\MadelineProto\EventHandler\Delete\DeleteChannelMessages » - Some messages in a supergroup/channel were deleted.
- danog\MadelineProto\EventHandler\Delete\DeleteMessages » - Some messages were deleted in a private chat or simple group.
- danog\MadelineProto\EventHandler\Delete\DeleteScheduledMessages » - Some scheduled messages were deleted from the schedule queue of a chat.
- danog\MadelineProto\EventHandler\InlineQuery » - An incoming inline query.
- danog\MadelineProto\EventHandler\Message » - Represents an incoming or outgoing message.
- danog\MadelineProto\EventHandler\Message\ChannelMessage » - Represents an incoming or outgoing channel message.
- danog\MadelineProto\EventHandler\Message\CommentReply » - Represents a reply to one of our messages in a channel comment group that we're not a member of (i.e. received via
@replies). - danog\MadelineProto\EventHandler\Message\GroupMessage » - Represents an incoming or outgoing group message.
- danog\MadelineProto\EventHandler\Message\PrivateMessage » - Represents an incoming or outgoing private message.
- danog\MadelineProto\EventHandler\Message\SecretMessage » - Represents New encrypted message.
- danog\MadelineProto\EventHandler\Message\ServiceMessage » - Represents info about a service message.
- danog\MadelineProto\EventHandler\Message\ServiceMessage » - Represents info about a service message.
- danog\MadelineProto\EventHandler\Message\Service\DialogBotAllowed » - We have given the bot permission to send us direct messages.
- danog\MadelineProto\EventHandler\Message\Service\DialogChannelCreated » - The channel was created.
- danog\MadelineProto\EventHandler\Message\Service\DialogChannelMigrateFrom » - Indicates the channel was migrated from the specified chat.
- danog\MadelineProto\EventHandler\Message\Service\DialogChatJoinedByLink » - A user joined the chat via an invite link.
- danog\MadelineProto\EventHandler\Message\Service\DialogChatMigrateTo » - Indicates the chat was migrated to the specified supergroup.
- danog\MadelineProto\EventHandler\Message\Service\DialogContactSignUp » - A contact just signed up to telegram.
- danog\MadelineProto\EventHandler\Message\Service\DialogCreated » - A chat or channel was created.
- danog\MadelineProto\EventHandler\Message\Service\DialogDeleteMessages » - Deleted messages.
- danog\MadelineProto\EventHandler\Message\Service\DialogGameScore » - Someone scored in a game.
- danog\MadelineProto\EventHandler\Message\Service\DialogGeoProximityReached » - A user of the chat is now in proximity of another user.
- danog\MadelineProto\EventHandler\Message\Service\DialogGiftPremium » - Info about a gifted Telegram Premium subscription.
- danog\MadelineProto\EventHandler\Message\Service\DialogGiftStars » - Info about a gifted Telegram Stars.
- danog\MadelineProto\EventHandler\Message\Service\DialogGroupCall » - Represents a service message about a group call.
- danog\MadelineProto\EventHandler\Message\Service\DialogGroupCall\GroupCall » - The group call has started or ended.
- danog\MadelineProto\EventHandler\Message\Service\DialogGroupCall\GroupCallInvited » - A set of users was invited to the group call.
- danog\MadelineProto\EventHandler\Message\Service\DialogGroupCall\GroupCallScheduled » - A group call was scheduled.
- danog\MadelineProto\EventHandler\Message\Service\DialogHistoryCleared » - Chat history was cleared.
- danog\MadelineProto\EventHandler\Message\Service\DialogMemberJoinedByRequest » - A user was accepted into the group by an admin.
- danog\MadelineProto\EventHandler\Message\Service\DialogMemberLeft » - A member left the chat or channel.
- danog\MadelineProto\EventHandler\Message\Service\DialogMembersJoined » - Some members joined the chat or channel.
- danog\MadelineProto\EventHandler\Message\Service\DialogMessagePinned » - A message was pinned in a chat.
- danog\MadelineProto\EventHandler\Message\Service\DialogNoForwardRequest » - Emitted only in private chats if the other side requested to disable content protection ».
- danog\MadelineProto\EventHandler\Message\Service\DialogNoForwardToggle » - Emitted only in private chats when enabling or disabling content protection ».
- danog\MadelineProto\EventHandler\Message\Service\DialogPaymentSent » - A payment was sent.
- danog\MadelineProto\EventHandler\Message\Service\DialogPaymentSentMe » - A user just sent a payment to me (a bot).
- danog\MadelineProto\EventHandler\Message\Service\DialogPeerRequested » - Contains info about a peer that the user shared with the bot after clicking on a keyboardButtonRequestPeer button.
- danog\MadelineProto\EventHandler\Message\Service\DialogPhoneCall » - A phone call.
- danog\MadelineProto\EventHandler\Message\Service\DialogPhotoChanged » - The photo of the dialog was changed or deleted.
- danog\MadelineProto\EventHandler\Message\Service\DialogReadMessages » - Messages marked as read.
- danog\MadelineProto\EventHandler\Message\Service\DialogScreenshotTaken » - A screenshot of the chat was taken.
- danog\MadelineProto\EventHandler\Message\Service\DialogSetChatTheme » - The chat theme was changed.
- danog\MadelineProto\EventHandler\Message\Service\DialogSetChatWallPaper » - The wallpaper of the current chat was changed.
- danog\MadelineProto\EventHandler\Message\Service\DialogSetTTL » - The Time-To-Live of messages in this chat was changed.
- danog\MadelineProto\EventHandler\Message\Service\DialogStarGift » - Info about a Star gifted.
- danog\MadelineProto\EventHandler\Message\Service\DialogSuggestProfilePhoto » - A new profile picture was suggested using photos.uploadContactProfilePhoto.
- danog\MadelineProto\EventHandler\Message\Service\DialogTitleChanged » - The title of a channel or group has changed.
- danog\MadelineProto\EventHandler\Message\Service\DialogTopicCreated » - A forum topic was created.
- danog\MadelineProto\EventHandler\Message\Service\DialogTopicEdited » - Forum topic information was edited.
- danog\MadelineProto\EventHandler\Message\Service\DialogWebView » - Data from an opened reply keyboard bot web app was relayed to the bot that owns it (user & bot side service message).
- danog\MadelineProto\EventHandler\Payments\Payment » - This object contains information about an incoming pre-checkout query.
- danog\MadelineProto\EventHandler\Pinned » - Indicates that some messages were pinned/unpinned.
- danog\MadelineProto\EventHandler\Pinned\PinnedChannelMessages » - Represents messages that were pinned/unpinned in a channel.
- danog\MadelineProto\EventHandler\Pinned\PinnedGroupMessages » - Represents messages that were pinned/unpinned in a chat/supergroup.
- danog\MadelineProto\EventHandler\Pinned\PinnedPrivateMessages » - Some messages were pinned in a private chat.
- danog\MadelineProto\EventHandler\Privacy » - Indicates some privacy rules for a user or set of users.
- danog\MadelineProto\EventHandler\Query\ButtonQuery » - Represents a query sent by the user by clicking on a button.
- danog\MadelineProto\EventHandler\Query\ChatButtonQuery » - Represents a query sent by the user by clicking on a button in a chat.
- danog\MadelineProto\EventHandler\Query\ChatGameQuery » - Represents a query sent by the user by clicking on a "Play game" button in a chat.
- danog\MadelineProto\EventHandler\Query\GameQuery » - Represents a query sent by the user by clicking on a "Play game" button.
- danog\MadelineProto\EventHandler\Query\InlineButtonQuery » - Represents a query sent by the user by clicking on a button in an inline message.
- danog\MadelineProto\EventHandler\Query\InlineGameQuery » - Represents a query sent by the user by clicking on a "Play game" button in an inline message.
- danog\MadelineProto\EventHandler\Story\Story » - Represents a Telegram story.
- danog\MadelineProto\EventHandler\Story\StoryDeleted » - Represents a deleted story.
- danog\MadelineProto\EventHandler\Story\StoryReaction » - Represents a reaction to a story.
- danog\MadelineProto\EventHandler\Typing » - A user is typing.
- danog\MadelineProto\EventHandler\Typing\ChatUserTyping » - The user is preparing a message in a group; typing, recording, uploading, etc. This update is valid for 6 seconds. If no further updates of this kind are received after 6 seconds, it should be considered that the user stopped doing whatever they were doing.
- danog\MadelineProto\EventHandler\Typing\SecretUserTyping » - The user is preparing a message in a secret chat; typing, recording, uploading, etc. This update is valid for 6 seconds. If no further updates of this kind are received after 6 seconds, it should be considered that the user stopped doing whatever they were doing.
- danog\MadelineProto\EventHandler\Typing\SupergroupUserTyping » - A user is typing in a supergroup.
- danog\MadelineProto\EventHandler\Typing\UserTyping » - The user is preparing a message; typing, recording, uploading, etc. This update is valid for 6 seconds. If no further updates of this kind are received after 6 seconds, it should be considered that the user stopped doing whatever they were doing.
- danog\MadelineProto\EventHandler\User\Blocked » - A peer was blocked.
- danog\MadelineProto\EventHandler\User\BotStopped » - A bot was stopped or re-started.
- danog\MadelineProto\EventHandler\User\Phone » - A user’s phone number was changed.
- danog\MadelineProto\EventHandler\User\Status » - Contains a status update.
- danog\MadelineProto\EventHandler\User\Status\Emoji » - The emoji status of a certain user has changed or was removed.
- danog\MadelineProto\EventHandler\User\Status\EmptyStatus » - User status has not been set yet.
- danog\MadelineProto\EventHandler\User\Status\LastMonth » - Online status: last seen last month.
- danog\MadelineProto\EventHandler\User\Status\LastWeek » - Online status: last seen last week.
- danog\MadelineProto\EventHandler\User\Status\Offline » - The user’s offline status.
- danog\MadelineProto\EventHandler\User\Status\Online » - Online status of the user.
- danog\MadelineProto\EventHandler\User\Status\Recently » - Online status: last seen recently.
- danog\MadelineProto\EventHandler\User\Username » - Changes were made to the user’s first name, last name or username.
- danog\MadelineProto\GroupCall » - This update represents a Telegram group call (a video chat, a livestream or a live story).
- danog\MadelineProto\VoIP » - This update represents a VoIP Telegram call.
- Filters - MadelineProto offers a very simple and intuitive message filtering system, based on PHP's type system and attributes.
- Plugins - MadelineProto offers a native plugin system, based on event handlers!
- Database - MadelineProto optionally can keep some of its internal data in a database, such as mysql, mariadb, postgres or redis (you can also add your own!), reducing RAM usage.
- Settings - MadelineProto has lots of settings that can be used to modify the behaviour of the library.
- AppInfo: App information.
- Auth: Cryptography settings.
- Connection: Connection settings.
- Files: File management settings.
- Logger: Logger settings.
- Peer: Peer database settings.
- Pwr: PWRTelegram settings.
- RPC: RPC settings.
- SecretChats: Secret chat settings.
- Serialization: Serialization settings.
- TLSchema: TL schema settings.
- Templates: Web and CLI template settings for login.
- VoIP: VoIP settings.
- Database\Memory: Memory backend settings.
- Database\Mysql: MySQL backend settings.
- Database\Postgres: Postgres backend settings.
- Database\Redis: Redis backend settings.
- Getting info about the current user - Here's how you can fetch info about the currently logged in user
- Exceptions - MadelineProto can throw lots of different exceptions.
- Avoiding FLOOD_WAITs - If you make too many requests to telegram, you might get FLOOD_WAITed for a while. To avoid these flood waits, you must calculate the flood wait rate.
- Logging - MadelineProto provides a unified class for logging messages to the logging destination defined in settings.
- Telegram VoIP phone calls - MadelineProto provides an easy wrapper to work with phone calls.
- 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.
- Getting info about chats - There are various methods that can be used to fetch info about chats, based on bot API id, Peer, User, Chat objects.
- Getting all chats (dialogs) - There are two ways to get a list of all chats, depending if you logged in as a user, or as a bot.
- Inline buttons - You can easily click inline buttons using MadelineProto, just access the correct button:
- Secret chats - MadelineProto provides wrappers to work with secret chats.
- Using a proxy - You can use a proxy with MadelineProto.
- Async - MadelineProto now features async, for incredible speed improvements, and parallel processing, all powered by amphp.
- FAQ - Here's a list of common MadelineProto questions and answers.
- Upgrading from MadelineProto v7 to v8 - MadelineProto v8 is a major MadelineProto update, that removes a large number of long-deprecated APIs: I've created this upgrade checklist, to simplify the upgrade process.
- Using methods - There are simplifications for many, if not all of, these methods.
- Named arguments
- Peers
- Files
- Secret chats
- Entities (Markdown & HTML)
- reply_markup (keyboards & inline keyboards)
- bot API objects
- No result
- Multiple method calls
- Cancellation
- FULL API Documentation with descriptions
- Login
- Change 2FA password: update2FA
- Get all chats, broadcast a message to all chats: getDialogIds, getDialogs, getFullDialogs
- Get the full participant list of a channel/group/supergroup: getPwrChat
- Get full info about a user/chat/supergroup/channel: getFullInfo
- Get info about a user/chat/supergroup/channel: getInfo
- Get the ID of a user/chat/supergroup/channel/update: getID
- Get info about the currently logged-in user: getSelf
- Upload or download files up to 4 GB: uploadFrom*, downloadTo*
- Make a phone call and play a song
- Create a secret chat bot
- A collectible gift we own » can be put up for sale on the gift marketplace » with this method, see here » for more info: payments.updateStarGiftPrice
- Abort a pending 2FA password reset, see here for more info »: account.declinePasswordReset
- Accept QR code login token, logging in the app that generated it: auth.acceptLoginToken
- Accept call: acceptCall
- Accept secret chat: acceptSecretChat
- Accept the new terms of service: help.acceptTermsOfService
- Activate or deactivate a Telegram Star subscription »: payments.changeStarsSubscription
- Activate or deactivate a purchased fragment.com username associated to a bot we own: bots.toggleUsername
- Activate or deactivate a purchased fragment.com username associated to a supergroup or channel we own: channels.toggleUsername
- Activate or deactivate a purchased fragment.com username associated to the currently logged-in user: account.toggleUsername
- Activates stories stealth mode, see here » for more info: stories.activateStealthMode
- Add GIF to saved gifs list: messages.saveGif
- Add a main mini app preview, see here » for more info: bots.addPreviewMedia
- Add a sticker to a stickerset. The sticker set must have been created by the current user/bot: stickers.addStickerToSet
- Add an existing telegram user as contact: contacts.addContact
- Add or remove gifts from a star gift collection », or rename the collection: payments.updateStarGiftCollection
- Add/remove sticker from recent stickers list: messages.saveRecentSticker
- Adds a peer to a blocklist, see here » for more info: contacts.block
- Adds a user to a chat and sends a service message on it: messages.addChatUser
- Adds or removes a song from the current user's profile see here » for more info on the music tab of the profile page: account.saveMusic
- Admins with ban_users admin rights » may allow users that apply a certain number of booosts » to the group to bypass slow mode » and other » supergroup restrictions, see here » for more info: channels.setBoostsToUnblockRestrictions
- Allow a user to send us messages without paying if paid messages » are enabled: account.toggleNoPaidMessagesException
- Allow or prevent a bot from changing our emoji status »: bots.toggleUserEmojiStatusPermission
- Allow the specified bot to send us messages: bots.allowSendMessage
- Answer an inline query, for bots only: messages.setInlineBotResults
- Answers a custom query; for bots only: bots.answerWebhookJSONQuery
- Appends one or more items to a todo list »: messages.appendTodoList
- Apply a Telegram Premium giftcode »: payments.applyGiftCode
- Apply changes to multiple stickersets: messages.toggleStickerSets
- Apply one or more boosts » to a peer: premium.applyBoost
- Approve or reject a suggested post »: messages.toggleSuggestedPostApproval
- Associate (or remove) a personal channel », that will be listed on our personal profile page »: account.updatePersonalChannel
- Associate a group to a channel as discussion group for that channel: channels.setDiscussionGroup
- Associate a stickerset to the supergroup: channels.setStickers
- Asynchronously lock a file: flock
- Asynchronously read line: readLine
- Asynchronously sleep: sleep
- Asynchronously write to stdout/browser: echo
- Ban/unban/kick a user in a supergroup/channel: channels.editBanned
- Base64URL encode: base64urlEncode
- Before offering the user the choice to add a message to a quick reply shortcut, to make sure that none of the limits specified here » were reached: messages.checkQuickReplyShortcut
- Bot owners only, fetch main mini app preview information, see here » for more info: bots.getPreviewInfo
- Bots may invoke this method to re-fetch the updateBotBusinessConnect constructor associated with a specific business connection_id, see here » for more info on connected business bots.: account.getBotBusinessConnection
- Broadcast a blockchain block to all members of a conference call, see here » for more info: phone.sendConferenceCallBroadcast
- Businesses » may advertise their location using this method, see here » for more info: account.updateBusinessLocation
- Can only be invoked by non-bot admins of a monoforum », obtains the original sender of a message sent by other monoforum admins to the monoforum, on behalf of the channel associated to the monoforum: channels.getMessageAuthor
- Can only be used by TSF members to obtain internal information: help.getUserInfo
- Cancel a bot subscription: payments.botCancelStarsSubscription
- Cancel a running broadcast: cancelBroadcast
- Cancel the code that was sent to verify an email to use as 2FA recovery method: account.cancelPasswordEmail
- Cancel the login verification code: auth.cancelCode
- Change default emoji reaction to use in the quick reaction menu: the value is synced across devices and can be fetched using help.getConfig, reactions_default field: messages.setDefaultReaction
- Change group call settings: phone.toggleGroupCallSettings
- Change media autodownload settings: account.saveAutoDownloadSettings
- <a href="https://docs.madelineproto.xyz/API_docs/methods