Skip to content

Commit

Permalink
Merge pull request #3 from ufoptg/patch-2
Browse files Browse the repository at this point in the history
Patch 2
  • Loading branch information
ufoptg authored Feb 8, 2024
2 parents 7688d1b + 72d7547 commit 089c119
Show file tree
Hide file tree
Showing 5 changed files with 249 additions and 3 deletions.
32 changes: 30 additions & 2 deletions assistant/callbackstuffs.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,10 @@ def text_to_url(event):
[Button.inline("OpenAI API", data="abs_openapi")],
[Button.inline("🌀ʊʄ⊕ք🌀 API", data="abs_uapi")],
[Button.inline("OCR API", data="abs_oapi")],
[Button.inline("OpenAI API", data="abs_openapi")],
[Button.inline("🌀ʊʄ⊕ք🌀 API", data="abs_uapi")],
[Button.inline("BARD API", data="abs_bapi")],
[Button.inline("GOOGLE API", data="abs_gapi")],
[Button.inline("« Back", data="setter")],
],
},
Expand All @@ -194,7 +198,7 @@ def text_to_url(event):
"dapi": {
"var": "DEEP_AI",
"name": "Deep AI Api Key",
"text": "Get Your Deep Api from deepai.org and send here.",
"text": "Get Your Deep Api from deepai.org and send here.\n\n /cancel to cancel",
"back": "cbs_apiset",
},
"uapi": {
Expand All @@ -212,7 +216,31 @@ def text_to_url(event):
"oapi": {
"var": "OCR_API",
"name": "Ocr Api Key",
"text": "Get Your OCR api from ocr.space and send that Here.",
"text": "Get Your OCR api from ocr.space and send that Here.\n\n /cancel to cancel",
"back": "cbs_apiset",
},
"uapi": {
"var": "UFOPAPI",
"name": "UFoP API Key",
"text": "Contact 🌀ʊʄ⊕ք🌀 or Visit @PerthUnity_Bot Support Group\n\n /cancel to cancel",
"back": "cbs_apiset",
},
"openapi": {
"var": "OPENAI_API",
"name": "OPENAI API Key",
"text": "Visit openai.com for an OPENAI Api key!\n\n /cancel to cancel",
"back": "cbs_apiset",
},
"bapi": {
"var": "BARDAPI",
"name": "Bard AI Api Key",
"text": "Get Your Bard cookie/api using a browsers developer mode\n\n /cancel to cancel",
"back": "cbs_apiset",
},
"gapi": {
"var": "GOOGLEAPI",
"name": "Google Api Key",
"text": "Get Your GOOGLE API from https://makersuite.google.com/app/apikey \n\n /cancel to cancel",
"back": "cbs_apiset",
},
"pmlgg": {
Expand Down
6 changes: 5 additions & 1 deletion plugins/_chatactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.

import asyncio
import os
import tempfile
from time import sleep

from telethon import events, types
from typing import Union

import requests
from telethon import events
from telethon.errors.rpcerrorlist import UserNotParticipantError
from telethon.tl.functions.channels import GetParticipantRequest
from telethon.utils import get_display_name
Expand Down
186 changes: 186 additions & 0 deletions plugins/chatgpt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
# Written by @TrueSaiyan Credits to dot arc for OpenAI
# Ultroid ~ UserBot
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid >
# PLease read the GNU Affero General Public License in
# <https://github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
**Get Answers from Chat GPT including OpenAI, Bing and Sydney**
**Or generate images with Dall-E-3XL**
> `{i}gpt` (-i = for image) (query)
**• Examples: **
> `{i}gpt How to fetch a url in javascript`
> `{i}gpt -i Cute Panda eating bamboo`
> `{i}bard Hello world`
• `{i}gpt` or `{i}gpt -i` Needs OpenAI API key to function!!
• `{i}bard` Need to save bard cookie to use bard. (Its still learning)
"""
import aiohttp
import asyncio
from os import remove, system
from telethon import TelegramClient, events
from io import BytesIO
from PIL import Image
import base64
import requests
import json
from . import *


try:
import openai
from bardapi import Bard
except ImportError:
system("pip3 install -q openai")
system("pip3 install -q bardapi")
import openai
from bardapi import Bard

from . import (
LOGS,
async_searcher,
check_filename,
fast_download,
udB,
ultroid_cmd,
)

if udB.get_key("UFOPAPI"):
UFoPAPI = udB.get_key("UFOPAPI")
else:
UFoPAPI = ""

if udB.get_key("BARDAPI"):
BARD_TOKEN = udB.get_key("BARDAPI")
else:
BARD_TOKEN = None


#------------------------------ GPT v1 ------------------------------#
# OpenAI API-Key Required |
#--------------------------------------------------------------------#
@ultroid_cmd(
pattern="(chat)?gpt( ([\\s\\S]*)|$)",
)
async def openai_chat_gpt(e):
api_key = udB.get_key("OPENAI_API")
if not api_key:
return await e.eor("OPENAI_API key missing..")

args = e.pattern_match.group(3)
reply = await e.get_reply_message()
if not args:
if reply and reply.text:
args = reply.message
if not args:
return await e.eor("Gimme a Question to ask from ChatGPT")

eris = await e.eor("Getting response...")
gen_image = False
if not OPENAI_CLIENT:
OPENAI_CLIENT = openai.AsyncOpenAI(api_key=api_key)
if args.startswith("-i"):
gen_image = True
args = args[2:]

if gen_image:
try:
response = await OPENAI_CLIENT.images.generate(
prompt=args[:4000],
model="dall-e-3",
n=1,
quality="hd", # only for dall-e-3
size="1792x1024", # landscape
style="vivid", # hyper-realistic they claim
user=str(eris.client.uid),
)
img_url = response.data[0].url
path, _ = await fast_download(img_url, filename=check_filename("dall-e.png"))
await e.respond(
f"<i>{args[:636]}</i>",
file=path,
reply_to=e.reply_to_msg_id or e.id,
parse_mode="html",
)
remove(path)
await eris.delete()
except Exception as exc:
LOGS.warning(exc, exc_info=True)
await eris.edit(f"GPT (v1) ran into an Error:\n\n> {exc}")

return

try:
response = await OPENAI_CLIENT.chat.completions.create(
model="gpt-3.5-turbo-1106",
messages=[{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": args}],
)
# LOGS.debug(f'Token Used on ({question}) > {response["usage"]["total_tokens"]}')
answer = response.choices[0].message.content.replace("GPT:\n~ ", "")

if len(response.choices[0].message.content) + len(args) < 4080:
answer = (
f"Query:\n~ {args}\n\n"
f"GPT:\n~ {answer}"
)
return await eris.edit(answer)

with BytesIO(response.encode()) as file:
file.name = "gpt_response.txt"
await e.respond(
f"<i>{args[:1000]} ...</i>",
file=file,
reply_to=e.reply_to_msg_id or e.id,
parse_mode="html",
)
await eris.delete()
except Exception as exc:
LOGS.warning(exc, exc_info=True)
await eris.edit(f"GPT (v1) ran into an Error:\n\n> {exc}")


#--------------------------Bard w Base ----------------------------#
# Bard Cookie Token. |
#------------------------------------------------------------------#

@ultroid_cmd(
pattern="(chat)?bard( ([\\s\\S]*)|$)",
)
async def handle_bard(message):
owner_base = "You are an AI Assistant chatbot called Ultroid AI designed for many different helpful purposes"
query = message.raw_text.split('.bard', 1)[-1].strip()
reply = await message.edit(f"Generating answer...")

if BARD_TOKEN:
token = BARD_TOKEN
else:
error_message = f"ERROR NO BARD COOKIE TOKEN"
await reply.edit(error_message)
return

try:
headers = {
"Host": "bard.google.com",
"X-Same-Domain": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"Origin": "https://bard.google.com",
"Referer": "https://bard.google.com/",
}

cookies = {"__Secure-1PSID": token}

async with aiohttp.ClientSession(headers=headers, cookies=cookies) as session:
bard = Bard(token=token, session=session, timeout=30)
bard.get_answer(owner_base)["content"]
message_content = bard.get_answer(query)["content"]
await reply.edit(message_content)

except Exception as e:
LOGS.exception(f"Error: {str(e)}")
error_message = f"An unexpected error occurred: {str(e)}"
await reply.edit(error_message)
3 changes: 3 additions & 0 deletions pyUltroid/_misc/_supporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,9 @@ class Config((object)):
DEEP_AI = os.environ.get("DEEP_AI", None)
TAG_LOG = os.environ.get("TAG_LOG", None)
UFOPAPI = os.environ.get("UFOPAPI", "h32dfKsl8pQUxsNftkogIuDF32pYTwKluIY8emI1Hs")
GOOGLEAPI = os.environ.get("GOOGLEAPI", None)
BARDAPI = os.environ.get("BARDAPI", None)


else:
DB_URI = None
Expand Down
25 changes: 25 additions & 0 deletions pyUltroid/fns/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,31 @@ async def check_reply_to(event):
return False
return False

async def check_reply_to(event):
truai = [event.client.me.id] #Adding to this list will allow for anon or masked usermode
if (event.is_private and event.is_reply) or (
event.is_reply and event.reply_to_msg_id
):
try:
replied_message = await event.client.get_messages(
event.chat_id, ids=event.reply_to_msg_id
)
if replied_message.from_id:
user_id = replied_message.from_id.user_id
if user_id in truai:
return True
elif replied_message.peer_id and not replied_message.from_id:
channel_id = replied_message.peer_id.channel_id
if channel_id in truai:
return True
# If neither user_id nor channel_id is in truai, return False
return False
except Exception as e:
# Log the exception for debugging
print(f"Exception: {e}")
return False
return False

# ----------------- Load \\ Unloader ---------------- #


Expand Down

0 comments on commit 089c119

Please sign in to comment.