async def main(): objs: List[LTUser] = await queries.get_lt_user_by(available=True, is_vip=True) for i, obj in enumerate(objs): await post_heartbeat(i, len(objs), obj) await asyncio.sleep(5) logging.info(f"Post heart beat task done({len(objs)}).\n\n")
async def sync_raffle(redis): raffles = await RedisRaffle.get_all(redis=redis) for raffle in raffles: raffle_id = raffle["raffle_id"] cloud_get_uid = False if "winner_uid" in raffle and "winner_name" in raffle: uid = raffle["winner_uid"] name = raffle["winner_name"] if not uid: uid = await BiliUser.get_uid_by_name(name=name) if not uid: cloud_get_uid = True uid = await ReqFreLimitApi.get_uid_by_name(user_name=name) raffle["winner_uid"] = uid r = await Raffle.create(**raffle) if uid: # notice await notice_qq(room_id=raffle["room_id"], winner_uid=uid, winner_name=name, prize_gift_name=raffle["prize_gift_name"], sender_name=raffle["sender_name"]) logging.info( f"Saved: T:{raffle['raffle_id']} {r.id} Raffle Full. cloud_get_uid: {cloud_get_uid}" ) else: r = await Raffle.record_raffle_before_result(**raffle) logging.info(f"Saved: T:{raffle['raffle_id']} {r.id} Raffle Pre.") await RedisRaffle.delete(raffle_id, redis=redis)
async def main(): start_time = time.time() lock_key = "EXE_RECORD_RAFFLE" if not await redis_cache.set_if_not_exists( lock_key, value=1, timeout=60 * 3): logging.info("RECORD_RAFFLE Another proc is Running. Now exit.") await redis_cache.close() return await objects.connect() x_node_redis = await gen_x_node_redis() try: await sync_guard(x_node_redis) await sync_raffle(x_node_redis) await sync_anchor(x_node_redis) except Exception as e: logging.error(f"{e}\n{traceback.format_exc()}") # tears down. await x_node_redis.close() await objects.close() await redis_cache.delete(lock_key) await redis_cache.set(key="LT_RAFFLE_DB_UPDATE_TIME", value=time.time()) await redis_cache.close() logging.info(f"RECORD_RAFFLE done! cost: {time.time() - start_time:.3f}.")
async def auto_shutdown(): while True: today_key = f"STORM:HT:{datetime.datetime.now().date()}" r = await redis_cache.set_if_not_exists(key=today_key, value=1) if r: logging.info(f"今日未重启,现在重启.") sys.exit(0) await asyncio.sleep(60)
async def sync_guard(redis): data = await RedisGuard.get_all(redis=redis) for d in data: raffle_id = d["gift_id"] await Guard.create(**d) await RedisGuard.delete(raffle_id, redis=redis) logging.info( f"Saved: G:{d['gift_id']} {d['sender_name']} -> {d['room_id']}")
async def main(): start_prompt = f"Start do sign task" print(start_prompt) split_char_len = (100 - len(start_prompt)) // 2 split_char = f"{'-' * split_char_len}" logging_msg_list = [ f"\n{split_char}{start_prompt}{split_char}\n\n", ] start_time = time.time() lt_users: List[LTUser] = await queries.get_lt_user_by(available=True) for lt_user in lt_users: _m = f"Now proc {lt_user.name}(uid: {lt_user.DedeUserID}): \n" print(_m) logging_msg_list.append(_m) lt_user.name = await BiliApi.get_user_name(lt_user.user_id) await queries.update_lt_user(lt_user, fields=["name"]) cookie = lt_user.cookie flag, result = await BiliApi.do_sign(cookie) if not flag and "请先登录" in result: logging_msg_list.append( f"WARNING: Do sign failed, user: {lt_user.name} - {lt_user.DedeUserID}, " f"flag: {flag}, result: {result}\n") await queries.set_lt_user_invalid(lt_user=lt_user) continue flag, is_vip = await BiliApi.get_if_user_is_live_vip(cookie) if flag: if is_vip != lt_user.is_vip: await queries.set_lt_user_if_is_vip(lt_user=lt_user, is_vip=is_vip) else: logging_msg_list.append( f"WARNING: Get if it is vip failed, user: {lt_user.name} - {lt_user.DedeUserID}, " f"flag: {flag}, is_vip: {is_vip}\n") r, data = await BiliApi.do_sign_group(cookie) if not r: logging_msg_list.append( f"ERROR: Sign group failed, {lt_user.name}-{lt_user.DedeUserID}: {data}\n" ) if lt_user.DedeUserID == g.BILI_UID_DD: # 触发领取今日辣条 await BiliApi.silver_to_coin(cookie) await BiliApi.get_bag_list(cookie=cookie) await BiliApi.receive_daily_bag(cookie=cookie) logging_msg_list.append("\tSuccess !\n") logging_msg_list.append( f"\nDo sign task done. cost: {int((time.time() - start_time) *1000)} ms.\n" ) logging_msg_list.append(f"{'-'*100}") logging.info("".join(logging_msg_list))
async def main(): start_prompt = f"Start do sign task" print(start_prompt) split_char_len = (100 - len(start_prompt)) // 2 split_char = f"{'-' * split_char_len}" logging_msg_list = [ f"\n{split_char}{start_prompt}{split_char}\n\n", ] start_time = time.time() objs = await DBCookieOperator.get_objs(available=True) for obj in objs: _m = f"Now proc {obj.name}(uid: {obj.DedeUserID}): \n" print(_m) logging_msg_list.append(_m) cookie = obj.cookie flag, result = await BiliApi.do_sign(cookie) if not flag and "请先登录" in result: logging_msg_list.append( f"WARNING: Do sign failed, user: {obj.name} - {obj.DedeUserID}, " f"flag: {flag}, result: {result}\n" ) await DBCookieOperator.set_invalid(obj) continue flag, is_vip = await BiliApi.get_if_user_is_live_vip(cookie) if flag: if is_vip != obj.is_vip: await DBCookieOperator.set_vip(obj, is_vip) else: logging_msg_list.append( f"WARNING: Get if it is vip failed, user: {obj.name} - {obj.DedeUserID}, " f"flag: {flag}, is_vip: {is_vip}\n" ) r, data = await BiliApi.do_sign_group(cookie) if not r: logging_msg_list.append(f"ERROR: Sign group failed, {obj.name}-{obj.DedeUserID}: {data}\n") await BiliApi.do_sign_double_watch(cookie) if obj.DedeUserID == g.BILI_UID_DD: # 触发领取今日辣条 await BiliApi.silver_to_coin(cookie) await BiliApi.get_bag_list(cookie=cookie) await BiliApi.receive_daily_bag(cookie=cookie) logging_msg_list.append("\tSuccess !\n") logging_msg_list.append(f"\nDo sign task done. cost: {int((time.time() - start_time) *1000)} ms.\n") logging_msg_list.append(f"{'-'*100}") logging.info("".join(logging_msg_list))
async def notice_qq(room_id, winner_uid, winner_name, prize_gift_name, sender_name): qq_1 = await RaffleToCQPushList.get(bili_uid=winner_uid) if qq_1: message = f"恭喜{winner_name}[{winner_uid}]中了{prize_gift_name}!\n[CQ:at,qq={qq_1}]" r = await ml_qq.send_group_msg(group_id=981983464, message=message) logging.info(f"__ML NOTICE__ r: {r}") if winner_uid in (g.BILI_UID_DD, g.BILI_UID_TZ, g.BILI_UID_CZ): message = (f"恭喜{winner_name}({winner_uid})[CQ:at,qq={g.QQ_NUMBER_DD}]" f"获得了{sender_name}提供的{prize_gift_name}!\n" f"https://live.bilibili.com/{room_id}") await async_zy.send_private_msg(user_id=g.QQ_NUMBER_DD, message=message)
async def get_live_room_status(self, room_id: int) -> bool: if not room_id: return False if time.time( ) - self._last_check_time < self.LIVE_STATUS_CHECK_INTERVAL: return True flag, status = await BiliApi.get_live_status(room_id) logging.info( f"Check live room status: room_id: {room_id} -> status: {status}") if not flag: raise RuntimeError(f"BiliApi Exception: {status}") if status: self._last_check_time = time.time() return status
async def post_heartbeat(index, total, lt_user_obj): cookie = lt_user_obj.cookie r, data = await BiliApi.post_heartbeat_5m(cookie) if not r: logging.error(f"post_heartbeat_5m failed! msg: {data}") return r, data = await BiliApi.post_heartbeat_last_timest(cookie) if not r: logging.error(f"post_heartbeat_last_timest failed! msg: {data}") return if lt_user_obj.access_token: r, data = await BiliApi.post_heartbeat_app(cookie=cookie, access_token=lt_user_obj.access_token) if not r: logging.error(f"post_heartbeat_app failed! msg: {data}") await record_heart_beat(user_id=lt_user_obj.user_id) logging.info(f"({index + 1}/{total}) Post heartbeat for {lt_user_obj} done.")
async def post_heartbeat(index, total, lt_user_obj): cookie = lt_user_obj.cookie r, data = await BiliApi.post_heartbeat_5m(cookie) if not r: logging.error(f"post_heartbeat_5m failed! msg: {data}") return r, data = await BiliApi.post_heartbeat_last_timest(cookie) if not r: logging.error(f"post_heartbeat_last_timest failed! msg: {data}") return r, data = await BiliApi.post_heartbeat_app( cookie=cookie, access_token=lt_user_obj.access_token) if not r: logging.error(f"post_heartbeat_app failed! msg: {data}") return logging.info( f"({index + 1}/{total}) Post heartbeat for {lt_user_obj.name}(uid: {lt_user_obj.DedeUserID}) done." )
async def run(self): hbe = None small_hb_task = None hbx_index = 1 while True: is_living = await self.get_live_room_status(self.room_id) if not is_living: hbe = None self.room_id = await self.find_living_room() if small_hb_task: small_hb_task.cancel() small_hb_task = None if self.room_id is None: await asyncio.sleep(60 * 5) continue user: LTUser = await queries.get_lt_user_by_uid(self.user_id) if not user: logging.error(f"User {self.user_id} 认证过期,需要重新登录!") break api = BiliPrivateApi(req_user=user) if hbe is None: hbe = await api.storm_heart_e(self.room_id) small_hb_task = asyncio.create_task(self.heartbeat_small(api)) await asyncio.sleep(hbe.heartbeat_interval) continue response = await api.storm_heart_x(hbx_index, hbe, self.room_id) logging.info(f"storm_heart_x: {response}") hbx_index += 1 if hbx_index > 7: break await asyncio.sleep(hbe.heartbeat_interval) if small_hb_task is not None: small_hb_task.cancel()
async def find_living_room(self) -> Optional[int]: flag, data = await BiliApi.get_user_medal_list(self.user_id) if not flag: return medals = list(data[str(self.user_id)]["medal"].values()) master_id_list = [m["master_id"] for m in medals] api = BiliPublicApi() for master_id in master_id_list: r = await api.get_live_room_info(user_id=master_id) if r.liveStatus != 1: await asyncio.sleep(2) continue r = await api.get_live_room_detail(r.roomid) if r: room_id = r.short_id or r.room_id logging.info( f"Find live room for user {self.user_id} -> room_id: {room_id}" ) return room_id await asyncio.sleep(2)
async def main(): objs = await DBCookieOperator.get_objs(available=True, is_vip=True) for i, obj in enumerate(objs): await post_heartbeat(i, len(objs), obj) await asyncio.sleep(5) logging.info(f"Post heart beat task done({len(objs)}).\n\n")
async def sync_anchor(redis): raffles = await RedisAnchor.get_all(redis=redis) for raffle in raffles: raffle_id = raffle["id"] room_id = raffle["room_id"] prize_gift_name = raffle["award_name"] prize_count = raffle["award_num"] gift_name = "天选时刻" gift_type = "ANCHOR" users = await objects.execute( BiliUser.select().where(BiliUser.real_room_id == room_id)) if users: sender = users[0] sender_name = sender.name else: flag, info = await BiliApi.get_live_room_info_by_room_id( room_id=room_id) if not flag: logging.error( f"ANCHOR_LOT_AWARD Cannot get live room info of {room_id}, reason: {info}." ) continue sender_uid = info["uid"] flag, info = await BiliApi.get_user_info(uid=sender_uid) if not flag: logging.error( f"ANCHOR_LOT_AWARD Cannot get get_user_info. uid: {sender_uid}, reason: {info}." ) continue sender_name = info["name"] sender_face = info["face"] sender = await BiliUser.get_or_update(uid=sender_uid, name=sender_name, face=sender_face) logging.info( f"ANCHOR_LOT_AWARD Sender info get from biliapi. {sender_name}({sender_uid})" ) for i, user in enumerate(raffle["award_users"]): inner_raffle_id = raffle_id * 10000 + i winner_name = user["uname"] winner_uid = user["uid"] winner_face = user["face"] winner = await BiliUser.get_or_update(uid=winner_uid, name=winner_name, face=winner_face) r = await objects.create(Raffle, id=inner_raffle_id, room_id=room_id, gift_name=gift_name, gift_type=gift_type, sender_obj_id=sender.id, sender_name=sender_name, winner_obj_id=winner.id, winner_name=winner_name, prize_gift_name=prize_gift_name, prize_count=prize_count, created_time=datetime.datetime.now() - datetime.timedelta(seconds=600), expire_time=datetime.datetime.now()) logging.info(f"Saved: Anchor:{raffle_id} {r.id}") # notice await notice_qq( room_id=room_id, winner_uid=winner_uid, winner_name=winner_name, prize_gift_name=prize_gift_name, sender_name=sender_name, ) await RedisAnchor.delete(raffle_id, redis=redis)