Beispiel #1
0
def init_alarm():
    """ 初始化定时提醒 """
    alarm_info = get_yaml().get('alarm_info', None)
    if not alarm_info: return
    is_alarm = alarm_info.get('is_alarm', False)
    if not is_alarm: return
    alarm_timed = alarm_info.get('alarm_timed', None)
    if not alarm_timed: return
    hour, minute = [int(x) for x in alarm_timed.split(':')]

    # 检查数据的有效性
    for info in get_yaml().get('girlfriend_infos'):
        if not info: break  # 解决无数据时会出现的 bug。
        wechat_name = info.get('wechat_name')
        if (wechat_name and wechat_name.lower() not in FILEHELPER_MARK
                and not get_friend(wechat_name)):
            print('定时任务中的好友名称『{}』有误。'.format(wechat_name))

        # 更新信息
        group_name = info.get('group_name')
        if group_name and not get_group(group_name):
            print('定时任务中的群聊名称『{}』有误。'
                  '(注意:必须要把需要的群聊保存到通讯录)'.format(group_name))

    # 定时任务
    scheduler = BackgroundScheduler()
    # 每天9:30左右给女朋友发送每日一句
    scheduler.add_job(send_alarm_msg, 'cron', hour=hour,
                      minute=minute, misfire_grace_time=15 * 60)

    # # 每隔 30 秒发送一条数据用于测试。
    # scheduler.add_job(send_alarm_msg, 'interval', seconds=30)

    print('已开启定时发送提醒功能...')
    scheduler.start()
Beispiel #2
0
def init_wechat():
    """ 初始化微信所需数据 """
    conf = get_yaml()
    itchat.get_friends(update=True)  # 更新好友数据。
    itchat.get_chatrooms(update=True)  # 更新群聊数据。
    for name in conf.get('auto_reply_names'):
        if name.lower() in FILEHELPER_MARK:  # 判断是否文件传输助手
            if FILEHELPER not in reply_userNames:
                reply_userNames.append(FILEHELPER)
            continue
        friend = get_friend(name)
        if friend:
            reply_userNames.append(friend['UserName'])
        else:
            print('自动回复中的好友昵称『{}』有误。'.format(name))
    # print(reply_userNames)

    # 加载自动回复群消息
    auto_reply_group_conf = get_yaml().get('auto_reply_group_conf', None)
    if not auto_reply_group_conf: return
    is_open = auto_reply_group_conf.get('is_open', False)
    if not is_open: return
    group_names = auto_reply_group_conf.get('group_names')
    for group_name in group_names:
        if group_name and get_group(group_name):
            print('添加自动回复群组『{}』成功。'.format(group_name))
            reply_groupNames.append(group_name)
        else:
            print('自动回复中的群组名称『{}』有误。'.format(group_name))
Beispiel #3
0
def text_reply(msg):
    """ 监听用户消息,用于自动回复 """
    try:
        if not get_yaml().get('is_auto_relay'):
            return
        # print(json.dumps(msg, ensure_ascii=False))
        # print(reply_userNames)
        # 获取发送者的用户id
        uuid = FILEHELPER if msg['ToUserName'] == FILEHELPER else msg.fromUserName
        # 如果用户id是自动回复列表的人员
        if uuid in reply_userNames:
            receive_text = msg.text  # 好友发送来的消息内容
            # 好友叫啥
            nickName = FILEHELPER if uuid == FILEHELPER else msg.user.nickName
            print('\n{}发来信息:{}'.format(nickName, receive_text))
            reply_text = get_bot_info(receive_text, uuid)  # 获取自动回复
            time.sleep(random.randint(0, 2))  # 休眠一秒,保安全。想更快的,可以直接注释。
            if reply_text:  # 如内容不为空,回复消息
                reply_text = reply_text if not uuid == FILEHELPER else '机器人回复:' + reply_text
                itchat.send(reply_text, toUserName=uuid)
                print('回复{}:{}\n'.format(nickName, reply_text))
            else:
                print('自动回复失败\n'.format(receive_text))
    except Exception as e:
        print(str(e))
def get_bot_info(message, userId=''):
    """
    获取自动回复的话。
    # 优先获取图灵机器人API的回复,但失效时,会使用青云客智能聊天机器人API(过时)
    :param message:str, 发送的话
    :return:str, 回复的话
    """
    channel = get_yaml().get('bot_channel', 3)

    tuling = importlib.import_module(
        'everyday_wechat.control.bot.' + "tuling123", __package__)
    reply_msg = tuling.get_auto_reply(message, userId)

    if reply_msg == None:
        source = BOT_NAME_DICT.get(channel, 'qingyunke')
        addon = importlib.import_module(
            'everyday_wechat.control.bot.' + source, __package__)
        reply_msg = addon.get_auto_reply(message, userId)
    return reply_msg
    # reply_msg = get_tuling123(message)
    # if not reply_msg:
    #     reply_msg = get_qingyunke(message)
    #     reply_msg = get_yigeai(message)

    return None
