Building a Telegram Bot with Python and Gemini AI (2024)

Building a Telegram Bot with Python and Gemini AI (2)

Telegram bots are a great way to interact with users and automate tasks. In this tutorial, we’ll walk through the process of creating a Telegram bot using Python and integrating it with the Gemini AI API to add advanced conversational capabilities.

Before we begin, make sure you have the following:

  • A Telegram account
  • Python installed on your system
  • Visual Studio Code (or any other preferred text editor/IDE)
  • Access to the Gemini AI API
  • Go to Telegram and search for BotFather.
  • Start a chat with BotFather and type /newbot.
  • Follow the instructions to create a new bot. Give it a unique name ending with “bot”.
  • Once created, BotFather will provide you with a token. Keep this token safe as it will be needed to authenticate your bot.
  • Open a terminal or command prompt.
  • Now on we are following the steps from https://github.com/eternnoir/pyTelegramBotAPI repository.
  • Use pip, Python’s package installer, to install the pyTelegramBotAPI library:
pip install pyTelegramBotAPI
  • Inside the project folder, create a new Python script file. You can name it main.py.
  • Open main.py in VSCode.
  • Copy the Python code provided in the transcript that sets up the Telegram bot.
  • Paste the code into main.py.
import telebot

bot = telebot.TeleBot("TOKEN", parse_mode=None) # You can set parse_mode by default. HTML or MARKDOWN

  • Replace the placeholder for the bot token with the token obtained from BotFather.
  • Then copy the code for the message handlers.
@bot.message_handler(func=lambda m: True)
def echo_all(message):
bot.reply_to(message, message.text)
  • This lambda function will take a message and reply back to the user the same message. (we will change this reply to Gemini AI response later on)
  • Then we add the following code to start the bot.
bot.infinity_polling()
  • Now if you run your python file (you will get a blank output in the console) and go to your bot, you can check whether it’s properly connected. For that you can send something and the bot will reply with the same message.
Building a Telegram Bot with Python and Gemini AI (3)
  • Visit the DeepMind website (https://ai.google.dev). Then navigate to google ai studio and locate the section for accessing the Gemini AI API.
  • In ai studio you can even create your own prompt as well.
  • In main.py, import any necessary libraries for interacting with the Gemini AI API.
  • Configure the API key for Gemini AI in your Python script.
  • In the upper right conner you have get code option to get the code snippet.
  • Copy the code snippet from the transcript that interacts with the Gemini AI API.
  • Create a new file named gemini.py and paste the code that you copied.
  • You need to install the package for google generative AI pip install google-generativeai using this code.
  • After that you need to replace YOUR_API_KEY with the API key that you got from the Gemini AI.
  • At the below of the code you have the user message that sending to the Gemini chat bot and after that it will print the response that you are getting.
convo.send_message("Hello! How old are you?")
print(convo.last.text)
  • Then you can copy the code from gemini.py and paste it to the main.py. Remember to replace your message_handler lambda function output with the Gemini response that we are getting.
@bot.message_handler(func=lambda m: True)
def echo_all(message):
convo.send_message(message.text)
response = convo.last.text
bot.reply_to(message, response)
  • Make sure to use a .env file to keep your secret keys and API keys safe.
  • Create a file named .env in the root folder. Add your keys inside .env file as variables.
  • Install python-dotenv package. pip install python-dotenv
  • Then in the main.py file, import them.
import os
from dotenv import load_dotenv, dotenv_values

load_dotenv()

  • You can access your environment varibles using,
os.getenv("API_KEY")
  • Save main.py in VSCode.
  • Open a terminal or command prompt and navigate to the project folder.
  • Run the Python script using the command:
python main.py
  • Verify that the bot is running without any errors.
  • Your code now should look like this
  • Open Telegram and search for the username of your bot.
  • Start a conversation with the bot and send messages to test its functionality.
  • Ensure that the bot responds appropriately to different inputs.
  • If you wish to make your bot accessible to others 24x7 , you’ll need to deploy it to a server.
  • Choose a hosting provider such as Heroku, AWS, or DigitalOcean.
  • Follow their instructions to deploy your Python script and ensure that it runs continuously.

Congratulations! You’ve successfully built a Telegram bot with Python and integrated it with the Gemini AI API. Happy bot building!

Thank you for reading my article! If you enjoyed it and would like to support my work, please consider making a donation. Unfortunately, I’m not in an eligible country to receive payouts from Medium, so your support would mean a lot to me. You can donate through the following link:

Donate Here

Thank you for your generosity!

Building a Telegram Bot with Python and Gemini AI (2024)
Top Articles
akron-canton pickups and trucks for sale - craigslist
Regal Amc Near Me
Health Stream Kaiser
Gasbuddy Costco Hawthorne
Goodwill Bellingham Donation Hours
Cmx Cinemas Gift Card Balance
Craigsist Houston
Florida death row inmates promised more humane treatment after lawsuit settlement
Kimpton Hotels In Charleston Sc
5 Best Vanilla Vodka co*cktails
Magic Seaweed Pleasure Point
Rogers Breece Obituaries
Probasketball Reference
Pwc Transparency Report
Www.jetnet.aa.com
Insidekp.kp.org Myhr Portal
Mighty B Wcostream
Coleman Funeral Home Olive Branch Ms Obituaries
Kagtwt
‘There’s no Planet B’: UNLV first Nevada university to launch climate change plan
Beaver Dam Locations Ark Lost Island
Spicy Bourbon Pumpkin Pie
Wolf Of Wall Street Tamil Dubbed Full Movie
My Eschedule Greatpeople Me
OC IDEAS TO DRAW [80+ IDEAS!] ✍🏼 | Spin the Wheel - Random Picker
Watch ESPN - Stream Live Sports & ESPN Originals
Kayak Parts Amazon
Craigs List Waco
Stanley Steemer Medford Oregon
Amarillos (FRIED SWEET PLANTAINS) Recipe – Taste Of Cochin
Ludwig Nutsac
Dumb Money Showtimes Near Regal Dickson City
Labcorp.leavepro.com
Colorado Pick 3 Lottery
Peoplesgamezgiftexchange House Of Fun Coins
Odawa Hypixel
Presentato il Brugal Maestro Reserva in Italia: l’eccellenza del rum dominicano
New York Sports Club Carmel Hamlet Photos
Cardholder.bhnincentives.com
Star Wars Galaxy Of Heroes Webstore
Craigslist Covington Georgia
Hourly Weather Forecast for Amsterdam, North Holland, Netherlands - The Weather Channel | Weather.com
Kens5 Great Day Sa
Payback Bato
Inter Miami Vs Fc Dallas Total Sportek
Cambridge Assessor Database
Csgo Xray Command
Lesson 2 Homework 4.1 Answer Key
Kirstin Kresse
Busted Newspaper Lynchburg County VA Mugshots
Fired Up | Rotten Tomatoes
Chirp One Medical Seniors
Latest Posts
Article information

Author: Msgr. Benton Quitzon

Last Updated:

Views: 5951

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Msgr. Benton Quitzon

Birthday: 2001-08-13

Address: 96487 Kris Cliff, Teresiafurt, WI 95201

Phone: +9418513585781

Job: Senior Designer

Hobby: Calligraphy, Rowing, Vacation, Geocaching, Web surfing, Electronics, Electronics

Introduction: My name is Msgr. Benton Quitzon, I am a comfortable, charming, thankful, happy, adventurous, handsome, precious person who loves writing and wants to share my knowledge and understanding with you.