Learn How to Build a Telegram Robot Using Python
-
Python 3
-
Python-telegram-bot
-
Public API Random Dog
The first step to get started
First, a token must be created for the robot before writing commands in the Python program. To create a token, we must have access to Telegram AIP.
Create a new bot in BotFather
Before building the robot, the registration process must be done. After registration, we will have access to the token and by using it, AIR Telegram can be obtained. Create a new bot by sending the / newbot command in BotFather.
Follow the relevant steps to get the relevant username and token. You can use it to access your robot:
1
|
https://telegram.me/YOUR_BOT_USERNAME
|
The token obtained should look like the following code:
************* 704418931: AAEtcZ **************
Library installation
Using the following command, a library is prepared for this purpose:
1
|
pip3 install python–telegram–bot
|
Write a program
Now we are trying to build the first robot using the Python program . After executing all the codes, the image of a dog should be displayed on the monitor if we have followed all the steps correctly.
The importance of the library
First, list all relevant libraries using the following command:
1
2
3
4
5
|
from telegram.ext import Updater, CommandHandler
import requests
import re
|
Now access the API and URL of the photo using the thumbnail:
1
|
contents = requests.get(‘https://random.dog/woof.json’).json()
|
Obtain jason data using the URL below.
https://random.dog/woof.json
The result should look like the following code:
1
|
{“url“:”https://random.dog/*****.JPG”}
|
Now get the image URL:
1
|
image_url = contents[‘url’]
|
Now cover the code using the get_url () function:
1
2
3
|
def get_url():
contents = requests.get(‘https://random.dog/woof.json’).json()
|
Send image
To send a message or image, we need an item and a parameter. For photo parameters:
- the image URL
- the recipient’s ID
By calling get_url () function. You can find the URL of the photo:
1
|
url = get_url()
|
recipient’s ID can also be obtained using the following command:
1
|
chat_id = update.message.chat_id
|
Now that the image URL and the recipient’s ID have been obtained, it is time to send the relevant image with the following command:
1
|
bot.send_photo(chat_id=chat_id, photo=url)
|
The relevant code must be in a function called bop, and the resulting code must be in accordance with the following code.
1
2
3
4
5
6
7
|
def bop(bot, update):
url = get_url()
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
|
The main program
Now create a function called main to run the program. Do not forget that the generated token must be replaced with the previous one:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
def main():
updater = Updater(‘YOUR_TOKEN’)
dp = updater.dispatcher
dp.add_handler(CommandHandler(‘bop’,bop))
updater.start_polling()
updater.idle()
if __name__ == ‘__main__’:
main()
|
Finally, the following code should be displayed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import requests
import re
def get_url():
contents = requests.get(‘https://random.dog/woof.json’).json()
url = contents[‘url’]
return url
def bop(bot, update):
url = get_url()
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def main():
updater = Updater(‘YOUR_TOKEN’)
dp = updater.dispatcher
dp.add_handler(CommandHandler(‘bop’,bop))
updater.start_polling()
updater.idle()
if __name__ == ‘__main__’:
main()
|
Run the program
The construction of the Telegram robot in Python is now complete. Now its efficiency must be checked. Save its name as main.py and run the following command:
1
|
python3 main.py
|
By writing the address https://telegram.me/YOUR_BOT_USERNAME. Access your telegram robot and send the / bop command. Now, if a picture of a dog is created on the monitor, all the steps have been completed successfully.
Fix errors
Using this method and the codes mentioned in the above step, you have been able to create a bot that will send you funny photos of dogs whenever you want. With it, not only will you have a picture of funny dogs, but also videos and various gifts from them are available to you.
Now we are trying to be able to write a text with a few other changes along with the submitted image.
We will use regex to solve this problem. In order to be able to distinguish between existing photos, videos and gifs, we consider the final part of the relevant oral:
https://random.dog/*****.JPG
Specify the relevant files or better named:
1
|
allowed_extension = [‘jpg’,‘jpeg’,‘png’]
|
Now we use regex to extract the corresponding horoscope from the existing oral.
1
|
file_extension = re.search(“([^.]*)$”,url).group(1).lower()
|
Using the above code, a function called get_image_url () is created. Now we can get the relevant file with the following command.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
def get_image_url():
allowed_extension = [‘jpg’,’jpeg’,’png’]
file_extension = ‘’
while file_extension not in allowed_extension:
url = get_url()
file_extension = re.search(“([^.]*)$”,url).group(1).lower()
return url
|
Change the relevant code
Now in the last step, place url = get_url () in the bop () function with url = get_image_url (). The final code should look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import requests
import re
def get_url():
contents = requests.get(‘https://random.dog/woof.json’).json()
url = contents[‘url’]
return url
def get_image_url():
allowed_extension = [‘jpg’,‘jpeg’,‘png’]
file_extension = ”
while file_extension not in allowed_extension:
url = get_url()
file_extension = re.search(“([^.]*)$”,url).group(1).lower()
return url
def bop(bot, update):
url = get_image_url()
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def main():
updater = Updater(‘YOUR_TOKEN’)
dp = updater.dispatcher
dp.add_handler(CommandHandler(‘bop’,bop))
updater.start_polling()
updater.idle()
if __name__ == ‘__main__’:
main()
|
Now everything will be fine. Now you have built a telegram robot using the Python program.
The importance of building a telegram robot with Python
Telegram Messenger has undoubtedly been able to gain the status of a feature in recent years due to its extraordinary advantages and has received special attention compared to other programs of its kind.
For this reason, the creators of this program are trying to increase its efficiency and use by upgrading some of its features, and enjoy special popularity. The presence of the Telegram bot or robot option in Telegram also makes it sufficiently separate from other programs.
The method followed in the previous section helps us to build and benefit from the Telegram robot using the Python program.
Bots are an automated user account that allows the user to do interesting things, for example, when you use this program to communicate with your friends, you can easily share various videos and photos with your friends.
Of course, without using them, there are other ways to share all kinds of photos and videos.
As a Telegram bot, you have to do the following steps:
- Open the YouTube website in a web browser and go to the search section
- Find the video you want to share with your friends
- Select the share via option and encounter different sharing methods
- Now go back to Telegram and share the relevant link.
Do not use the Telegram robot
Although this method is normal for all of us and we are accustomed to do the above steps to publish photos and videos in the telegram in many cases, but in some cases the mentioned steps may not even be successful.
For example, when the internet speed is low, then you can not connect to the filter breaker to enter YouTube. Now, easily use the Telegram bot to publish the desired messages in the Telegram space. In this case, just follow the steps below:
- When communicating with people when you are in the Telegram application.
- You can share the word @vid with the video you selected
- By clicking the submit button, the relevant video will be published in Telegram chat
There is no doubt that the second method is much easier, and you can transfer the relevant messages in less time by using the Telegram bot. To create a Telegram bot using Python, you must first have a special account in Telegram.
Once you have installed Telegram and created a separate account, look for the word botfather in the search field. After you find the chat in it and send the command newbot / first, the next steps will be automatically provided to you under this section. Now that you have completed the necessary steps in this section, you will have the following:
-
Your special token
-
URL for Telegram API
-
Link for Telegram bats
These are the starting points for using the Telegram bot. At this stage, the Telegram bot has been created, but we still do not have the opportunity to benefit from it.
Python program
Python is one of the simple yet powerful programming languages that has enabled us to improve the power and efficiency of our software by designing special code. Today from the Python program for:
- Data science,
- Machine learning
- Automation of systems
- Web Development
Programming interfaces are widely used.
Another way to build a telegram robot with Python
A cyberspace must first be created
1
|
$ python –m venv botenv/
|
Now activate virtualenv using the following command
1
|
$ source botenv/bin/activate
|
Our library needs the following
We can install them using the following command:
1
2
3
4
5
|
(telebot) $ pip install flask
(telebot) $ pip install python–telegram–bot
(telebot) $ pip install requests
|
Search for the project by yourself now:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
├── app.py
├── telebot
│ ├── credentials.py
│ | .
│ | you can build your engine here
│ | .
│ └── __init__.py
└── botenv
|
In the credentials.py section we will need three variables:
1
2
3
4
5
|
bot_token = “here goes your access token from BotFather”
bot_user_name = “the username you entered”
URL = “the heroku app link that we will create later”
|
Now enter the following commands in app.py:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
# import everything
from flask import Flask, request
import telegram
from telebot.credentials import bot_token, bot_user_name,URL
global bot
global TOKEN
TOKEN = bot_token
bot = telegram.Bot(token=TOKEN)
# start the flask app
app = Flask(__name__)
|
The telegram URL required for / {token is called using the following command to respond to messages sent to the bot:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
@app.route(‘/{}’.format(TOKEN), methods=[‘POST’])
def respond():
# retrieve the message in JSON and then transform it to Telegram object
update = telegram.Update.de_json(request.get_json(force=True), bot)
chat_id = update.message.chat.id
msg_id = update.message.message_id
# Telegram understands UTF-8, so encode text for unicode compatibility
text = update.message.text.encode(‘utf-8’).decode()
# for debugging purposes only
print(“got text message :”, text)
# the first time you chat with the bot AKA the welcoming message
if text == “/start”:
# print the welcoming message
bot_welcome = “”“
Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name.
““”
# send the welcoming message bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)
else:
try:
# clear the message we got from any non alphabets
text = re.sub(r“\W”, “_”, text)
# create the api link for the avatar based on http://avatars.adorable.io/
url = “https://api.adorable.io/avatars/285/{}.png”.format(text.strip())
# reply with a photo to the name the user sent,
# note that you can send photos by url and telegram will fetch it for you
bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)
except Exception:
# if things went wrong
bot.sendMessage(chat_id=chat_id, text=“There was a problem in the name you used, please enter different name”, reply_to_message_id=msg_id)
return ‘ok’@app.route(‘/setwebhook’, methods=[‘GET’, ‘POST’])
def set_webhook():
# we use the bot object to link the bot to our app which live
# in the link provided by URL
s = bot.setWebhook(‘{URL}{HOOK}’.format(URL=URL, HOOK=TOKEN))
# something to let us know things work
if s:
return “webhook setup ok”
else:
return “webhook setup failed”
|
Now that everything is ready, it is enough to create an interesting web page with the following command:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@app.route(‘/’)
def index():
return ‘.’
if __name__ == ‘__main__’:
# note the threaded arg which allow
# your app to have more than one thread
app.run(threaded=True)
|
After the previous command, the final version of app.py should look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
import re
from flask import Flask, request
import telegram
from telebot.credentials import bot_token, bot_user_name,URL
global bot
global TOKEN
TOKEN = bot_token
bot = telegram.Bot(token=TOKEN)
app = Flask(__name__)
@app.route(‘/{}’.format(TOKEN), methods=[‘POST’])
def respond():
# retrieve the message in JSON and then transform it to Telegram object
update = telegram.Update.de_json(request.get_json(force=True), bot)
chat_id = update.message.chat.id
msg_id = update.message.message_id
# Telegram understands UTF-8, so encode text for unicode compatibility
text = update.message.text.encode(‘utf-8’).decode()
# for debugging purposes only
print(“got text message :”, text)
# the first time you chat with the bot AKA the welcoming message
if text == “/start”:
# print the welcoming message bot_welcome = “”“
Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name.
““”
# send the welcoming message
bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)
else: try:
# clear the message we got from any non alphabets
text = re.sub(r“\W”, “_”, text)
# create the api link for the avatar based on http://avatars.adorable.io/
url = “https://api.adorable.io/avatars/285/{}.png”.format(text.strip())
# reply with a photo to the name the user sent,
# note that you can send photos by url and telegram will fetch it for you
bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)
except Exception:
# if things went wrong
bot.sendMessage(chat_id=chat_id, text=“There was a problem in the name you used, please enter different name”, reply_to_message_id=msg_id)
return ‘ok’@app.route(‘/set_webhook’, methods=[‘GET’, ‘POST’])
def set_webhook():
s = bot.setWebhook(‘{URL}{HOOK}’.format(URL=URL, HOOK=TOKEN))
if s:
return “webhook setup ok”
else:
return “webhook setup failed”
@app.route(‘/’)
def index():
return ‘.’
if __name__ == ‘__main__’:
app.run(threaded=True)
|
We use the requirements.txt file to help Heroku detect which libraries are being used.
To generate the relevant file, consider the following command:
1
|
pip freeze > requirements.txt
|
Now use Procfile to determine where the relevant software will start. Create a Procfile using the following command:
1
|
web: gunicorn app:app
|
By adding the .gitignore option you will no longer need to update it.
To build a deploy, follow these steps:
1
|
$ heroku login
|
If you encounter a problem in the waiting for login section, use the following command:
1
2
3
4
5
6
7
8
9
10
|
$ heroku login –i
waiting for login :
$ git init
$ heroku git:remote –a {heroku–project–name}
|
Now Deploy the software:
1
2
3
4
5
|
$ git add .
$ git commit –m “first commit”
$ git push heroku master
|
If all the above steps are correct, you should see the following on the monitor:
1
2
3
4
5
6
7
8
9
|
remote: ——-> Launching...
remote: Released v6
remote: https://project-name.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
|
Now you have the relevant Telegram bot and you can make your Telegram bot more practical by adding some items such as typing option.
The option to write along with the submitted photos is obtained through the following commands.
Obtain the following code using the respond () function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
if text == “/start”:
# print the welcoming message
bot_welcome = “”“
Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name.
““”
# send the welcoming message
bot.sendChatAction(chat_id=chat_id, action=“typing”)
sleep(1.5)
bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)
else: try:
# clear the message we got from any non alphabets
text = re.sub(r“\W”, “_”, text)
# create the api link for the avatar based on http://avatars.adorable.io/
url = “https://api.adorable.io/avatars/285/{}.png”.format(text.strip())
# reply with a photo to the name the user sent,
# note that you can send photos by url and telegram will fetch it for you
bot.sendChatAction(chat_id=chat_id, action=“upload_photo”)
sleep(2)
bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)
except Exception:
# if things went wrong
bot.sendMessage(chat_id=chat_id, text=“There was a problem in the name you used, please enter different name”, reply_to_message_id=msg_id)
|
By calling the respond () function, you can easily separate the corresponding logic from the others and create an AI bot this way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
├── app.py
├── telebot
│ ├── credentials.py
│ ├──ai.py
│ | .
│ | you can build your engine here
│ | .
│ └── __init__.py
└── botenv
|
Inside ai.py:
1
2
3
4
5
|
def generate_smart_reply(text):
# here we can do all our work
return “this is a smart reply from the ai!”
|
Now enter it in app.py:
1
2
3
4
5
6
7
8
9
10
11
|
import re
from time import sleep
from flask import Flask, request
import telegram
From telebot.ai import generate_smart_reply
from telebot.credentials import bot_token, bot_user_name,URL
|
Then call the previous command inside the respond () code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
def respond():
# retrieve the message in JSON and then transform it to Telegram object
update = telegram.Update.de_json(request.get_json(force=True), bot)
chat_id = update.message.chat.id
msg_id = update.message.message_id
# Telegram understands UTF-8, so encode text for unicode compatibility
text = update.message.text.encode(‘utf-8’).decode()
# for debugging purposes only
print(“got text message :”, text)
# here call your smart reply message
reply = generate_smart_reply(text)
bot.sendMessage(chat_id=chat_id, text=reply, reply_to_message_id=msg_id)
|
Now that you have mastered the various steps of building a Telegram robot with Python, it is better to easily transfer your messages by having special bots when using Telegram.