def get_yigeai(text, userid):
    """
    『一个AI』自动回复 (http://www.yige.ai/)
    接口说明:http://docs.yige.ai/Query%E6%8E%A5%E5%8F%A3.html
    :param text:str, 需要发送的话
    :userid:str,机器唯一标识
    :return:str
    """
    conf = get_yaml()
    token = conf['yigeai_conf']['client_token']
    if not token:
        print('错误 .一个「AI」token 为空')
        return None
    session_id = md5_encode(userid)
    try:
        # print('发出消息:{}'.format(text))
        resp = requests.post('http://www.yige.ai/v1/query',
                             data={'token': token, 'query': text, 'session_id': session_id})
        if resp.status_code == 200 and is_json(resp):
            # print(resp.text)
            re_data = resp.json()
            code = re_data['status']['code']
            # 错误码返回有时是数字,有点是str。一起做处理
            if code and str(code) not in TULING_ERROR_CODE_LIST:
                return_text = re_data['answer']
                return return_text
            else:
                error_text = re_data['status']['error_type']
                print('『一个AI』机器人错误信息:{}'.format(error_text))
        print('『一个AI』机器人获取数据失败')
    except Exception as e:
        print(e)
        print('『一个AI』机器人获取数据失败')
Beispiel #6
0
def init_wechat():
    """ 初始化微信所需数据 """
    set_system_notice('登录成功')

    conf = get_yaml()
    itchat.get_friends(update=True)  # 更新好友数据。
    itchat.get_chatrooms(update=True)  # 更新群聊数据。
    for name in conf.get('auto_reply_names'):

        if name.lower() in FILEHELPER_MARK:  # 判断是否文件传输助手
            if FILEHELPER not in reply_userNames:
                reply_userNames.append(FILEHELPER)
            continue

        friend = get_friend(name)
        if friend:
            reply_userNames.append(friend['UserName'])
        else:
            print('自动回复中的好友昵称『{}』有误。'.format(name))
    # print(reply_userNames)

    if conf.get('is_auto_relay'):
        print('已开启图灵自动回复...')

    init_alarm()  # 初始化定时任务
Beispiel #7
0
def send_alarm_msg():
    """ 发送定时提醒 """
    print('\n启动定时自动提醒...')
    conf = get_yaml()
    for gf in conf.get('girlfriend_infos'):
        dictum = get_dictum_info(gf.get('dictum_channel'))
        weather = get_weather_info(gf.get('city_name'))
        diff_time = get_diff_time(gf.get('start_date'))
        sweet_words = gf.get('sweet_words')
        horoscope = get_xzw_info(gf.get("birthday"))
        joke = get_joke_info(gf.get('is_joke', False))
        # 如果渠道是一个·ONE 就发图片
        # send_image_path = get_one_image(gf.get('dictum_channel'))
        send_image_path = get_one_image(1)  #强制发one图片

        send_msg = '\n'.join(x for x in [
            weather, "\r", dictum, "\r", diff_time, sweet_words, "\r",
            horoscope
        ] if x)
        print(send_msg)

        if not send_msg or not is_online(): continue
        # 给微信好友发信息
        wechat_name = gf.get('wechat_name')
        if wechat_name:
            if wechat_name.lower() in FILEHELPER_MARK:
                if send_image_path:
                    itchat.send_image(send_image_path, toUserName=FILEHELPER)
                itchat.send(send_msg, toUserName=FILEHELPER)
                if joke:
                    itchat.send(joke, toUserName=FILEHELPER)
                print('定时给『{}』发送的内容是:\n{}\n发送成功...\n\n'.format(
                    wechat_name, send_msg))
            else:
                wechat_users = itchat.search_friends(name=wechat_name)
                if not wechat_users: continue
                if send_image_path:
                    wechat_users[0].send_image(send_image_path)
                wechat_users[0].send(send_msg)
                if joke:
                    wechat_users[0].send(joke)
                print('定时给『{}』发送的内容是:\n{}\n发送成功...\n\n'.format(
                    wechat_name, send_msg))

        # 给群聊里发信息
        group_name = gf.get('group_name')
        if group_name:
            group = get_group(group_name)
            if group:
                if send_image_path:
                    group.send_image(send_image_path)
                group.send(send_msg)
                if joke:
                    group.send(joke)
                print('定时给群聊『{}』发送的内容是:\n{}\n发送成功...\n\n'.format(
                    group_name, send_msg))

    print('自动提醒消息发送完成...\n')
Beispiel #8
0
def run():
    """ 主运行入口 """
    conf = get_yaml()
    if not conf:  # 如果 conf,表示配置文件出错。
        print('程序中止...')
        return
    # 判断是否登录,如果没有登录则自动登录,返回 False 表示登录失败
    if not is_online(auto_login=True):
        return
Beispiel #9
0
def run():
    """ 主运行入口 """
    conf = get_yaml()
    if not conf:  # 如果 conf,表示配置文件出错。
        print('程序中止...')
        return
    # 判断是否登录,如果没有登录则自动登录,返回 False 表示登录失败
    if not is_online(auto_login=True):
        return
    set_system_notice('登录成功')
    if conf.get('is_auto_relay'):
        print('已开启图灵自动回复...')
