Ejemplo n.º 1
0
 def send_text(self, text: STRING, uid=""):
     if not uid:
         uid = self.openid
     if text.startswith("http") or text.startswith("dtxuexi"):
         login_tempid = cfg_get("addition.wechat.login_tempid", "")
         if login_tempid:
             return self.send_template(login_tempid,
                                       {"name": {
                                           "value": "用户"
                                       }}, uid, text)
     if "当前学 xi 总积分" in text:
         login_tempid = cfg_get("addition.wechat.score_tempid", "")
         if login_tempid:
             return self.send_template(login_tempid,
                                       {"score": {
                                           "value": text
                                       }}, uid, "")
     token = self.get_access_token()
     url_msg = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?'
     body = {"touser": uid, "msgtype": "text", "text": {"content": text}}
     res = requests.post(
         url=url_msg,
         params={
             'access_token': token
         },
         data=json.dumps(body, ensure_ascii=False).encode('utf-8')).json()
     print(res)
     if res["errcode"] == 40001:
         self.get_access_token(True)
         self.send_text(text, uid)
Ejemplo n.º 2
0
 def get_access_token(self, refresh=False):
     if not refresh:
         # 检查变量
         if self.token and self.token[1] > time.time():
             return self.token
         # 检查文件
         template_json_str = '''[]'''
         token_json_obj = file.get_json_data("user/wechat_token.json",
                                             template_json_str)
         if token_json_obj and token_json_obj[1] > time.time():
             self.token = token_json_obj
             return self.token
     # 获取新token
     appid = cfg_get("addition.wechat.appid", "")
     appsecret = cfg_get("addition.wechat.appsecret", "")
     url_token = 'https://api.weixin.qq.com/cgi-bin/token?'
     res = requests.get(url=url_token,
                        params={
                            "grant_type": 'client_credential',
                            'appid': appid,
                            'secret': appsecret,
                        }).json()
     token = res.get('access_token')
     expires = int(res.get('expires_in')) - 10 + time.time()
     self.token = [token, expires]
     file.save_json_data("user/wechat_token.json", self.token)
     return self.token
Ejemplo n.º 3
0
def init_global():
    """
    初始化全局变量
    """
    global nohead, islooplogin, single, scheme, pushmode, accesstoken, secret, zhuanxiang, is_init, lock, stime, tg_bot, wechat, topic
    if os.getenv('Nohead') == "True":
        nohead = True
    else:
        nohead = cfg_get("addition.Nohead", False)

    if os.getenv('islooplogin') == "True":
        islooplogin = True

    if os.getenv('Single') == "True":
        single = True

    if os.getenv('Pushmode'):
        pushmode = os.getenv('Pushmode')
    else:
        pushmode = cfg_get("addition.Pushmode", "0")

    if os.getenv("Scheme") != None:
        scheme = os.getenv("Scheme")
    # elif pushmode in ["5"]: # telegram 默认开启我们提供的
    #    scheme = 'https://techxuexi.js.org/jump/techxuexi-20211023.html?'

    if os.getenv('AccessToken'):
        accesstoken = os.getenv('AccessToken')
    else:
        if pushmode == "5":
            accesstoken = cfg_get("addition.telegram.bot_token", "")
        else:
            accesstoken = cfg_get("addition.token", "")

    if os.getenv('Secret'):
        secret = os.getenv('Secret')
    else:
        if pushmode == "5":
            secret = str(cfg_get("addition.telegram.user_id", ""))
        else:
            secret = cfg_get("addition.secret", "")

    if os.getenv("ZhuanXiang"):
        zhuanxiang = os.getenv("ZhuanXiang") == "True"
    else:
        zhuanxiang = cfg_get("parameter.zhuanxiang_nohead", False)
    if pushmode == "5":
        tg_bot = TelegarmHandler(accesstoken, secret,
                                 cfg_get("addition.telegram.proxy"))
    if pushmode == "2":
        wechat = WechatHandler()

    # pushplus topic
    topic = os.getenv('topic') if os.getenv('topic') else ''
    is_init = True
Ejemplo n.º 4
0
def send_qrbase64(qcbase64):
    """
    推送登录二维码
    """
    if pushmode == "3":
        ft = FangtangHandler(accesstoken)
        ft.ftmsgsend(qcbase64)
    elif pushmode == "4":
        push = PlusPushHandler(accesstoken, topic)
        push.ftmsgsend(qcbase64)
    elif pushmode == "5" and cfg_get("addition.telegram.send_qrimage", 0) == 1:
        img_b64decode = base64.b64decode(qcbase64[qcbase64.index(';base64,') +
                                                  8:])
        tg_bot.send_qrurl(Image.open(io.BytesIO(img_b64decode)))
    elif pushmode == "6":
        web.add_qrurl(qcbase64)
