whats this? """ ✘ Commands Available • {i}chatgpt <userinput> ChatGPT Interact with…
- User
whats this?
""" ✘ Commands Available
•
{i}chatgpt<user_input> | ChatGPT Interact with ChatGPT AI using the selected model. --m| chat with different models --c| clears history --ls| to check available models•
{i}chat2<user_input> | ChatGPT Works same as .chatgpt but with some more models.Available Models:
- gpt-4
- gpt-4-turbo
- gpt-4o
- gpt-4o-mini """ #chatgpt from telethon import events import requests import os from collections import deque from io import BytesIO
from . import ( ultroid_cmd, async_searcher, udB, LOGS, get_paste, eor )
AVAILABLE_MODELS = [ "gpt-4", "gpt-4-turbo", "gpt-4o", "gpt-4o-mini" ]
API_URL = "https://itzpire.com/ai/chat-gpt/v2" GPT_CHAT_HISTORY = deque(maxlen=30) CURRENT_MODEL = "gpt-4o"
@ultroid_cmd(pattern="chatgpt (.*)") async def chatgpt_handler(e):
global GPT_CHAT_HISTORY, CURRENT_MODEL, AVAILABLE_MODELS command = e.raw_text.strip() query = command.split(".chatgpt", maxsplit=1)[-1].strip() if not query: reply = await e.get_reply_message() if reply and reply.text: query = reply.message if not query: return await e.eor("`Gimme a query too...`", time=5) pross = await e.eor("⏳ **Processing**") if query.startswith("-c"): GPT_CHAT_HISTORY.clear() return await pross.eor("__Cleared Chat History!__", time=6) if query.startswith("-ls"): models_text = "\n".join(AVAILABLE_MODELS) return await pross.edit(f"**Available Models:**\n\n{models_text}\n\n**Selected model:** {CURRENT_MODEL}") if query.startswith("-m"): new_model = query.split("-m", maxsplit=1)[-1].strip() if new_model in AVAILABLE_MODELS: CURRENT_MODEL = new_model return await pross.edit(f"✅ **Model switched to:** `{CURRENT_MODEL}`") return await pross.edit("⚠️ **Invalid model name! Use `.gpt4 -ls` to view available models.**") GPT_CHAT_HISTORY.append({"role": "user", "content": query}) payload = { "message": list(GPT_CHAT_HISTORY), "model": f"{CURRENT_MODEL}"} try: response = requests.post(API_URL, json=payload) response_data = response.json() if response.status_code == 200 and response_data.get("status") == "success": #ai = response_data.get("data").get("choices") #resp = ai[0]["message"].get("content") resp = response_data.get("result") if len(resp+query) > 4096: with BytesIO(resp.encode()) as file: file.name = "gpt-4o-output.txt" await e.respond( f"__{response[:360]} ...__", file=file, reply_to=e.reply_to_msg_id or e.id, ) await pross.try_delete() else: await pross.edit(f"🤖 **GPT:**\n{resp}") else: await pross.edit(f"⚠️ **Error from API:** {response_data.get('message', 'Unknown error occurred.')}") except Exception as e: await pross.edit(f"⚠️ **An error occurred:** {e}\n{response_data}")#@AgainOwner
MODELS = [ "gpt-4", "gpt-4-0613", "gpt-4-32k", "gpt-4-0314", "gpt-4-32k-0314", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-16k-0613", "gpt-3.5-turbo-0301", "text-davinci-003", "text-davinci-002", "code-davinci-002", "gpt-3", "text-curie-001" ]
API_URL = "https://itzpire.com/ai/chat-gpt/" CHAT_HISTORY = deque(maxlen=100) MODEL = "gpt-4"
@ultroid_cmd(pattern="chat2 (.*)") async def chatgpt_handler(e):
global CHAT_HISTORY, MODEL, MODELS command = e.raw_text.strip() query = command.split(".chat2", maxsplit=1)[-1].strip() reply = await e.get_reply_message() file_content = None x = await e.eor("⏳ **Processing**") if query: # Check if query contains 'from filename' if ' from ' in query: query_text, filename = query.split(' from ', 1) query_text = query_text.strip() filename = filename.strip() file_found = False async for message in e.client.iter_messages(e.chat_id, search=filename, limit=10): if message.media and hasattr(message, 'file') and message.file and message.file.name == filename: file_found = True try: file = await e.client.download_media(message) with open(file, "r", encoding='utf-8') as f: file_content = f.read() os.remove(file) break except Exception as exc: LOGS.error(f"Error reading file: {exc}") file_content = None if not file_found: query = query_text else: if file_content: query = f"{query_text}\n\n{file_content}" if query_text else file_content else: return await eod(x,"`Failed to read file content.`", time=5) else: if reply and reply.media and hasattr(reply, 'file') and reply.file and ( reply.file.name.endswith(".txt") or reply.file.name.endswith(".py") ): file = await e.client.download_media(reply) try: with open(file, "r", encoding='utf-8') as f: file_content = f.read() except Exception as exc: LOGS.error(f"Error reading file: {exc}") return await x.eod("`Failed to read file content.`", time=5) finally: os.remove(file) query = f"{query}\n\n{file_content}" elif reply and reply.message: query = f"{query}\n\n{reply.message}" else: if reply and reply.media and hasattr(reply, 'file') and reply.file and ( reply.file.name.endswith(".txt") or reply.file.name.endswith(".py") ): file = await e.client.download_media(reply) try: with open(file, "r", encoding='utf-8') as f: file_content = f.read() except Exception as exc: LOGS.error(f"Error reading file: {exc}") return await x.eod("`Failed to read file content.`", time=5) finally: os.remove(file) query = file_content elif reply and reply.message: query = reply.message else: return await x.eod("`Please provide something to proceed.`", time=5) if query.startswith("-c"): CHAT_HISTORY.clear() return await x.eor("__Cleared Chat History!__", time=6) if query.startswith("-ls"): models_text = "\n".join(MODELS) return await x.edit(f"**Available Models:**\n\n{models_text}\n\n**Selected model:** {CURRENT_MODEL}") if query.startswith("-m"): new_model = query.split("-m", maxsplit=1)[-1].strip() if new_model in MODELS: MODEL = new_model return await x.edit(f"✅ **Model switched to:** `{MODEL}`") return await x.edit("⚠️ **Invalid model name! Use `.gpt4 -ls` to view available models.**") CHAT_HISTORY.append({"role": "user", "content": query}) payload = { "message": list(CHAT_HISTORY), "model": f"{MODEL}"} try: response = requests.post(API_URL, json=payload) response_data = response.json() if response.status_code == 200 and response_data.get("status") == "success": resp = response_data["result"] if len(resp+query) > 4096: with BytesIO(resp.encode()) as file: file.name = "gpt-4o-output.txt" await e.respond( f"__{response[:360]} ...__", file=file, reply_to=e.reply_to_msg_id or e.id, ) await x.try_delete() else: await x.edit(f"🤖 **GPT({MODEL}):**\n{resp}") CHAT_HISTORY.append({"role": "assistent", "content": resp}) else: await x.edit(f"⚠️ **Error from API:** {response_data.get('message', 'Unknown error occurred.')}") except Exception as e: await x.edit(f"⚠️ **An error occurred:** {e}") - Assistant
The provided code snippet appears to be a Python script designed for a Telegram bot that interacts with OpenAI's ChatGPT API. The script features two main commands:
{i}chatgptand{i}chat2, which allow users to send messages to the ChatGPT AI model and receive responses.Key Components of the Code:
-
Imports:
- The script imports various libraries such as
telethon,requests, and others required for handling network requests, managing chat history, and responding to users.
- The script imports various libraries such as
-
API and Configuration:
- It defines a URL
API_URLto send requests to the ChatGPT API, lists available models inAVAILABLE_MODELS(e.g.,gpt-4,gpt-4-turbo), and initializes chat history management using a deque.
- It defines a URL
-
Command Handlers:
- Two command handlers are set up using the
@ultroid_cmddecorator. These handlers listen for commands in a specific format that users can invoke in a Telegram chat. - The
{i}chatgptcommand allows interaction with ChatGPT using a selected model, while the{i}chat2command is set up similarly but may allow for different models or features.
- Two command handlers are set up using the
-
Command Functionality:
- Users can:
- Send queries to the AI model.
- Clear chat history by using a command switch
-c. - List available models with
-ls. - Switch models with
-mfollowed by the model name.
- Certain checks ensure that the query and input from the user are valid.
- If the response from the API is too long for Telegram messages, it saves the response to a file and sends the file instead.
- Users can:
-
Error Handling:
- The script includes error handling that reports issues that may arise during API requests or file operations.
-
Chat History:
- It keeps track of the conversation by maintaining a history of messages exchanged with the user, which is important for context when interacting with the AI.
Functionality Overview:
- With this bot, users can engage in dynamic conversations with different configurations of ChatGPT.
- They can manage their interaction session through various input commands, making the bot quite flexible.
- The bot is designed to work within a Telegram chat, providing a user-friendly interface for AI interactions.
Possible Use Cases:
- Education
- Customer Service
- Creative Writing
- Interactive Learning
This bot demonstrates how one can leverage AI models in practical applications by integrating with popular communication platforms like Telegram.
-