randydev commited on
Commit
b46c083
1 Parent(s): c088675

Upload chat.py

Browse files
Files changed (1) hide show
  1. chatbot/plugins/chat.py +23 -295
chatbot/plugins/chat.py CHANGED
@@ -17,98 +17,41 @@
17
  # You should have received a copy of the GNU Affero General Public License
18
  # along with this program. If not, see <https://www.gnu.org/licenses/>.
19
 
20
- import requests
21
- import time
22
- import json
23
- import asyncio
24
- import io
25
- import os
26
- import re
27
- import aiohttp
28
- from PIL import Image
29
-
30
  from pyrogram import *
31
  from pyrogram import enums
32
  from pyrogram import Client, filters
33
  from pyrogram.types import *
34
  from pyrogram.errors import *
35
- from RyuzakiLib import FaceAI, FullStackDev, GeminiLatest, RendyDevChat
36
- from g4f.client import Client as Clients_g4f
37
  from config import *
38
 
39
  from database import db
40
  from logger import LOGS
41
  import datetime
42
- from chatbot import send_log
43
- from openai import AsyncOpenAI as openai
44
- import akenoai.openai as akeno
45
- import akenoai.logger as akeno_log
46
 
 
47
  from chatbot.plugins.user_database import users_collection
48
  from chatbot.plugins.keyboards import get_language_keyboard
49
  from chatbot.plugins.languages import LANGUAGES
50
 
51
  from . import force_sub
52
 
53
-
54
- BASE_PROMPT = f"""
55
- You are my name Akeno AI and python language powered by @xtdevs on telegram support and language models GPT-5-ULTRA
56
-
57
- - off topic free questions
58
- - Code python clone user telegram available : [HERE LINK](https://github.com/TeamKillerX/akenoai-lib/blob/main/examples/clone.py) by credits @xtdevs
59
- - Support pyrogram and telethon not python-telegram-bot
60
-
61
- {datetime.datetime.now()}
62
- """
63
-
64
- NOT_ALLOWED_NON_PROGRAMMER = [
65
- 466019692, # @myexcid,
66
- 1423479724, # tonic,
67
- 883761960, # ari
68
- 6824458358, # None
69
- 1982318761, # paman
70
- 6477856957, # test
71
- 5575183435, #suku
72
- 948247711, # akay
73
- ]
74
-
75
-
76
- DISABLE_COMMAND = [
77
- "start",
78
- "offchat",
79
- "onchat",
80
- "ask"
81
- ]
82
-
83
- LANGUAGES_DEFAULT = "en"
84
-
85
- async def translate(text, target_lang):
86
- API_URL = "https://translate.googleapis.com/translate_a/single"
87
- HEADERS = {"User-Agent": "Mozilla/5.0"}
88
- params = {
89
- "client": "gtx",
90
- "sl": "auto",
91
- "tl": target_lang,
92
- "dt": "t",
93
- "q": text,
94
- }
95
- async with aiohttp.ClientSession() as session:
96
- async with session.post(API_URL, headers=HEADERS, params=params) as response:
97
- if response.status == 200:
98
- translation = await response.json()
99
- translated_text = "".join([item[0] for item in translation[0]])
100
- return translated_text
101
- else:
102
- return None
103
-
104
- GEMINI_START_TEXT = """
105
- Hey! {name}
106
-
107
- I am ready to be a GPT-4 bot developer
108
-
109
- - Command: /onchat (pm or group)
110
- - Command: /offchat (pm or group)
111
- """
112
 
113
  @Client.on_message(
114
  ~filters.scheduled
@@ -116,8 +59,6 @@ I am ready to be a GPT-4 bot developer
116
  & ~filters.forwarded
117
  )
118
  async def startbot(client: Client, message: Message):
119
- if message.from_user.id in NOT_ALLOWED_NON_PROGRAMMER:
120
- return
121
  buttons = [
122
  [
123
  InlineKeyboardButton(
@@ -128,98 +69,14 @@ async def startbot(client: Client, message: Message):
128
  text="Channel",
129
  url='https://t.me/RendyProjects'
130
  ),
131
- ],
132
- [
133
- InlineKeyboardButton(
134
- text="Donate Via Web",
135
- web_app=WebAppInfo(url="https://sociabuzz.com/randydev99/tribe")
136
- )
137
  ]
138
  ]
139
  await message.reply_text(
140
- text=GEMINI_START_TEXT.format(name=message.from_user.mention),
141
  disable_web_page_preview=True,
142
  reply_markup=InlineKeyboardMarkup(buttons)
143
  )
