Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Patch 2 #5

Merged
merged 34 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
faebe3f
Update tools.py
ufoptg Jan 26, 2024
537fe81
Update helper.py
ufoptg Jan 26, 2024
da811f1
Update _chatactions.py
ufoptg Jan 26, 2024
7ecf00c
Update chatbot.py
ufoptg Jan 26, 2024
4514193
Update requirements.txt
ufoptg Jan 26, 2024
c7b7867
Update requirements.txt
ufoptg Feb 1, 2024
9911793
Update tools.py
ufoptg Feb 1, 2024
c2c051b
Create chatgpt.py
ufoptg Feb 1, 2024
cd0c535
Update tools.py
ufoptg Feb 2, 2024
ad6b1eb
Update helper.py
ufoptg Feb 2, 2024
f375564
Update _supporter.py
ufoptg Feb 2, 2024
c8afbe3
Update chatgpt.py
ufoptg Feb 2, 2024
3109365
Update chatgpt.py
ufoptg Feb 2, 2024
ca375ce
Update chatgpt.py
ufoptg Feb 2, 2024
72c43fb
Update _supporter.py
ufoptg Feb 8, 2024
7f08e94
Update _supporter.py
ufoptg Feb 8, 2024
3809c15
Update tools.py
ufoptg Feb 8, 2024
409ac83
Update tools.py
ufoptg Feb 8, 2024
094b42a
Update callbackstuffs.py
ufoptg Feb 8, 2024
673bd0e
Update chatgpt.py
ufoptg Feb 8, 2024
7672e7a
Update tools.py
ufoptg Feb 8, 2024
703df21
Update tools.py
ufoptg Feb 8, 2024
088092d
Update tools.py
ufoptg Feb 8, 2024
cb60427
Update helper.py
ufoptg Feb 8, 2024
69c9b62
Update tools.py
ufoptg Feb 8, 2024
6004b62
Update _chatactions.py
ufoptg Feb 8, 2024
2fcb4e1
Update _chatactions.py
ufoptg Feb 8, 2024
12f80e0
Merge branch 'TeamUltroid:main' into patch-2
ufoptg Feb 8, 2024
e8fe490
Update callbackstuffs.py
ufoptg Feb 8, 2024
b2256bc
Update .env.sample
ufoptg Feb 8, 2024
7688d1b
Merge pull request #2 from ufoptg/patch-1
ufoptg Feb 8, 2024
72d7547
Merge branch 'test' into patch-2
ufoptg Feb 8, 2024
27a42e1
Update helper.py
ufoptg Feb 8, 2024
dec8f05
Update callbackstuffs.py
ufoptg Feb 8, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ API_HASH=
SESSION=
REDIS_URI=
REDIS_PASSWORD=
LOG_CHANNEL=
BOT_TOKEN=

# [OPTIONAL]

LOG_CHANNEL=
BOT_TOKEN=
MONGO=
PMLOGGROUP=
GOOGLEAPI=
32 changes: 23 additions & 9 deletions assistant/callbackstuffs.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,10 @@ def text_to_url(event):
[Button.inline("Remove.bg API", data="abs_rmbg")],
[Button.inline("DEEP API", data="abs_dapi")],
[Button.inline("OpenAI API", data="abs_openapi")],
[Button.inline("🌀ʊʄ⊕ք🌀 API", data="abs_uapi")],
[Button.inline("OCR API", data="abs_oapi")],
[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,13 +196,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.",
"back": "cbs_apiset",
},
"uapi": {
"var": "UFOPAPI",
"name": "UFoP API Key",
"text": "Contact 🌀ʊʄ⊕ք🌀 or Visit @PerthUnity_Bot Support Group\n\n /cancel to cancel",
"text": "Get Your Deep Api from deepai.org and send here.\n\n /cancel to cancel",
"back": "cbs_apiset",
},
"openapi": {
Expand All @@ -212,7 +208,25 @@ 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",
},
"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
7 changes: 3 additions & 4 deletions pyUltroid/fns/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
Repo = None


import asyncio
import multiprocessing
from concurrent.futures import ThreadPoolExecutor
from functools import partial, wraps
Expand Down Expand Up @@ -97,7 +96,7 @@ def inline_mention(user, custom=None, html=False):
return mention_text

async def check_reply_to(event):
replytoIDS = [event.client.me.id]
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
):
Expand All @@ -107,11 +106,11 @@ async def check_reply_to(event):
)
if replied_message.from_id:
user_id = replied_message.from_id.user_id
if user_id in replytoIDS:
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 replytoIDS:
if channel_id in truai:
return True
# If neither user_id nor channel_id is in truai, return False
return False
Expand Down
Loading