Beispiel #1
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()
Beispiel #2
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))
Beispiel #3
0
def drive_mode_on(forward_index, tg_group_id, tg_user, qq_group_id, qq):
    if JQ_MODE:
        return
    PIC_LINK_MODE[forward_index] = False
    msg = 'QQ 图片链接模式已关闭'
    global_vars.tg_bot.sendMessage(tg_group_id, msg)
    global_vars.qq_bot.send(SendGroupMessage(group=qq_group_id, text=msg))
Beispiel #4
0
def drive_mode_on(qq_group_id: int, qq: int):
    result = ''
    for command in global_vars.command_list:
        result += command.command + ': ' + ('telegram command' if command.tg_only else ('qq command' if command.qq_only else '')) + '\n'
        if command.description:
            result += '  ' + command.description + '\n'
    global_vars.qq_bot.send(SendGroupMessage(group=qq_group_id, text=result))
Beispiel #5
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))
Beispiel #6
0
def cq_send(update: telegram.Update, text: str, qq_group_id: int, edited: bool = False):
    """
    send telegram message to qq with forward of reply support
    :param update: telegram.Update
    :param text: text to send, in coolq format
    :param qq_group_id: which group to send
    :param edited: add '✎' icon
    """
    if edited:
        sender_name = get_full_user_name(update.edited_message.from_user)
        forward_from = get_forward_from(update.edited_message)
        reply_to = get_reply_to(update.edited_message.reply_to_message)
    else:
        sender_name = get_full_user_name(update.message.from_user)
        forward_from = get_forward_from(update.message)
        reply_to = get_reply_to(update.message.reply_to_message)

    # get real sender from telegram message
    if forward_from and update.message.forward_from.id == global_vars.tg_bot_id:
        left_start = text.find(': ')
        if left_start != -1:
            text = text[left_start + 2:]
    text = emoji_to_cqemoji(text)

    if edited:
        edit_mark = ' ✎ '
    else:
        edit_mark = ''

    global_vars.qq_bot.send(SendGroupMessage(
        group=qq_group_id,
        text=sender_name + reply_to + forward_from + edit_mark + ': ' + text
    ))
Beispiel #7
0
def send_group_id(tg_group_id, tg_user):
    qq_group_id, _, forward_index = get_forward_index(
        tg_group_id=int(tg_group_id))
    if forward_index == -1:
        raise DispatcherHandlerStop()
    username = get_full_user_name(tg_user)
    msg = username + ': [CQ:dice]'
    global_vars.qq_bot.send(SendGroupMessage(group=qq_group_id, text=msg))
Beispiel #8
0
def set_drive_mode(forward_index, status, tg_group_id, qq_group_id):
    ## set drive mode on/off
    global tg_bot
    global qq_bot
    global drive_modes
    if status == 1:
        msg = 'Telegram向QQ转发消息已暂停'
    elif status == 0:
        msg = 'Telegram向QQ转发消息已重启'
    drive_modes[forward_index] = status
    tg_bot.sendMessage(tg_group_id, msg)
    qq_bot.send(SendGroupMessage(group=qq_group_id, text=msg))
Beispiel #9
0
def set_sticker_link_mode(forward_index, status, tg_group_id, qq_group_id):
    ## set sticker link mode on/off
    global tg_bot
    global qq_bot
    global sticker_link_modes
    if status == 1:
        msg = 'Telegram Sticker图片链接已启用'
    elif status == 0:
        msg = 'Telegram Sticker图片链接已禁用'
    sticker_link_modes[forward_index] = status
    tg_bot.sendMessage(tg_group_id, msg)
    qq_bot.send(SendGroupMessage(group=qq_group_id, text=msg))
Beispiel #10
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))
Beispiel #11
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))
Beispiel #12
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)
Beispiel #13
0
def poll_avatar():
    resp = session.get(url=Avatar.twitter_url,
                       params=Avatar.twitter_params,
                       **REQUESTS_OPTIONS_PROXIED)

    if resp.status_code == 200:
        user = resp.json()
        url = Avatar.image_prog.sub(Avatar.image_repl,
                                    user['profile_image_url_https'])
    else:
        error("[Avatar]", "Response failed:", resp.status_code, resp.text)
        return

    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 g in notify['group']:
                qqbot.send(SendGroupMessage(group=g, text=text))