144
 
145
- @Client.on_message(
146
- ~filters.scheduled
147
- & filters.command(["onchat"])
148
- & ~filters.forwarded
149
- )
150
- async def okon_(client: Client, message: Message):
151
- if message.from_user.id in NOT_ALLOWED_NON_PROGRAMMER:
152
- return
153
- buttons = [
154
- [
155
- InlineKeyboardButton(
156
- text="Offline",
157
- callback_data=f"off_{message.from_user.id}_{message.chat.id}"
158
- ),
159
- InlineKeyboardButton(
160
- text="Online",
161
- callback_data=f"on_{message.from_user.id}_{message.chat.id}"
162
- ),
163
- ],
164
- ]
165
- await message.reply_text(
166
- "I want to go offline",
167
- reply_markup=InlineKeyboardMarkup(buttons)
168
- )
169
-
170
- @Client.on_callback_query(filters.regex("^off_"))
171
- async def off_mode(client, cb):
172
- data = cb.data.split("_")
173
- if len(data) != 3:
174
- await cb.answer("❌ Format data tidak valid.", show_alert=True)
175
- return
176
- _, user_id_str, chat_id_str = data
177
- try:
178
- user_id = int(user_id_str)
179
- except ValueError:
180
- await cb.answer("❌ Invalid user ID.", show_alert=True)
181
- return
182
- try:
183
- chat_id = int(chat_id_str)
184
- except ValueError:
185
- await cb.answer("❌ Invalid chat ID.", show_alert=True)
186
- return
187
- if cb.from_user.id != user_id:
188
- await cb.answer("❌ You have no right to do this.", show_alert=True)
189
- return
190
- try:
191
- await db.remove_chatbot(chat_id)
192
- await cb.edit_message_text("ok stopped GPT")
193
- await cb.answer()
194
- except Exception as e:
195
- await cb.answer(f"❌ Error: {e}", show_alert=True)
196
-
197
- @Client.on_callback_query(filters.regex("^on_"))
198
- async def on_mode(client: Client, cb: CallbackQuery):
199
- data = cb.data.split("_")
200
- if len(data) != 3:
201
- await cb.answer("❌ Format data tidak valid.", show_alert=True)
202
- return
203
- _, user_id_str, chat_id_str = data
204
- try:
205
- user_id = int(user_id_str)
206
- except ValueError:
207
- await cb.answer("❌ Invalid user ID.", show_alert=True)
208
- return
209
- try:
210
- chat_id = int(chat_id_str)
211
- except ValueError:
212
- await cb.answer("❌ Invalid chat ID.", show_alert=True)
213
- return
214
- if cb.from_user.id != user_id:
215
- await cb.answer("❌ You have no right to do this.", show_alert=True)
216
- return
217
- try:
218
- await db.add_chatbot(chat_id, client.me.id)
219
- await cb.edit_message_text("Added chatbot user")
220
- await cb.answer()
221
- except Exception as e:
222
- await cb.answer(f"❌ Error: {e}", show_alert=True)
223
 
224
  @Client.on_message(
225
  ~filters.scheduled
@@ -228,35 +85,16 @@ async def on_mode(client: Client, cb: CallbackQuery):
228
  )
229
  @force_sub
230
  async def askcmd(client: Client, message: Message):
231
- if message.from_user.id in NOT_ALLOWED_NON_PROGRAMMER:
232
- return
233
- pro = await message.reply("Processing your request...", quote=True)
234
- chat_user = await db.get_chatbot(message.chat.id)
235
- user_id = message.from_user.id
236
- user = await users_collection.find_one({"user_id": user_id})
237
- lang = user.get("language") if user else LANGUAGES_DEFAULT
238
- if not chat_user:
239
- await pro.edit_text("Ok disable")
240
- return
241
  if len(message.command) > 1:
242
  prompt = message.text.split(maxsplit=1)[1]
243
  elif message.reply_to_message:
244
  prompt = message.reply_to_message.text
245
  else:
246
- return await pro.edit_text("Give ask from GPT-5")
247
  await client.send_chat_action(message.chat.id, enums.ChatAction.TYPING)
248
  await asyncio.sleep(1.5)
249
  try:
