DEV Community

Cover image for 8 ChatGPT-Bots Every Newbie Can Develop
Igor Diev
Igor Diev

Posted on • Edited on

8 ChatGPT-Bots Every Newbie Can Develop

Hello everyone! My name is Igor and I'm here to give you an easy tutorial for coding on Python from total scratch.

I want you to stay motivated while learning, that's why I give you a reachable, but ambitios goal 💪 of making your own ChatGPT bot. You can choose from 8 different bot ideas: if one of them corresponds with you, it will be easier and more pleasurable for you to pass the tutorial.

If you are a programmer, feel free to skip the first steps and move forward to ideas part. You can also send this article to your noncoding friends (or even your Grandma), maybe they will understand your profession better and try to build their own first script.

Tutorial structure:

  1. Google Colab opening, 'Hello world' script
  2. OpenAI Token generation
  3. First ChatGPT script
  4. Telegram-bot and 'start' function creation
  5. Enabling ChatGPT in Telegram, 'make_reply' function creation
  6. 8 useful ChatGPT bots ideas implementation

Each idea description consists of:

  • Code for 'make_reply' function
  • Code for 'start' function
  • Way of implementation
  • Way of enhancement

I hope you will enjoy🤟

Google colab opening. 'Hello world' script

I want to make this guide as simple as possible, so we'll use Google Colab for coding, as it works right inside your browser and there is no need to install any additional software.

Google Colab New notebook creation

  • Compose a name for your script, like this: Dev.to Simple ChatGPT Bot

Google Colab New notebook naming

  • Put these code print('Hello, world!') into the line next to the play button (a triangle in a circle). 'Print' is a Python function, which outputs content, placed inside the brackets. I want to print 'Hello, world' sentence.

Python Print function call

Let's press 'Play button' ('Run cell') and see what will happen:

Python Print function output

You see, the phraze 'Hello, world' is printed and we can congratulate ourselves as we've passed the first stage of the tutorial 🙌 You are great!

OpenAI Token generation

Now we need to get an OpenAI token.

The algorithm:

OpenAI Create new API key button

  • Click 'Create secret key'

OpenAI Create new secret key button

  • Click 'Copy button'

OpenAI new API key copy button

✔️ Congrats! You've got your secret key. Save this key to some text document stored locally on your computer.

First ChatGPT script

Let's return to the 'Google Colab' and create a file 'Settings.py'. To do this, click on the three-dots button:

Three dots butto in Google Colab

And choose 'New file'

Google Colab new file creation

Name the file 'Settings.py'

Google Colab new file naming

Paste your OpenAI API Key (token) here:

OpenAI API Key proper storage

⚠️ I'm hiding my Key on the screenshot, because it is a secret information. Please, note, that you shouldn't show your API Keys to anyone, shouldn't put it into the main script, post it publicly, etc.

Now delete all the previos code and paste this line:
!pip install openai.

pip install openai call in Google Colab

This code is intalling Openai Module so that we can use OpenAI API. To run the process of installation, press the 'Play' button and wait untill the line 'Successfully installed' appears.

OpenAI Modules installation on Python using pip

Now press the '+ Code' button to add another line of code. It gives us an opportunity to run the 'pip-install' code and the main code separately.

Google Colab new code section

Now put the following lines into our new code section:

import settings
import openai

openai.api_key = settings.openai_token
Enter fullscreen mode Exit fullscreen mode

import settings — we are connecting our file, where we store our key, to the main script.
import openai — we are importing OpenAI Modules (that we've installed previously).
openai.api_key — it is an expression, which tells OpenAI our secret API Key to help it authorize our connection to API.
settings.openai_token — here we call openai_token variable from settings.py file.

Here's how it should look like at the moment:

Google Colab openai import

Let's now make a function using Python's 'def' expression: def func_name(argument1, argument2):.

We are creating a 'make_response' function, which fulfills a request to OpenAI.

Note, that every offset ➡️ of every line is crucially important

def make_response():
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": "Say hello to dev.to users"}
        ]
    )
    return response.choices[0].message.content
Enter fullscreen mode Exit fullscreen mode