def drive_mode_off(forward_index, tg_group_id, tg_user, qq_group_id, qq):
    DRIVE_MODE[forward_index] = False
    msg = 'Telegram向QQ转发消息已重启'
    global_vars.tg_bot.sendMessage(tg_group_id, msg)
    global_vars.qq_bot.send(SendGroupMessage(group=qq_group_id, text=msg))
Beispiel #15
0
def notify_pratice():
    qqbot.send(SendGroupMessage(
        group=POI_GROUP, text="演习快刷新啦、赶紧打演习啦!"))
Beispiel #16
0
def notify_hourly():
    hour = str(datetime.now(pytz.timezone("Asia/Tokyo")).hour)
    text = NOTIFY_HOURLY.get(hour, '')
    if text:
        qqbot.send(SendGroupMessage(group=POI_GROUP, text=text))
Beispiel #17
0
def join(message):
    qqbot.send(SendGroupMessage(
        group=message.group,
        text="{} 欢迎来到 poi 用户讨论群。新人请发女装照一张。".format(
            CQAt(message.operatedQQ))
    ))
Beispiel #18
0
def tg_msg_receive(msg):
    global tg_bot
    global qq_bot
    global tg_bot_id
    global forward_ids
    global sticker_link_modes
    global drive_modes
    global server_pic_url

    ## log message
    logging.info(msg)

    ## drop if not Telegram group message
    chat_type = msg[u'chat'][u'type']
    if chat_type != u'group':
        return

    ## get QQ group to forward message
    tg_group_id = msg[u'chat'][u'id']
    qq_group_id, _, forward_index = get_forward_info(0, int(tg_group_id))

    ### special instruction: show group id
    if u'text' in msg and msg[u'text'] == u'[showgroupid]':
        tg_bot.sendMessage(tg_group_id,
                           u'DEBUG: tg_group_id = ' + str(tg_group_id))
        return

    if forward_index == -1:
        return

    ## get sender name
    sender = msg[u'from'][u'first_name']
    if u'last_name' in msg[u'from']:
        sender += " " + msg[u'from'][u'last_name']

    ## get text in message
    text = u''

    ### plain text
    if u'text' in msg:
        text = msg[u'text']

    ### photo message
    elif u'photo' in msg:
        fileId = msg[u'photo'][-1][u'file_id']
        pic_url = tg_get_pic_url(tg_bot, fileId, 'jpg')
        text = u'[图片, 请点击查看' + pic_url + u']'

    ### video message (show placeholder)
    elif u'video' in msg:
        text = u'[视频]'

    ### audio message (show placeholder)
    elif u'audio' in msg:
        text = u'[音频]'

    ### document message (show placeholder)
    elif u'document' in msg:
        text = u'[文件]'

    ### sticker message
    elif u'sticker' in msg:
        text = u'[' + msg[u'sticker'][u'emoji'] + u' sticker]'
        file_id = msg[u'sticker'][u'file_id']

        #### check sticker link mode
        if sticker_link_modes[forward_index] == 1:
            pic_url = tg_get_pic_url(tg_bot, file_id, 'png')
            text = u'[' + msg[u'sticker'][
                u'emoji'] + ' sticker, 请点击查看' + pic_url + u']'

    ## add picture caption to text
    if u'caption' in msg:
        text = text + ' ' + msg[u'caption']

    ## handle special instructions
    if text == u'[sticker link on]':
        set_sticker_link_mode(forward_index, 1, tg_group_id, qq_group_id)
    elif text == u'[sticker link off]':
        set_sticker_link_mode(forward_index, 0, tg_group_id, qq_group_id)
    elif text == u'[drive mode on]':
        set_drive_mode(forward_index, 1, tg_group_id, qq_group_id)
    elif text == u'[drive mode off]':
        set_drive_mode(forward_index, 0, tg_group_id, qq_group_id)

    else:
        ## add `forward from` tag
        forwardFrom = u''
        if u'forward_from' in msg:
            forward_sender = msg[u'forward_from'][u'first_name']
            if forward_sender == 'null' and u'forward_from_chat' in msg:
                forward_sender = msg[u'forward_from_chat'][u'title']
            if u'last_name' in msg[u'forward_from']:
                forward_sender += " " + msg[u'forward_from'][u'last_name']
            forwardFrom = u' (forwarded from ' + forward_sender + u') '

        ## add `reply to` tag
        replyTo = u''
        if u'reply_to_message' in msg:
            reply_sender = msg[u'reply_to_message'][u'from'][u'first_name']
            if u'last_name' in msg[u'reply_to_message'][u'from']:
                reply_sender += " " + msg[u'reply_to_message'][u'from'][
                    u'last_name']
            replyTo = u' (reply to ' + reply_sender + u') '
            if msg[u'reply_to_message'][u'from'][u'id'] == tg_bot_id:
                reply_msg_text = ''
                if (u'photo' in msg[u'reply_to_message']
                        or u'document' in msg[u'reply_to_message']
                    ) and u'caption' in msg[u'reply_to_message']:
                    reply_msg_text = msg[u'reply_to_message'][u'caption']
                elif u'text' in msg[u'reply_to_message']:
                    reply_msg_text = msg[u'reply_to_message'][u'text']

                if reply_msg_text.find(':') > 0:
                    replyTo = u' (reply to ' + reply_msg_text.split(
                        ":")[0] + u') '

        ## replace emoji to CQ:emoji
        for i in range(8986, 12287):
            text, _ = re.subn(chr(i), "[CQ:emoji,id=" + str(i) + "]", text)
        for i in range(126980, 129472):
            text, _ = re.subn(chr(i), "[CQ:emoji,id=" + str(i) + "]", text)

        ## blank message add placeholder
        if len(text) == 0:
            text = '[不支持的消息类型]'

        ## check drive mode
        if drive_modes[forward_index] == 1:
            return

        ## send message to QQ group
        qq_bot.send(
            SendGroupMessage(group=qq_group_id,
                             text=sender + replyTo + forwardFrom + ': ' +
                             text))
