Exemple #1
0
async def choose_song(bot, ev):
    key = f'{ev.group_id}-{ev.user_id}'
    if key not in temp:
        if str(ev.group_id) in last_check and datetime.datetime.now(
        ) - last_check[str(ev.group_id)] < expire:
            await bot.send(ev, '不可以替他人选歌哦', at_sender=True)
        return
    song_dict = temp[key]
    song_idx = []
    for msg_seg in ev.message:
        if msg_seg.type == 'text' and msg_seg.data['text']:
            song_idx.append(msg_seg.data['text'].strip())
    if not song_idx:
        await bot.send(ev, '你想听什么呀?', at_sender=True)
    else:
        song_idx = ''.join(song_idx)
        for idx in song_idx:
            if idx in song_dict:
                song = song_dict[idx]
                if song['type'] == '163':
                    music = MessageSegment.music(song['type'], song['id'])
                elif song['type'] == 'custom':
                    music = MessageSegment(type_='music', data=song)
                else:
                    music = MessageSegment(type_='music',
                                           data={
                                               'id': str(song['id']),
                                               'type': song['type'],
                                               'content': song['artists']
                                           })
                await bot.send(ev, music)
        del temp[key]
        del last_check[str(ev.group_id)]
Exemple #2
0
async def tietie(bot, ev):
    await bot.send(ev, '贴贴成功! 记得回礼哦~')
    await bot.send(
        ev, MessageSegment(type_='gift', data={
            'qq': str(ev.user_id),
            'id': 0
        }))
Exemple #3
0
async def send_poke(bot, ev):
    user_id = extract_target_members(ev.message)
    text = extract_plain_text(ev.message)
    m = re.match(r'[x|X](\d+)', text)
    if user_id and user_id != 'all':
        if not m:
            for uid in user_id:
                await bot.send(ev,
                               MessageSegment(type_='poke', data={'qq': uid}))
        elif m and int(m.group(1)) <= 5:
            uid = user_id[0]
            for _ in range(int(m.group(1))):
                await bot.send(ev,
                               MessageSegment(type_='poke', data={'qq': uid}))
        else:
            await bot.send(ev, '好累的样子, 我不!')
Exemple #4
0
async def echo(bot, ev):
    context = []
    for msg_seg in ev.message:
        if msg_seg.type == 'text':
            context.append(msg_seg.data['text'].strip())
    if context:
        _type, _dict_text = re.match(r'\[CQ:(\w+),(.*)\]',
                                     unescape(''.join(context))).groups()
        _dict = {}
        for item in _dict_text.split(','):
            item = item.split('=')
            k = item[0]
            v = ''.join(item[1:])
            _dict[k.strip()] = v.strip()
        await bot.send(ev, MessageSegment(type_=_type, data=_dict))
Exemple #5
0
    async def prior_intercept(cls, bot, context, msg, input_vars, update_vars, extras, **kwargs):
        if context['post_type'] == 'message':
            if context.get('sender'):
                for msg_data in context['message']:
                    if msg_data['type'] == 'rich':
                        detail_1 = json.loads(msg_data.get('data', {}).get('content', "{}").replace("&#91;", "[").replace("&#93;", "]").replace("&#44;", ",")).get("detail_1", {})
                        pic_url = detail_1.get("preview", "")

                        if detail_1.get("title") is not None and detail_1.get("desc") is not None:
                            output_msg = Message(detail_1.get("title", "无标题") + ":" + detail_1.get("desc", "无简介"))
                            if not pic_url is None and not pic_url.strip() == "":
                                if not pic_url.startswith("http"):
                                    pic_url = "http://" + pic_url

                                async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as session:
                                    async with session.get(pic_url) as resp:
                                        pic = await resp.read()

                                output_msg = output_msg + MessageSegment(type_='image', data={'file': "base64://" + base64.b64encode(pic).decode("ascii")})
                            
                            await bot.send(context, output_msg)

        return False
Exemple #6
0
async def test_reply_msg(bot, ev):
    tts = MessageSegment(type_='tts', data={'text': '肥肠抱歉本视频由于以下原因导致无法正常播放'})
    await bot.send(ev, tts)
Exemple #7
0
async def get_poke(session: NoticeSession):
    ev = session.event
    logger.info(f'被{ev.user_id}戳了')
    if ev.self_id == ev['target_id']:
        uid = ev.user_id
        await session.send(MessageSegment(type_='poke', data={'qq': str(uid)}))
