Build a Telegram Bot using Co:here and Python

Build a Telegram Bot using Co:here and Python

Introduction

I vividly remember when I first heard the word NLP back in high school. At that moment, I didn't even know the distinctions between different areas of artificial intelligence. Fast forward to today, natural language processing has reached everywhere and more people are becoming aware of its immense potential. In simple words, natural language processing is the ability of a computer to understand human language. With so much going on, companies want to assess certain information from large data. However, this is just one way of using it. Let me put it like this, you want to write a program that can translate a language for you. The old way of programming will make this process complex complicated. So to make this happen you will use NLP algorithms and follow certain steps the first might be breaking down the chunk of words to a single word and analyzing the relationship between them. However, NLP is not just for machine translation it can also be used for tasks such as automatic summarization, text classification, and sentiment analysis.

Today we are going to use the mere concept of NLP to make a Telegram bot using python. For these purposes, we are going to use Co:here. I first used Co:here in a hackathon and loved it right away as it simplifies so many things. You can use Co:here for cases that need classification, semantic search, paraphrasing, summarization, and, content generation. So let's dive in.

PREREQUISITES

If you have some experience with python and telegram bots, it will not be hard for you. For the project though, you need to have Python, Telegram, and Co:here package.

Requirements

  • For a code editor, I'm going to use VSCode but you can have your choice.
  • Python Installed (For some unforeseen reasons I recommend using python version 3.5+)
  • Basic knowledge of Python.
  • Telegram account to create the bot and access the HTTP API
  • A Cohere API key. After you create a Cohere account, navigate to “Dashboard” and click Create API Key.

Let's go

Step 1: create the bot

We start by creating our bot. You could use different approaches, for now, we are going to use BotFather. Go to BotFather and type /start

Screenshot 2022-08-05 113446.jpg To create our bot we are going to use the following commands:

  • /newbot - create a new bot, make sure to add bot at the end of the name. I'll name it generate_jobs1_bot.
  • /setname - change a bot's name
  • /setdescription - change bot description You can also check the documentation if want to learn and explore more.

After creating the bot, you will have a token

Screenshot 2022-08-05 171223.jpg You can set the bot description, and profile picture, and customize it as you want.

Step 2: write the python code for the bot

Now that we have our bot created, let's write our code. First, install the module we need to create the bot using pip install python-telegram-bot. I assume you already have installed python at this point.

from telegram.ext.updater import Updater
from telegram.update import Update
from telegram.ext.callbackcontext import CallbackContext
from telegram.ext.commandhandler import CommandHandler
from telegram.ext.messagehandler import MessageHandler
from telegram.ext.filters import Filters

updater = Updater("your telegram access token, the one you got from BotFather",
                use_context=True)


def start(update: Update, context: CallbackContext):
    update.message.reply_text(
        "Welcome to Quote by Cohere.Please write\
        /help to see the commands available.")

def help(update: Update, context: CallbackContext):
    update.message.reply_text("""Available Commands :-
    /generate - To generate quotes
    /about - This bot is made using Cohere
    """)

def generated(update: Update, context: CallbackContext):
    update.message.reply_text(g) 

def about1(update: Update, context: CallbackContext):
    update.message.reply_text("Hello I'm Henok check out my github github.com/HenokB")     


updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('generate', generated))
updater.dispatcher.add_handler(CommandHandler('help', help))
updater.dispatcher.add_handler(CommandHandler('about', about1))

updater.start_polling()

As you can see the generated function is where we are going to put the new quotes. The help function will help users to list all the potential commands that the bot uses.

Step 3 start playing on Cohere

First, go to the Cohere dashboard and create an API key. Make sure to keep your API Key safe and secure.

Now, let's go to the Cohere playground prompt Cohere to generate the quotes based on famous people's names. You can delete the pre-loaded prompt in the window on the playground and change it according to your use. Try clicking Generate to see how Cohere's Generate endpoint works. Cohere's large language models read the prompt and decide which next tokens to return are the most appropriate.

Populate the models with a few examples of outputs we are looking for. Here are a few examples:

Screenshot 2022-08-05 172322.jpg

"--" is called stop sequence and I’ve separated the questions using it. The stop sequence is a completely arbitrary character, though it's recommended a character you don't expect to see in your generations because the model will stop generating text after it returns the stop character.

If you want greater control over the output, try playing with the frequency penalty, presence penalty temperature, top-k, and top-p values.

Now we can click generate and It'll give us the output. Here is an example below

Screenshot 2022-08-05 174029.jpg

Step 4: Embed Cohere to the bot

To use Cohere in your python code install it using pip install cohere. We can now integrate Cohere into your app. Go to the Cohere playground and click export. You will have the chance to export it using different programming languages and for now, click python.

Screenshot 2022-08-05 172525.jpg

Copy the following code and paste it above the previous python code we wrote. Make sure to replace the last print statement with the following code.

quotes=str('Quote of the day: {}'.format(response.generations[0].text))

After that, update the existing generated function as follows.

def generated(update: Update, context: CallbackContext):
    update.message.reply_text(generated_jobs)

🎉Yay, we are almost done now. The final step is deploying the following code to a server. If you just want to see it you can put the code on Google Colab and test it otherwise you can use Google Cloud, Heroku, or others to deploy the code.

I hope it helps and I'll be writing more so make sure to follow me.

import cohere
co = cohere.Client('your API key from Cohere')
response = co.generate(
  model='xlarge',
  prompt='This program will generate quotes from famous people given names.\n--\nName: Jim Carrey\nQuote: Behind every great man is a woman rolling her eyes.\n--\nName: Bertrand Russell\nQuote: To be without some of the things you want is an indispensable part of happiness.\n--\nName: J. Pierpont Morgan\nQuote: A man always has two reasons for doing anything—a good reason and the real reason.\n--\n',   max_tokens=50,
  temperature=0.9,
  k=0,
  p=0.75,
  frequency_penalty=0,
  presence_penalty=0,
  stop_sequences=["--"],
  return_likelihoods='NONE')
g=str('Quote of the day: {}'.format(response.generations[0].text))
print(g)


from telegram.ext.updater import Updater
from telegram.update import Update
from telegram.ext.callbackcontext import CallbackContext
from telegram.ext.commandhandler import CommandHandler
from telegram.ext.messagehandler import MessageHandler
from telegram.ext.filters import Filters

updater = Updater("telegram bot access token from BotFather",
                use_context=True)


def start(update: Update, context: CallbackContext):
    update.message.reply_text(
        "Welcome to Quote by Cohere.Please write\
        /help to see the commands available.")

def help(update: Update, context: CallbackContext):
    update.message.reply_text("""Available Commands :-
    /generate - To generate quotes
    /about - This bot is made using Cohere
    """)

def generated(update: Update, context: CallbackContext):
    update.message.reply_text(g) 

def about1(update: Update, context: CallbackContext):
    update.message.reply_text("Hello I'm Henok check out my github github.com/HenokB")     


updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('generate', generated))
updater.dispatcher.add_handler(CommandHandler('help', help))
updater.dispatcher.add_handler(CommandHandler('about', about1))

updater.start_polling()