Beispiel #19
0
def handle_group_message(msg):
    text = msg.text
    qq = msg.qq
    group = msg.group
    current_time = int(time.time() * 1000)

    global watched_group_messages

    parts = text.split(" ")
    if parts[0] == "/subscribe" or parts[0] == "/unsubscribe":
        try:
            subscribe_type = parts[1]
            op = None

            if subscribe_type == "from":
                from_qq = parts[2]
                op = {
                    "qq": qq,
                    "from_group": group,
                    "type": "from",
                    "from_qq": from_qq
                }
            elif subscribe_type == "keyword":
                kw = parts[2]
                op = {
                    "qq": qq,
                    "from_group": group,
                    "type": "keyword",
                    "keyword": kw
                }
            else:
                qqbot.send(SendGroupMessage(group=group, text="未知的订阅类型。"))
                return

            current = db.group_subscriptions.find_one(op)

            if parts[0] == "/subscribe":
                if current != None:
                    qqbot.send(SendGroupMessage(group=group,
                                                text="消息订阅记录已存在。"))
                else:
                    db.group_subscriptions.insert_one(op)
                    qqbot.send(SendGroupMessage(group=group, text="订阅成功。"))
            else:
                if current == None:
                    qqbot.send(SendGroupMessage(group=group,
                                                text="消息订阅记录不存在。"))
                else:
                    db.group_subscriptions.delete_many(op)
                    qqbot.send(SendGroupMessage(group=group, text="取消订阅成功。"))

        except Exception as e:
            print(e)
            qqbot.send(SendGroupMessage(group=group, text="订阅失败。"))
    else:
        for ss in db.group_subscriptions.find({
                "type": "from",
                "from_group": group,
                "from_qq": qq
        }):
            watched_group_messages.append({
                "qq": ss["qq"],
                "from_group": group,
                "from_qq": qq,
                "content": text,
                "create_time": current_time
            })
        for ss in db.group_subscriptions.find({
                "type": "keyword",
                "from_group": group
        }):
            if ss["keyword"] in text:
                watched_group_messages.append({
                    "qq": ss["qq"],
                    "from_group": group,
                    "from_qq": qq,
                    "content": text,
                    "create_time": current_time
                })
def drive_mode_on(forward_index, tg_group_id, tg_user, qq_group_id, qq):
    global_vars.qq_bot.send(
        GetGroupMemberList(group=qq_group_id))  # send reload action
    msg = 'QQ群名片已重新加载'
    global_vars.tg_bot.sendMessage(tg_group_id, msg)
    global_vars.qq_bot.send(SendGroupMessage(group=qq_group_id, text=msg))
Beispiel #21
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)
Beispiel #22
0
def join(message):
    qqbot.send(
        SendGroupMessage(group=message.group,
                         text="{} 欢迎来到民政统计群,请将群名片改为地区+姓氏的格式。".format(
                             CQAt(message.operatedQQ))))