Advertisement
Guest User

Untitled

a guest
Jun 12th, 2023
979
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.97 KB | None | 0 0
  1. import asyncio
  2. import os
  3. import re
  4. import telebot
  5. from EdgeGPT import Chatbot, ConversationStyle
  6. from telebot.util import quick_markup
  7.  
  8. TOKEN = "token"
  9. COOKIE_PATH = './cookie.json'
  10. bot = telebot.TeleBot(TOKEN)
  11. EDGES = {}
  12. my_conversation_style = ConversationStyle.balanced
  13.  
  14. @bot.message_handler(commands=['start', 'help'])
  15. def send_welcome(message):
  16.     bot.reply_to(
  17.         message, "Введи /help для показа информации\nДля смены стилей вводи /switch и следующую приписку: \ncreative (Креативный)\nbalanced (Баланс)\nprecise (Строгий)")
  18.  
  19. @bot.message_handler(commands=['reset'])
  20. def send_reset(message):
  21.     try:
  22.         if message.from_user.id not in EDGES:
  23.             EDGES[message.from_user.id] = Chatbot(cookie_path=COOKIE_PATH)
  24.         asyncio.run(EDGES[message.from_user.id].reset())
  25.     except Exception as e:
  26.         bot.reply_to(message, "Ошибка: " + str(e), parse_mode='Markdown')
  27.     else:
  28.         bot.reply_to(message, "Очищено успешно!")
  29.  
  30. @bot.message_handler(commands=['switch'])
  31. def switch_style(message):
  32.     message_list = message.text.split(" ")
  33.     if len(message_list) > 1:
  34.         styles = {
  35.             "creative": ConversationStyle.creative,
  36.             "balanced": ConversationStyle.balanced,
  37.             "precise": ConversationStyle.precise
  38.         }
  39.         if message_list[1] in styles:
  40.             global my_conversation_style
  41.             my_conversation_style = styles[message_list[1]]
  42.             bot.reply_to(
  43.                 message, f"Текущий стиль: {message_list[1].capitalize()}")
  44.         else:
  45.             bot.reply_to(
  46.                 message, "Выберите один из параметров! (/help)")
  47.     else:
  48.         bot.reply_to(
  49.             message, "Выберите один из параметров! (/help)")
  50.  
  51. @bot.message_handler(func=lambda msg: True)
  52. def response_all(message):
  53.     message_text = ''
  54.     if message.chat.type == "private":
  55.         message_text = message.text
  56.         bot.reply_to(message, "Обработка запроса, ожидайте!")
  57.         response_list = asyncio.run(bing_chat(message_text, message))
  58.         if len(response_list[0]) > 4095:
  59.             for x in range(0, len(response_list[0]), 4095):
  60.                 bot.reply_to(
  61.                     message, response_list[0][x:x + 4095], parse_mode='Markdown', reply_markup=response_list[1])
  62.         else:
  63.             bot.reply_to(
  64.                 message, response_list[0], parse_mode='Markdown', reply_markup=response_list[1])
  65.  
  66. @bot.callback_query_handler(func=lambda msg: True)
  67. def callback_all(callback_query):
  68.     try:
  69.         response_list = asyncio.run(
  70.             bing_chat(callback_query.data, callback_query))
  71.     except Exception as e:
  72.         bot.reply_to(callback_query.message, "Ошибка: " +
  73.                      str(e), parse_mode='Markdown')
  74.     else:
  75.         if len(response_list[0]) > 4095:
  76.             for x in range(0, len(response_list[0]), 4095):
  77.                 bot.reply_to(
  78.                     callback_query.message, response_list[0][x:x +
  79.                                                              4095], parse_mode='Markdown',
  80.                     reply_markup=response_list[1])
  81.         else:
  82.             bot.reply_to(
  83.                 callback_query.message, response_list[0], parse_mode='Markdown', reply_markup=response_list[1])
  84.  
  85. async def bing_chat(message_text, message):
  86.     if message.from_user.id not in EDGES:
  87.         EDGES[message.from_user.id] = Chatbot(cookie_path=COOKIE_PATH)
  88.     response_dict = await EDGES[message.from_user.id].ask(prompt=message_text,
  89.                                                           conversation_style=my_conversation_style)
  90.  
  91.     if 'text' in response_dict['item']['messages'][1]:
  92.         response = re.sub(r'\[\^\d\^]', '',
  93.                           response_dict['item']['messages'][1]['text'])
  94.     else:
  95.         response = "Что-то не так. Пожалуйста, перезагрузите чат"
  96.  
  97.     if 'suggestedResponses' in response_dict['item']['messages'][1]:
  98.         suggested_responses = response_dict['item']['messages'][1]['suggestedResponses']
  99.         markup = quick_markup({
  100.             re.sub(r'\[\^\d\^]', '', suggested_responses[i]['text']): {
  101.                 'callback_data': suggested_responses[i]['text'].encode('utf-8')[:64].decode('utf-8', 'ignore')}
  102.             for i in range(min(len(suggested_responses), 3))
  103.         }, row_width=1)
  104.     else:
  105.         markup = quick_markup({
  106.             'Предложенных ответов нет': {'url': 'https://bing.com/chat'}
  107.         }, row_width=1)
  108.  
  109.     throttling = response_dict['item']['throttling']
  110.     if 'maxNumUserMessagesInConversation' in throttling and 'numUserMessagesInConversation' in throttling:
  111.         max_num_user_messages_in_conversation = throttling['maxNumUserMessagesInConversation']
  112.         num_user_messages_in_conversation = throttling['numUserMessagesInConversation']
  113.         response += "\n———————\n"
  114.         response += f"Контекст: {num_user_messages_in_conversation} / {max_num_user_messages_in_conversation}"
  115.  
  116.     if num_user_messages_in_conversation >= max_num_user_messages_in_conversation:
  117.         await EDGES[message.from_user.id].reset()
  118.         response += "\nКонтекст был автоматически очищен"
  119.  
  120.     attributions = response_dict['item']['messages'][1]['sourceAttributions']
  121.     if len(attributions) >= 3:
  122.         response += "\n———————\nИсточники:\n"
  123.         for i in range(3):
  124.             provider_display_name = re.sub(
  125.                 r'\[\^\d\^]', '', attributions[i]['providerDisplayName'])
  126.             see_more_url = re.sub(
  127.                 r'\[\^\d\^]', '', attributions[i]['seeMoreUrl'])
  128.             response += f"{i + 1}.[{provider_display_name}]({see_more_url})\n"
  129.  
  130.     response_list = [response, markup]
  131.     return response_list
  132.  
  133. bot.polling()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement