0% found this document useful (0 votes)
33 views2 pages

Telegram Bot с ChatGpt  На Python. - UPROGER - Программирование

Uploaded by

ymkvk6tksr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views2 pages

Telegram Bot с ChatGpt  На Python. - UPROGER - Программирование

Uploaded by

ymkvk6tksr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Russian English

Machine Learning Channel


Go over
@ai_machinelearning_big_data

Telegram bot with


ChatGpt in Python.
07.02.2023
PYTHON, CHATGPT, ARTIFICIAL
INTELLIGENCE, POSTS

This is a guide to creating a Telegram


ChatGPT bot with just a few lines of Python
code. Whether you are a programming
professional or just starting out, we have
prepared a step-by-step guide for you. Get
ready to revolutionize your chat rooms and
have a lot of fun!

@vistehno-chatgpt in telegram.

1. First, make sure that


Python is installed on your
computer.
If python is not installed, follow the
instructions here:

Каĸ установить pip на


Windows
Вступление
Системы
управления
паĸетами –

инструменты, ĸоторые обычно


создают для языĸов
программирования. Они упрощают
настройĸу и управление паĸетами
сторонних производителей. Pip –
лучшая система управления паĸетами
в Python ĸаĸ для собственных модулей
Pip, таĸ и для модулей, установленных
в виртуальных средах. При вызове Pip
он автоматичесĸи выполняет обход
хранилища общедоступных паĸетов
Python (индеĸс паĸетов Python, таĸже
известный ĸаĸ PyPI), загружает паĸеты
и устанавливает файлы установĸи. В
этой статье мы научимся
устанавливать Pip в операционных
системах Windows. Устанавливаем
Python Проверим, установлены ли уже
у нас Python и Pip. Запустим Терминал
Windows из меню “Пусĸ” – через него
мы будем использовать PowerShell. …
Читать далее

UPROGER |
0
Программирование

2. Then get your


Telegram API
authentication
credentials.
First, you will need to create a new bot and
get its API token. Don't worry, it's very
simple! Just chat with the BotFather bot on
Telegram and it will help you with the
implementation of this process. Follow
these steps:

Open a dialog with the BotFather bot in


Telegram by searching for "@BotFather " in
the search bar. Enter the “/newbot "
command to create a new bot. Follow the
instructions to choose a username and
username for your bot. The user name
must end with " bot "(for example,
"my_new_bot").

Once the bot is created, BotFather will


provide you with a token. This token is used
to authenticate your bot and grant it access
to the Telegram API. Copy the token and
use it in your bot's code for authentication
and API access. Don't share your bot's
token with anyone.

Then you will need to get the chat ID of the


channel that you just created in Telegram.
This ID is a unique identifier and is used
when someone wants to integrate Telegram
with their own apps or services.

Send a message to this channel via the bot


API using your channel name and access
token.

{"ok":true,
"result":{
"message_id":191,
"sender_chat":{
"id":-1001527664788,
"title":"Test Channel Name",

"username":"TestChannel","type
":"channel"
},
"chat":{
"id":-1001527664788,
"title":"",

"username":"TestChannel","type
":"channel"
},
"date":1670434355,
"text":"123"
}
}

You will find the channel id in the chat/id


section.

It is important to grant your bot


administrator rights so that it can
perform all the necessary tasks.
Attention to all programmers! These access
token IDs may look nice, but they're just for
show. Next, you'll need your own one for
your app.

3. It's time to get your API


key and connect to the
OpenAI engine.
If ChtGpt is not available in your region,
here are instructions for getting an api key,

ChatGpt как зарегистр…

To get an API key from OpenAI, you will


need to create an account on the OpenAI
website . Once you have an account, you
can access your API keys by going to the
“API Keys " tab in the user's control panel.

From there, you can generate a new key


and use it to authenticate your API
requests. It is important to keep this API
key secret and secure to protect your
account.

Keep in mind that OpenAI may limit the


number of API calls you can make. With a
personal account, you will receive a grant
of $ 18 for use in API requests. Be sure to
read the terms of service and pricing
information on the OpenAI website before
using the API.

Connecting to Text-
davinci-003

Text-davinci-003 is a large language model


developed by OpenAI. It is considered one
of the most efficient language models
currently available, due to its ability to
generate human-like text and perform a
wide range of language tasks. It has been
trained on a data set of billions of words
and can generate coherent text that reads
as if it was written by a human.

With a few simple steps and a bit of Python


magic, you'll be able to connect and deploy
your ChatGPT bot to your group in no time
at all. Let's start writing code!

4. Start writing Python


