The Wayback Machine - https://web.archive.org/web/20240921213434/https://www.geeksforgeeks.org/send-message-to-telegram-user-using-python/
Open In App

Send message to Telegram user using Python

Last Updated : 12 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Have you ever wondered how people do automation on Telegram? You may know that Telegram has a big user base and so it is one of the preferred social media to read people. What good thing about Telegram is that it provides a bunch of API’s methods, unlike Whatsapp which restricts such things. So in this post, we will be sharing how to send messages to a Telegram user using Python.

Getting Started

First, create a bot using Telegram BotFather. To create a BotFather follow the below steps as follows:  

  • Open the telegram app and search for @BotFather.
  • Click on the start button or send “/start”.
  • Then send “/newbot” message to set up a name and a username.
  • After setting name and username BotFather will give you an API token which is your bot token.\

Then create an app on the telegram. Follow the below steps: 

  • Log into the telegram core: https://my.telegram.org
  • Go to ‘API development tools’ and fill out the form.
  • You will get the api_id and api_hash parameters required for user authorization. 

Modules needed

You need several Python library imports for the script functioning.  

  • telebot: To install this module type the below command in the terminal.
pip install telebot
  • telethon: To install this module type the below command in the terminal. 
pip install telethon

Below is the implementation. 

Python3




# importing all required libraries
import telebot
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerUser, InputPeerChannel
from telethon import TelegramClient, sync, events
 
  
# get your api_id, api_hash, token
# from telegram as described above
api_id = 'API_id'
api_hash = 'API_hash'
token = 'bot token'
message = "Working..."
 
# your phone number
phone = 'YOUR_PHONE_NUMBER_WTH_COUNTRY_CODE'
  
# creating a telegram session and assigning
# it to a variable client
client = TelegramClient('session', api_id, api_hash)
  
# connecting and building the session
client.connect()
 
# in case of script ran first time it will
# ask either to input token or otp sent to
# number or sent or your telegram id
if not client.is_user_authorized():
  
    client.send_code_request(phone)
     
    # signing in the client
    client.sign_in(phone, input('Enter the code: '))
  
  
try:
    # receiver user_id and access_hash, use
    # my user_id and access_hash for reference
    receiver = InputPeerUser('user_id', 'user_hash')
 
    # sending message using telegram client
    client.send_message(receiver, message, parse_mode='html')
except Exception as e:
     
    # there may be many error coming in while like peer
    # error, wrong access_hash, flood_error, etc
    print(e);
 
# disconnecting the telegram session
client.disconnect()


Code Explanation: 

  1. The code starts by importing all the required libraries.
  2. The first library is telebot which is used to interact with Telegram.
  3. Next, we import the sync module which helps us to keep our code organized and easy to read.
  4. We also import the events module so that we can handle various telegram related events.
  5. Next, we get our API_id, API_hash, and token from Telegram as described earlier in this tutorial.
  6. Then, we create a variable called message for holding our message.
  7. We then connect to Telegram and assign the session to a variable called client .
  8. Next, we sign in the client using its phone number and user ID ( input(‘Enter the code: ‘)) .
  9. Finally, we try sending a message using the telegram client but there may be many errors coming in while trying so let’s print them out for further analysis.
  10. Once everything is okay, we disconnect the session by calling client.disconnect() .
  11. The code will first import all the required libraries and set up a TelegramClient instance.
  12. Next, it will get your API_id, API_hash and token from Telegram.
  13. Finally, it will create a message variable and assign it to the client object. 


Previous Article
Next Article

Similar Reads