Explanation:
def make_response(): — creating a function.
response = openai.ChatCompletion.create( — we put results, which OpenAI returns, to the 'response' instance.
model="gpt-3.5-turbo", — AI model, which we want to use.
messages=[{"role": "user", "content": "Say hello to dev.to users"}] — we tell ChatGPT, that we are in the user role and that we want it to reply to a sentence, written after the word 'content'.
return response.choices[0].message.content — we return only the text from OpenAI. Each response includes many fields like id, model name, etc, but we need only text, that's why we write choices[0].message.content.

Python function creation, ChatGPT API call creation

Let's call this function and print the result of print(make_response()).

Let's press the 'Play' button and see what's happening:

OpenAI API call output in Python

💡Congrats! We've made our first simple script, that uses Open AI (GPT) API.

Telegram-bot creation

To create a Telegram-bot, we should follow these easy steps:

Telegram new bot creation

  • Create a name for you bot (this name appears on the left panel of Telegram, as other usernames).
  • Enter a unique address for you bot, which will act as an URL in Telegram.
  • You will see a message from Botfather with a token. Like that:

Telegram botfather token generation

  • Copy-paste token to your 'settings.py'.

Telegram Token proper storage

Great! Now we install Telebot Module to operatw with Telegram API. To do this, create another Code line with the button 'Code' and paste !pip install telebot.

Telebot Modules installation on Python using pip

Press 'Play' to install the module. Make sure, that it's succesfully installed.

Telegram Telebot Module installation progress

Now import our new module to our code with 'import telebot':

Telebot Module import in Python script

Now put bot = telebot.TeleBot(settings.tg_token) line to connect our Python script to our Telegram-bot through the token we've been given earlier.

Telebot instance creation on Python, Telegram bot initialization

'/start' command

Let's now create a function, that will run every time the command '/start' in Telegram is clicked.

Put this code right after 'make_response' function:

@bot.message_handler(commands = ["start"])
def start(message):
  bot.send_message(message.chat.id, text="Hello! I'm a clever bot doing " 
                                         "clever tasks")
Enter fullscreen mode Exit fullscreen mode

Explanation:
@bot.message_handler(commands = ["start"]) — It is a function, that says, what function should be called when command '/start' is clicked.
def start(message): — It is a function, that's called, when '/start' command is clicked.
bot.send_message(message.chat.id, text="..." — we call the 'send_message' method of Telegram for our bot. The arguments of this method are id of the user and the text, which we send to the user. The code 'message.chat.id' is used, because several users can connect to our bot at the same time. Our code needs to know chat id of this very user, who pressed the command. Chat ID is taken from the object 'message', that is passed to our function '/start'. Each Chat ID is unique and lets us identify the user.

At the bottom line of our code we put bot.polling() expression. 'Polling' method is used to make our code work permanently. If we run our code without this line, it will be finished immediately, the code will not understand, that we want our bot to wait for our commands.

The code now should look like this:

import settings
import openai
import telebot

openai.api_key = settings.openai_token
bot = telebot.TeleBot(settings.tg_token)

def make_response():
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": "Say hello to dev.to users"}
        ]
    )
    return response.choices[0].message.content

@bot.message_handler(commands = ["start"])
def start(message):
  bot.send_message(message.chat.id, text="Hello! I'm a clever bot, doing " 
                                         "clever tasks")

print(make_response())
bot.polling()
Enter fullscreen mode Exit fullscreen mode

Let's run it. If everything's correct, there'll be no mistakes in the command line of our Google Colab. If there are mistakes, click 'Stack overflow' button to try to find the solution. If all is ok, the 'Play' button should be substituted with the 'Stop' button (a square inside a circle).

The running Google Colab Python script with polling

Now go to our Telegram bot and press the '/start' command. If you forgot your Telegram bot address, you can return to Botfather and run '/mybots' command.

Here's how the response should look like.

ChatGPT bot in Telegram response

🙌 Hooray! It works! We've made our first Telegram bot. Let's transform it to a ChatGPT-bot.

Enabling ChatGPT in Telegram, 'make_reply' function

Let's create another message handler:
@bot.message_handler(content_types = ["text"]) and a function def text(message):. This function will run when someone sends some text to a bot (eventually, it will not run only if '/start' command is sent).

Now let's link our ChatGPT 'make_response' function to our bot.

To do this, let's put this funtion call to 'send_message' argument.

Telegram Bot send_message text

It will look like that:

Telegram bot's start and text functions

If we type any text to our Telegram bot, it will return basic answer from 'make_response' function, greeting dev.to users.

ChatGPT reply via Telegram bot