Ejemplo n.º 5
0
@bot.message_handler(commands=['v'], func=authorize)
def rep_update(message):
    bot.reply_to(message, "当前版本:v0.10.29")


def polling():
    try:
        bot.polling(non_stop=True, timeout=120)
    except Exception as e:
        print("telegtram listener reconnecting...")
    finally:  #资源回收
        gc.collect()  #资源回收
        polling()


if __name__ == '__main__':
    if os.getenv('Nohead') == "True" and pushmode == "5":
        proxy = cfg_get("addition.telegram.proxy")
        if proxy and cfg_get("addition.telegram.use_proxy", False):
            apihelper.proxy = {'http': proxy, 'https': proxy}
            apihelper.CONNECT_TIMEOUT = 120
            try:
                info = bot.get_me()  # 尝试通过代理获取信息
                info.full_name
            except Exception as e:
                apihelper.proxy = {}
                print("代理请求异常,已关闭代理:" + str(e))
        bot.send_message(master, "学xi助手上线啦,快来学xi吧")
        polling()
Ejemplo n.º 6
0
def start_learn(uid, name):
    #  0 读取版本信息
    start_time = time.time()
    nohead, lock, stime, Single = get_argv()
    print("是否无头模式:{0} {1}".format(nohead, os.getenv('Nohead')))
    cookies = user.get_cookie(uid)
    if nohead == True:
        TechXueXi_mode = "3"
    else:
        TechXueXi_mode = str(cfg_get("base.ModeType", 3))
        print("当前选择模式:" + TechXueXi_mode + "\n" + "=" * 60)

    if not name:
        user_fullname = user.get_fullname(uid)
        name = user_fullname.split('_', 1)[1]
    else:
        user_fullname = uid + "_" + name

    if not cookies or TechXueXi_mode == "0":
        msg = ""
        if name == "新用户":
            msg = "需要增加新用户,请扫码登录,否则请无视"
        else:
            msg = name + " 登录信息失效,请重新扫码"
        # print(msg)
        gl.pushprint(msg, chat_id=uid)
        if gl.pushmode == "6":
            gl.pushprint("web模式跳过自动获取二维码,请手动点击添加按钮", chat_id=uid)
            print(color.red("【#️⃣】 若直接退出请运行:webserverListener.py"))
            return
        driver_login = Mydriver()
        cookies = driver_login.login()
        driver_login.quit()
        if not cookies:
            print("登录超时")
            return
        user.save_cookies(cookies)
        uid = user.get_userId(cookies)
        user_fullname = user.get_fullname(uid)
        name = user_fullname.split('_', 1)[1]
        user.update_last_user(uid)
    output = name + " 登录正常,开始学习...\n"

    article_index = user.get_article_index(uid)
    video_index = 1  # user.get_video_index(uid)

    total, scores = show_score(cookies)
    gl.pushprint(output, chat_id=uid)
    if TechXueXi_mode in ["1", "3"]:

        article_thread = threads.MyThread("文章学 xi ",
                                          article,
                                          uid,
                                          cookies,
                                          article_index,
                                          scores,
                                          lock=lock)
        video_thread = threads.MyThread("视频学 xi ",
                                        video,
                                        uid,
                                        cookies,
                                        video_index,
                                        scores,
                                        lock=lock)
        article_thread.start()
        video_thread.start()
        article_thread.join()
        video_thread.join()
    if TechXueXi_mode in ["2", "3"]:
        print('开始每日答题……')
        daily(cookies, scores)
        print('开始每周答题……')
        weekly(cookies, scores)
        if nohead != True or gl.zhuanxiang == True:
            print('开始专项答题……')
            zhuanxiang(cookies, scores)

    if TechXueXi_mode == "4":
        user.select_user()
    if TechXueXi_mode == "5":
        user.refresh_all_cookies(display_score=True)
    if TechXueXi_mode == "6":
        user.refresh_all_cookies(live_time=11.90)

    seconds_used = int(time.time() - start_time)
    gl.pushprint(name + " 总计用时 " + str(math.floor(seconds_used / 60)) + " 分 " +
                 str(seconds_used % 60) + " 秒",
                 chat_id=uid)
    show_scorePush(cookies, chat_id=uid)
    try:
        user.shutdown(stime)
    except Exception as e:
        pass
