Telegram Bot с ChatGpt На Python. - UPROGER - Программирование
Telegram Bot с ChatGpt На Python. - UPROGER - Программирование
@vistehno-chatgpt in telegram.
UPROGER |
0
Программирование
{"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"
}
}
Connecting to Text-
davinci-003
# 1. импорт стандартных
библиотек
import json
import os
import threading
'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
'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']
'https://api.telegram.org/bot'
+ BOT_TOKEN + '/sendMessage',
json=data
)
return response.json()
response =
requests.post(url, data=data)
return response.json()
# 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()
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)
return "done"
# 5 секунд таймер
threading.Timer(timertime,
main).start()
# 1. Начните с импорта
необходимых библиотек и
настройки клиентов API
import requests
import json
import os
import threading
'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
'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']
'https://api.telegram.org/bot'
+ BOT_TOKEN + '/sendMessage',
json=data
)
return response.json()
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()
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"
# запускаем main
if __name__ == "__main__":
main()
Код :
https://github.com/Develp10/telegramchat
gpt/blob/main/README.md
4 10 1 3 4
Просмотры: 16 706
+8
Похожие записи
Ответить
Ваш адрес email не будет опублиĸован.
Обязательные поля помечены *
Имя *
Email *
Сайт
Отправить ĸомментарий