import uiautomator2 as u2 import time import re class ShopeeBot: def __init__(self, device_ip: str): print(f"Đang kết nối tới thiết bị {device_ip}...") self.d = u2.connect(device_ip) print("Kết nối thành công!") def get_commission_rate(self, url: str) -> str: try: # 1. Đảm bảo màn hình sáng self.d.screen_on() # 2. Khởi động lại Shopee từ đầu để tránh lỗi luồng cũ print("Khởi động Shopee...") self.d.app_start("com.shopee.vn", stop=True) time.sleep(6) # Chờ app khởi động hoàn toàn # Tắt popup quảng cáo nếu có (nhấn phím Back hoặc tìm nút Tắt) # Dùng thử phím Back 1 lần nếu có popup che màn hình self.d.press("back") time.sleep(1) # 3. Chuyển sang tab "Tôi" print("Vào tab Tôi...") if self.d(text="Tôi").exists: self.d(text="Tôi").click() else: return "Lỗi: Không tìm thấy tab 'Tôi'" time.sleep(2) # 4. Tìm và ấn "Shopee Tiếp Thị Liên Kết" print("Tìm mục Shopee Tiếp Thị Liên Kết...") # Cuộn xuống cho đến khi thấy chữ này self.d(scrollable=True).scroll.to(textContains="Tiếp Thị Liên Kết") if self.d(textContains="Tiếp Thị Liên Kết").exists: self.d(textContains="Tiếp Thị Liên Kết").click() else: return "Lỗi: Không tìm thấy mục Tiếp Thị Liên Kết" time.sleep(6) # Mục này có thể tải hơi lâu vì gọi API # 5. Ấn tab "Chuyển đổi" ở thanh menu dưới cùng print("Vào tab Chuyển đổi...") if self.d(text="Chuyển đổi").exists: self.d(text="Chuyển đổi").click() else: return "Lỗi: Không tìm thấy tab Chuyển đổi" time.sleep(2) # 6. Nhập link vào ô Text print("Nhập link sản phẩm...") # Nếu có nút "Xóa tất cả" link cũ thì xóa trước if self.d(text="Xóa tất cả").exists: self.d(text="Xóa tất cả").click() time.sleep(0.5) # Tìm ô nhập liệu (thường là EditText) edit_text = self.d(className="android.widget.EditText") if edit_text.exists: edit_text.set_text(url) else: return "Lỗi: Không tìm thấy ô nhập link" time.sleep(1) # 7. Bấm nút Chuyển Đổi màu cam print("Bấm nút Chuyển Đổi...") if self.d(text="Chuyển Đổi").exists: self.d(text="Chuyển Đổi").click() else: return "Lỗi: Không tìm thấy nút Chuyển Đổi" time.sleep(4) # Chờ Shopee convert link và hiện kết quả # 8. Lấy tỷ lệ hoa hồng print("Đang đọc tỷ lệ hoa hồng...") commission_element = self.d(textContains="Tỷ lệ hoa hồng") if commission_element.exists: text_result = commission_element.get_text() # Text có dạng "Tỷ lệ hoa hồng 10,5%" return text_result else: # Nếu không tìm thấy, dump UI ra để debug xml_dump = self.d.dump_hierarchy() with open("error_dump.xml", "w", encoding="utf-8") as f: f.write(xml_dump) return "Lỗi: Không thấy Tỷ lệ hoa hồng (Đã lưu error_dump.xml)" except Exception as e: return f"Lỗi không xác định: {str(e)}"