MALIKA KAROUM

MALIKA KAROUM

  • Home
  • Inleiding
  • Unite Arab Emirates
  • Blog
  • video’s
  • Promotion
    • Worth for free now
    • Work from Home 2023
    • Gadgets
    • All about Windows
    • about Whatsapp
    • Whats the
    • About websites
    • New Ways
    • New Way of Watching
    • Virtual
    • Website
    • All about Video
    • How to Use
    • YouTube Info
    • All about Twitter
    • The Best of
    • About Apps
    • Google News
    • For Free
    • About This
    • Need More
    • Why should you
    • Iphone news
    • Interesting News
    • About Amazone
    • Some tips
    • About Netflix
    • All about Music
    • About Facebook
  • Marketing
    • Malika Karoum Strategie Modules
    • Malika Karoum Online Marketing
    • Malika Karoum Business Service
    • Malika Karoum Marketing Platform
    • Online business marketing
  • Luxury
    • The Indulgence Business site
    • The Luxury Web site
    • The Ultimate Indulgence
    • The Indulgence Site
    • The Ultimate Luxury Information site
    • Online luxury
  • Malika Karoum
    • Malika Karoum LinkedIn
    • Malika Karoum Facebook
    • Malika Karoum Instagram
    • Malika Karoum Business News
    • Adverteren grote fraude
    • Menu POS
    • Malika Karoum Evenementen
  • Security
  • Malika Karoum link
  • Home
  • Malika Karoum Global News
  • How to Build a Basic Telegram Bot With Python 3
June 8, 2023

How to Build a Basic Telegram Bot With Python 3

How to Build a Basic Telegram Bot With Python 3

by Malika Karoum / Monday, 28 December 2020 / Published in Malika Karoum Global News

If you’re a Telegram user, you’re bound to have had a ‘conversation’ with a chatbot at some point. With their amazing customizability, Telegram’s bots offer a variety of advantages—be it for automating tasks or just having a bit of fun with games in your chat group.

While some may find developing a bot to be a daunting task, it really isn’t. With the right planning, you can have a Telegram bot up and running in less than an hour! Here’s how to create a simple Telegram bot that outputs cute pictures of internet cats when prompted.

Getting Started

For this tutorial, we are going to use Python 3, the python-telegram-bot and requests library, and TheCatAPI.

Every bot in Telegram has a unique token that helps it communicate with Bot API in order to use the app’s messaging interface. Bot API, one of Telegram’s most popular features among developers, allows you to use its messages as an interface.

To get the token, start a conversation with @BotFather which, as the name suggests, is an official bot that lets you create and customize your own bots. You can access the bot using the given link or alternatively search ‘@botfather’ on Telegram.

Once in the chat, create your bot by typing the /newbot command. Continue to set the name and username of your bot (we decided to name ours @pawsomebot). Following this, you will get a token unique to your bot.

Now that we have all the prerequisites, it’s time to get to the exciting part!

Installing Libraries

If you’re using Windows, open up command prompt and type the following commands:

pip install python-telegram-bot
pip install requests

If you’re using macOS or Linux, use the following commands on your terminal instead. Additionally in Linux, make sure you are logged in as a user with sudo privileges.

pip3 install python-telegram-bot
pip3 install requests

Writing the Program

Create a new folder on your computer and open it in your favorite editor. Create a new file and name it main.py. This file will contain the source code for your bot.

Now, let’s import the libraries we installed earlier along with some of their built-in functions.

from telegram.ext import Updater, CommandHandler
import requests
import re

The flow of the program from here on out is to access TheCatAPI, obtain the URL of a random image, and send that image to the user’s chat.

Let’s start with a function to get the image URL, which can be done using the requests module. In this function, we load the JSON data of a random file provided by TheCatAPI and extract its URL to later use. To look at the format of the JSON object, head over to https://api.thecatapi.com/v1/images/search on your browser. You will notice something like this:

[{"breeds":[],"id":"a8c","url":"url.jpg","width":800,"height":533}]

Notice that the JSON object is an array that holds a dictionary. This dictionary contains the URL with the key ‘url’. To extract the URL, we need to reference the first element of the array, and then the relevant key.

def getUrl():
#obtain a json object with image details
#extract image url from the json object
contents = requests.get('https://api.thecatapi.com/v1/images/search')
url = contents[0]['url']
return url

Next up, we need to send this image into a user’s chat. For this, we need an image URL as well as the unique ID of the user’s chat. Let’s create a wrapper function to do this. First, we call the getUrl(). function to obtain the URL of a random image—this URL changes every time your program iterates through the function.

This is then followed by obtaining the recipient user’s chat ID, which defines the bot’s target location for messages and parsing the URL through the Bot API’s inbuilt send_photo() function.

def sendImage(bot, update):
url = getUrl()
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, image=url)

To find out more about Bot API’s various inbuilt functions and how they work, feel free to check out Telegram’s official documentation after this tutorial.

Finally, let’s create a function that controls the overall working of the bot. This function—conventionally called main()—is where we send an HTTP request to Bot API using the token we obtained at the beginning of the tutorial and then define what the bot’s user interaction will be like. In a case as simple as ours, this essentially means initiating the bot and calling the sendImage() function when prompted by the user.

def main():
updater = Updater("1190888035:AAGeJ9316R95NqJLFefV5vQA-UL4np11V2c")
#call sendImage() when the user types a command in the telegram chat
updater.dispatcher.add_handler(CommandHandler('meow',sendImage))
#start the bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()

Your final program should look like this:

from telegram.ext import Updater, CommandHandler
import requests
import re
def getUrl():
#obtain a json object with image details
#extract image url from the json object
contents = requests.get('https://api.thecatapi.com/v1/images/search')
url = contents[0]['url']
return url
def sendImage(bot, update):
url = getUrl()
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, image=url)
def main():
updater = Updater("1190888035:AAGeJ9316R95NqJLFefV5vQA-UL4np11V2c")
#call sendImage() when the user types a command in the telegram chat
updater.dispatcher.add_handler(CommandHandler('meow',sendImage))
#start the bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()

Your Own Telegram Bot

Congratulations! You’ve built your very own stress-relieving bot that sends open-source images of the cutest internet cats upon being prompted. Try running your program and type /meow in your bot’s chat to activate it.

While this may be a simple bot with limited functionality, it shows just how powerful Telegram’s bot development ecosystem is. You can add in any number of complex subroutines and features to enhance the functionality of your bot—the sky’s the limit. To find out more about awesome Telegram bots that contributors have made over the years, check out our list of useful Telegram bots.

You can also find a variety of open-source licensed programs for Telegram bots on platforms such as GitHub. Most open-source licenses allow you to use, study, download, or modify the source code of a program.

Host Your Telegram Bot Online

Now that you have your bot up and running, try closing main.py on your PC and use the bot on your Telegram messenger app. Does it still respond to the /meow command? No, it doesn’t.

As a beginner, you may be confused as to why main.py on your PC needs to be up and running when you have already created a bot running on the internet. The reason for this is that the program uses your PC as a local server to send HTTP requests to the APIs used in this program.

As such, having to run the program every time you want to use the app is neither feasible nor convenient. In order to solve this issue, we need to remove the bot’s dependency on your device

One way to do so is to use a low-cost printed circuit board (PCB), such as Raspberry Pi, to set up your own web server and use it to run your program. It has the same benefits as running the program on your PC without the costs of keeping it on all day and night since PCBs tend to have a significantly lower energy footprint.

Alternatively, you can also deploy your program to the cloud. Head over to a web-app hosting platform such as Heroku, AWS, Google Cloud, or Microsoft Azure and choose a subscription that best suits your needs. We recommend choosing a free trial or subscription and upgrading it as you increase the scale or scope of your program.

MakeUseOf – Feed

  • Tweet
Tagged under: Basic, Build, Python, Telegram

About Malika Karoum

What you can read next

How to Make Sure Your Computer Can Run Windows 10
5 Apps and Sites Every Freelance Professional Should Check Out
Google Adds Haptic Feedback to Gboard for iOS

Malika Karoum Blog 2023

  • How to Delete the Last 15 Minutes of Your Google Search History

    There’s a quick way for you to clear your...
  • Lenovo Wants You to Know Its Yoga Pad Pro Can Be Used as a Portable Switch Display

    Sometimes, when playing with your Nintendo Swit...
  • The 5 Best Apps for Buying and Selling Pre-Owned Books

    We’ve all been at the point where we have...
  • Humble’s Recent "Heal Covid-19" Bundle Raised 1.2 Million for Charity

    To help raise money for COVID-19 relief in Indi...
  • Nintendo Partners With PlayVS to Make Its Games Recognized High School Varsity Athletics

    It’s odd—Nintendo gets a lot of flak for ...
  • The Pros and Cons of Playing Video Games on an Emulator

    If you’re a fan of playing retro video ga...
  • 5 Curators to Find the Best Articles Worth Reading on the Internet

    When anyone and everyone is a publisher, it isn...
  • Apple Could Unveil iPads With OLED Screens in 2023

    Apple only just switched from LCD to mini-LED d...
  • What Is Signal and How Does It Work?

    The chances are that you use at least one of th...
  • Samsung’s Upcoming Flagship Exynos Chipset Will Feature AMD’s RDNA2 GPU

    AMD confirmed its partnership with Samsung at C...
  • Atari Finally Reveals the Launch Date for the New Atari VCS Console

    At last, after what seems like an age (it pract...
  • Twitter Starts Testing Full-Screen Ads in Fleets

    Twitter has announced that it will be adding fu...
  • When Is Facebook Messenger Going to Offer End-to-End Encryption?

    Facebook Messenger is easy to use and has great...
  • Get Paid to Play Apps: How They Work and What You Risk

    You’ve probably seen advertisements for a...
  • When Will PS5 Production Ensure Supply Meets Demand?

    Despite the PS5’s launch taking place in ...
  • How to Manage Processes on Ubuntu Using System Monitor

    Linux, like most modern operating systems, is v...
  • How to Get Verified on Twitter and Finally Get That Blue Check Mark

    Twitter, like most social media platforms, offe...
  • 10 Street Photography Tips That Will Make You a Better Photographer

    Street photography is enjoyed by many enthusias...
  • Huawei Freebuds 4i Review: Quality ANC Earbuds for $100

    Huawei Freebuds 4i 8.00 / 10 Read Reviews Read ...
  • What Is Extended Reality (XR) and How Does It Work?

    We’re living in a digital age where the virtual...

MALIKA KAROUM ONLINE MARKETING PLATFORM

Office:
RME HOLDINGS SARL – DUBAI BRANCH

BUSINESS CENTER

Parcel ID: 345-835

Area: Bur Dubai

Sub Area: Burj Khalifa

UNITED ARAB EMIRATES

 

 

 

Malika Karoum Concept

Malika Karoum Projects

  • GET SOCIAL

© 2014 Malika Karoum -United Arab Emirate Dubai- All Rights Reserved

TOP