In this article, you will learn how to build a Telegram chatbot that will tell you your horoscope using the Python programming language. The article is structured into the following sections:
- How to Get Your Bot Token
- How to Set Up Your Coding Environment
- How to Create Your First Bot
- How to Code the Horoscope Bot
How to Get Your Bot Token
To set up a new bot, you will need to talk to BotFather on the Telegram platform. BotFather is not a person, but a bot that manages all Telegram bots. Follow these steps to get your bot token:
- Search for @botfather in Telegram.
- Start a conversation with BotFather by clicking on the Start button.
- Type
/newbot
and follow the prompts to set up a new bot. The BotFather will give you a token that you will use to authenticate your bot and grant it access to the Telegram API.
Note: Make sure to store the token securely. Anyone with your token access can easily manipulate your bot.
How to Set Up Your Coding Environment
Let’s set up the coding environment. We’ll be using the pyTelegramBotAPI
library to create a Telegram bot. Install the library using pip:
pip install pyTelegramBotAPI
Next, create a .env
file to store your token as follows:
export BOT_TOKEN=your-bot-token-here
After that, run the source .env
command to read the environment variables from the .env
file.
How to Create Your First Bot
The TeleBot
class in the pyTelegramBotAPI
library provides various methods for listening to incoming messages and sending messages. Start by creating a new bot.py
file and pasting the following code:
“`python
import os
import telebot
BOT_TOKEN = os.environ.get(‘BOT_TOKEN’)
bot = telebot.TeleBot(BOT_TOKEN)
“`
Next, add message handlers that handle various commands and messages. For example, you can create a message handler that handles the /start
and /hello
commands as follows:
python
@bot.message_handler(commands=['start', 'hello'])
def send_welcome(message):
bot.reply_to(message, "Howdy, how are you doing?")
Now, add another handler that echoes all incoming text messages back to the sender:
python
@bot.message_handler(func=lambda msg: True)
def echo_all(message):
bot.reply_to(message, message.text)
Finally, add the following line to the end of the bot.py
file to launch the bot:
python
bot.infinity_polling()
You can now run the Python file and test the bot on the Telegram platform.
How to Code the Horoscope Bot
The main functionality of the Horoscope bot involves fetching horoscope data from an API and responding with the horoscope for a specific day. The bot will first ask for the user’s zodiac sign and then the day.
How to Fetch the Horoscope Data
Create a utility function to fetch the horoscope data for a particular day:
“`python
import requests
def get_daily_horoscope(sign: str, day: str) -> dict:
url = “https://horoscope-app-api.vercel.app/api/v1/get-horoscope/daily”
params = {“sign”: sign, “day”: day}
response = requests.get(url, params)
return response.json()
“`
How to Add a Message Handler
Now, create a message handler in the bot that asks for the user’s zodiac sign:
python
@bot.message_handler(commands=['horoscope'])
def sign_handler(message):
text = "What's your zodiac sign? Choose one: *Aries*, *Taurus*, *Gemini*, *Cancer,* *Leo*, *Virgo*, *Libra*, *Scorpio*, *Sagittarius*, *Capricorn*, *Aquarius*, and *Pisces*."
sent_msg = bot.send_message(message.chat.id, text, parse_mode="Markdown")
bot.register_next_step_handler(sent_msg, day_handler)
Next, define the day_handler()
function that accepts the message:
python
def day_handler(message):
sign = message.text
text = "What day do you want to know? Choose one: *TODAY*, *TOMORROW*, *YESTERDAY*, or a date in format YYYY-MM-DD."
sent_msg = bot.send_message(message.chat.id, text, parse_mode="Markdown")
bot.register_next_step_handler(sent_msg, fetch_horoscope, sign.capitalize())
Finally, define the fetch_horoscope()
function that accepts the message and the sign:
python
def fetch_horoscope(message, sign):
day = message.text
horoscope = get_daily_horoscope(sign, day)
data = horoscope["data"]
horoscope_message = f'*Horoscope:* {data["horoscope_data"]}\n*Sign:* {sign}\n*Day:* {data["date"]}'
bot.send_message(message.chat.id, "Here's your horoscope!")
bot.send_message(message.chat.id, horoscope_message, parse_mode="Markdown")
You can now run the Python file and test the bot’s horoscope functionality on the Telegram platform.
Recommended Next Steps
Consider deploying the bot on platforms like Heroku or Render to make it always available. You can also explore the Telegram APIs to add more functionalities to the bot.