async def search_flac(session: CommandSession): keyword = session.current_arg_text resp = requests.get('http://mtage.top:8099/acg-music/search', params={'title-keyword': keyword}, timeout=1) res = resp.json() if res['success'] is False: logger.error( f"Flac query failed.\nerrorCode={res['errorCode']}\nerrorMsg={res['errorMsg']}" ) session.finish( f'查询失败 请至acgjc官网查询 http://www.acgjc.com/?s={quote(keyword)}', at_sender=True) music_list = res['result']['content'] music_list = music_list[:min(5, len(music_list))] details = [ " ".join([ f"{ele['title']}", f"{ele['downloadLink']}", f"密码:{ele['downloadPass']}" if ele['downloadPass'] else "" ]) for ele in music_list ] msg = [ f"共 {res['result']['totalElements']} 条结果" if len(music_list) > 0 else '没有任何结果', *details, '数据来自 http://www.acgjc.com', f'当前库内不包括acgjc的全部数据,更多结果可见 http://www.acgjc.com/?s={quote(keyword)}' ] session.finish('\n'.join(msg), at_sender=True)
async def get_weather_hour(location, key): tenkiyohou_list = [] location_info = await get_location_name(location, key) location = location_info[0]['id'] url = f'https://devapi.qweather.com/v7/weather/24h?key=' + key + '&location=' + location try: resp = requests.request('GET', url, timeout=5).json() if resp and resp['code'] == '200': for item in resp['hourly']: tenkiyohou_list.append({ 'fxTime': item['fxTime'], 'temp': item['temp'], 'icon': item['icon'], 'text': item['text'], 'wind360': item['wind360'], 'windDir': item['windDir'], 'windScale': item['windScale'], 'windSpeed': item['windSpeed'], 'humidity': item['humidity'], 'pop': item['pop'], 'precip': item['precip'], 'pressure': item['pressure'], 'cloud': item['cloud'], 'dew': item['dew'], 'fxLink': resp['fxLink'], 'name': location_info[0]['name'] }) else: e = stauts_code(resp['code']) logger.error(f'天气预报获取接口调用失败,{e}') tenkiyohou_list = (resp['code'], e) except Exception as e: logger.error(f'获取天气预报数据超时,错误信息为{e}') tenkiyohou_list = ('请求超时,请重试', f'错误信息为{e}') return tenkiyohou_list
async def get_steamid_from_username(user_name,is_d2_msid=False): """ 仅限于查询steam平台的命运2玩家 """ try: if not is_d2_msid: d2_resp = await api.callapi(api.search_destiny_player(displayName=user_name, membershipType=3)) d2_data = d2_resp.data membershipId = d2_data[0]['membershipId'] else: membershipId = user_name msd_resp = await api.callapi(api.get_memberships_by_id(membershipId=membershipId,membershipType=3)) # 通过d2的membershipId获取BungieNet的ID msd_data = msd_resp.data bungie_id = msd_data['bungieNetUser']['membershipId'] bungie_profie_url = f'https://www.bungie.net/zh-cht/Profile/{bungie_id}' scraper = cloudscraper.create_scraper() resp = scraper.get(bungie_profie_url, timeout=5, proxies=proxies).text soup = BeautifulSoup(resp, 'lxml') div_results = soup.find_all('div', class_="title") for i in div_results: data = i.text if '(ID: 7656' in data: steamid = data[-18:-1] if is_steamid64(steamid): return steamid else: continue except Exception as e: logger.error(f'GetSteamIdFromUsername error, reason: {e}') return None
def music_keyword(keyword): url = 'http://music.163.com/api/search/pc' headers = { 'Cookie': 'appver = 2.0.2', 'refer': 'http://music.163.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36' } params = {'s': keyword, 'offset': 0, 'limit': 1, 'type': 1} try: keywordResult = session.post(url=url, headers=headers, params=params, timeout=10) except (requests.exceptions.RequestException) as e: logger.error(f'[music.163.com connect failed]{e}') return '点歌失败惹 QAQ\n有可能是服务器网络爆炸,请重试一次' keywordJson = keywordResult.json() if keywordJson['result']['songCount']: id = keywordJson['result']['songs'][0]['id'] # title = keywordJson['result']['songs'][0]['name'] # artist = keywordJson['result']['songs'][0]['artists'][0]['name'] # image = keywordJson['result']['songs'][0]['album']['blurPicUrl'] # imageUrl = f'{image}?param=90y90' # audioUrl = f'http://music.163.com/song/media/outer/url?id={id}.mp3' else: return '没有版权,发不出去勒...' return MessageSegment.music(type_='163', id_=id)
async def search_flac(bot, ev: CQEvent): keyword = ev.message.extract_plain_text() resp = await aiorequests.get('http://mtage.top:8099/acg-music/search', params={'title-keyword': keyword}, timeout=1) res = await resp.json() if res['success'] is False: logger.error( f"Flac query failed.\nerrorCode={res['errorCode']}\nerrorMsg={res['errorMsg']}" ) await bot.finish(ev, f'查询失败 请至acgjc官网查询 www.acgjc.com/?s={quote(keyword)}', at_sender=True) music_list = res['result']['content'] music_list = music_list[:min(5, len(music_list))] details = [ " ".join([ f"{ele['title']}", f"{ele['downloadLink']}", f"密码:{ele['downloadPass']}" if ele['downloadPass'] else "" ]) for ele in music_list ] msg = [ f"共 {res['result']['totalElements']} 条结果" if len(music_list) > 0 else '没有任何结果', *details, '数据来自 www.acgjc.com', f'更多结果可见 www.acgjc.com/?s={quote(keyword)}' ] await bot.send(ev, '\n'.join(msg), at_sender=True)
async def d2_user_bind(bot, ev): ptext = ev.message.extract_plain_text().strip() uid = str(ev.user_id) gid = str(ev.group_id) if not ptext or ptext.isdigit() and len(ptext) <= 2: # if passed index num try: userdata = get_search_data(uid, gid, ptext) except Exception as e: await bot.send(ev, f"绑定玩家出错,{e}", at_sender=True) return elif is_steamid64(ptext): userdata = await search_player_from_steamid(ptext)[0] #elif is_bungie_membershipid(ptext): userdata = await search_player_from_steamid(ptext)[0] try: mstype = userdata["membershipType"] msid = userdata["membershipId"] name = userdata["displayName"] bind_user(int(uid), membership_id=msid, membership_type=mstype, display_name=name) except KeyError as e: logger.error(f"bind user failed: key error {e}, origin data is {userdata}") await bot.send(ev, f"绑定玩家失败,请重试或截图联系BOT管理员\norigin data: {userdata}", at_sender=True) return except Exception as e: logger.error(f"bind user failed: origin data is {userdata}") await bot.send(ev, f"绑定玩家失败,请重试或截图联系BOT管理员\norigin data: {userdata}", at_sender=True) return await bot.send(ev, f"已经帮変態さん绑定好用户名为【{name}】的玩家啦", at_sender=True)
async def search_timeline(bot, ev: CQEvent): gid = str(ev.group_id) if gid not in recent: recent[gid] = '' if gid not in last_search: last_search[gid] = datetime(2000, 1, 1) try: s = ev.message.extract_plain_text() if s == recent[gid] and last_search[gid] + timedelta(minutes=2) > datetime.now(): await bot.send(ev, '这个轴两分钟内才发过, 往上翻一翻吧~', at_sender=True) return db = TLSqliteDao(get_dbname(ev.group_id)) if len(s) == 0: await bot.send(ev, '为防止长消息风控, 请输入具体的BOSS编号, 如B1', at_sender=True) elif s.startswith('T'): recent[gid] = s last_search[gid] = datetime.now() r = db._find_by_id(tid2id(s)) msg = f'{r[0]}, {r[1]}伤害, {r[3]}\n' await bot.send(ev, msg + r[2]) else: recent[gid] = s last_search[gid] = datetime.now() r = db._find_by_bossname(s) msg = [ f'{MessageSegment.at(user_id=ev.user_id)}\n编号|boss|伤害|备注|赞同数'] msg.extend(r) await bot.send(ev, '\n'.join(msg)) except Exception as e: logger.error(e) await bot.send(ev, '查找轴失败,请输入\"帮助pcr会战\"查看指令的使用方式')
def gen_icon_img(self, size, star_slot_verbose=True) -> Image: try: pic = self.icon.open().convert('RGBA').resize((size, size), Image.LANCZOS) except FileNotFoundError: logger.error(f'File not found: {self.icon.path}') pic = unknown_chara_icon.convert('RGBA').resize((size, size), Image.LANCZOS) l = size // 6 star_lap = round(l * 0.15) margin_x = (size - 6 * l) // 2 margin_y = round(size * 0.05) if self.star: for i in range(5 if star_slot_verbose else min(self.star, 5)): a = i * (l - star_lap) + margin_x b = size - l - margin_y s = gadget_star if self.star > i else gadget_star_dis s = s.resize((l, l), Image.LANCZOS) pic.paste(s, (a, b, a + l, b + l), s) if 6 == self.star: a = 5 * (l - star_lap) + margin_x b = size - l - margin_y s = gadget_star_pink s = s.resize((l, l), Image.LANCZOS) pic.paste(s, (a, b, a + l, b + l), s) if self.equip: l = round(l * 1.5) a = margin_x b = margin_x s = gadget_equip.resize((l, l), Image.LANCZOS) pic.paste(s, (a, b, a + l, b + l), s) return pic
async def search(keyword, result_num: int = 3): """ 搜索音乐 """ number = 5 song_list = [] params = {"w": keyword, "format": "json", "p": 0, "n": number} headers = {"referer": "http://m.y.qq.com", "User-Agent": USER_AGENT} try: resp = await aiorequests.get( url="http://c.y.qq.com/soso/fcgi-bin/search_for_qq_cp", params=params, headers=headers, timeout=3) res_data = await resp.json() except Exception as e: logger.error(f'Request QQ Music Timeout {e}') return None for item in res_data['data']['song']['list'][:result_num]: song_list.append({ 'name': item['songname'], 'id': item['songid'], 'artists': ' '.join(artist['name'] for artist in item['singer']), 'type': 'qq' }) return song_list
def find_by(self, gid=None, cid=None, uid=None): cond_str = [] cond_tup = [] if not gid is None: cond_str.append('gid=?') cond_tup.append(gid) if not cid is None: cond_str.append('cid=?') cond_tup.append(cid) if not uid is None: cond_str.append('uid=?') cond_tup.append(uid) if 0 == len(cond_tup): return self.find_all() cond_str = " AND ".join(cond_str) with self._connect() as conn: try: ret = conn.execute( ''' SELECT {1} FROM {0} WHERE {2} '''.format(self._table, self._columns, cond_str), cond_tup).fetchall() return [self.row2item(r) for r in ret] except (sqlite3.DatabaseError) as e: logger.error(f'[MemberDao.find_by] {e}') raise DatabaseError('查找成员失败')
def delete_by(self, gid=None, cid=None, uid=None): cond_str = [] cond_tup = [] if not gid is None: cond_str.append('gid=?') cond_tup.append(gid) if not cid is None: cond_str.append('cid=?') cond_tup.append(cid) if not uid is None: cond_str.append('uid=?') cond_tup.append(uid) if 0 == len(cond_tup): raise DatabaseError('删除成员的条件有误') cond_str = " AND ".join(cond_str) with self._connect() as conn: try: cur = conn.execute( ''' DELETE FROM {0} WHERE {1} '''.format(self._table, cond_str), cond_tup) return cur.rowcount except (sqlite3.DatabaseError) as e: logger.error(f'[MemberDao.find_by] {e}') raise DatabaseError('查找成员失败')
def find_by(self, uid=None, alt=None, order_by_user=False): cond_str = [] cond_tup = [] order = 'round, boss, eid' if not order_by_user else 'uid, alt, round, boss, eid' if not uid is None: cond_str.append('uid=?') cond_tup.append(uid) if not alt is None: cond_str.append('alt=?') cond_tup.append(alt) if 0 == len(cond_tup): return self.find_all() cond_str = " AND ".join(cond_str) with self._connect() as conn: try: ret = conn.execute( ''' SELECT {1} FROM {0} WHERE {2} ORDER BY {3} '''.format(self._table, self._columns, cond_str, order), cond_tup).fetchall() return [self.row2item(r) for r in ret] except (sqlite3.DatabaseError) as e: logger.error(f'[BattleDao.find_by] {e}') raise DatabaseError('查找记录失败')
async def wrapper(): try: logger.info(f'Scheduled job {func.__name__} start.') await func() logger.info(f'Scheduled job {func.__name__} completed.') except Exception as e: logger.exception(e) logger.error( f'{type(e)} occured when doing scheduled job {func.__name__}.')
def delete(self, eid): with self._connect() as conn: try: conn.execute( ''' DELETE FROM {0} WHERE eid=? '''.format(self._table), (eid, )) except (sqlite3.DatabaseError) as e: logger.error(f'[BattleDao.delete] {e}') raise DatabaseError('删除记录失败')
def delete(self, gid, cid): with self._connect() as conn: try: conn.execute( ''' DELETE FROM {0} WHERE gid=? AND cid=? '''.format(self._table), (gid, cid)) except (sqlite3.DatabaseError) as e: logger.error(f'[ClanDao.delete] {e}') raise DatabaseError('删除公会失败')
def delete(self, uid, alt): with self._connect() as conn: try: conn.execute( ''' DELETE FROM {0} WHERE uid=? AND alt=? '''.format(self._table), (uid, alt)) except (sqlite3.DatabaseError) as e: logger.error(f'[MemberDao.delete] {e}') raise DatabaseError('删除成员失败')
def find_all(self): with self._connect() as conn: try: ret = conn.execute( ''' SELECT {1} FROM {0} ORDER BY round, boss, eid '''.format(self._table, self._columns), ).fetchall() return [self.row2item(r) for r in ret] except (sqlite3.DatabaseError) as e: logger.error(f'[BattleDao.find_all] {e}') raise DatabaseError('查找记录失败')
def find_one(self, uid): with self._connect() as conn: try: ret = conn.execute( ''' SELECT {0} FROM Colle WHERE uid=? '''.format(self._columns), (uid, )).fetchone() return self.row2item(ret) except (sqlite3.DatabaseError) as e: logger.error(f'[Gacha.find_one]{e}') raise DatabaseError('查找仓库失败')
def add(self, clan): with self._connect() as conn: try: conn.execute( ''' INSERT INTO {0} ({1}) VALUES (?, ?, ?, ?) '''.format(self._table, self._columns), (clan['gid'], clan['cid'], clan['name'], clan['server'])) except (sqlite3.DatabaseError) as e: logger.error(f'[ClanDao.add] {e}') raise DatabaseError('添加公会失败')
def modify(self, clan): with self._connect() as conn: try: conn.execute( ''' UPDATE {0} SET name=?, server=? WHERE gid=? AND cid=? '''.format(self._table), (clan['name'], clan['server'], clan['gid'], clan['cid'])) except (sqlite3.DatabaseError) as e: logger.error(f'[ClanDao.modify] {e}') raise DatabaseError('修改公会失败')
def modify(self, character): with self._connect() as conn: try: conn.execute( ''' UPDATE Colle SET colle=?,jewel=?,hiishi=? WHERE uid=? ''', (character['colle'], character['jewel'], character['hiishi'], character['uid'])) except (sqlite3.DatabaseError) as e: logger.error(f'[Gacha.modify]{e}') raise DatabaseError('修改仓库失败')
def add(self, character): with self._connect() as conn: try: conn.execute( ''' INSERT INTO Colle ({0}) VALUES (?, ?, ?,?) '''.format(self._columns), (character['uid'], character['colle'], character['jewel'], character['hiishi'])) except (sqlite3.DatabaseError) as e: logger.error(f'[Gacha.add]{e}') raise DatabaseError('创建仓库失败')
def modify(self, member): with self._connect() as conn: try: conn.execute( ''' UPDATE {0} SET name=?, gid=?, cid=? WHERE uid=? AND alt=? '''.format(self._table), (member['name'], member['gid'], member['cid'], member['uid'], member['alt'])) except (sqlite3.DatabaseError) as e: logger.error(f'[MemberDao.modify] {e}') raise DatabaseError('修改成员失败')
def find_one(self, gid, cid): with self._connect() as conn: try: ret = conn.execute( ''' SELECT {1} FROM {0} WHERE gid=? AND cid=? '''.format(self._table, self._columns), (gid, cid)).fetchone() return self.row2item(ret) except (sqlite3.DatabaseError) as e: logger.error(f'[ClanDao.find_one] {e}') raise DatabaseError('查找公会失败')
def find_one(self, uid, alt): with self._connect() as conn: try: ret = conn.execute( ''' SELECT {1} FROM {0} WHERE uid=? AND alt=? '''.format(self._table, self._columns), (uid, alt)).fetchone() return self.row2item(ret) except (sqlite3.DatabaseError) as e: logger.error(f'[MemberDao.find_one] {e}') raise DatabaseError('查找成员失败')
def add(self, member): with self._connect() as conn: try: conn.execute( ''' INSERT INTO {0} ({1}) VALUES (?, ?, ?, ?, ?) '''.format(self._table, self._columns), (member['uid'], member['alt'], member['name'], member['gid'], member['cid'])) except (sqlite3.DatabaseError) as e: logger.error(f'[MemberDao.add] {e}') raise DatabaseError('添加成员失败')
def find_by_gid(self, gid): with self._connect() as conn: try: ret = conn.execute( ''' SELECT {1} FROM {0} WHERE gid=? '''.format(self._table, self._columns), (gid, )).fetchall() return [self.row2item(r) for r in ret] except (sqlite3.DatabaseError) as e: logger.error(f'[ClanDao.find_by_gid] {e}') raise DatabaseError('查找公会失败')
def modify(self, challenge): with self._connect() as conn: try: conn.execute( ''' UPDATE {0} SET uid=?, alt=?, time=?, round=?, boss=?, dmg=?, flag=? WHERE eid=? '''.format(self._table), (challenge['uid'], challenge['alt'], challenge['time'], challenge['round'], challenge['boss'], challenge['dmg'], challenge['flag'], challenge['eid'])) except (sqlite3.DatabaseError) as e: logger.error(f'[BattleDao.modify] {e}') raise DatabaseError('修改记录失败')
def add(self, challenge): with self._connect() as conn: try: cur = conn.execute( ''' INSERT INTO {0} ({1}) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?) '''.format(self._table, self._columns), (challenge['uid'], challenge['alt'], challenge['time'], challenge['round'], challenge['boss'], challenge['dmg'], challenge['flag'])) return cur.lastrowid except (sqlite3.DatabaseError) as e: logger.error(f'[BattleDao.add] {e}') raise DatabaseError('添加记录失败')
def __init__(self, status, url, result=None): self.status = status self.url = url self.data = None self.message = None self.error_code = None self.error_status = None self.exception = None if self.status == 200: self.message = result['Message'] self.error_code = result['ErrorCode'] self.error_status = result['ErrorStatus'] if self.error_code == 1: try: self.data = result['Response'] except Exception as e: logger.error( "ResponseSummary: 200 status and error_code 1, but there was no result['Response']" ) logger.error( f"Exception: {e}.\nType: {e.__class__.__name__}") self.exception = e.__class__.__name__ else: logger.error( f'No data returned for url: {self.url}.\n {self.error_code} was the error code with status 200.' ) else: logger.error( f'Request failed for url: {self.url}.\n.Status: {self.status}')