from appium import webdriver
 
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.support import expected_conditions as EC
import time
 
desired_caps = {
    "platformName": "Android",  
    "platformVersion": "10.0",  
    "deviceName": "b68548ed",  
    "appPackage": "com.tencent.mm",  
    "appActivity": ".ui.LauncherUI",  
    'unicodeKeyboard': True,  
    'noReset': True  
}
 
 
def is_element_exist(driver, by, value):
    try:
        driver.find_element(by=by, value=value)
    except Exception as e:
        return False
    else:
        return True
 
 
 
def del_red_envelope(wait, driver):
    
    r8 = wait.until(EC.element_to_be_clickable(
        (By.ID, "com.tencent.mm:id/ahs")))
    TouchAction(driver).long_press(r8).perform()
    time.sleep(1)
    
    wait.until(EC.element_to_be_clickable(
        (By.ID, "com.tencent.mm:id/dt5"))).click()
    
    wait.until(EC.element_to_be_clickable(
        (By.ID, "com.tencent.mm:id/ffp"))).click()
 
 
def del_red_public(wait, driver):
    
    r8 = wait.until(EC.element_to_be_clickable(
        (By.ID, "com.tencent.mm:id/fzg")))
    TouchAction(driver).long_press(r8).perform()
    time.sleep(1)
    
    wait.until(EC.element_to_be_clickable((By.XPATH, "//android.widget.TextView[@text='不显示该聊天']"))).click()
    
    wait.until(EC.element_to_be_clickable(
        (By.ID, "com.tencent.mm:id/ffp"))).click()
 
 
if __name__ == '__main__':
    
    wait = WebDriverWait(driver, 500)
 
    while True:
    
        g73 = wait.until(EC.element_to_be_clickable(
            (By.ID, "com.tencent.mm:id/fzg")))
        g73.click()
        print("进入了第一个聊天窗口")
        
        is_weichat = is_element_exist(driver, "id", "com.tencent.mm:id/u1")
        if is_weichat == True:
        
            
            wait.until(EC.element_to_be_clickable(
                (By.ID, "com.tencent.mm:id/u1"))).click()
            print("点击了红包")
            
            is_open = is_element_exist(driver, "id", "com.tencent.mm:id/f4f")
            print("红包是否被领取:", is_open)
            if is_open == True:
                
                wait.until(EC.element_to_be_clickable(
                    (By.ID, "com.tencent.mm:id/f4f"))).click()
                print('已经领取红包')
                
                driver.keyevent(4)
                
                del_red_envelope(wait, driver)
                print('···删除已经领取的红包,等待新的红包')
                driver.keyevent(4)
            else:
                
                driver.keyevent(4)
                
                del_red_envelope(wait, driver)
                print('···删除无法领取的红包,等待新的红包')
                driver.keyevent(4)
 
        else:
            print('没有红包则隐藏此聊天框')
            
            driver.keyevent(4)
            
            del_red_public(wait, driver)
            print('隐藏了第一个聊天框')