250
- backup_chat = await db._get_openai_chat_from_db(message.from_user.id)
251
- backup_chat.append({"role": "system", "content": BASE_PROMPT})
252
- backup_chat.append({"role": "user", "content": prompt})
253
- response = await akeno.OpenAI.run(
254
- ...,
255
- openai_meta=openai,
256
- model="gpt-4o-mini-2024-07-18",
257
- messages=backup_chat
258
- )
259
- output = response
260
  if len(output) > 4096:
261
  with open("chat.txt", "w+", encoding="utf8") as out_file:
262
  out_file.write(output)
@@ -267,118 +105,8 @@ async def askcmd(client: Client, message: Message):
267
  await pro.delete()
268
  os.remove("chat.txt")
269
  else:
270
- await pro.edit_text(output, disable_web_page_preview=True)
271
- backup_chat.append({"role": "assistant", "content": output})
272
- user_detail = (
273
- f"**Akeno GPT Bot**\n"
274
- f"**User Username**: @{message.from_user.username if message.from_user else None}\n"
275
- f"**User ID**: `{message.from_user.id}`\n"
276
- f"**Chat Title**: `{message.chat.title if message.chat else None}`\n"
277
- f"**Chat ID**: `{message.chat.id if message.chat else None}`\n"
278
- )
279
- response_log = await send_log(user_detail)
280
- if response_log is None:
281
- LOGS.warning("Error response")
282
- LOGS.info(response_log)
283
- await db._update_openai_chat_in_db(message.from_user.id, backup_chat)
284
  await client.send_chat_action(message.chat.id, enums.ChatAction.CANCEL)
285
  return
286
  except Exception as e:
287
- return await pro.edit_text(f"Error: {e}")
288
-
289
- @Client.on_message(
290
- filters.incoming
291
- & (
292
- filters.text
293
- | filters.regex(r"\b(Randy|Rendi)\b(.*)", flags=re.IGNORECASE)
294
- )
295
- & (filters.private | filters.group | filters.business)
296
- & filters.reply
297
- & ~filters.command(DISABLE_COMMAND)
298
- & ~filters.bot
299
- & ~filters.via_bot
300
- & ~filters.forwarded,
301
- group=2,
302
- )
303
- @force_sub
304
- @akeno_log.log_performance
305
- async def chatbot_talk(client: Client, message: Message):
306
- if message.from_user.id in NOT_ALLOWED_NON_PROGRAMMER:
307
- return
308
- chat_user = await db.get_chatbot(message.chat.id)
309
- user_id = message.from_user.id
310
- user = await users_collection.find_one({"user_id": user_id})
311
- lang = user.get("language") if user else LANGUAGES_DEFAULT
312
- if not chat_user:
313
- await message.reply_text("Ok disable")
314
- return
315
- if message.reply_to_message and message.reply_to_message.from_user:
316
- if message.reply_to_message.from_user.id != client.me.id:
317
- return
318
- if message.text:
319
- await client.send_chat_action(
320
- message.chat.id,
321
- enums.ChatAction.TYPING,
322
- business_connection_id=message.business_connection_id if message else None,
323
- )
324
- await asyncio.sleep(1.5)
325
- query = message.text.strip()
326
- match = re.search(r"\b(Randy|Rendi)\b(.*)", query, flags=re.IGNORECASE)
327
- if match:
328
- rest_of_sentence = match.group(2).strip()
329
- query_base = rest_of_sentence if rest_of_sentence else query
330
- else:
331
- query_base = query
332
- parts = query.split(maxsplit=1)
333
- command = parts[0].lower()
334
- pic_query = parts[1].strip() if len(parts) > 1 else ""
335
- try:
336
- backup_chat = await db._get_openai_chat_from_db(message.from_user.id)
337
- backup_chat.append({"role": "system", "content": BASE_PROMPT})
338
- backup_chat.append({"role": "user", "content": query_base})
339
- response = await akeno.OpenAI.run(
340
- ...,
341
- openai_meta=openai,
342
- model="gpt-4o-mini-2024-07-18",
343
- messages=backup_chat
344
- )
345
- output = response
346
- if len(output) > 4096:
347
- with open("chat.txt", "w+", encoding="utf8") as out_file:
348
- out_file.write(output)
349
- await message.reply_document(
350
- document="chat.txt",
351
- business_connection_id=message.business_connection_id if message else None,
352
- disable_notification=True
353
- )
354
- os.remove("chat.txt")
355
- else:
356
- await message.reply_text(
357
- output,
358
- business_connection_id=message.business_connection_id if message else None,
359
- disable_web_page_preview=True
360
- )
361
- backup_chat.append({"role": "assistant", "content": output})
362
- user_detail = (
363
- f"**Akeno GPT Bot**\n"
364
- f"**User Username**: @{message.from_user.username if message.from_user else None}\n"
365
- f"**User ID**: `{message.from_user.id}`\n"
366
- f"**Chat Title**: `{message.chat.title if message.chat else None}`\n"
367
- f"**Chat ID**: `{message.chat.id if message.chat else None}`\n"
368
- )
369
- response_log = await send_log(user_detail)
370
- if response_log is None:
371
- LOGS.warning("Error response")
372
- LOGS.info(response_log)
373
- await db._update_openai_chat_in_db(message.from_user.id, backup_chat)
374
- await client.send_chat_action(
375
- message.chat.id,
376
- enums.ChatAction.CANCEL,
377
- business_connection_id=message.business_connection_id if message else None,
378
- )
379
- return
380
- except Exception as e:
381
- return await message.reply_text(
382
- f"Error: {e}",
383
- business_connection_id=message.business_connection_id if message else None
384
- )
 
