Click here to Skip to main content
15,888,026 members
Articles / Artificial Intelligence / ChatGPT

Setting Up Your Own Telegram Bot with ChatGPT: A Beginner’s Guide

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
30 May 2023CPOL3 min read 7.1K   3  
Discover how to create your own conversational Telegram bot powered by OpenAI's ChatGPT, with this step-by-step guide designed for beginners.
This article serves as a comprehensive guide for beginners looking to create their own Telegram bot powered by OpenAI's ChatGPT. It explains the concept of Telegram bots and ChatGPT, guiding the reader through the process of setting up a Telegram bot, integrating it with ChatGPT, and running it. By the end of the article, the reader will have a functioning, conversational Telegram bot and a foundational understanding of how to further develop and enhance its capabilities.

Image 1

Introduction

Welcome to the fascinating world of software development! This article is especially for beginners who have a keen interest in creating their own Telegram bot using ChatGPT, an advanced language model developed by OpenAI. Whether you're a hobbyist, a budding software developer, or just someone who loves technology, this guide is for you.

Contents

  1. Introduction to Telegram Bots and ChatGPT
  2. Setting Up a Telegram Bot and OpenAI API
  3. Integrating ChatGPT with Your Telegram Bot
  4. Running Your Bot

Introduction to Telegram Bots and ChatGPT

Telegram Messenger is a globally accessible messaging service. In June 2015, Telegram launched a platform to create bots. Telegram bots are essentially programs that respond to messages or commands they receive. They can do a variety of things, from providing weather updates to sending reminders. In our case, we will be building a chatbot, a bot that can carry out a conversation with a user.

To power our chatbot, we'll be using ChatGPT (API version of it). This is a powerful language model trained by OpenAI that can generate human-like text. By integrating ChatGPT with our Telegram bot, we can easily create a bot that can be as powerful as ChatGPT, but in your messenger!

Setting Up a Telegram Bot and OpenAI API

The first step is to create a Telegram bot. We'll need to register our bot with Telegram and get a token we can use to send and receive messages.

Here are the steps:

  1. Open Telegram and search for the "BotFather" bot with verified mark.

    Image 2

  2. Start a chat and type /newbot to create a new bot.
  3. Follow the instructions to name your bot.
  4. Once done, BotFather will give you a token. Keep this token safe.
  5. Go to https://platform.openai.com/apps and choose API option.
  6. Click on Personal and then View API keys.
  7. Press Create new key.

Image 3

Integrating ChatGPT with Your Telegram Bot

Now, it's time to make our bot smart! We will be using the telebot and OpenAI library:

  1. First, install the necessary libraries. Open your terminal and type:
    Shell
    pip install telebot openai
  2. Create a new Python script (I named it bot.py), and paste code:
    Python
    import telebot
    import openai
    
    bot = telebot.TeleBot ('<Your telegram bot token>')
    
    openai.api_key = '<Your openai API token>'
    
    def generate_answer(text):
        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "user", "content": text},
                ]
            )
    
            result = ''
            for choice in response.choices:
                result += choice.message.content
    
        except Exception as e:
            return f"Oops!! Some problems with openAI. Reason: {e}"
    
        return result
    
    
    @bot.message_handler(content_types=['text'])
    def send_text(message):
        answer = generate_answer(message.text)
        bot.send_message(message.chat.id, answer)
    
    bot.polling()

We have defined a function called generate_answer. This function takes text that our bot receives during conversation and makes an API call to OpenAI. We are using gpt-3.5-turbo to generate a response. You have a limit of 3 requests per minute. If you want to remove it, buy a premium subscription. Keep in mind, if you are using premium ChatGPT sub, you cannot use it in API, because it is an independent product and you need to buy an extra sub for it).

For I/O message, we are using a decorator @bot.message_handler from telebot lib. We have defined a text content and defied a function, that relieves message from telegram chat, generates a response from OpenAI API and returns answers to the chat using bot.send_message. To execute the bot, we are using bot.polling() command.

Running Your Bot

You can now run your bot! In your terminal, navigate to the directory containing your Python script and run:

Python
python <your_script>.py

Your bot is now live! You can talk to it on Telegram, and it will respond using the power of ChatGPT.

Conclusion

Remember, this is a very basic example. There's a lot more you can do with Telegram bots and ChatGPT. You can add more commands, use different engines from OpenAI, and much more. So keep exploring and experimenting!

Happy coding!

History

  • 30th May, 2023: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader Re:start
Kazakstan Kazakstan
• 5+ YoE as an engineer. Last 3 years as a backend developer using Python, TS, and other linked technologies;
• In one of my previous companies (Halyk bank), I worked my way up from a junior developer to a senior developer in a very short time (half a year), got the highest scores as an employee in my department;
• Successfully designed and developed an end-to-end solution from scratch in a robotics startup as a Team Lead & Tech Lead member and managed a team of 7;
• Got a “Best Developer Project Kazakhstan” prize in Tekla BIM Awards International Project Competition;
• Currently, I’m a backend developer (TS + NodeJS) in Re:start Financial;

Comments and Discussions

 
-- There are no messages in this forum --