Send Direct Message On Instagram using Selenium in Python
In this article, we will learn how we can send a direct message to users on Instagram without any manual action. We will be using the selenium module to do this task. Requirements:Chrome Driver for Chrome Browser (https://chromedriver.chromium.org/) or Gecko Driver for Firefox(https://github.com/mozilla/geckodriver/releases)Selenium Package. To ins
2 min read
Send Message on Instagram Using Instabot module in Python
In this article, we are going to see how to send messages on Instagram using the Instabot module in Python. Instagram is a nice platform for chatting but when it comes to sending the same message to all friends this is a really boring and time-consuming task especially if you have a large number of followers. To make this easy we make a bot using P
2 min read
Send message to FB friend using Python
The power of Python comes because of the large number of modules it has. This time we are going to use one of those. Every one of us, one time or another, has a wish of the message (or spamming -.-) our Facebook friend. This is a program that can do something similar. So without further delay, let’s jump right in. C/C++ Code import fbchat from getp
3 min read
Send an SMS Message with Python
In today's fastest-growing world, SMS is still a powerful tool by which we can reach billions of users and one can establish a connection globally. In this new world when instant messaging and social media are dominating you can feel our humble SMS outdated but you don't underestimate its power, it will remain an omnipresent tool for communication
4 min read
Create a Telegram Bot using Python
In this article, we are going to see how to create a telegram bot using Python. In recent times Telegram has become one of the most used messaging and content sharing platforms, it has no file sharing limit like Whatsapp and it comes with some preinstalled bots one can use in any channels (groups in case of whatsapp) to control the behavior or filt
6 min read
Keyboard buttons in Telegram bot Using Python
One common way that we interact with the Telegram bot is through the use of keyboard buttons. These buttons give a convenient and intuitive way to input data and perform specific actions within the bot. Without keyboard buttons, we would have to manually type in commands or responses, which could be time-consuming and may lead to errors. Keyboard b
9 min read
Building Powerful Telegram Bots with Telethon in Python
Creating a Telegram bot can significantly enhance how you interact with users, automate tasks, and provide information quickly. Here, we'll use the Telethon library in Python to build a powerful Telegram bot. Creating Telegram Bot in PythonPrerequisites Telegram Account: We need a Telegram account to create and manage our bot.Telethon Library: We'l
4 min read
Send SMS updates to mobile phone using python
If you are running any python script and want to send regular updates from your script to your mobile phone through SMS, you can use SinchSMS API to send SMS.Approach : Create an app on Sinch and get the key and secret of the app and use these credentials in the following script to send SMS to your mobile.Limitation of Sinch : If you don't have any
2 min read
Python | Send SMS using Twilio
As we know Python is a cool scripting language and can be used to write scripts to easify day-to-day task. Also, since python has large community support and lots of module/API available, it makes Python more versatile and popular among users. In this article, we will see how to use Twilio API to send SMS using Python. It will be a very quick and e
2 min read
How to send SMS alert using Python and MSG91 API
In our college days we most often forget our daily classes, right? To keep track of classes every day, we can send a Notification (i.e, ) SMS Alert regards their classes to their mobile phones using Python. We need to use two functionalities: http module and MSG91 API for sending SMS. import http.client as ht conn = ht.HTTPSConnection("api.msg
3 min read
Send Text messages to any mobile number using Fast2SMS API in Python
This article is going to be about how can we send text messages using Python. We will be using Fast2SMS API to send messages. You don't need to install any Python package for this purpose. First, you need a Fast2SMS account. You can sign up for Fast2SMS from here. Now, go to Dev API option and copy the API Authorization Key. This API key is generat
2 min read
Send Email Using yagmail in Python
In this article, we are going to see how to send email using yagmail. yagmail(Yet Another Gmail) is a module in python which used to send emails using Python. This module is nothing, just a Gmail/SMTP(Simple Mail Transfer Protocol) client that removes the issues of sending emails through Python. This helps the Web App to interact with Gmail without
3 min read
Send Chrome Notification Using Python
In this article, we are going to see how to send a Chrome notification from your PC to a phone or several devices in this article. We may send messages, links, and other content. For this, we'll use Python's notify2 module and its various capabilities, which will help us in delivering messages to many devices. notify2 is a Python module that is use
2 min read
Send SMS with REST Using Python
In this article, we are going to see how we can send SMS with REST using Python. The requests library can be used to make REST requests using Python to send SMS. Approach:You need to first create a REST API KEY for sending SMS using Python Script. We have used Fast2SMS for creating API KEY.You can go on the website and create an account after which
2 min read
Send mail with attachment from your Gmail account using Python
In last article, we have discussed the basics of sending a mail from a Gmail account without any subject as well as without any attachment. Today, we will learn how to send mail with attachment and subject using Python. Before moving on, it is highly recommended to learn how to send a simple mail using Python and learn the basics working of 'smtpli
4 min read
How To Send Files Using Python Built-In Http Server
Python's built-in HTTP server offers a straightforward way to share files over a local network or the internet without the need for complex setups. In this tutorial, we'll walk through the step-by-step process of using Python's built-in HTTP server to send files to clients. Setting Up the HTTP ServerThe first step is to start the HTTP server. Open
2 min read
Send Emails Using Python
By using Python, you can send emails which can be a valuable skill for automation, communication, and data-driven processes. In this article, we will explore how to send mail from Gmail using Python. How can you send Emails using Python?Python offers a library to send emails- "SMTP" Library. "smtplib" creates a Simple Mail Transfer Protocol (SMTP)
4 min read
Python | Message Encode-Decode using Tkinter
Prerequisite : Basics of TkinterPython offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Python pr
5 min read
Create a Yes/No Message Box in Python using tkinter
Python offers a number Graphical User Interface(GUI) framework but Tk interface or tkinter is the most widely used framework. It is cross-platform which allows the same code to be run irrespective of the OS platform (Windows, Linux or macOS). Tkinter is lightweight, faster and simple to work with. Tkinter provides a variety of widgets that can be c
4 min read
How To Encode And Decode A Message using Python?
Encryption is the process of converting a normal message (plain text) into a meaningless message (Ciphertext). Whereas, Decryption is the process of converting a meaningless message (Cipher text) into its original form (Plain text). In this article, we will take forward the idea of encryption and decryption and draft a python program. In this artic
3 min read
Send PDF File through Email using pdf-mail module
pdf_mail module is that library of Python which helps you to send pdf documents through your Gmail account. Installing Library This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the terminal. pip install pdf-mail Function of pdf_mail This module only comes with a singl
2 min read
Python - Web App To Send Push Notification To Your Phone
In this article, we will discuss two apps and how they can be configured using python to send notifications. Pushbullet Pushbullet, a prominent Python package, which connects multiple devices using python code. In this article, we will discuss how to send messages or notifications through it. Using our computer and python code, we will send some me
6 min read
How to Send Automated Email Messages in Python
In this article, we are going to see how to send automated email messages which involve delivering text messages, essential photos, and important files, among other things. in Python. We'll be using two libraries for this: email, and smtplib, as well as the MIMEMultipart object. This object has multiple subclasses; these subclasses will be used to
6 min read
How to Send Beautiful Emails in Python
In this article we will send stylized emails using Python we will be using smtplib. The Python smtplib module defines an SMTP client session object which can be used to send mail to any recipient with an SMTP listener. To send emails to any legitimate email address on the internet, "smtplib" produces a Simple Mail Transfer Protocol client session o
3 min read
Message Boxes using PyAutoGUI
PyAutoGUI is a Python module which can automate your GUI and programmatically control your keyboard and mouse. This article illustrates the GUI functions to create display boxes. If you want to know more about PyAutoGUI and its ability to automate your keyboard and mouse, follow this article : Mouse and Keyboard Automation using PyAutoGUI PyAutoGUI
2 min read
Python | Issue Warning Message
Problem - To have a program that can issue warning messages (e.g., about deprecated features or usage problems). Code #1 : Use the warnings.warn() function import warnings def func(x, y, logfile = None, debug = False): if logfile is not None: warnings.warn('logfile argument deprecated', DeprecationWarning) The arguments to warn() are a warning mess
2 min read
Python | Prompt for Password at Runtime and Termination with Error Message
Say our Script requires a password, but since the script is meant for interactive use, it is likely to prompt the user for a password rather than hardcode it into the script. Python’s getpass module precisely does what it is needed. It will allow the user to very easily prompt for a password without having the keyed-in password displayed on the use
3 min read
Python Tkinter - Message
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task
3 min read
Python PyQt5 – How to change font and size of Status Bar Message
We can set message to a Status Bar by using showMessage() method. In this article, we will see how to change the font and the size of StatusBar message. In order to do this we will use setFont() method. Syntax : self.statusBar().setFont(QFont(font_name, font_size)) Argument : It take two argument : 1. Font name it can be ‘Arial’, ’Times’ etc. 2. Si
1 min read
Python EasyGUI - Message Box
Message Box : It is used to display a window having a message or information in EasyGUI, it can be used where there is a need to display some message or some important information, it contains message and a "Ok" button which when pressed closes the message, below is how the message box looks like EasyGUI is a module for very simple, very easy GUI p
2 min read
Practice Tags :