code.
First, we'll import the necessary libraries
and set the key authentication parameter.

# 1. импорт стандартных
библиотек
import json
import os
import threading

# серктный ключ чатджипити,


полученный ранее
API_KEY =
'xxxxxxxxxxxsecretAPIxxxxxxxxx
x'
# Models: text-davinci-
003,text-curie-001,text-
babbage-001,text-ada-001
MODEL = 'text-davinci-003'

#токен, полученный от телеграм


бота ботфазер
BOT_TOKEN =
'xxxxxxbotapikeyxxxxx'

# определяем личность бота, мы


сделали бота-шутника для
примера
BOT_PERSONALITY = 'Answer in a
funny tone, '

Enter the parameter BOT_PERSONALITY -


set the ChatGpt response style in telegram
! Use this convenient constant to give your
bot a specific tone or conversation style,
such as friendly, professional, or
humorous. By setting the
BOT_PERSONALITY parameter, you can
customize the way ChatGPT communicates
with your users and create a more
personalized and attractive object.:

Вот 15 видов персоналий,


которые можно выбрать
of ChatGPT:
1. Friendly
2. Professional
3. Humorous
4. Sarcastic
5. Witty
6. Sassy
7. Charming
8. Cheeky
9. Quirky
10. Laid-back
11. Elegant
12. Playful
13. Soothing
14. Intense
15. Passionate

Then create a function that gets a response


from the OpenAI chatbot.

# 2a. ответ от openAi