Ejemplo n.º 7
0
    gl.pushprint("请登录(登录方式请仔细阅读文档,如果觉得这是让你下载,就是你没仔细读文档):", chat_id=chat_id)
    driver_login = Mydriver()
    cookies = driver_login.login(chat_id)
    driver_login.quit()
    if not cookies:
        gl.pushprint("登录超时。", chat_id=chat_id)
        return
    user.save_cookies(cookies)
    uid = user.get_userId(cookies)
    user_fullname = user.get_fullname(uid)
    user.update_last_user(uid)
    gl.pushprint(user_fullname + "登录成功", chat_id=chat_id)


if __name__ == '__main__':
    if (cfg_get('display.banner') != False):  # banner文本直接硬编码,不要放在conf中
        print(
            "=" * 60 +
            '\n    我们的网站,GitHub 等页面已经被中国大陆的浏览器加入黑名单,请用谷歌浏览器 chrome 打开我们的站点。' +
            '\n    科技强 guo 官方网站:https://techxuexi.js.org' +
            '\n    Github地址:https://github.com/TechXueXi' +
            '\n使用本项目,必须接受以下内容,否则请立即退出:' +
            '\n    - TechXueXi 仅额外提供给“爱党爱 guo ”且“工作学业繁重”的人' +
            '\n    - 项目开源协议 LGPL-3.0' + '\n    - 不得利用本项目盈利' +
            '\n另外,我们建议你参与一个维护劳动法的项目:' +
            '\nhttps://996.icu/ 或 https://github.com/996icu/996.ICU/blob/master/README_CN.md'
        )
    print("=" * 60, '''\nTechXueXi 现支持以下模式(答题时请值守电脑旁处理少部分不正常的题目):''')
    print(cfg_get('base.ModeText', "") + '\n' + "=" * 60)
    # 模式提示文字请在 ./config/default_template.conf 处修改。
    start()
Ejemplo n.º 8
0
    def get_cookie_from_network(self, chat_id=None):
        print("正在打开二维码登陆界面,请稍后")
        self.web_log('正在打开二维码登陆界面,请稍后')
        self.driver.get("https://pc.xuexi.cn/points/login.html")
        try:
            remover = WebDriverWait(self.driver, 30, 0.2).until(
                lambda driver: driver.find_element_by_class_name("redflagbox"))
        except exceptions.TimeoutException:
            print("网络缓慢,请重试")
        else:
            self.driver.execute_script('arguments[0].remove()', remover)
        try:
            remover = WebDriverWait(
                self.driver, 30,
                0.2).until(lambda driver: driver.find_element_by_class_name(
                    "layout-header"))
        except exceptions.TimeoutException:
            print("当前网络缓慢...")
        else:
            self.driver.execute_script('arguments[0].remove()', remover)
        try:
            remover = WebDriverWait(
                self.driver, 30,
                0.2).until(lambda driver: driver.find_element_by_class_name(
                    "layout-footer"))
        except exceptions.TimeoutException:
            print("当前网络缓慢...")
        else:
            self.driver.execute_script('arguments[0].remove()', remover)
            #修改了适配新版本的二维码的滚动位置
            self.driver.execute_script(
                'window.scrollTo(document.body.scrollWidth/2 - 200 , 400)')
        qrurl = ''
        qcbase64 = ''
        # 取出iframe中二维码,并发往钉钉
        if gl.nohead == True or cfg_get("addition.SendLoginQRcode", 0) == 1:
            print("二维码将发往机器人...\n" + "=" * 60)
            qrurl, qcbase64 = self.sendmsg(chat_id)

        # 扫码登录后删除二维码和登录链接 准备
        web_qr_url = web_db.session.query(WebQrUrl).filter_by(
            url=qcbase64).first()
        web_msg = web_db.session.query(WebMessage).filter_by(
            text=qrurl).first()

        # print(' ----------------------------------------------------------------')
        # print(web_qr_url)
        # print(' ----------------------------------------------------------------')
        # print(web_msg)
        # print(web_db.session.query(WebMessage).all())

        # try:
        #     # 取出iframe中二维码,并发往方糖,拿到的base64没办法直接发钉钉,所以发方糖
        #     if  gl.nohead==True or cfg["addition"]["SendLoginQRcode"] == 1 :
        #         print("二维码将发往方糖机器人...\n" + "=" * 60)
        #         self.toFangTang()
        # except Exception as e:
        #     print("未检测到SendLoginQRcode配置,请手动扫描二维码登陆..."+e)

        try:
            # 获取二维码图片  # 这一块等待测试完毕再加入代码
            # self.driver.switch_to.frame("ddlogin-iframe")
            # source = self.driver.page_source
            # picc = re.search(
            #     "(data:image/png;base64,)(.*)(\"></div><div data-v-be4de7b6)", source).group(2)
            # pic = base64.b64decode(picc)
            # 微信发送图片到手机,以便扫码(此配置项暂未应用至代码。结合 default_template.conf 修改)
            # wx = WeChat()
            # media_id = wx.get_media_url(pic)
            # wx.send_image(media_id)

            # WebDriverWait(self.driver, 270).until(EC.title_is(u"我的学习"))
            WebDriverWait(self.driver, 270).until(title_of_login())
            cookies = self.get_cookies()
            user.save_cookies(cookies)
            # 扫码登录后删除二维码和登录链接
            # print('扫码登录后删除二维码和登录链接 {} - {}'.format(web_msg, web_qr_url))
            self.web_log('扫码登录后删除二维码和登录链接')
            web_qr_url and web_db.session.delete(web_qr_url)
            web_msg and web_db.session.delete(web_msg)
            web_db.session.commit()
            return cookies

        except Exception as e:
            print("扫描二维码超时... 错误信息:" + str(e))
            self.web_log("扫描二维码超时... 错误信息:" + str(e))
            if (gl.islooplogin == True):
                print("循环模式开启,即将重新获取二维码")
                self.web_log("循环模式开启,即将重新获取二维码")
                time.sleep(3)
                return self.get_cookie_from_network()
            self.quit()

            if str(e).find("check_hostname") > -1 and str(e).find(
                    "server_hostname") > -1:
                print("针对“check_hostname requires server_hostname”问题:")
                print("您的网络连接存在问题,请检查您与xuexi.cn的网络连接并关闭“某些”软件")
                self.web_log("针对“check_hostname requires server_hostname”问题:")
                self.web_log("您的网络连接存在问题,请检查您与xuexi.cn的网络连接并关闭“某些”软件")
            auto.prompt("按回车键退出程序. ")
            exit()