17
  # You should have received a copy of the GNU Affero General Public License
18
  # along with this program. If not, see <https://www.gnu.org/licenses/>.
19
 
 
 
 
 
 
 
 
 
 
 
20
  from pyrogram import *
21
  from pyrogram import enums
22
  from pyrogram import Client, filters
23
  from pyrogram.types import *
24
  from pyrogram.errors import *
 
 
25
  from config import *
26
 
27
  from database import db
28
  from logger import LOGS
29
  import datetime
 
 
 
 
30
 
31
+ from huggingface_hub import InferenceClient
32
  from chatbot.plugins.user_database import users_collection
33
  from chatbot.plugins.keyboards import get_language_keyboard
34
  from chatbot.plugins.languages import LANGUAGES
35
 
36
  from . import force_sub
37
 
38
+ async def process_stream(message):
39
+ client_hf = InferenceClient(api_key=HF_KEY)
40
+ messages=[
41
+ {"role": "system", "content": f"Your name is Randy Dev. A kind and friendly AI assistant that answers in a short and concise answer.\nGive short step-by-step reasoning if required.\n\n{datetime.datetime.now()}"},
42
+ {"role": "user", "content": message}
43
+ ]
44
+ stream = client_hf.chat.completions.create(
45
+ model="mistralai/Mixtral-8x7B-Instruct-v0.1",
46
+ messages=messages,
47
+ max_tokens=500,
48
+ stream=True
49
+ )
50
+ accumulated_text = ""
51
+ for chunk in stream:
52
+ new_content = chunk.choices[0].delta.content
53
+ accumulated_text += new_content
54
+ return accumulated_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  @Client.on_message(
57
  ~filters.scheduled
 
59
  & ~filters.forwarded
60
  )
61
  async def startbot(client: Client, message: Message):
 
 
62
  buttons = [
63
  [
64
  InlineKeyboardButton(
 
69
  text="Channel",
70
  url='https://t.me/RendyProjects'
71
  ),
 
 
 
 
 
 
72
  ]
73
  ]
74
  await message.reply_text(
75
+ text="Woohoo! Welcome! I'm excited to get started as a Meta AI bot!\n\n• Command /ask hello",
76
  disable_web_page_preview=True,
77
  reply_markup=InlineKeyboardMarkup(buttons)
78
  )
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  @Client.on_message(
82
  ~filters.scheduled
 
85
  )
86
  @force_sub
87
  async def askcmd(client: Client, message: Message):
 
 
 
 
 
 
 
 
 
 
88
  if len(message.command) > 1:
89
  prompt = message.text.split(maxsplit=1)[1]
90
  elif message.reply_to_message:
91
  prompt = message.reply_to_message.text
92
  else:
93
+ return await message.reply_text("Give ask from Meta AI")
94
  await client.send_chat_action(message.chat.id, enums.ChatAction.TYPING)
95
  await asyncio.sleep(1.5)
96
  try:
97
+ output = await process_stream(prompt)
 
 
 
 
 
 
 
 
 
98
  if len(output) > 4096:
99
  with open("chat.txt", "w+", encoding="utf8") as out_file:
100
  out_file.write(output)
 
105
  await pro.delete()
106
  os.remove("chat.txt")
107
  else:
108
+ await message.reply_text(output, disable_web_page_preview=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  await client.send_chat_action(message.chat.id, enums.ChatAction.CANCEL)
110
  return
111
  except Exception as e:
112
+ return await message.reply_text(f"Error: {e}")