def openAI(prompt):
# делаем запрос на сервер
с ключами
response = requests.post(

'https://api.openai.com/v1/com
pletions',
headers=
{'Authorization': f'Bearer
{API_KEY}'},
json={'model': MODEL,
'prompt': prompt,
'temperature': 0.4,
'max_tokens': 300}
)

result = response.json()
final_result =
''.join(choice['text'] for
choice in result['choices'])
return final_result

# 2b. функция обработки


изображений
def openAImage(prompt):
# запрос на OpenAI API
resp = requests.post(

'https://api.openai.com/v1/ima
ges/generations',
headers=
{'Authorization': f'Bearer
{API_KEY}'},
json={'prompt':
prompt,'n' : 1, 'size':
'1024x1024'}
)
response_text =
json.loads(resp.text)

return
response_text['data'][0]
['url']

This 2.a function will send a POST request


to the OpenAI API with the specified input
data (for example “" What is entropy?”) for
API analysis. The temperature parameter
determines how random the generated
response will be — lower values mean more
predictable text. The max_tokens
parameter sets a limit on the number of
words and punctuation marks in the
response. And voila! The function returns
the generated response from the specified
OpenAI model.

Next, it's time to create a function that


sends a message to a specific group in
Telegram:

# 3a. функция отправки в


заданную телеграм группу
def
telegram_bot_sendtext(bot_mess
age,chat_id,msg_id):
data = {
'chat_id': chat_id,
'text': bot_message,
'reply_to_message_id':
msg_id
}
response = requests.post(

'https://api.telegram.org/bot'
+ BOT_TOKEN + '/sendMessage',
json=data
)
return response.json()

# 3b. Функция, которая


отправляет изображение в
определенную группу телеграмм
def
telegram_bot_sendimage(image_u
rl, group_id, msg_id):
data = {
'chat_id': group_id,
'photo': image_url,
'reply_to_message_id':
msg_id
}
url =
'https://api.telegram.org/bot'
+ BOT_TOKEN + '/sendPhoto'

response =
requests.post(url, data=data)
return response.json()

The above 3.a function sends a message to


a specific Telegram group using the
Telegram API. The function takes three
arguments: bot_message, which is the
message to be sent, chat_id, which is the
unique identifier of the chat to which the
message will be sent, and msg_id, which
sets the unique identifier of the message
you want to respond to. The function uses
the request library to send a GET request to
the Telegram API with the necessary
parameters, including the API key, chat ID,
and message to send.

Now it's time to move on to the fun part-


creating a function that retrieves the latest
requests from users in the Telegram group,
generates a smart response using OpenAI,
and sends it back to the group. Let's do it!

# 4. Функция получения
последних запросов от
пользователей в группе
Telegram,
# генерирует ответ, используя
OpenAI, и отправляет ответ
обратно в группу.

def Chatbot():
# Retrieve last ID message
from text file for ChatGPT
update
cwd = os.getcwd()
filename = cwd +
'/chatgpt.txt'
if not
os.path.exists(filename):
with open(filename,
"w") as f:
f.write("1")
else:
print("File Exists")

with open(filename) as f:
last_update = f.read()

# Проверить наличие новых


сообщений в группе Telegram
url =
f'https://api.telegram.org/bot
{BOT_TOKEN}/getUpdates?offset=
{last_update}'
response =
requests.get(url)
data =
json.loads(response.content)

for result in
data['result']:
try:
# Проверить наличие
новых сообщений
if
float(result['update_id']) >
float(last_update):
# Checking for
new messages that did not come
from chatGPT
if not
result['message']['from']
['is_bot']:

last_update =
str(int(result['update_id']))

# Получение
идентификатора сообщения
отправителя запроса
msg_id =
str(int(result['message']
['message_id']))

#
Retrieving the chat ID
chat_id =
str(result['message']['chat']
['id'])

# Получение
идентификатора сообщения
отправителя запроса
if '/img'
in result['message']['text']:
prompt
= result['message']
['text'].replace("/img", "")

bot_response =
openAImage(prompt)

print(telegram_bot_sendimage(b
ot_response, chat_id, msg_id))

# Проверка
того, что пользователь
упомянул имя пользователя чат-
бота в сообщении
if
'@ask_chatgptbot' in
result['message']['text']:
prompt
= result['message']
['text'].replace("@ask_chatgpt
bot", "")
# Вызов
OpenAI API с использованием
личности бота

bot_response = openAI(f"
{BOT_PERSONALITY}{prompt}")
#
Sending back response to
telegram group

print(telegram_bot_sendtext(bo
t_response, chat_id, msg_id))
# Проверка того,
что пользователь отвечает боту
ChatGPT
if
'reply_to_message' in
result['message']:
if
result['message']
['reply_to_message']['from']
['is_bot']:

prompt = result['message']
['text']

bot_response = openAI(f"
{BOT_PERSONALITY}{prompt}")

print(telegram_bot_sendtext(bo
t_response, chat_id, msg_id))
except Exception as e:
print(e)

# Updating file with last


update ID
with open(filename, 'w')
as f:
f.write(last_update)

return "done"

But wait, that's not all! We will also make


sure that they are from a real user (and not
from an annoying bot), and send them to
the OpenAI API for analysis if they mention
the bot's username and are a response to
the bot. Make sure you rename your bot in
the script by replacing “@ask_chatgptbot”
with the desired name.

So, the last step! It's time to add a


scheduling component to your bot so that it
can regularly check for new messages in
the group and send responses as needed.
The Python streaming library can help you
with this:

# 5 Запускаем проверку каждые


5 секунд на наличие новых
сообщений
def main():
timertime=5
Chatbot()

# 5 секунд таймер
threading.Timer(timertime,
main).start()

# запускаем функцию main


if __name__ == "__main__":
main()

Ta-da! We present the fruits of your labor:


the final Python code for your new fun
chatbot. Just copy and paste this " guy”
into your favorite code editor, connect your
API keys and chat group ID, and you'll be
chatting with ChatGPT in no time.

Full version of the code (github link


here):

# 1. Начните с импорта
необходимых библиотек и
настройки клиентов API
import requests
import json
import os
import threading

# OpenAI секретный ключ


API_KEY =
'xxxxxxxxxxxsecretAPIxxxxxxxxx
x'
# Models: text-davinci-
003,text-curie-001,text-
babbage-001,text-ada-001
MODEL = 'text-davinci-003'

# Telegram токен бота


BOT_TOKEN =
'xxxxxxbotapikeyxxxxx'
# определяем характер телеграм
бота
BOT_PERSONALITY = 'Answer in a
funny tone, '

# 2a. получаем ответ от OpenAI


def openAI(prompt):
# запрос на OpenAI API
response = requests.post(

'https://api.openai.com/v1/com
pletions',
headers=
{'Authorization': f'Bearer
{API_KEY}'},
json={'model': MODEL,
'prompt': prompt,
'temperature': 0.4,
'max_tokens': 300}
)

result = response.json()
final_result =
''.join(choice['text'] for
choice in result['choices'])
return final_result

# 2b. функци получения


изображения от OpenAI
def openAImage(prompt):
# запрос на OpenAI API
resp = requests.post(

'https://api.openai.com/v1/ima
ges/generations',
headers=
{'Authorization': f'Bearer
{API_KEY}'},
json={'prompt':
prompt,'n' : 1, 'size':
'1024x1024'}
)
response_text =
json.loads(resp.text)

return
response_text['data'][0]
['url']

# 3a. функция отправки


сообщения в группу
def
telegram_bot_sendtext(bot_mess
age,chat_id,msg_id):
data = {
'chat_id': chat_id,
'text': bot_message,
'reply_to_message_id':
msg_id
}
response = requests.post(

'https://api.telegram.org/bot'
+ BOT_TOKEN + '/sendMessage',
json=data
)
return response.json()

# 3b. функция отправки


картинки в группу
def
telegram_bot_sendimage(image_u
rl, group_id, msg_id):
data = {
'chat_id': group_id,
'photo': image_url,
'reply_to_message_id':
msg_id
}
url =
'https://api.telegram.org/bot'
+ BOT_TOKEN + '/sendPhoto'

response =
requests.post(url, data=data)
return response.json()

# 4. Функция получения
последних запросов от
пользователей в группе
Telegram,
# генерирует ответ, используя
OpenAI, и отправляет ответ
обратно в группу.
def Chatbot():
# Получить последнее сообщение
ID из текстового файла для
обновления ChatGPT
cwd = os.getcwd()
filename = cwd +
'/chatgpt.txt'
if not
os.path.exists(filename):
with open(filename,
"w") as f:
f.write("1")
else:
print("File Exists")

with open(filename) as f:
last_update = f.read()

# Проверить наличие новых


сообщений в группе Telegram
url =
f'https://api.telegram.org/bot
{BOT_TOKEN}/getUpdates?offset=
{last_update}'
response =
requests.get(url)
data =
json.loads(response.content)

for result in
data['result']:
try:
# Проверка нового
сообщения
if
float(result['update_id']) >
float(last_update):
# Проверка
новых сообщений, пришедших не
из chatGPT
if not
result['message']['from']
['is_bot']:

last_update =
str(int(result['update_id']))

# Получение
идентификатора сообщения
отправителя запроса
msg_id =
str(int(result['message']
['message_id']))

# получаем
ID
chat_id =
str(result['message']['chat']
['id'])

# проверка
нужна ли картинка пользователю
if '/img'
in result['message']['text']:
prompt
= result['message']
['text'].replace("/img", "")

bot_response =
openAImage(prompt)

print(telegram_bot_sendimage(b
ot_response, chat_id, msg_id))
# Проверка
того, что пользователь
упомянул имя пользователя чат-
бота в сообщении
if
'@ask_chatgptbot' in
result['message']['text']:
prompt
= result['message']
['text'].replace("@ask_chatgpt
bot", "")
# Вызов
OpenAI API с использованием
личности бота

bot_response = openAI(f"
{BOT_PERSONALITY}{prompt}")
#
Отправляем ответ группе
телеграмм

print(telegram_bot_sendtext(bo
t_response, chat_id, msg_id))
# Проверка того,
что пользователь отвечает боту
ChatGPT
if
'reply_to_message' in
result['message']:
if
result['message']
['reply_to_message']['from']
['is_bot']:

prompt = result['message']
['text']

bot_response = openAI(f"
{BOT_PERSONALITY}{prompt}")

print(telegram_bot_sendtext(bo
t_response, chat_id, msg_id))
except Exception as e:
print(e)

# в файл сохраняем
последний id
with open(filename, 'w')
as f:
f.write(last_update)

return "done"

# 5 Запускаем проверку каждые


5 секунд на наличие новых
сообщений
def main():
timertime=5
Chatbot()
# 5 sec timer
threading.Timer(timertime,
main).start()

# запускаем main
if __name__ == "__main__":
main()

С помощью несĸольĸих простых шагов и


небольшого ĸоличества магии Python вы
успешно создали чат-бота для своей
группы Telegram с помощью OpenAI.
Поздравляю! Время отĸинуться на
спинĸу стула и понаблюдать за
поступающими весёлыми ответами. Или,
знаете ли, проведите неĸоторую тонĸую
настройĸу, чтобы сделать вашего чат-
бота действительно униĸальным.

Код :

https://github.com/Develp10/telegramchat
gpt/blob/main/README.md

4 10 1 3 4

 Просмотры: 16 706

+8

Похожие записи

Выпущена новая версия Python 3.13


07.10.2024

Лучший бесплатный ĸурс Python


2025
22.09.2024

Machine Learning: Медицинсĸий


дайджест за период 7.09 – 14.09 2024
года
16.09.2024

Ответить
Ваш адрес email не будет опублиĸован.
Обязательные поля помечены *

Имя *

Email *

Сайт

Оставьте свой ĸомментарий

Сохранить моё имя, Email и адрес сайта в

этом браузере для последующих ĸомментариев.

Отправить ĸомментарий

Все права защищены © 2024 UPROGER |


Программирование

You might also like