Beispiel #10
0
def init_wechat():
    """ 初始化微信所需数据 """
    conf = get_yaml()
    itchat.get_friends(update=True)  # 更新好友数据。
    itchat.get_chatrooms(update=True)  # 更新群聊数据。
    for name in conf.get('auto_reply_names'):
        if name.lower() in FILEHELPER_MARK:  # 判断是否文件传输助手
            if FILEHELPER not in reply_userNames:
                reply_userNames.append(FILEHELPER)
            continue
        friend = get_friend(name)
        if friend:
            reply_userNames.append(friend['UserName'])
        else:
            print('自动回复中的好友昵称『{}』有误。'.format(name))
Beispiel #11
0
def is_online(auto_login=False):
    """
    判断是否还在线。
    :param auto_login: bool,当为 Ture 则自动重连(默认为 False)。
    :return: bool,当返回为 True 时,在线;False 已断开连接。
    """
    def _online():
        """
        通过获取好友信息,判断用户是否还在线。
        :return: bool,当返回为 True 时,在线;False 已断开连接。
        """
        try:
            if itchat.search_friends():
                return True
        except IndexError:
            return False
        return True

    if _online(): return True  # 如果在线,则直接返回 True
    if not auto_login:  # 不自动登录,则直接返回 False
        print('微信已离线..')
        return False

    hotReload = not get_yaml().get('is_forced_switch', False)  # 切换微信号,重新扫码。
    loginCallback = init_wechat
    exitCallback = exit_msg
    for _ in range(2):  # 尝试登录 2 次。
        if os.environ.get('MODE') == 'server':
            # 命令行显示登录二维码。
            itchat.auto_login(enableCmdQR=2,
                              hotReload=hotReload,
                              loginCallback=loginCallback,
                              exitCallback=exitCallback)
            itchat.run(blockThread=False)
        else:
            itchat.auto_login(hotReload=hotReload,
                              loginCallback=loginCallback,
                              exitCallback=exitCallback)
            itchat.run(blockThread=False)
        if _online():
            print('登录成功')
            return True

    print('登录失败。')
    return False
def get_tuling123(text, userId):
    """
    接口地址:(https://www.kancloud.cn/turing/www-tuling123-com/718227)
    获取图灵机器人对话
    :param text: 发送的话
    :param userId: 用户唯一标识(最好用微信好友uuid)
    :return: 对白
    """
    info = get_yaml()['turing_conf']
    apiKey = info['apiKey']

    if not apiKey:
        print('图灵机器人 apikey 为空,请求出错')
        return None
    userId = md5_encode(userId if userId else '250')

    content = {
        'perception': {
            'inputText': {
                'text': text
            }
        },
        'userInfo': {
            'apiKey': apiKey,
            'userId': userId
        }
    }
    try:
        # print('发出消息:{}'.format(text))
        resp = requests.post(URL, json=content)
        if resp.status_code == 200 and is_json(resp):
            # print(resp.text)
            re_data = resp.json()
            if re_data['intent']['code'] not in TULING_ERROR_CODE_LIST:
                return_text = re_data['results'][0]['values']['text']
                return return_text
            else:
                error_text = re_data['results'][0]['values']['text']
                print('图灵机器人错误信息:{}'.format(error_text))

        print('图灵机器人获取数据失败')
    except Exception as e:
        print(e)
        print('图灵机器人获取数据失败')
Beispiel #13
0
def send_alarm_msg():
    """ 发送定时提醒 """
    print('\n启动定时自动提醒...')
    conf = get_yaml()
    for gf in conf.get('girlfriend_infos'):
        dictum = get_dictum_info(gf.get('dictum_channel'))
        weather = get_weather_info(gf.get('city_name'))
        horoscope = get_xzw_info(gf.get("birthday"))

        send_msg = '\n'.join(x for x in [weather, dictum, horoscope] if x)

        if not send_msg or not is_online(): continue
        # 给微信好友发信息
        wechat_name = gf.get('wechat_name')
        if wechat_name:
            if wechat_name.lower() in FILEHELPER_MARK:
                itchat.send(send_msg, toUserName=FILEHELPER)
                print('定时给『{}』发送的内容是:\n{}\n发送成功...\n\n'.format(
                    wechat_name, send_msg))
            else:
                wechat_users = itchat.search_friends(name=wechat_name)
                if not wechat_users: continue
                wechat_users[0].send(send_msg)
                print('定时给『{}』发送的内容是:\n{}\n发送成功...\n\n'.format(
                    wechat_name, send_msg))

        # 给群聊里发信息
        group_name = gf.get('group_name')
        if group_name:
            group = get_group(group_name)
            if group:
                group.send(send_msg)
                print('定时给群聊『{}』发送的内容是:\n{}\n发送成功...\n\n'.format(
                    group_name, send_msg))

    print('自动提醒消息发送完成...\n')