Making Your Bot Talks

Making Your Bot Talks

What’s better than having a bot? Having a bot that talks.

In the previous post, we already discuss how to create a Telegram bot with the help of the mighty BotFather. But unfortunately, our bot still does nothing. It will not respond to our commands nor answer to our questions — even the easiest one. It feels like we have a fully functional car, but we can’t drive it anywhere because the key is nowhere around.

Now, we’re going to make our bot talks and able to send us random quotes by writing some code. Basically, we can choose any programming language we love — or even the one we hate the most — to develop the system behind the bot, but I prefer to use Python. It’s easy and simple yet powerful.

My favourite package when it comes to Telegram bot is python-telegram-bot, it’s one of the best we can find out there. We can easily install it using this command:

$ pip install python-telegram-bot

This Python package support both web hook and long polling methods. But personally, I‘d choose the second one most of the time since I don’t have to setup many things like a public IP address or domain and an SSL certificate. When we choose long polling method, all we need is a computer with working internet connection. That’s it!

Now, we’re going to write a simple Python script that will make our bot alive.

from telegram.ext import Updater, CommandHandler
from engine import get_random_quote

# Your bot token (from BotFather)
token = "YOUR TOKEN HERE"

def start(bot, update):
  bot.sendMessage(chat_id=update.message.chat_id, text=("Hi %s. Send me /quote command to get a random quote from "
                              "me!" %
                              update.message.from_user.name))

def quote(bot, update):
  bot.sendMessage(chat_id=update.message.chat_id,
          text=get_random_quote())

def main():
  updater = Updater(token);
  dp = updater.dispatcher

  # Define all the commands that the bot will receive
  dp.add_handler(CommandHandler("start", start))
  dp.add_handler(CommandHandler("quote", quote))

  # Start the bot
  updater.start_polling()
  print("================================")
  print("========= Bot Running ==========")
  print("================================")

  updater.idle()


if __name__ == "__main__":
  main()

Our next step is writing a function that will generate the random quote. This function will be called by our Telegram bot script. For this project, I do not create the quotes by myself (of course, who will?), I simply take it from TextFiles.com instead. Here is the file snippet:

...
%%
 problems are seldom as    bad as they seem at first sight.
                         venessa williams
%%
 there is virtually nothing that has come from molecular biology
 that can be of    any value to human living in the conventional sense
 of what is good, and quite tremendous possibilities of    evil...
                         sir frank macfarlane
%%
 god has infinite time to give us; but how did he give it? in one
 immense treat of lazy milleniums? no, he cut it up into a neat
 succession of new mornings.
                         ralph waldo emerson
%%
...

The %% is the separator symbol between quotes, which means that the text above the separator symbol is different and not related with the text below the separator symbol. So we’ll create a function that will read the text between two %%'s.

from random import randint

quote_file = "quotes.txt"

def get_random_quote():
    start_line  = None
    end_line    = None

    # Open the quote file
    with open(quote_file) as file:
        line = file.readlines()

    # Let's begin with some random line number
    # When '%%' is found, save the line number and break the loop
    for i in range(len(line)-1):
        random_line = (randint(0, len(line)-1))
        if "%%" in line[random_line]:
            start_line = random_line
            break

    # Find the closest next '%%' line number
    for i in range(start_line+1, len(line)):
        if "%%" in line[i]:
            end_line = i
            break

    # We don't need the '%%' to be printed
    start_line += 1

    # Join all the text between these two '%%'
    quote = "".join(line[start_line:end_line])

    return quote

Pretty simple and easy to understand, huh?

Our bot in action

We already have 2 scripts to make our bot talks, but we haven’t tried to run it yet. I wonder how does it look when the scripts are running? To use the script, simply run this command from your terminal:

$ python telegram-bot.py

Here’s the look when the bot is running.

Our bot is alive! Yay!Our bot is alive! Yay!

Finally, we have a minimum yet fully working Telegram bot by ourselves. If you’re interested to make your own, I already put all the files in my Github so you can easily clone and run it by yourself. You can also modify the scripts to fit your need.

I’ll see you soon in the next article with more interesting project. Don’t forget to tell a story about your Telegram bot project, I’m looking forward to it!


This story is imported from my Medium; and the featured image in this post is edited using my Spotify Photo Filter which you can use for free from my Mini Product.