__version__ = (1, 0, 0) import contextlib """ █▀▄▀█ █▀█ █▀█ █ █▀ █ █ █▀▄▀█ █▀▄▀█ █▀▀ █▀█ █ ▀ █ █▄█ █▀▄ █ ▄█ █▄█ █ ▀ █ █ ▀ █ ██▄ █▀▄ Copyright 2022 t.me/morisummermods Licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International """ # meta developer: @morisummermods # meta banner: https://i.imgur.com/H1vPM6U.jpg from telethon.tl.types import Message import requests import logging import re from .. import loader, utils # noqa logger = logging.getLogger(__name__) @loader.tds class ChatGPT(loader.Module): """ChatGPT AI API interaction""" strings = { "name": "ChatGPT", "no_args": ( "🚫 No arguments" " provided" ), "question": ( "👤 Question:" " {question}\n" ), "answer": ( "🤖 Answer: {answer}" ), "loading": "Loading...", "no_api_key": ( "🚫 No API key provided\nℹ️ Get it from official OpenAI" " website and add it to config" ), } strings_ru = { "no_args": ( "🚫 Не указаны" " аргументы" ), "question": ( "👤 Вопрос:" " {question}\n" ), "answer": ( "🤖 Ответ: {answer}" ), "loading": "Загрузка...", "no_api_key": ( "🚫 Не указан API ключ\nℹ️ Получите его на официальном" " сайте OpenAI и добавьте в конфиг" ), } strings_es = { "no_args": ( "🚫 No se han" " proporcionado argumentos" ), "question": ( "👤 Pregunta:" " {question}\n" ), "answer": ( "🤖 Respuesta:" " {answer}" ), "loading": "Cargando...", "no_api_key": ( "🚫 No se ha proporcionado una clave API\nℹ️ Obtenga una en el sitio web" " oficial de OpenAI y agréguela a la configuración" ), } strings_fr = { "no_args": ( "🚫 Aucun argument" " fourni" ), "question": ( "👤 Question:" " {question}\n" ), "answer": ( "🤖 Réponse: {answer}" ), "loading": "Chargement...", "no_api_key": ( "🚫 Aucune clé API fournie\nℹ️ Obtenez-en un sur le site" " officiel d'OpenAI et ajoutez-le à la configuration" ), } strings_de = { "no_args": ( "🚫 Keine Argumente" " angegeben" ), "question": ( "👤 Frage:" " {question}\n" ), "answer": ( "🤖 Antwort: {answer}" ), "loading": "Laden...", "no_api_key": ( "🚫 Kein API-Schlüssel angegeben\nℹ️ Holen Sie sich einen auf der" " offiziellen OpenAI-Website und fügen Sie ihn der Konfiguration hinzu" ), } strings_tr = { "no_args": ( "🚫 Argümanlar" " verilmedi" ), "question": ( "👤 Soru: {question}\n" ), "answer": ( "🤖 Cevap: {answer}" ), "loading": "Yükleniyor...", "no_api_key": ( "🚫 API anahtarı verilmedi\nℹ️ OpenAI'nın resmi websitesinden" " alın ve yapılandırmaya ekleyin" ), } strings_uz = { "no_args": ( "🚫 Argumentlar" " ko'rsatilmadi" ), "question": ( "👤 Savol:" " {question}\n" ), "answer": ( "🤖 Javob: {answer}" ), "loading": "Yuklanmoqda...", "no_api_key": ( "🚫 API kalit ko'rsatilmadi\nℹ️ Ofitsial OpenAI veb-saytidan" " oling" ), } strings_it = { "no_args": ( "🚫 Nessun argomento" " fornito" ), "question": ( "👤 Domanda:" " {question}\n" ), "answer": ( "🤖 Risposta: {answer}" ), "loading": "Caricamento...", "no_api_key": ( "🚫 Nessuna chiave API fornita\nℹ️ Ottienila dal sito ufficiale" " di OpenAI e aggiungila al tuo file di configurazione" ), } def __init__(self): self.config = loader.ModuleConfig( loader.ConfigValue( "api_key", "", "API key from OpenAI", validator=loader.validators.Hidden(loader.validators.String()), ), ) async def _make_request( self, method: str, url: str, headers: dict, data: dict, ) -> dict: resp = await utils.run_sync( requests.request, method, url, headers=headers, json=data, ) return resp.json() def _process_code_tags(self, text: str) -> str: return re.sub( r"`(.*?)`", r"\1", re.sub(r"```(.*?)```", r"\1", text, flags=re.DOTALL), flags=re.DOTALL, ) async def _get_chat_completion(self, prompt: str) -> str: resp = await self._make_request( method="POST", url="https://api.openai.com/v1/chat/completions", headers={ "Content-Type": "application/json", "Authorization": f'Bearer {self.config["api_key"]}', }, data={ "model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": prompt}], }, ) if resp.get("error", None): return f"🚫 {resp['error']['message']}" return resp["choices"][0]["message"]["content"] @loader.command( ru_doc="<вопрос> - Задать вопрос", it_doc=" - Fai una domanda", fr_doc=" - Posez une question", de_doc=" - Stelle eine Frage", es_doc=" - Haz una pregunta", tr_doc=" - Soru sor", uz_doc=" - Savol ber", ) async def gpt(self, message: Message): """ - Ask a question""" if self.config["api_key"] == "": return await utils.answer(message, self.strings("no_api_key")) args = utils.get_args_raw(message) if not args: return await utils.answer(message, self.strings("no_args")) await utils.answer( message, "\n".join( [ self.strings("question").format(question=args), self.strings("answer").format(answer=self.strings("loading")), ] ), ) answer = await self._get_chat_completion(args) await utils.answer( message, "\n".join( [ self.strings("question").format(question=args), self.strings("answer").format( answer=self._process_code_tags(answer) ), ] ), )