So, we've made our first ChatGPT bot, that's cool. But it doesn't operate our inputed text, let's use it.

Do do this, let's send text from a user to the 'make_respose' function. We are taking 'message.text' as an argument. As you remember, 'message' itself contains many different things, but we need only text.

Telegram Telebot API message.text usage

Now let's modify the 'make_response' function.

First, we are adding an argument 'text' to our function:
def make_response(text):

Now let's add a 'role' to our ChatGPT request, it's made by this line:
{"role": "system", "content": "You are a helful assistant"},

And let's send 'text' from the user to ChatGPT:
{"role": "user", "content": text}

You see, the word 'text' here is a variable, that's been sent as an argument to the function.

Our code should look like this:

import settings
import openai
import telebot

openai.api_key = settings.openai_token
bot = telebot.TeleBot(settings.tg_token)

def make_response(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a helful assistant"},
            {"role": "user", "content": text}
        ]
    )
    return response.choices[0].message.content

@bot.message_handler(commands = ["start"])
def start(message):
  bot.send_message(message.chat.id, text="Hello! I'm a clever bot doing " 
                                         "clever tasks")

@bot.message_handler(content_types = ["text"])
def text(message): 
  bot.send_message(message.chat.id, text=make_response(message.text))

bot.polling()
Enter fullscreen mode Exit fullscreen mode

If we run our script and talk to our bot, we'll see, that it operates with our inputs.

Talking to ChatGPT through Telegram

At this point we've made a simple ChatGPT-bot 💪 Let's learn, how to modify it to fulfill certain tasks.

1. Fairy-tales maker

Lets' modify 'make_response' function:

def make_response(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            { "role": "system", "content": "You are a great writer " 
              "of therapeutic tales. You compose "
              "short therapeutic instructive stories with dynamic plots for kids"},
            { "role": "user", "content": "Compose an interesting tale in 4"
              " paragraphs that I can read to my kids, using given kids names, "
              "pecularities and given problem: " + text}
        ]
    )
    return response.choices[0].message.content
Enter fullscreen mode Exit fullscreen mode

If we press 'Play' button, return to our bot and ask him to make a tale, we can see the result. Frankly speaking, it's even better, than I've expected:

Fairy-tales maker ChatGPT bot

If we want someone else to interact with our bot, we must put the rules of usage to our '/start' command, like this:

@bot.message_handler(commands = ["start"])
def start(message):
  bot.send_message(message.chat.id, text= "Hello! I can create a therapeutic "
                                          "tale for your kid(s)! Send me kid(s)' " 
                                          "name(s), pecularities and a problem "
                                          " you want to solve")
Enter fullscreen mode Exit fullscreen mode

That's a new output of the '/start' command:
Telegram start command handler

Way of implementation:
One can use it to help kids cope with their problems. Kids can also play with this bot, composing funny tales about themselves or their friends.

Way of enhancement:
You can give GPT examples of tales and it will try to fit it to your format. After advancing your programming skills you can add Database to remember previous tales and to make them exist in one universe of tales for given kids.

2. RoboDoctor

It helps with prediagnosis.

'make_response' function:

def make_response(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            { "role": "system", "content": "You are a great doctor " 
              "like House. You are a diagnostician. You can give a "
              "diagnosis"},
            { "role": "user", "content": "Read my anamnesis and tell me"
              " what to do with this. Is it a desease? What should I do?" + text}
        ]
    )
    return response.choices[0].message.content
Enter fullscreen mode Exit fullscreen mode

'start' function

@bot.message_handler(commands = ["start"])
def start(message):
  bot.send_message(message.chat.id, text= "Hello! I am an AI-diagnostician. I " 
                                          "can help you with basic diagnosis "
                                          "before you go to the doctor. Describe" 
                                          " your problem, please ")
Enter fullscreen mode Exit fullscreen mode

The result:

ChatGPT doctor Telegram bot

The way of implementation:
Some medical centers already use ChatGPT for prediagnostics. Who knows. maybe you can use this idea to build your startup MVP?

The way of enhancement:
If you have some experience at coding, you can add, for example, additional parameters and dialog trees, asking age, gender, other useful information. But don't forget to comply with all the regulatory rules and don't store sensitive data without proper permissions.

3. AI-Lawyer

It helps to comprehend legal texts.

'make_response' function:

def make_response(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            { "role": "system", "content": "You are a lawyer " 
              "you can explain documents in simple terms "
              "diagnosis"},
            { "role": "user", "content": "Can you explain this document in up "
              "to 4 sentences? Simple words, as for 12-year old \т" + text}
        ]
    )
    return response.choices[0].message.content
Enter fullscreen mode Exit fullscreen mode

'start' function

@bot.message_handler(commands = ["start"])
def start(message):
  bot.send_message(message.chat.id, text= "Hello! I am an AI legal assitant. I " 
                                          "can explain any document in simple"
                                          " words. Send me text of your contract"
                                          " or policy ")
Enter fullscreen mode Exit fullscreen mode

The result:

AI-Lawyer ChatGPT bot

AI-Lawyer ChatGPT Telegram bot

The way of implementation:
Managers can use it to save their time on understanding the core idea of a contact.

The way of enhancement:

  1. Telegram cannot process a huge document in one message, so you can enhance the code by adding long messages handler.
  2. Another idea — to ask GPT to compose structured synopsis for each of the paragraphs.
  3. You also can modify this bot to make it emphasize the most important line of the contract. Or the lines, that can be unfavorable for the user.

4. Privacy policy maker

It is a similar idea to the previos one, but it works in opposite direction.

'make_response' function:

def make_response(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            { "role": "system", "content": "You are a privacy policy specialist. " 
              "You can compose a great Privacy Policy for given company "},
            { "role": "user", "content": "Compose a Privacy Policy  "
              "for given personal data usage, for given purpose, for given company"
               + text}
        ]
    )
    return response.choices[0].message.content
Enter fullscreen mode Exit fullscreen mode

'start' function

@bot.message_handler(commands = ["start"])
def start(message):
  bot.send_message(message.chat.id, text= "Hi! I am an AI privacy policy maker! " 
                                          "Send me your company name, types "
                                          "of personal data - e.g. email, phone," 
                                          " name and the purpose of usage e.g. to"
                                          " send personal offers by email and "
                                          "SMS. I will compose a privacy policy "
                                          "for you.")
Enter fullscreen mode Exit fullscreen mode

The result:
Privacy policy maker ChatGPT bot

The way of implementation:
You can save some money if you are opening your startup and you don't have enough budget to make a professional Policy. But don't forget to consult with a real lawyer in future.

The way of enhancement:
You can teach your ChatGPT bot to compose other types of legal docs.

5. Official letters composer

This bot can write a whole letter having just a brief synopsis.

'make_response' function:

def make_response(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            { "role": "system", "content": "You are a great letters writer. " 
              "You can compose the whole letter in perfect style having "
              "just a sender name, reciever name and a single phraze"},
            { "role": "user", "content": "I give you sender, reciever  "
              "and an idea for a letter. You should compose a letter with "
              "header, suject, goodbye at the end." + text}
        ]
    )
    return response.choices[0].message.content
Enter fullscreen mode Exit fullscreen mode

'start' function

@bot.message_handler(commands = ["start"])
def start(message):
  bot.send_message(message.chat.id, text= "I can compose a letter for you. "
                                          "Send me your name, the "
                                          "reciever's name and the main idea "
                                          "of a letter")
Enter fullscreen mode Exit fullscreen mode

The result:
ChatGPT bot for composing letters

The way of implementation:
You can make a draft for a letter.

The way of enhancement:

  1. We can add an intention and type of the letter to our prompt (negotiations, deal proposal, etc).
  2. We can easily make another bot, who can retell someone's letter in brief. Just to remake a meme:

The comics on ChatGPT

6. Psychologist

Let's make a Psychological bot with a little bit more complex logic. We will compose 2 functions, one will be enabled, when the text 'cbt' will be written and the second will work for 'pa' line.

'make_response' function:

def make_response_cbt(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            { "role": "system", "content": "You are a great psychologist CBT. " 
              "You give a great consultation in CBT style"},
            { "role": "user", "content": "Please, help me with a short "
              "useful CBT algorythm on the problem:" + text}
        ]
    )
    return response.choices[0].message.content

def make_response_pa(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            { "role": "system", "content": "You are a great Psychoanalyst. " 
              "You give a great consultation in Psychoanalyst style"},
            { "role": "user", "content": "Please, help me with a short "
              "useful Psychoanalitical algorythm on the problem:" + text}
        ]
    )
    return response.choices[0].message.content
Enter fullscreen mode Exit fullscreen mode

