# #Telegram bot API + chatGPT API (Python)

### BotFather steps: (From Telegram find BotFather contact)

<pre class="language-markup"><code class="lang-markup">User:
*/start*

BotFather, [Feb 5, 2023 at 2:08:07 PM]:
I can help you create and manage Telegram bots. If you're new to the Bot API, please see the manual.
You can control me by sending these commands:
*/newbot* - create a new bot
...
User:, [Feb 5, 2023 at 2:08:40 PM]:
*/newbot*

BotFather, [Feb 5, 2023 at 2:08:40 PM]:
<strong>Alright, a new bot. How are we going to call it? Please choose a name for your bot.
</strong>
User, [Feb 5, 2023 at 2:09:23 PM]:
*Dec_22_chatGPT*

BotFather, [Feb 5, 2023 at 2:09:23 PM]:
Good. Now let's choose a username for your bot. It must end in `bot`. 
Like this, for example: TetrisBot or tetris_bot.

User, [Feb 5, 2023 at 2:10:14 PM]:
*chat_dec_22_bot*

BotFather, [Feb 5, 2023 at 2:10:14 PM]:
Done! Congratulations on your new bot. You will find it at t.me/chat_dec_22_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.

Use this token to access the HTTP API:
6185472765:PIbwepibvWEfvweurwEO$I#)$#$D
Keep your token secure and store it safely, it can be used by anyone to control your bot.

For a description of the Bot API, see this page: https://core.telegram.org/bots/api
</code></pre>

**Pre-requisites:**

OpenAI.com valid API key

Telegram API key

**Steps:**

1. The best practice is to run the app in their own virtual environment&#x20;

   ```sh
   python -m venv .myenv
   source .myenv/bin/activate
   ```
2. Install the **aiogram and openai** libraries:

```bash
pip install aiogram
pip install openai
```

2. Register a new bot with BotFather on Telegram and obtain the API key.
3. Create a new Python file like "***chatGPT\_telegram\_bot.py***" and import the necessary libraries:

```python
chatGPT_telegram_bot.py
-----------------------
#!/bin/python

import openai
import os
from aiogram import Bot, Dispatcher, executor, types

from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.middlewares import BaseMiddleware
from aiogram.types import Message

```

4. Initialize the OpenAI API client and the Telegram bot with the API key obtained from BotFather:

```python
openai.api_key = "YOUR_OPENAI_API_KEY"
# Initialize bot and dispatcher
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
```

5. Define a function to handle user messages:

```python
@dp.message_handler(commands='start')
async def cmd_start(message: Message):
    await message.answer("Hi there! I am Chat GPT bot owned by Sergei L. and  powered by OpenAI.")
```

6. Define a function to handle user text messages and send them to the OpenAI API:

```python
@dp.message_handler()
async def chat_bot(message: Message):
    text = message.text
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=text,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.5,
    ).choices[0].text
    await bot.send_message(chat_id=message.chat.id, text=response)

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)

```

7. Start the bot and make it listen for incoming messages by running ***"run.sh"***:

```sh
run.sh

--------------
#!/bin/sh

source .myenv/bin/activate
python chatGPT_telegram_bot.py 
if [ $? = 0 ]; then
  echo "Chatbot is running"
else
  echo "Something went wrong"
fi

```

Now the bot should be ready to receive questions from users and respond to them using the OpenAI API.

{% hint style="info" %}
To run it in Docker we need to create Dockerfile and Docker image:
{% endhint %}

### Create requirements and Dockerfile

```
pip freeze > requirements.txt
```

#### Put Dockerfile into the same directory with  run.sh and  chatGPT\_telegram\_bot.py ifles&#x20;

{% hint style="info" %}
NOTE: Make the file run.sh executable&#x20;

*<mark style="color:red;">$ sudo chmod +x run.sh</mark>*
{% endhint %}

````docker
Dockerfile
____________
# Use an official Python runtime as the base image
FROM python:3.9-alpine

# Set the working directory in the container to /app
WORKDIR /home/app

RUN python -m venv .myenv 
# Copy the requirements.txt file to the container

COPY requirements.txt .

# Install required packages specified in the requirements.txt file
RUN source .myenv/bin/activate && pip install --upgrade pip &&\
 pip install --cache-dir .myenv/lib -r requirements.txt 

# Copy the contents of the current directory to the container
COPY . /home/app

# Specify the command to run the app when the container starts
CMD ["./run.sh" ]
```
````

```sh
#Create image "chatbot"
docker build -it chatbot .

# Run chatbot container as a deamon:
docker run -it -d chatbot
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://portfolio.litovchenko.net/master/telegram-bot-api-+-chatgpt-api-python.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
