Example #1
0
 def run(self):
     # 1. Send before restart notification
     text = '\n'.join([
         "** WARNING **",
         "No message for {tolerance}. Restarting CoolQ.",
         "If you don't receive finish message in 2 mintues, "  # No comma
         "send /online to check or restart manually."
         ]).format(tolerance=ONLINE.TOLERANCE)
     for qq in ONLINE.ADMIN:
         qqbot.send(SendPrivateMessage(qq=qq, text=text))
     time.sleep(10)
     # 2.1. Stop CoolQ
     logging.warning("Stopping CoolQ")
     os.system("taskkill /F /T /IM CQP.exe")
     time.sleep(20)
     # 2.2. Start CoolQ
     logging.warning("Starting CoolQ")
     subprocess.Popen([
         CQ_ROOT + "/CQP.exe",
         "/account", "1695676191"],
         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
     time.sleep(30)
     # 3. Send after restart notification
     text = '\n'.join([
         "** INFO **",
         "Restart has finished.",
         ])
     for qq in ONLINE.ADMIN:
         qqbot.send(SendPrivateMessage(qq=qq, text=text))
Example #2
0
def process_twitter(post):
    id_ = post['id_str']
    user = post['user']['screen_name']
    text = post['text']
    tweet = Tweet(id_)
    if len(text) == 0:
        return

    tweet.user = post['user']['name']
    tweet.date = datetime.strptime(post['created_at'],
                                   "%a %b %d %H:%M:%S %z %Y")
    for ent in post['entities'].get('urls', []):
        text = text.replace(ent['url'], ent['expanded_url'])
    for ent in post['entities'].get('media', []):
        text = text.replace(ent['url'], ent['expanded_url'])
        url = ent['media_url']
        filename = os.path.basename(url)
        FileDownloader(
            url=url,
            path=os.path.join(CQ_IMAGE_ROOT, Twitter.image_subdir, filename),
            requests_kwargs=REQUESTS_OPTIONS_PROXIED,
        ).run()
        tweet.media.append(
            CQImage(os.path.join(Twitter.image_subdir, filename)))
    tweet.ja = text

    text = str(tweet)
    # info(text)
    for notify in NOTIFY:
        if user not in notify.get('type'):
            continue
        for q in notify.get('qq', []):
            qqbot.send(SendPrivateMessage(qq=q, text=text))
        for g in notify.get('group', []):
            qqbot.send(SendGroupMessage(group=g, text=text))
Example #3
0
def process_avatar(post):
    user = post['user']
    if user['screen_name'] != 'KanColle_STAFF':
        return

    url = Avatar.image_prog.sub(Avatar.image_repl,
                                user['profile_image_url_https'])
    if Avatar.latest is None:
        Avatar.latest = url
        print("[Avatar]", url)
        return

    if Avatar.latest != url:
        print("[Avatar]", url)
        filename = os.path.basename(url)
        FileDownloader(url=url,
                       path=os.path.join(CQ_IMAGE_ROOT, Avatar.image_subdir,
                                         filename),
                       requests_kwargs=REQUESTS_OPTIONS_PROXIED).run()
        Avatar.latest = url

        text = '\n'.join([
            user['name'], "【アイコン変更】",
            str(CQImage(os.path.join(Avatar.image_subdir, filename)))
        ])
        for notify in NOTIFY:
            if '_avatar_' not in notify.get('type'):
                continue
            for q in notify.get('qq', []):
                qqbot.send(SendPrivateMessage(qq=q, text=text))
            for g in notify.get('group', []):
                qqbot.send(SendGroupMessage(group=g, text=text))
Example #4
0
def reply(qqbot, message, text):
    reply_msg = None
    f = open('logs/record.log','a',encoding='gbk')
    if isinstance(message, RcvdPrivateMessage):
        reply_msg = SendPrivateMessage(
            qq=message.qq,
            text=text,
            )
    if isinstance(message, RcvdGroupMessage):
        reply_msg = SendGroupMessage(
            group=message.group,
            text=text,
            )
    if isinstance(message, RcvdDiscussMessage):
        reply_msg = SendDiscussMessage(
            discuss=message.discuss,
            text=text,
            )
    if reply_msg:
        qqbot.send(reply_msg)
        NOW =datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(NOW)
        f.write(NOW+'   '+str(message)+'\n')
        f.write(NOW+'   '+str(reply_msg)+'\n')
        print("↘", message)
        print("↗", reply_msg)
        f.close()
Example #5
0
def handle_private_message(msg):
    text = msg.text
    qq = msg.qq
    current_time = int(time.time() * 1000)

    parts = text.split(" ")

    if parts[0] == "/connect":
        username = parts[1]
        req_id = parts[2]
        r = app_backend_request("/api/qqbot/verify_user",
                                data={
                                    "username": username,
                                    "request_id": req_id,
                                    "qq": qq
                                })
        print(r)
        if r["msg"] != "OK":
            qqbot.send(SendPrivateMessage(qq=qq, text=r["msg"]))
        else:
            qqbot.send(SendPrivateMessage(qq=qq, text="关联成功。"))
Example #6
0
def poll_twitter(user):
    Template = dict(TEMPLATE_TWITTER)
    Template['params']['screen_name'] = user

    resp = session.get(**Template)
    if resp.status_code != 200:
        print(user, "Response not success", resp)
    posts = resp.json()
    posts.reverse()

    for post in posts:
        id_ = post['id_str']
        text = post['text']
        tweet = Twitter.tweets.get(id_, Tweet(id_))
        if len(text) == 0:
            continue
        if len(tweet.ja) > 0:
            continue

        tweet.user = post['user']['name']
        tweet.date = datetime.strptime(post['created_at'],
                                       "%a %b %d %H:%M:%S %z %Y")
        for ent in post['entities'].get('urls', []):
            text = text.replace(ent['url'], ent['expanded_url'])
        for ent in post['entities'].get('media', []):
            text = text.replace(ent['url'], ent['expanded_url'])
            url = ent['media_url']
            filename = os.path.basename(url)
            FileDownloader(
                url=url,
                path=os.path.join(CQ_IMAGE_ROOT, Twitter.image_subdir,
                                  filename),
                requests_kwargs=REQUESTS_OPTIONS_PROXIED,
            ).run()
            tweet.media.append(
                CQImage(os.path.join(Twitter.image_subdir, filename)))
        tweet.ja = text
        Twitter.tweets[id_] = tweet

        if Twitter.inited.get(user):
            text = str(tweet)
            info(text)
            for notify in NOTIFY:
                if user not in notify.get('type'):
                    continue
                for q in notify.get('qq', []):
                    qqbot.send(SendPrivateMessage(qq=q, text=text))
                for g in notify.get('group', []):
                    qqbot.send(SendGroupMessage(group=g, text=text))

    if not Twitter.inited.get(user):
        Twitter.inited[user] = True
        print(user, "init", len(posts))
Example #7
0
def check():
    now = datetime.now()
    last = ONLINE.last
    if (now - last) < ONLINE.TOLERANCE or ONLINE.notified_last == last:
        return
    ONLINE.notified_last = last
    text = '\n'.join([
        "** WARNING **",
        "No message for {tolerance}. Restarting CoolQ.",
        "If you don't receive finish message in 2 mintues, "  # No comma
        "send /online to check or restart manually."
        ]).format(tolerance=ONLINE.TOLERANCE)
    for qq in ONLINE.ADMIN:
        qqbot.send(SendPrivateMessage(qq=qq, text=text))
    time.sleep(10)  # Wait for warn message sending
    Restarter().start()
Example #8
0
 def run(self):
     logging.warn("Stopping CoolQ")
     os.system("taskkill /F /T /IM CQP.exe")
     time.sleep(10)
     logging.warn("Starting CoolQ")
     subprocess.Popen([
         "C:/Users/dazzy/Desktop/CoolQ/CQP.exe",
         "/account", "1695676191"],
         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
     time.sleep(10)
     logging.warn("Sending finish message")
     text = '\n'.join([
         "** INFO **",
         "Restart has finished.",
         ])
     for qq in ONLINE.ADMIN:
         qqbot.send(SendPrivateMessage(qq=qq, text=text))
Example #9
0
def poll_kcwiki():
    user = '******'
    resp = requests.get(**TEMPLATE_KCWIKI)
    if resp.status_code != 200:
        print(user, "Response not success", resp)
        return
    posts = resp.json()
    posts.reverse()

    for post in posts:
        id_ = post['id']
        text = post['zh']
        tweet = Twitter.tweets.get(id_, Tweet(id_))
        if len(text) == 0:
            continue
        if len(tweet.zh) > 0:
            continue

        text = Twitter.html_tag.sub('', text)
        tweet.zh = text
        Twitter.tweets[id_] = tweet

        # Dont post old translation.
        date = datetime.strptime(post['date'], "%Y-%m-%d %H:%M:%S") \
                       .replace(tzinfo=timezone(timedelta(hours=8)))
        now = datetime.utcnow() \
                      .replace(tzinfo=timezone(timedelta(hours=0)))
        if now - date > timedelta(hours=2):
            continue

        if Twitter.inited.get(user):
            text = str(tweet)
            info(text)
            for notify in NOTIFY:
                if 'KanColle_STAFF' not in notify.get('type'):
                    continue
                for q in notify.get('qq', []):
                    qqbot.send(SendPrivateMessage(qq=q, text=text))
                for g in notify.get('group', []):
                    qqbot.send(SendGroupMessage(group=g, text=text))

    if not Twitter.inited.get(user):
        Twitter.inited[user] = True
        print(user, "init", len(posts))
Example #10
0
def reply(qqbot, message, text):
    reply_msg = None
    if isinstance(message, RcvdPrivateMessage):
        reply_msg = SendPrivateMessage(
            qq=message.qq,
            text=text,
            )
    if isinstance(message, RcvdGroupMessage):
        reply_msg = SendGroupMessage(
            group=message.group,
            text=text,
            )
    if isinstance(message, RcvdDiscussMessage):
        reply_msg = SendDiscussMessage(
            discuss=message.discuss,
            text=text,
            )
    if reply_msg:
        qqbot.send(reply_msg)
        print("↘", message)
        print("↗", reply_msg)
Example #11
0
		print('新的INS时间:' + str(insTimeNew))
		if insTimeNew > insTime:
			time_local = time.localtime(insTimeNew)
			insTimeText = time.strftime("%Y-%m-%d %H:%M:%S",time_local)
			text = dataInsNew[1]
			like = dataInsNew[2]
			comments = dataInsNew[3]
			picurl = dataInsNew[4]
			picname = picurl[-50:]
			picpath = 'E:/SNH/CoolQ_Pro/data/image/' + picname
			insUrl = dataInsNew[5]
			print(picname)
			print('最新INS地址:' + insUrl)
			print('最新INS内容:' + text)
			r = requests.get(picurl,proxies=proxies)
			with open(picpath,'wb') as f:
				f.write(r.content)
			print('INS更新!最新地址为: ' + insUrl)
			msgIns = '[李艺彤更新INS]!' +  '\r' + '发送时间:' + insTimeText + '\r'
			print(video)
#			if video == 'True':
#				msgIns += '本次INS内容为视频,请前往观看\r'
			msgIns += '\r' + text + '\r' + '[CQ:image,file='+ picname +']' + '\r' + '当前 ' + str(like) + ' 赞 ' + str(comments) + ' 评论!' + '\r' + insUrl
			qqbot.send(SendGroupMessage(group, msgIns))
			qqbot.send(SendPrivateMessage(qqtest, msgIns))
			insTime = insTimeNew
		else:
			print('INS no change')
	except Exception as e:
		print("error","10s to continue")
		time.sleep(10)