Exemple #8
0
    async def all_state_intercept(cls, bot, context, msg, input_vars,
                                  update_vars, extras, **kwargs):
        if u'疫情' in msg and u'提醒' in msg:
            if u'立即' in msg:
                await cls.check_alert_update_tg(
                    "pneunomia_alert_tg/%s" %
                    (util.get_identity(context, const.GROUP)), util.global_bot,
                    context, False)
                return True

            if u'取消' in msg:
                if u'telegram' in msg.lower():
                    any = False
                    result = "取消了疫情动态(Telegram)。"
                    j: Job
                    for j in util.get_jobs():
                        real_id = j.id.split(":")[-1]
                        args = real_id.split("/")
                        if args[0] == "pneunomia_alert_tg" and args[
                                1] == util.get_identity(context, const.GROUP):
                            j.remove()
                            any = True

                    if any:
                        await bot.send(context, result)
                    return True
                else:
                    any = False
                    result = "取消了疫情动态。"
                    j: Job
                    for j in util.get_jobs():
                        real_id = j.id.split(":")[-1]
                        args = real_id.split("/")
                        if args[0] == "pneunomia_alert" and args[
                                1] == util.get_identity(context, const.GROUP):
                            j.remove()
                            any = True

                    if any:
                        await bot.send(context, result)
                    return True

            else:
                if u'telegram' in msg.lower():
                    digest = u'摘要' in msg
                    jobcall = util.make_jobcall(cls.check_alert_update_tg,
                                                context, digest)
                    job_id = "pneunomia_alert_tg/%s" % (util.get_identity(
                        context, const.GROUP))

                    try:
                        util.add_job(jobcall,
                                     trigger=IntervalTrigger(minutes=9),
                                     id=job_id)
                    except ConflictingIdError:
                        await bot.send(context, "设置开启疫情动态(Telegram):失败:已有这个任务")
                        return True

                    await bot.send(
                        context,
                        "设置开启疫情动态(Telegram):成功" + ("(摘要)" if digest else ""))
                    return True
                else:
                    jobcall = util.make_jobcall(cls.check_alert_update,
                                                context)
                    job_id = "pneunomia_alert/%s" % (util.get_identity(
                        context, const.GROUP))

                    try:
                        util.add_job(jobcall,
                                     trigger=IntervalTrigger(minutes=10),
                                     id=job_id)
                    except ConflictingIdError:
                        await bot.send(context, "设置开启疫情动态:失败:已有这个任务")
                        return True

                    await bot.send(context, "设置开启疫情动态:成功")
                    return True

        elif u'疫情' == msg.strip():
            data = await util.http_get("https://3g.dxy.cn/newh5/view/pneumonia"
                                       )
            byregion_data = REGEX_BYREGION_EXTRACT_JSON.search(data).group(
                "json")
            byregion_data = json.loads(byregion_data)

            news_data = REGEX_NEWS_EXTRACT_JSON.search(data).group("json")
            news_data = json.loads(news_data)

            result = ""

            for region in byregion_data:
                result += ("%s:" % (region["provinceShortName"]))
                result += ("确诊 %s 例" % (region["confirmedCount"]))
                if region["suspectedCount"]:
                    result += (",疑似 %s 例" % (region["suspectedCount"]))
                if region["curedCount"]:
                    result += (",治愈 %s 例" % (region["curedCount"]))
                if region["deadCount"]:
                    result += (",死亡 %s 例" % (region["deadCount"]))
                result += "\n"

            result += "\n"

            total_data = REGEX_TOTAL_EXTRACT_JSON.search(data).group("json")
            total_data = json.loads(total_data)

            remarks = []
            notes = []
            for i in range(5):
                remark = total_data.get("remark" + str(i + 1), "").strip()
                if remark != "":
                    remarks.append(remark)

            for i in range(5):
                note = total_data.get("note" + str(i + 1), "").strip()
                if note != "":
                    notes.append(note)

            remarks = "\n".join(remarks)
            notes = "\n".join(notes)
            total_data["remarks"] = remarks
            total_data["notes"] = notes
            total_data["confirmedIncr"] = total_data.get(
                "confirmedIncr", "???")
            total_data["suspectedIncr"] = total_data.get(
                "suspectedIncr", "???")
            total_data["seriousIncr"] = total_data.get("seriousIncr", "???")
            total_data["curedIncr"] = total_data.get("curedIncr", "???")
            total_data["deadIncr"] = total_data.get("deadIncr", "???")

            result += "总计全国确诊 %(confirmedCount)s 例(较昨日+%(confirmedIncr)s),疑似 %(suspectedCount)s 例(较昨日+%(suspectedIncr)s),重症 %(seriousCount)s 例(较昨日+%(seriousIncr)s),治愈 %(curedCount)s 例(较昨日+%(curedIncr)s),死亡 %(deadCount)s 例(较昨日+%(deadIncr)s)\n\n%(notes)s\n%(remarks)s" % total_data

            result += "\n"

            for i, news_obj in enumerate(news_data[0:5]):
                result += "\n" + (
                    "%d. " % (i + 1)) + datetime.datetime.fromtimestamp(
                        news_obj["modifyTime"] / 1000,
                        tz=datetime.timezone(datetime.timedelta(hours=8))
                    ).strftime("%Y-%m-%d %H:%M:%S") + " - " + news_obj["title"]

            await bot.send(context, Message(result))

            # data = await util.http_get("https://news.sina.cn/zt_d/yiqing0121")

            # sina_data = REGEX_SINA_EXTRACT_JSON.search(data).group("json")
            # sina_data = json.loads(sina_data)

            # pic_data_url = sina_data["data"]["apiRes"]["data"]["components"][0]["data"][0]["pic"]

            # await bot.send(context, MessageSegment(MessageSegment(type_='image', data={'file': pic_data_url})))

            # pic_data_url = total_data["imgUrl"]

            # await bot.send(context, MessageSegment(MessageSegment(type_='image', data={'file': pic_data_url})))

            pic_data = total_data["quanguoTrendChart"]

            for pic_data_obj in pic_data:
                await bot.send(
                    context,
                    Message(pic_data_obj["title"]) + MessageSegment(
                        type_='image', data={'file': pic_data_obj["imgUrl"]}))

            return True

        return False