Ejemplo n.º 9
0
from hashlib import sha1
import os
import time
from flask import Flask, request
import requests
import json

from selenium.webdriver.support import ui
from pdlearn.config import cfg_get
from pdlearn.wechat import WechatHandler
from pdlearn.threads import MyThread
from pdlearn import file
import pandalearning as pdl

app = Flask(__name__)
appid = cfg_get("addition.wechat.appid", "")
appsecret = cfg_get("addition.wechat.appsecret", "")
token = cfg_get("addition.wechat.token", "")
openid = cfg_get("addition.wechat.openid", "")
wechat = WechatHandler()


class MessageInfo:
    to_user_name = ""
    from_user_name = ""
    create_time = ""
    msg_type = ""
    content = ""
    msg_id = ""
    event = ""
    event_key = ""
Ejemplo n.º 10
0
def answer_question(quiz_type,
                    cookies,
                    scores,
                    score_all,
                    quiz_xpath,
                    category_xpath,
                    uid=None,
                    driver_default=None):
    quiz_zh_CN = {"daily": "每日", "weekly": "每周", "zhuanxiang": "专项"}
    if (quiz_type not in ["daily", "weekly", "zhuanxiang"]):
        print("quiz_type 错误。收到的quiz_type:" + quiz_type)
        exit(0)
    if uid is None:
        uid = user.get_userId(cookies)
    if scores[quiz_type] < score_all:  # 还没有满分,需要答题
        if driver_default is None:
            driver_ans = Mydriver(nohead=gl.nohead)
            ##### driver_ans = Mydriver(nohead=True)
        else:
            driver_ans = driver_default
        driver_daily = driver_ans
        driver_weekly = driver_ans
        driver_zhuanxiang = driver_ans
        # try:
        #     nohead = gl.nohead
        # except:
        #     nohead=False
        # if nohead:
        #     print("使用默认窗口大小")
        # else:
        driver_ans.driver.maximize_window()
        print('请保持窗口最大化\n' * 3)
        driver_ans.get_url("https://www.xuexi.cn/notFound.html")
        driver_ans.set_cookies(cookies)
        pass_count = 0
        # 最大值,用于nohead模式退出
        max_count = 0
        # 从数据库获取答案
        answer_from_db = False
        answer_error_max = cfg_get("parameter.answer_error_max", 100)
        # 是否开启错题收集
        answer_error_collect = cfg_get("parameter.answer_error_collect", True)
        if scores[quiz_type] < score_all:
            letters = list("ABCDEFGHIJKLMN")
            driver_ans.get_url('https://pc.xuexi.cn/points/my-points.html')
            refresh_my_page_count = 0
            # 页面title为积分则一直循环
            while driver_ans.title_is(u"我的积分") and refresh_my_page_count < 20:
                time.sleep(1)  # 等待页面刷新提示
                refresh_buttons = driver_ans.driver.find_elements_by_css_selector(
                    ".ant-modal-wrap .ant-btn:not(.ant-btn-primary)")
                if len(refresh_buttons) > 0:  #
                    refresh_buttons[0].click()
                driver_ans.click_xpath(quiz_xpath)  # 点击各个题目的去答题按钮
                time.sleep(1)
                refresh_my_page_count += 1
                if refresh_my_page_count >= 20:
                    print("没有找到答题按钮")
            if quiz_type != "daily":  # 如果是每日答题就不用找available了
                # 此处修改是因为页面可能刷新后导致的查找元素button 丢失从而引发异常重新此处用可以重新查找来解决
                try:
                    to_click = find_available_quiz(quiz_type, driver_ans, uid)
                except Exception as e:
                    to_click = find_available_quiz(quiz_type, driver_ans, uid)
                if to_click is not None:
                    to_click.click()
                    time.sleep(0.5)
                else:
                    print(color.blue("无题可答。即将跳过。"))
                    if driver_default is None:
                        try:
                            driver_ans.quit()
                        except Exception as e:
                            print('driver_ans 在 answer_question 退出时出了一点小问题...')
                    else:
                        pass  # 其他函数传入函数的driver,不自动退出
            while scores[quiz_type] < score_all:
                try:
                    category = driver_ans.xpath_getText(
                        category_xpath)  # 获取题目类型 get_attribute("name")
                except Exception as e:
                    print('查找题目类型...查找元素失败!')
                    break
                # 全局出错次数
                if max_count >= answer_error_max and globalvar.nohead == True:
                    print("略过次数已经超过" + str(answer_error_max) +
                          "次,且出于Nohead模式,退出答题")
                    break
                print(category)
                q_text = ""
                tips = []
                tip_full_text = ""
                if quiz_type == "daily":
                    ans_results = driver_ans.driver.find_elements_by_css_selector(
                        ".practice-result .infos .info")
                    if (len(ans_results) != 0):  # 已经找到答题结果页面
                        print(ans_results[0].get_attribute("innerHTML"))
                        print(ans_results[0].text)
                        print(ans_results[2].get_attribute("innerHTML"))
                        print(ans_results[2].text)
                        time.sleep(1)
                        # exit(2)
                        break
                    log_daily("\n====================")
                    log_daily(log_timestamp())
                try:
                    log_daily("【" + category + "】")
                    log_daily("【题干】")
                    q_body = driver_ans.driver.find_element_by_css_selector(
                        ".q-body")
                    q_html = q_body.get_attribute('innerHTML')
                    q_text = q_body.text
                    print(q_text)
                    log_daily(q_html)
                except Exception as e:
                    print("获取题干出错" + str(e))
                # 上次出错,则采用数据库答题
                if answer_from_db:
                    answer_from_db = False  # 下次从页面获取提示
                    try:
                        if not q_text:
                            q_body = driver_ans.driver.find_element_by_css_selector(
                                ".q-body")
                            q_html = q_body.get_attribute('innerHTML')
                            q_text = q_body.text
                        tips = search_answer(q_text)
                    except Exception as e:
                        print("数据搜索答案异常:" + str(e))
                else:
                    tips, tip_full_text = driver_ans._view_tips()

                if quiz_type == "daily":
                    log_daily("【提示信息】")
                    log_daily(str(tips) + "\n" + tip_full_text)
                if not tips:
                    print("页面未找到提示,尝试从题库搜索答案。\n")
                    try:
                        answer_from_db = False  # 下次从页面获取提示
                        if not q_text:
                            q_body = driver_ans.driver.find_element_by_css_selector(
                                ".q-body")
                            q_html = q_body.get_attribute('innerHTML')
                            q_text = q_body.text
                        tips = search_answer(q_text)
                    except Exception as e:
                        print("数据搜索答案异常:" + str(e))
                if not tips:
                    print("本题没有提示")
                    max_count += 1
                    pass_count += 1

                    if pass_count >= 5:
                        print(
                            "暂时略过已达到 5 次,【 建议您将此题目的题干、提示、选项信息提交到github问题收集issue:https://github.com/TechXueXi/techxuexi-tiku/issues/1 】"
                        )
                        auto.prompt("等待用户手动答题...完成后请在此按回车...")
                        pass_count = 0
                        continue
                    # if quiz_type == "daily":
                    #     log_daily("!!!!!本题没有找到提示,暂时略过!!!!!")
                    #     auto.prompt("等待用户手动答题...完成后请在此按回车...")
                    #     time.sleep(1)
                    #     continue
                    if "填空题" in category:
                        print('没有找到提示,暂时略过')
                        # print('使用默认答案  好 ')   #如无填空答案,使用默认答案 好 字 by Sean
                        ##### tips = ['好']
                        if gl.nohead and answer_error_collect:
                            gl.push_msg += "[题干]" + q_text + '\n'
                        continue
                    elif "多选题" in category:
                        print('没有找到提示,多选题默认全选')
                        # print('使用默认答案 全选')    #by Sean
                        ## continue  #####
                        tips = driver_daily.radio_get_options()
                        if gl.nohead and answer_error_collect:
                            gl.push_msg += f"[题干]{q_text}\n[选项]{str(tips)}\n"
                    elif "单选题" in category:
                        print('没有找到提示,单选题默认选A')  # 如无单选答案,使用默认答案
                        # print('使用默认答案 B')   #by Sean
                        # continue  #####
                        # return driver_daily._search(driver_daily.content, driver_daily.options, driver_daily.excludes)
                        ops = driver_daily.radio_get_options()
                        tips = [ops[0]]
                        if gl.nohead and answer_error_collect:
                            gl.push_msg += f"[题干]{q_text}\n[选项]{str(ops)}\n"
                    else:
                        print("题目类型非法")
                        if quiz_type == "daily":
                            log_daily("!!!!!无提示,题目类型非法!!!!!")
                        break
                if tips:
                    if "填空题" in category:
                        answer = tips
                        if quiz_type != "zhuanxiang":
                            driver_ans.fill_in_blank(answer)
                        else:
                            driver_ans.zhuanxiang_fill_in_blank(answer)
                    elif "多选题" in category:
                        if quiz_type == "daily":
                            options = driver_daily.radio_get_options()
                            ##### len_option = len(options)
                            log_daily("【多选题选项】")
                            log_daily(str(options))
                            radio_in_tips, radio_out_tips = "", ""
                            for letter, option in zip(letters, options):
                                for tip in tips:
                                    if tip in option:
                                        # print(f'{option} in tips')
                                        if letter not in radio_in_tips:
                                            radio_in_tips += letter
                            radio_out_tips = [
                                letter
                                for letter, option in zip(letters, options)
                                if (letter not in radio_in_tips)
                            ]

                            print('包含提示的选项 ', radio_in_tips, ',不包含提示的选项 ',
                                  radio_out_tips)
                            log_daily('包含提示的选项 ' + str(radio_in_tips) +
                                      ',不包含提示的选项 ' + str(radio_out_tips))
                            # and radio_in_tips not in driver_daily.excludes:
                            if len(radio_in_tips) > 1:
                                print('根据提示', radio_in_tips)
                                driver_daily.radio_check(radio_in_tips)
                            elif len(
                                    radio_out_tips
                            ) > 1:  # and radio_out_tips not in excludes
                                print('根据提示', radio_out_tips)
                                driver_daily.radio_check(radio_out_tips)
                            # return driver_daily._search(content, options, excludes)
                            else:
                                max_count += 1
                                answer_from_db = True
                                print('无法根据提示判断,将在数据库中查询答案……')
                                log_daily("!!!!!无法根据提示判断,请自行答题……!!!!!")
                                # print('将使用默认全选答题')     #by Sean
                                ##### len_option = len(options)
                                ##### radio_in_tips = letters[:len_option]
                                # driver_daily.radio_check(radio_in_tips)
                                if not gl.nohead:
                                    auto.prompt("等待用户手动答题...完成后请在此按回车...")
                        elif quiz_type == "weekly":
                            options = driver_weekly.radio_get_options()
                            radio_in_tips, radio_out_tips = "", ""
                            for letter, option in zip(letters, options):
                                for tip in tips:
                                    if tip in option:
                                        # print(f'{option} in tips')
                                        if letter not in radio_in_tips:
                                            radio_in_tips += letter
                            radio_out_tips = [
                                letter
                                for letter, option in zip(letters, options)
                                if (letter not in radio_in_tips)
                            ]

                            print('含 ', radio_in_tips, '不含', radio_out_tips)
                            # and radio_in_tips not in driver_weekly.excludes:
                            if len(radio_in_tips) > 1:
                                print('根据提示', radio_in_tips)
                                driver_weekly.radio_check(radio_in_tips)
                            elif len(
                                    radio_out_tips
                            ) > 1:  # and radio_out_tips not in excludes
                                print('根据提示', radio_out_tips)
                                driver_weekly.radio_check(radio_out_tips)
                            # return driver_weekly._search(content, options, excludes)
                            else:
                                max_count += 1
                                answer_from_db = True
                                print('无法根据提示判断,将在数据库中查询答案……')
                                # print('将使用默认全选答题')     #by Sean
                                ##### len_option = len(options)
                                ##### radio_in_tips = letters[:len_option]
                                # driver_weekly.radio_check(radio_in_tips)
                                if not gl.nohead:
                                    auto.prompt("等待用户手动答题...完成后请在此按回车...")
                        elif quiz_type == "zhuanxiang":
                            options = driver_zhuanxiang.radio_get_options()
                            radio_in_tips, radio_out_tips = "", ""
                            for letter, option in zip(letters, options):
                                for tip in tips:
                                    if tip in option:
                                        # print(f'{option} in tips')
                                        if letter not in radio_in_tips:
                                            radio_in_tips += letter
                            radio_out_tips = [
                                letter
                                for letter, option in zip(letters, options)
                                if (letter not in radio_in_tips)
                            ]

                            print('含 ', radio_in_tips, '不含', radio_out_tips)
                            # and radio_in_tips not in driver_zhuanxiang.excludes:
                            if len(radio_in_tips) > 1:
                                print('根据提示', radio_in_tips)
                                driver_zhuanxiang.radio_check(radio_in_tips)
                            elif len(
                                    radio_out_tips
                            ) > 1:  # and radio_out_tips not in excludes
                                print('根据提示', radio_out_tips)
                                driver_zhuanxiang.radio_check(radio_out_tips)
                            # return driver_zhuanxiang._search(content, options, excludes)
                            else:
                                max_count += 1
                                answer_from_db = True
                                print('无法根据提示判断,将在数据库中查询答案……')
                                # print('将使用默认全选答题')     #by Sean
                                ##### len_option = len(options)
                                ##### radio_in_tips = letters[:len_option]
                                # driver_zhuanxiang.radio_check(radio_in_tips)
                                if not gl.nohead:
                                    auto.prompt("等待用户手动答题...完成后请在此按回车...")
                    elif "单选题" in category:
                        if quiz_type == "daily":
                            options = driver_daily.radio_get_options()
                            log_daily("【单选题选项】")
                            log_daily(str(options))
                            if '因此本题选' in tips:  # 提示类型1
                                check = [x for x in letters if x in tips]
                                log_daily("根据提示类型1,选择答案:" + str(check))
                                driver_daily.radio_check(check)
                            else:
                                radio_in_tips, radio_out_tips = "", ""
                                '''
                                option_elements = driver_daily.wait.until(driver_daily.EC.presence_of_all_elements_located(
                                    (driver_daily.By.XPATH, '//*[@id="app"]/div/div[2]/div/div[4]/div[1]')))
                                # option_elements = self.find_elements(rules['challenge_options'])
                                options = [x.get_attribute("name") for x in option_elements]'''
                                for letter, option in zip(letters, options):
                                    for tip in tips:
                                        if tip in option:
                                            # print(f'{option} in tips')
                                            if letter not in radio_in_tips:
                                                radio_in_tips += letter
                                        else:
                                            # print(f'{option} out tips')
                                            if letter not in radio_out_tips:
                                                radio_out_tips += letter

                                print('包含提示的选项 ', radio_in_tips, ',不包含提示的选项 ',
                                      radio_out_tips)
                                log_daily('包含提示的选项 ' + str(radio_in_tips) +
                                          ',不包含提示的选项 ' + str(radio_out_tips))
                                # and radio_in_tips not in driver_daily.excludes:
                                if 1 == len(radio_in_tips):
                                    print('根据提示', radio_in_tips)
                                    driver_daily.radio_check(radio_in_tips)
                                # and radio_out_tips not in excludes
                                elif 1 == len(radio_out_tips):
                                    print('根据提示', radio_out_tips)
                                    driver_daily.radio_check(radio_out_tips)
                                # return driver_daily._search(content, options, excludes)
                                else:
                                    max_count += 1
                                    answer_from_db = True
                                    print('无法根据提示判断,将在数据库中查询答案……')
                                    log_daily("!!!!!无法根据提示判断,请自行答题……!!!!!")
                                    # print('将使用默认选 B')     #by Sean
                                    ##### radio_in_tips = "B"
                                    # driver_daily.radio_check(radio_in_tips)
                                    if not gl.nohead:
                                        auto.prompt("等待用户手动答题...完成后请在此按回车...")
                        elif quiz_type == "weekly":
                            options = driver_weekly.radio_get_options()
                            if '因此本题选' in tips:
                                check = [x for x in letters if x in tips]
                                driver_weekly.radio_check(check)
                            else:
                                radio_in_tips, radio_out_tips = "", ""
                                '''
                                option_elements = driver_weekly.wait.until(driver_weekly.EC.presence_of_all_elements_located(
                                    (driver_weekly.By.XPATH, '//*[@id="app"]/div/div[2]/div/div[4]/div[1]')))
                                # option_elements = self.find_elements(rules['challenge_options'])
                                options = [x.get_attribute("name") for x in option_elements]'''
                                for letter, option in zip(letters, options):
                                    for tip in tips:
                                        if tip in option:
                                            # print(f'{option} in tips')
                                            if letter not in radio_in_tips:
                                                radio_in_tips += letter
                                        else:
                                            # print(f'{option} out tips')
                                            if letter not in radio_out_tips:
                                                radio_out_tips += letter

                                print('含 ', radio_in_tips, '不含',
                                      radio_out_tips)
                                # and radio_in_tips not in driver_weekly.excludes:
                                if 1 == len(radio_in_tips):
                                    print('根据提示', radio_in_tips)
                                    driver_weekly.radio_check(radio_in_tips)
                                # and radio_out_tips not in excludes
                                elif 1 == len(radio_out_tips):
                                    print('根据提示', radio_out_tips)
                                    driver_weekly.radio_check(radio_out_tips)
                                # return driver_weekly._search(content, options, excludes)
                                else:
                                    max_count += 1
                                    answer_from_db = True
                                    print('无法根据提示判断,将在数据库中查询答案……')
                                    # print('将使用默认选 B')     #by Sean
                                    ##### radio_in_tips = "B"
                                    # driver_weekly.radio_check(radio_in_tips)
                                    if not gl.nohead:
                                        auto.prompt("等待用户手动答题...完成后请在此按回车...")
                        elif quiz_type == "zhuanxiang":
                            options = driver_zhuanxiang.radio_get_options()
                            if '因此本题选' in tips:
                                check = [x for x in letters if x in tips]
                                driver_zhuanxiang.radio_check(check)
                            else:
                                radio_in_tips, radio_out_tips = "", ""
                                '''
                                option_elements = driver_zhuanxiang.wait.until(driver_zhuanxiang.EC.presence_of_all_elements_located(
                                    (driver_zhuanxiang.By.XPATH, '//*[@id="app"]/div/div[2]/div/div[4]/div[1]')))
                                # option_elements = self.find_elements(rules['challenge_options'])
                                options = [x.get_attribute("name") for x in option_elements]'''
                                for letter, option in zip(letters, options):
                                    for tip in tips:
                                        if tip in option:
                                            # print(f'{option} in tips')
                                            if letter not in radio_in_tips:
                                                radio_in_tips += letter
                                        else:
                                            # print(f'{option} out tips')
                                            if letter not in radio_out_tips:
                                                radio_out_tips += letter

                                print('含 ', radio_in_tips, '不含',
                                      radio_out_tips)
                                # and radio_in_tips not in driver_zhuanxiang.excludes:
                                if 1 == len(radio_in_tips):
                                    print('根据提示', radio_in_tips)
                                    driver_zhuanxiang.radio_check(
                                        radio_in_tips)
                                # and radio_out_tips not in excludes
                                elif 1 == len(radio_out_tips):
                                    print('根据提示', radio_out_tips)
                                    driver_zhuanxiang.radio_check(
                                        radio_out_tips)
                                # return driver_zhuanxiang._search(content, options, excludes)
                                else:
                                    max_count += 1
                                    answer_from_db = True
                                    print('无法根据提示判断,将在数据库中查询答案……')
                                    # print('将使用默认选 B')     #by Sean
                                    ##### radio_in_tips = "B"
                                    # driver_zhuanxiang.radio_check(radio_in_tips)
                                    if not gl.nohead:
                                        auto.prompt("等待用户手动答题...完成后请在此按回车...")
                    else:
                        print("题目类型非法")
                        if quiz_type == "daily":
                            log_daily("!!!!!有提示,但题目类型非法!!!!!")
                        break
                    time.sleep(1)
            total, scores = show_score(cookies)
            # 答题完成,并存在全局错题,进行推送
            if gl.nohead and answer_error_collect and gl.push_msg:
                gl.pushprint('')
            if scores[quiz_type] >= score_all:
                print("检测到" + quiz_zh_CN[quiz_type] + "答题分数已满,退出学 xi ")
            else:
                print(
                    "!!!!!没拿到满分,请收集日志反馈错误题目!!!!!https://github.com/TechXueXi/techxuexi-tiku/issues/1"
                )
                auto.prompt("完成后(或懒得弄)请在此按回车...")
                # log_daily("!!!!!没拿到满分!!!!!")
        if driver_default == None:
            try:
                driver_ans.quit()
            except Exception as e:
                print('driver_ans 在 answer_question 退出时出了一点小问题...')
        else:
            pass  # 其他函数传入函数的driver,不自动退出
    else:
        print(quiz_zh_CN[quiz_type] + "答题已满分.")
Ejemplo n.º 11
0
 def __init__(self):
     self.token = []
     self.token = self.get_access_token()
     self.openid = cfg_get("addition.wechat.openid", "")