'start' function

@bot.message_handler(commands = ["start"])
def start(message):
  bot.send_message(message.chat.id, text= "I am a psychologist. Send me your "
                                          "problem and send me the key phraze "
                                          "'CBT' for cognitive behavioral therapy "
                                          "or 'PA' for Psychoanalysis.")
Enter fullscreen mode Exit fullscreen mode

'text' function (with if operator):

@bot.message_handler(content_types = ["text"])
def text(message): 
  if (message.text.find("cbt")>0):
    bot.send_message(message.chat.id, text=make_response_cbt(message.text))
  elif (message.text.find("pa")>0):
    bot.send_message(message.chat.id, text=make_response_pa(message.text))
  else:
    bot.send_message(message.chat.id, text=make_response_pa(message.text))
Enter fullscreen mode Exit fullscreen mode

The result:
Psychologist ChatGPT bot

Psychologist ChatGPT bot in Telegram

The way of implementation:
You can use it to make a basic self-help consultation.

The way of enhancement:
You can add more different techniques.

Important tip:
Every time you return to your code after a break, you should install telebot and openai Modules again.

Installing telebot and openai modules on Python

7. Litеrary editor

This bot will help you or your friends with text enhancement. You give it a drafty text and the bot transform it to The New York Times style masterpiece.

'make_response' function:

def make_response(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            { "role": "system", "content": "You are an editor of The New York Times. " 
              "You can make every phraze grammatically correct, plaind, laconic and strong."},
            { "role": "user", "content": "Please, enhance my phraze: " + text}
        ]
    )
    return response.choices[0].message.content
Enter fullscreen mode Exit fullscreen mode

'start' function:

@bot.message_handler(commands = ["start"])
def start(message):
  bot.send_message(message.chat.id, text= "I am an editor. Send me your "
                                          "phraze and I will enhance it.")
Enter fullscreen mode Exit fullscreen mode

The result:

Litеrary editor ChatGPT bot

The way of implementation:
It can help bloggers and journalists to enhance certain phrazes and speed up their work.

The way of enhancement:
You can ask you robo-editor to work in different styles.

8. Dialogs analyzer

This is a psychologist and an arbiter, who can give an objective overview of your dialogs.

'make_response' function:

def make_response(text):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            { "role": "system", "content": "You are a psychologist. You can analyze " 
              "dialogs and give conclusions, what each person supposedly felt, what they "
              "realy wanted to say. Who used arguments and who was trying to manioulate"},
            { "role": "user", "content": "Please, analyze the dialog, figure out, if "
              "one of the parties uses passive agression or manipulation. Give hypothesis  "
              "on the reasons for the certain words being said:"  + text}
        ]
    )
    return response.choices[0].message.content
Enter fullscreen mode Exit fullscreen mode

'start' function:

@bot.message_handler(commands = ["start"])
def start(message):
  bot.send_message(message.chat.id, text= "I am an psychologist. I can help you "
                                          "to figure out how to communicate better. "
                                          "Give me your dialog and I will analyze it")
Enter fullscreen mode Exit fullscreen mode

The result:
Dialogs analyzer ChatGPT bot

The way of implementation:
You can use it to analyze your dialogs with your friends and relatives and to understand them better.

The way of enhancement:
We are using a prompt about manipulation and passive aggresion. You can emphisize other aspects and the bot will stress other accents.


The article was written by a human being without using LLMs for text processing :)

Feel free to ask questions. Good luck!

Top comments (3)

Collapse
 
ayudascolombia profile image
Yo Emprendo Ayudas Colombia

Random Joke Bot - Create a bot that tells random jokes to users in the chat.

Weather Bot - Develop a bot that provides weather updates for any location.

Quote Bot - Create a bot that shares inspirational quotes with users in the chat.

Trivia Bot - Develop a bot that quizzes users on various topics and provides feedback on their answers.

Reminder Bot - Create a bot that helps users set reminders for important events or tasks.

Translation Bot - Develop a bot that translates messages into different languages for users who don't speak the same language.

News Bot - Create a bot that delivers breaking news or headlines to users in the chat.

Personal Assistant Bot - Develop a bot that helps users with various tasks such as scheduling meetings, making reservations and more.

Collapse
 
kvapt profile image
Igor Diev

Nice ideas!

Collapse
 
dio77 profile image
Ivan Pavlov

Thank you. I'll try to build one