Join Telegram Channel via Phone Number and Username

  • Share this:

Code introduction


This function uses the Telethon library to connect to Telegram, obtain the corresponding user and channel objects through the phone number and channel username, and then invite the user to the channel.


Technology Stack : Telethon

Code Type : Telegram Bot

Code Difficulty : Intermediate


                
                    
from telethon import TelegramClient
from telethon.tl.functions.channels import InviteToChannelRequest
from telethon.tl.functions.contacts import GetContactsRequest
from telethon.tl.types import InputPeerUser

def join_channel(client: TelegramClient, phone_number: str, channel_username: str):
    # Get the user object from the phone number
    user = client.get_entity(phone_number)
    # Get the channel object from the username
    channel = client.get_entity(channel_username)
    # Join the channel
    client(InviteToChannelRequest(channel, [user]))
    return "Successfully joined the channel"                
              
Tags: