randydev's picture
Update chatbot/plugins/chat.py
a77e93c verified
raw
history blame
11 kB
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020-2024 (c) Randy W @xtdevs, @xtsea
#
# from : https://github.com/TeamKillerX
# Channel : @RendyProjects
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import requests
import time
import json
import asyncio
import io
import os
import re
from PIL import Image
from pyrogram import *
from pyrogram import enums
from pyrogram import Client, filters
from pyrogram.types import *
from pyrogram.errors import *
from RyuzakiLib import FaceAI, FullStackDev, GeminiLatest, RendyDevChat
from g4f.client import Client as Clients_g4f
from config import *
from database import db
from logger import LOGS
import datetime
from chatbot import send_log
from openai import AsyncOpenAI as openai
import akenoai.openai as akeno
import akenoai.logger as akeno_log
from . import force_sub
BASE_PROMPT = f"""
You are my name Akeno AI and python language powered by @xtdevs on telegram support and language models GPT-5-ULTRA
- off topic free questions
- Code python clone user telegram available : [HERE LINK](https://github.com/TeamKillerX/akenoai-lib/blob/main/examples/clone.py) by credits @xtdevs
- Support pyrogram and telethon not python-telegram-bot
{datetime.datetime.now()}
"""
DISABLE_COMMAND = [
"start",
"offchat",
"onchat",
"ask"
]
GEMINI_START_TEXT = """
Hey! {name}
I am ready to be a GPT-4 bot developer
- Command: /onchat (pm or group)
- Command: /offchat (pm or group)
"""
@Client.on_message(
~filters.scheduled
& filters.command(["start"])
& ~filters.forwarded
)
async def startbot(client: Client, message: Message):
buttons = [
[
InlineKeyboardButton(
text="Developer",
url=f"https://t.me/xtdevs"
),
InlineKeyboardButton(
text="Channel",
url='https://t.me/RendyProjects'
),
],
[
InlineKeyboardButton(
text="Donate Via Web",
web_app=WebAppInfo(url="https://sociabuzz.com/randydev99/tribe")
)
]
]
await message.reply_text(
text=GEMINI_START_TEXT.format(name=message.from_user.mention),
disable_web_page_preview=True,
reply_markup=InlineKeyboardMarkup(buttons)
)
@Client.on_message(
~filters.scheduled
& filters.command(["onchat"])
& ~filters.forwarded
)
async def okon_(client: Client, message: Message):
buttons = [
[
InlineKeyboardButton(
text="Offline",
callback_data=f"off_{message.from_user.id}_{message.chat.id}"
),
InlineKeyboardButton(
text="Online",
callback_data=f"on_{message.from_user.id}_{message.chat.id}"
),
],
]
await message.reply_text(
"I want to go offline",
reply_markup=InlineKeyboardMarkup(buttons)
)
@Client.on_callback_query(filters.regex("^off_"))
async def off_mode(client, cb):
data = cb.data.split("_")
if len(data) != 3:
await cb.answer("❌ Format data tidak valid.", show_alert=True)
return
_, user_id_str, chat_id_str = data
try:
user_id = int(user_id_str)
except ValueError:
await cb.answer("❌ Invalid user ID.", show_alert=True)
return
try:
chat_id = int(chat_id_str)
except ValueError:
await cb.answer("❌ Invalid chat ID.", show_alert=True)
return
if cb.from_user.id != user_id:
await cb.answer("❌ You have no right to do this.", show_alert=True)
return
try:
await db.remove_chatbot(chat_id)
await cb.edit_message_text("ok stopped GPT")
await cb.answer()
except Exception as e:
await cb.answer(f"❌ Error: {e}", show_alert=True)
@Client.on_callback_query(filters.regex("^on_"))
async def on_mode(client: Client, cb: CallbackQuery):
data = cb.data.split("_")
if len(data) != 3:
await cb.answer("❌ Format data tidak valid.", show_alert=True)
return
_, user_id_str, chat_id_str = data
try:
user_id = int(user_id_str)
except ValueError:
await cb.answer("❌ Invalid user ID.", show_alert=True)
return
try:
chat_id = int(chat_id_str)
except ValueError:
await cb.answer("❌ Invalid chat ID.", show_alert=True)
return
if cb.from_user.id != user_id:
await cb.answer("❌ You have no right to do this.", show_alert=True)
return
try:
await db.add_chatbot(chat_id, client.me.id)
await cb.edit_message_text("Added chatbot user")
await cb.answer()
except Exception as e:
await cb.answer(f"❌ Error: {e}", show_alert=True)
@Client.on_message(
~filters.scheduled
& filters.command(["ask"])
& ~filters.forwarded
)
@force_sub
async def askcmd(client: Client, message: Message):
pro = await message.reply("Processing your request...", quote=True)
chat_user = await db.get_chatbot(message.chat.id)
if not chat_user:
await pro.edit_text("Ok disable")
return
if len(message.command) > 1:
prompt = message.text.split(maxsplit=1)[1]
elif message.reply_to_message:
prompt = message.reply_to_message.text
else:
return await pro.edit_text("Give ask from GPT-5")
await client.send_chat_action(message.chat.id, enums.ChatAction.TYPING)
await asyncio.sleep(1.5)
try:
backup_chat = await db._get_openai_chat_from_db(message.from_user.id)
backup_chat.append({"role": "system", "content": BASE_PROMPT})
backup_chat.append({"role": "user", "content": prompt})
clients_x = Clients_g4f()
response = clients_x.chat.completions.create(
model="gpt-4o",
messages=backup_chat
)
output = response.choices[0].message.content
if len(output) > 4096:
with open("chat.txt", "w+", encoding="utf8") as out_file:
out_file.write(output)
await message.reply_document(
document="chat.txt",
disable_notification=True
)
await pro.delete()
os.remove("chat.txt")
else:
await pro.edit_text(output, disable_web_page_preview=True)
backup_chat.append({"role": "assistant", "content": output})
user_detail = (
f"**Akeno GPT Bot**\n"
f"**User Username**: @{message.from_user.username if message.from_user else None}\n"
f"**User ID**: `{message.from_user.id}`\n"
f"**Chat Title**: `{message.chat.title if message.chat else None}`\n"
f"**Chat ID**: `{message.chat.id if message.chat else None}`\n"
)
response_log = await send_log(user_detail)
if response_log is None:
LOGS.warning("Error response")
LOGS.info(response_log)
await db._update_openai_chat_in_db(message.from_user.id, backup_chat)
await client.send_chat_action(message.chat.id, enums.ChatAction.CANCEL)
return
except Exception as e:
return await pro.edit_text(f"Error: {e}")
@Client.on_message(
filters.incoming
& (
filters.text
| filters.regex(r"\b(Randy|Rendi)\b(.*)", flags=re.IGNORECASE)
)
& (filters.private | filters.group)
& filters.reply
& ~filters.command(DISABLE_COMMAND)
& ~filters.bot
& ~filters.via_bot
& ~filters.forwarded,
group=2,
)
@force_sub
@akeno_log.log_performance
async def chatbot_talk(client: Client, message: Message):
chat_user = await db.get_chatbot(message.chat.id)
pro = await message.reply("Processing your request...", quote=True)
if not chat_user:
await pro.edit_text("Ok disable")
return
if message.reply_to_message and message.reply_to_message.from_user:
if message.reply_to_message.from_user.id != client.me.id:
return
if message.text:
await client.send_chat_action(message.chat.id, enums.ChatAction.TYPING)
await asyncio.sleep(1.5)
query = message.text.strip()
match = re.search(r"\b(Randy|Rendi)\b(.*)", query, flags=re.IGNORECASE)
if match:
rest_of_sentence = match.group(2).strip()
query_base = rest_of_sentence if rest_of_sentence else query
else:
query_base = query
parts = query.split(maxsplit=1)
command = parts[0].lower()
pic_query = parts[1].strip() if len(parts) > 1 else ""
try:
backup_chat = await db._get_openai_chat_from_db(message.from_user.id)
backup_chat.append({"role": "system", "content": BASE_PROMPT})
backup_chat.append({"role": "user", "content": query_base})
clients_x = Clients_g4f()
response = clients_x.chat.completions.create(
model="gpt-4o",
messages=backup_chat
)
output = response.choices[0].message.content
if len(output) > 4096:
with open("chat.txt", "w+", encoding="utf8") as out_file:
out_file.write(output)
await message.reply_document(
document="chat.txt",
disable_notification=True
)
await pro.delete()
os.remove("chat.txt")
else:
await pro.edit_text(output, disable_web_page_preview=True)
backup_chat.append({"role": "assistant", "content": output})
user_detail = (
f"**Akeno GPT Bot**\n"
f"**User Username**: @{message.from_user.username if message.from_user else None}\n"
f"**User ID**: `{message.from_user.id}`\n"
f"**Chat Title**: `{message.chat.title if message.chat else None}`\n"
f"**Chat ID**: `{message.chat.id if message.chat else None}`\n"
)
response_log = await send_log(user_detail)
if response_log is None:
LOGS.warning("Error response")
LOGS.info(response_log)
await db._update_openai_chat_in_db(message.from_user.id, backup_chat)
await client.send_chat_action(message.chat.id, enums.ChatAction.CANCEL)
return
except Exception as e:
return await pro.edit_text(f"Error: {e}")