File size: 10,909 Bytes
732fabe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20b2672
732fabe
 
4f931f3
732fabe
1fc4fa4
 
732fabe
 
 
4bdfc4c
732fabe
4bdfc4c
 
 
732fabe
 
 
de7e62a
 
 
bd49c1e
 
de7e62a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
732fabe
 
41c5f07
732fabe
 
41c5f07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
732fabe
d5c0a21
 
 
 
 
239392a
bd49c1e
 
 
d5c0a21
 
bd49c1e
 
 
 
 
 
d5c0a21
 
 
 
 
bd49c1e
d5c0a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
732fabe
 
 
 
 
 
 
bd49c1e
47d83a8
732fabe
 
 
 
 
1fc4fa4
afd5448
732fabe
 
 
 
 
 
 
 
4f931f3
732fabe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f931f3
732fabe
 
2ce2a62
732fabe
f27d1f9
 
 
 
 
 
 
1ce619d
f27d1f9
 
 
732fabe
 
 
 
4f931f3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/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 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:
        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})
        response = await akeno.OpenAI.run(
            ...,
            openai_meta=openai,
            model="gpt-4o-mini-2024-07-18",
            messages=backup_chat
        )
        output = response
        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)
    if not chat_user:
        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:
        pro = await message.reply("Processing your request...", quote=True)
        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})
            response = await akeno.OpenAI.run(
                ...,
                openai_meta=openai,
                model="gpt-4o-mini-2024-07-18",
                messages=backup_chat
            )
            output = response
            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}")