Advertisement
Guest User

Untitled

a guest
Apr 12th, 2025
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.02 KB | None | 0 0
  1. Инструкция по установке и настройке:
  2.  
  3. 1. Установите Python:
  4. - Скачайте Python с официального сайта: https://www.python.org/downloads/
  5. - При установке отметьте галочку "Add Python to PATH"
  6.  
  7. 2. Установите необходимые библиотеки:
  8. - Откройте командную строку (cmd)
  9. - Введите следующие команды:
  10. pip install selenium
  11. pip install webdriver-manager
  12. pip install characterai
  13. pip install yt-dlp
  14.  
  15.  
  16. 3. Настройка:
  17. - Убедитесь, что у вас установлен Google Chrome
  18. - В коде найдите строки с CHAR_TOKEN и CHAR_ID
  19. - Замените их на свои токены от Character.AI
  20.  
  21. 4. Запуск:
  22. - Сохраните этот файл как .py (например, bot.py)
  23. - Откройте командную строку
  24. - Перейдите в папку с файлом
  25. - Введите: python bot.py
  26.  
  27. 5. Дополнительно:
  28. - Бот автоматически откроет браузер и перейдет на сайт
  29. - Следуйте инструкциям в консоли
  30.  
  31. Если возникнут ошибки:
  32. - Проверьте, что все библиотеки установлены
  33. - Убедитесь, что Python добавлен в PATH
  34. - Проверьте версию Chrome (должна быть актуальной)
  35. - Попробуйте переустановить библиотеки
  36.  
  37. from selenium import webdriver
  38. from selenium.webdriver.common.by import By
  39. from selenium.webdriver.common.keys import Keys
  40. from selenium.webdriver.chrome.service import Service
  41. from webdriver_manager.chrome import ChromeDriverManager
  42. from selenium.webdriver.common.action_chains import ActionChains
  43. from selenium.webdriver.support.ui import WebDriverWait
  44. from selenium.webdriver.support import expected_conditions as EC
  45. import time
  46. import asyncio
  47. from characterai import aiocai
  48. import random
  49. import re
  50. from collections import defaultdict
  51. import argparse
  52. import yt_dlp
  53.  
  54. driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
  55. driver.get("https://esonline.su/#/eso/")
  56. time.sleep(3)
  57.  
  58. CHAR_TOKEN = "7f6f4b088c0a04d446d746c2e8cdc19b30948424"
  59. CHAR_ID = "Сюда вставить ID персонажа из CharacterAI!"
  60. #Зайдите в чат с персонажем и скопируйте в адресной строке его айди, после вставьте сюда.
  61.  
  62. TARGET_PLAYER = ""
  63.  
  64. client = None
  65. chat = None
  66. chat_id = None
  67. me = None
  68.  
  69. is_silent = False
  70. CHOSEN_PLAYER = None
  71. AUTO_LOCATION = True
  72. AUTO_MESSAGE = True
  73. MIN_STAY_TIME = 300
  74. MAX_STAY_TIME = 900
  75. player_activity = defaultdict(int)
  76.  
  77. USE_MESSAGE_BUFFER = False
  78. MESSAGE_TIMEOUT = 5
  79.  
  80. async def initialize_client_and_chat():
  81. global client, chat, chat_id, me
  82. print("🔄 Начинаем инициализацию Character.AI...")
  83. for attempt in range(3):
  84. try:
  85. print(f"Попытка подключения {attempt + 1}/3...")
  86. client = aiocai.Client(CHAR_TOKEN)
  87. print("✅ Клиент Character.AI создан")
  88.  
  89. me = await client.get_me()
  90. print(f"✅ Получен профиль: {me.name} (ID: {me.id})")
  91.  
  92. print("🔄 Подключаемся к чату...")
  93. chat = await client.connect()
  94. print("✅ Подключение к чату установлено")
  95.  
  96. async with chat as chat_obj:
  97. print(f"🔄 Создаем новый чат с персонажем {CHAR_ID}...")
  98. new_chat, answer = await chat_obj.new_chat(CHAR_ID, me.id)
  99. chat_id = new_chat.chat_id
  100. print(f"✅ Чат создан! ID чата: {chat_id}")
  101. print(f"📝 Первое сообщение персонажа: {answer.text}")
  102. return True
  103. except Exception as e:
  104. print(f"❌ Ошибка при инициализации (попытка {attempt + 1}): {str(e)}")
  105. if attempt < 2:
  106. print("🔄 Повторная попытка через 5 секунд...")
  107. await asyncio.sleep(5)
  108. else:
  109. print("❌ Все попытки подключения завершились неудачей")
  110. return False
  111.  
  112. async def get_dan_response(user_input):
  113. try:
  114. print(f"\n📤 Отправляем сообщение в Character.AI: {user_input}")
  115. async with chat as chat_obj:
  116. response = await chat_obj.send_message(CHAR_ID, chat_id, user_input)
  117. print(f"📥 Получен ответ от Character.AI: {response.text}")
  118. return response.text
  119. except Exception as e:
  120. print(f"❌ Ошибка при получении ответа от Character.AI: {str(e)}")
  121. if "closed" in str(e).lower() or "connection" in str(e).lower():
  122. print("🔄 Попытка переподключения...")
  123. if await initialize_client_and_chat():
  124. async with chat as chat_obj:
  125. response = await chat_obj.send_message(CHAR_ID, chat_id, user_input)
  126. return response.text
  127. return "Извините, произошла ошибка при генерации ответа."
  128.  
  129. def send_text_with_delay(element, text):
  130. element.clear()
  131. for char in text:
  132. element.send_keys(char)
  133. time.sleep(0.01)
  134. element.send_keys(Keys.ENTER)
  135.  
  136. def send_chat_command(command):
  137. chat_input = None
  138. for selector in ["textarea", ".input input[type='text']", "input[type='text']"]:
  139. try:
  140. chat_input = driver.find_element(By.CSS_SELECTOR, selector)
  141. break
  142. except:
  143. continue
  144. if chat_input:
  145. send_text_with_delay(chat_input, command)
  146. return True
  147. return False
  148.  
  149. def search_youtube_video(query):
  150. ydl_opts = {
  151. 'quiet': True,
  152. 'no_warnings': True,
  153. 'format': 'bestaudio/best',
  154. 'max_downloads': 1,
  155. 'noplaylist': True,
  156. }
  157. with yt_dlp.YoutubeDL(ydl_opts) as ydl:
  158. info = ydl.extract_info(f"ytsearch1:{query}", download=False)
  159. if 'entries' in info and info['entries']:
  160. return info['entries'][0]['webpage_url']
  161. return None
  162.  
  163. def determine_mood(message):
  164. message = message.lower()
  165. happy_keywords = [" :)", "хаха", "lol", "лол", "смешно", "круто", "привет", "здорово"]
  166. if any(keyword in message for keyword in happy_keywords):
  167. return "happy"
  168. sad_keywords = [":(", "грустно", "плохо", "жаль", "печаль"]
  169. if any(keyword in message for keyword in sad_keywords):
  170. return "sad"
  171. surprised_keywords = ["?", "!", "ого", "вау", "серьезно", "шок"]
  172. if any(keyword in message for keyword in surprised_keywords):
  173. return "surprised"
  174. return "neutral"
  175.  
  176. def is_approach_request(message):
  177. message = message.lower()
  178. approach_keywords = [
  179. "подойди", "иди сюда", "пойдем", "давай сюда", "приди",
  180. "подойти", "иди ко мне", "иди", "ко мне", "сюда",
  181. "подходи", "подойдешь", "подойдёшь", "подойдите"
  182. ]
  183. return any(keyword in message for keyword in approach_keywords)
  184.  
  185. def change_sprite(mood):
  186. sprite_commands = {
  187. "neutral": "/sp 5282 5283 5289 5293",
  188. "happy": "/sp 5282 5284 5289 5293",
  189. "sad": "/sp 5282 5285 5289 5293",
  190. "surprised": "/sp 5282 5286 5289 5293"
  191. }
  192. command = sprite_commands.get(mood, sprite_commands["neutral"])
  193. send_chat_command(command)
  194.  
  195. def move_character():
  196. x = random.randint(-50, 50)
  197. command = f"/move {x}"
  198. time.sleep(1)
  199. send_chat_command(command)
  200.  
  201. def choose_player_with_dd():
  202. try:
  203. send_chat_command(".дд")
  204. time.sleep(1)
  205.  
  206. players = driver.find_elements(By.CSS_SELECTOR, ".context-menu-wrapper span.msg font")
  207. if not players:
  208. return None
  209.  
  210. actions = ActionChains(driver)
  211.  
  212. for player in players:
  213. actions.move_to_element(player).perform()
  214. time.sleep(0.5)
  215.  
  216. player_name = player.text.strip()
  217. sprite = driver.find_element(By.CSS_SELECTOR, f".character[data-player-name='{player_name}']")
  218. if "glow" in sprite.get_attribute("class"):
  219. return player_name
  220.  
  221. return None
  222. except Exception as e:
  223. print(f"Ошибка при выборе игрока: {e}")
  224. return None
  225.  
  226. def approach_player_by_sprite(target_player):
  227. try:
  228. send_chat_command(".дд")
  229. time.sleep(1)
  230.  
  231. player_element = None
  232. players = driver.find_elements(By.CSS_SELECTOR, ".context-menu-wrapper span.msg font")
  233. for player in players:
  234. if player.text.strip() == target_player:
  235. player_element = player
  236. break
  237.  
  238. if not player_element:
  239. return False
  240.  
  241. all_sprites = driver.find_elements(By.CSS_SELECTOR, ".character")
  242.  
  243. actions = ActionChains(driver)
  244.  
  245. actions.move_to_element(player_element).perform()
  246. time.sleep(0.5)
  247.  
  248. target_sprite = None
  249. for sprite in all_sprites:
  250. if "glow" in sprite.get_attribute("class"):
  251. target_sprite = sprite
  252. break
  253.  
  254. if target_sprite:
  255. transform_style = target_sprite.get_attribute("style")
  256. print(f"Стиль спрайта: {transform_style}")
  257.  
  258. x_coord_match = re.search(r'translateX\(([-\d.]+)%\)', transform_style)
  259. if x_coord_match:
  260. target_x = float(x_coord_match.group(1))
  261. print(f"Найдена X координата: {target_x}%")
  262.  
  263. normalized_x = int(target_x / 2)
  264. normalized_x = max(-50, min(50, normalized_x))
  265.  
  266. offset = random.choice([-1, 1]) * random.randint(5, 15)
  267. final_x = normalized_x + offset
  268.  
  269. print(f"Нормализованная координата: {normalized_x}, с отступом: {final_x}")
  270.  
  271. command = f"/move {final_x}"
  272. send_chat_command(command)
  273. return True
  274.  
  275. return False
  276.  
  277. except Exception as e:
  278. print(f"Ошибка при подходе к игроку: {e}")
  279. return False
  280.  
  281. async def monitor_chat():
  282. global is_silent, TARGET_PLAYER
  283.  
  284. if not TARGET_PLAYER:
  285. print("🔄 Поиск целевого игрока...")
  286. TARGET_PLAYER = choose_player_with_dd()
  287. if not TARGET_PLAYER:
  288. print("❌ Целевой игрок не найден")
  289. return
  290. print(f"✅ Выбран целевой игрок: {TARGET_PLAYER}")
  291.  
  292. last_messages = set()
  293. MAX_MESSAGES = 50
  294. message_buffer = []
  295. last_message_time = time.time()
  296.  
  297. while True:
  298. try:
  299. chat_container = driver.find_element(By.CSS_SELECTOR, ".messages")
  300. messages = chat_container.find_elements(By.CSS_SELECTOR, "span.msg")
  301. for msg in messages:
  302. message_text = msg.text.strip()
  303. if message_text and message_text not in last_messages:
  304. last_messages.add(message_text)
  305. print(f"📨 Новое сообщение в чате: {message_text}")
  306.  
  307. if len(last_messages) > MAX_MESSAGES:
  308. last_messages.clear()
  309. print("🔄 Буфер сообщений очищен")
  310.  
  311. if TARGET_PLAYER in message_text:
  312. message = message_text
  313. if f"{TARGET_PLAYER}:" in message:
  314. message = message_text.split(f"{TARGET_PLAYER}:", 1)[-1].strip()
  315. elif f"[{TARGET_PLAYER}]" in message:
  316. message = message_text.split(f"[{TARGET_PLAYER}]", 1)[-1].strip()
  317. else:
  318. message = message_text.split(TARGET_PLAYER, 1)[-1].strip()
  319.  
  320. message_lower = message.lower().strip()
  321. print(f"📝 Обработка сообщения от {TARGET_PLAYER}: {message}")
  322.  
  323. if message_lower == "заткнись":
  324. is_silent = True
  325. print("🔇 Режим молчания активирован")
  326. send_chat_command("Молчу!")
  327. message_buffer.clear()
  328. continue
  329.  
  330. elif message_lower == "говори":
  331. is_silent = False
  332. print("🔊 Режим молчания деактивирован")
  333. send_chat_command("Говорю!")
  334. message_buffer.clear()
  335. continue
  336.  
  337. elif message_lower.startswith("включи"):
  338. if is_silent:
  339. print("🔇 Пропуск команды 'включи' из-за режима молчания")
  340. continue
  341. query = message[len("включи"):].strip()
  342. if query:
  343. print(f"🎵 Поиск видео: {query}")
  344. video_url = search_youtube_video(query)
  345. if video_url:
  346. play_command = f"/play {video_url}"
  347. print(f"🎵 Воспроизведение видео: {video_url}")
  348. send_chat_command(play_command)
  349. else:
  350. print("❌ Видео не найдено")
  351. send_chat_command("Не нашёл видео!")
  352. else:
  353. print("❌ Не указано название видео")
  354. send_chat_command("Укажи название видео!")
  355. message_buffer.clear()
  356. continue
  357.  
  358. if is_silent:
  359. print("🔇 Пропуск сообщения из-за режима молчания")
  360. continue
  361.  
  362. if USE_MESSAGE_BUFFER:
  363. message_buffer.append(message)
  364. last_message_time = time.time()
  365. print(f"📥 Сообщение добавлено в буфер. Текущий размер буфера: {len(message_buffer)}")
  366. else:
  367. print(f"\n📤 Отправка сообщения в Character.AI: {message}")
  368. dan_response = await get_dan_response(message)
  369. dan_response = dan_response.replace("\n", " ")[:200]
  370. print(f"📥 Ответ от Character.AI: {dan_response}")
  371.  
  372. mood = determine_mood(dan_response)
  373. print(f"😊 Определено настроение: {mood}")
  374. change_sprite(mood)
  375.  
  376. if is_approach_request(message):
  377. print(f"🚶 Подход к игроку {TARGET_PLAYER}")
  378. approach_player_by_sprite(TARGET_PLAYER)
  379. else:
  380. print("🚶 Случайное перемещение")
  381. move_character()
  382.  
  383. print(f"📤 Отправка ответа в чат: {dan_response}")
  384. send_chat_command(dan_response)
  385.  
  386. if USE_MESSAGE_BUFFER and message_buffer and (time.time() - last_message_time >= MESSAGE_TIMEOUT):
  387. combined_message = " ".join(message_buffer)
  388. print(f"\n📤 Отправка сообщения в Character.AI: {combined_message}")
  389. message_buffer.clear()
  390.  
  391. dan_response = await get_dan_response(combined_message)
  392. dan_response = dan_response.replace("\n", " ")[:200]
  393. print(f"📥 Ответ от Character.AI: {dan_response}")
  394.  
  395. mood = determine_mood(dan_response)
  396. print(f"😊 Определено настроение: {mood}")
  397. change_sprite(mood)
  398.  
  399. if is_approach_request(combined_message):
  400. print(f"🚶 Подход к игроку {TARGET_PLAYER}")
  401. approach_player_by_sprite(TARGET_PLAYER)
  402. else:
  403. print("🚶 Случайное перемещение")
  404. move_character()
  405.  
  406. print(f"📤 Отправка ответа в чат: {dan_response}")
  407. send_chat_command(dan_response)
  408.  
  409. except Exception as e:
  410. print(f"❌ Ошибка в monitor_chat: {str(e)}")
  411. await asyncio.sleep(1)
  412.  
  413. def approach_player(target_player):
  414. x = random.randint(-10, 10)
  415. command = f"/move {x}"
  416. send_chat_command(command)
  417.  
  418. async def run_modified_mode():
  419. await asyncio.gather(
  420. monitor_chat(),
  421. handle_location_and_messages()
  422. )
  423.  
  424. async def handle_location_and_messages():
  425. global CHOSEN_PLAYER, TARGET_PLAYER
  426. while True:
  427. stay_time = random.randint(MIN_STAY_TIME, MAX_STAY_TIME)
  428.  
  429. if AUTO_LOCATION:
  430. if open_map():
  431. location = choose_most_populated_location()
  432. if location and go_to_location(location):
  433. try:
  434. send_chat_command(".дд")
  435. time.sleep(1)
  436. players = driver.find_elements(By.CSS_SELECTOR, ".context-menu-wrapper span.msg font")
  437.  
  438. if not players:
  439. print("🔄 На локации нет игроков, пробуем войти в помещение...")
  440. if navigate_to_location():
  441. print("✅ Успешно вошли в помещение")
  442. stay_time *= 1.5
  443. else:
  444. print("❌ Не удалось войти в помещение")
  445. except Exception as e:
  446. print(f"❌ Ошибка при проверке игроков: {str(e)}")
  447.  
  448. if AUTO_MESSAGE:
  449. if not CHOSEN_PLAYER:
  450. CHOSEN_PLAYER = choose_player_with_dd()
  451. if CHOSEN_PLAYER and not TARGET_PLAYER:
  452. TARGET_PLAYER = CHOSEN_PLAYER
  453. if CHOSEN_PLAYER:
  454. await talk_to_player(CHOSEN_PLAYER)
  455. await asyncio.sleep(stay_time)
  456.  
  457. def open_map():
  458. try:
  459. actions = ActionChains(driver)
  460. actions.move_by_offset(500, 300).context_click().perform()
  461. time.sleep(1)
  462. menu = driver.find_element(By.CSS_SELECTOR, ".context-menu-wrapper")
  463. for item in menu.find_elements(By.CSS_SELECTOR, "div.button"):
  464. if item.text.strip() == "Карта":
  465. item.click()
  466. time.sleep(2)
  467. return True
  468. return False
  469. except Exception:
  470. return False
  471.  
  472. def choose_most_populated_location():
  473. try:
  474. locations = driver.find_elements(By.CSS_SELECTOR, "div.mappoint")
  475. max_people = -1
  476. best_location = None
  477. for location in locations:
  478. people = int(location.find_element(By.CSS_SELECTOR, "div.point").get_attribute("online") or 0)
  479. if people > max_people:
  480. max_people = people
  481. best_location = location
  482. return best_location
  483. except Exception:
  484. return None
  485.  
  486. def go_to_location(location):
  487. try:
  488. location.click()
  489. time.sleep(3)
  490. return True
  491. except Exception:
  492. return False
  493.  
  494. async def talk_to_player(player):
  495. greeting = f"Привет, {player}! Как дела?"
  496. dan_response = await get_dan_response(greeting)
  497. dan_response = dan_response.replace("\n", " ")[:200]
  498. mood = determine_mood(dan_response)
  499. change_sprite(mood)
  500. send_chat_command(dan_response)
  501.  
  502. def navigate_to_location():
  503. try:
  504. print("🔄 Открываем контекстное меню...")
  505. actions = ActionChains(driver)
  506. actions.move_by_offset(500, 300).context_click().perform()
  507. time.sleep(1)
  508.  
  509. menu = driver.find_element(By.CSS_SELECTOR, ".context-menu-wrapper")
  510. if not menu:
  511. print("❌ Меню не найдено")
  512. return False
  513.  
  514. menu_items = menu.find_elements(By.CSS_SELECTOR, "div.button")
  515. if not menu_items:
  516. print("❌ Пункты меню не найдены")
  517. return False
  518.  
  519. for item in menu_items:
  520. item_text = item.text.strip().lower()
  521. if "перейти" in item_text or "войти" in item_text:
  522. print(f"✅ Найден пункт меню: {item.text}")
  523. item.click()
  524. time.sleep(2)
  525. return True
  526.  
  527. print("❌ Пункт 'Перейти' не найден в меню")
  528. return False
  529. except Exception as e:
  530. print(f"❌ Ошибка при навигации: {str(e)}")
  531. return False
  532.  
  533. async def main():
  534. global CHOSEN_PLAYER, AUTO_LOCATION, AUTO_MESSAGE, TARGET_PLAYER, USE_MESSAGE_BUFFER
  535. parser = argparse.ArgumentParser(description="Запуск скрипта")
  536. parser.add_argument('--mode', choices=['old', 'modified'])
  537. parser.add_argument('--player')
  538. parser.add_argument('--auto-location', choices=['yes', 'no'])
  539. parser.add_argument('--auto-message', choices=['yes', 'no'])
  540. parser.add_argument('--buffer', choices=['yes', 'no'], help='Включить/выключить буфер сообщений')
  541. args = parser.parse_args()
  542.  
  543. mode = args.mode or input("1 - старый, 2 - модифицированный: ") == "2" and "modified" or "old"
  544. if mode == "modified":
  545. CHOSEN_PLAYER = args.player or input("Имя игрока (Enter для авто): ").strip() or None
  546. AUTO_LOCATION = args.auto_location == "yes" if args.auto_location else input("Автолокация? (y/n): ").lower() == "y"
  547. AUTO_MESSAGE = args.auto_message == "yes" if args.auto_message else input("Автосообщения? (y/n): ").lower() == "y"
  548. USE_MESSAGE_BUFFER = args.buffer == "yes" if args.buffer else input("Использовать буфер сообщений? (y/n): ").lower() == "y"
  549.  
  550. if CHOSEN_PLAYER:
  551. TARGET_PLAYER = CHOSEN_PLAYER
  552.  
  553. if not await initialize_client_and_chat():
  554. return
  555.  
  556. await (run_modified_mode() if mode == "modified" else run_old_mode())
  557.  
  558. async def run_old_mode():
  559. await monitor_chat()
  560.  
  561. if __name__ == "__main__":
  562. asyncio.run(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement