How to Install СhatGPT in Telegram for Free and Always Active

Matros
Jul 07, 2024By Matros

Introduction


In this guide, we will walk you through the process of setting up a ChatGPT bot in Telegram that works 24/7 and is completely free. We'll be using Python, the Aiogram library, and other essential tools. Follow the steps below to get your ChatGPT bot up and running.

a green square with a white knot on it

Prerequisites
Before starting, make sure you have the following:

Python installed on your computer.
A Telegram account.
Basic knowledge of Python programming.
Step-by-Step Guide
Install Required Libraries

Open your terminal and run the following commands to install the necessary libraries:

pip install aiogram g4f speechrecognition pydub

Create a Telegram Bot

Open Telegram and search for the @BotFather bot.
Start a chat with BotFather and create a new bot by using the command /newbot.
Follow the instructions to get your bot's API token. Save this token for later use.
Set Up the Python Script

Create a new Python file (e.g., chatgpt_bot.py) and paste the following code into it:

import logging
import asyncio
from aiogram import Bot, Dispatcher, types, executor
import g4f
import speech_recognition as sr
from pydub import AudioSegment
import html

# Enable logging
logging.basicConfig(level=logging.INFO)

# Bot initialization
API_TOKEN = 'your_api_token'  # Replace 'your_api_token' with your actual Telegram bot API token
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)

# Dictionary for storing conversation history
conversation_history = {}

# Chat ID that will be allowed (replace with your chat ID)
allowed_chat_id = your_chat_id  # Replace 'your_chat_id' with your actual Telegram chat ID

# Function for trimming conversation history
def trim_history(history, max_length=4096):
    current_length = sum(len(message["content"]) for message in history)
    while history and current_length > max_length:
        removed_message = history.pop(0)
        current_length -= len(removed_message["content"])
    return history

async def handle_text_message(message: types.Message, text: str):
    user_id = message.from_user.id
    if user_id != allowed_chat_id:
        print(f"Access denied for user with ID {user_id}")
        return

    conversation_history.setdefault(user_id, []).append({"role": "user", "content": text})
    conversation_history[user_id] = trim_history(conversation_history[user_id])

    chat_history = conversation_history[user_id]

    try:
        # Send the "print" effect
        await bot.send_chat_action(message.chat.id, 'typing')
        await asyncio.sleep(0.7)  # Simulate a delay for the "printing" effect

        response = await g4f.ChatCompletion.create_async(
            model=g4f.models.default,
            messages=chat_history,
            provider=g4f.Provider.Bing,
        )
        chat_gpt_response = response
    except Exception as e:
        print(f"{g4f.Provider.Bing.__name__}:", e)
        chat_gpt_response = "Sorry, there was an error."

    conversation_history[user_id].append({"role": "assistant", "content": chat_gpt_response})
    print(conversation_history)
    length = sum(len(message["content"]) for message in conversation_history[user_id])
    print(length)

    if "```" in chat_gpt_response:
        # If the answer contains three backquotes, we consider it a code and send it with highlighting
        await message.answer(f"<code><pre style='white-space: pre-wrap; font-family: monospace;'>{html.escape(chat_gpt_response)}</pre></code>", parse_mode=types.ParseMode.HTML)
    else:
        # Otherwise, send the text as a regular message
        await message.answer(chat_gpt_response)

# Handler for the /start command
@dp.message_handler(commands=['start'])
async def handle_start(message: types.Message):
    user_id = message.from_user.id
    await message.answer("Hi! I'm a Gpt-4 bot. Send me a text or audio message to start a conversation.")

# Handler for each new message (including text and audio messages)
@dp.message_handler(content_types=['voice', 'text'])
async def handle_messages(message: types.Message):
    if message.content_type == 'voice':
        # Process audio message
        file_info = await bot.get_file(message.voice.file_id)
        file = await bot.download_file(file_info.file_path)
        file.seek(0)
        with open('audio.ogg', 'wb') as audio:
            audio.write(file.read())

        audio = AudioSegment.from_file("audio.ogg", format="ogg")
        audio.export("audio.wav", format="wav")

        recognizer = sr.Recognizer()

        with sr.AudioFile('audio.wav') as source:
            audio = recognizer.record(source)

        try:
            text = recognizer.recognize_google(audio, language='ru')
            await handle_text_message(message, text)
        except sr.UnknownValueError:
            await bot.send_message(message.chat.id, 'Failed to recognize voice')
        except sr.RequestError:
            await bot.send_message(message.chat.id, 'Error in request to speech recognition service')
    elif message.content_type == 'text':
        # Processing a text message
        text = message.text
        await handle_text_message(message, text)

# Launch the bot
if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)

Replace 'your_api_token' with the API token you received from BotFather and 'your_chat_id' with your actual Telegram chat ID.
Run the Script

Save the script and run it using the following command in your terminal:

python chatgpt_bot.py

Interact with Your Bot

Open Telegram and start a chat with your bot.
Use the /start command to initiate the conversation.
Send text or voice messages to interact with the bot.
Conclusion
By following these steps, you can set up a ChatGPT bot in Telegram that works 24/7 and is completely free. This bot can respond to both text and voice messages, making it a versatile and powerful tool for various applications. Enjoy your new ChatGPT bot!

Dark Background Example