Skip to content

Commit

Permalink
Merge pull request #217 from pistachiostudio/vl-update
Browse files Browse the repository at this point in the history
Vl update
  • Loading branch information
quojama authored Jan 6, 2024
2 parents fc9d166 + b7f3a74 commit 6b3ec91
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 26 deletions.
File renamed without changes.
8 changes: 5 additions & 3 deletions scripts/db_insert_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@
print("ELOは整数でなければなりません。")
exit(1)

region_input = input("プレイヤーのリージョンを入力してください。(eu, na, latam, br, ap, kr)")

conn = sqlite3.connect("data/takohachi.db")

cur = conn.cursor()

cur.execute(
"""
INSERT INTO val_puuids (puuid, region, name, tag, yesterday_elo)
VALUES (?, ?, ?, ?, ?)
INSERT INTO val_puuids (puuid, region, name, tag, yesterday_elo, yesterday_win, yesterday_lose)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(puuid_input, "ap", "xxxxx", "xxxxx", elo_input),
(puuid_input, region_input, "xxxxx", "xxxxx", elo_input, 0, 0),
)

conn.commit()
Expand Down
File renamed without changes.
6 changes: 5 additions & 1 deletion src/cogs/marimo.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ async def mt(self, interaction: discord.Interaction):
# summer time == hours=-4, not == hours=-5
now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-5)))
JST = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=+9)))
# summer time == hours=+2, not == hours=+1
paris = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=+1)))

marimo_time = f"{now.month}/{now.day} {now.hour}:{now.minute:02}"
sopot_time = f"{paris.month}/{paris.day} {paris.hour}:{paris.minute:02}"
japan_time = f"{JST.month}/{JST.day} {JST.hour}:{JST.minute:02}"

# slot
Expand All @@ -29,7 +33,7 @@ async def mt(self, interaction: discord.Interaction):
embed1 = discord.Embed()
embed1.color = discord.Color.dark_green()
embed1.set_footer(text=f"mt slot: {slot_left}{slot_center}{slot_right}")
embed1.description = f"marimo time = **{marimo_time}**\n(In Japan = {japan_time})"
embed1.description = f"marimo time = **{marimo_time}**\nSopot time = **{sopot_time}**\n(In Japan = {japan_time})"

embed2 = discord.Embed()
embed2.color = discord.Color.dark_green()
Expand Down
28 changes: 18 additions & 10 deletions src/cogs/valorant_api.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import os

import discord
import httpx
from discord import app_commands
from discord.ext import commands

current_season = "e7a3"
season_txt = current_season.replace("e", "Episode ").replace("a", " Act ")
VALORANT_TOKEN = os.environ["VALORANT_TOKEN"]


class Valo(commands.Cog):
Expand All @@ -24,8 +27,9 @@ async def vr(self, interaction: discord.Interaction, name: str, tagline: str):
await interaction.response.defer()

async def send_request(url, name, tagline):
headers = {"Authorization": VALORANT_TOKEN}
async with httpx.AsyncClient() as client:
res = await client.get(url, timeout=10)
res = await client.get(url, headers=headers, timeout=10)

data = res.json()

Expand All @@ -41,11 +45,20 @@ async def send_request(url, name, tagline):

return data

# URLのエンドポイント
rank_url = f"https://api.henrikdev.xyz/valorant/v2/mmr/ap/{name}/{tagline}"
# account_urlでユーザーのリージョンを取得
account_url = f"https://api.henrikdev.xyz/valorant/v1/account/{name}/{tagline}"

account_data = await send_request(account_url, name, tagline)
if account_data is None: # エラーチェック
return

# 取得したリージョン情報を使ってURLを更新
region = account_data["data"]["region"]
account_level = account_data["data"]["account_level"]
card_image_url = account_data["data"]["card"]["wide"]
rank_url = f"https://api.henrikdev.xyz/valorant/v2/mmr/{region}/{name}/{tagline}"
lifetime_matches_url = (
f"https://api.henrikdev.xyz/valorant/v1/lifetime/matches/ap/{name}/{tagline}"
f"https://api.henrikdev.xyz/valorant/v1/lifetime/matches/{region}/{name}/{tagline}"
)

try:
Expand All @@ -54,10 +67,6 @@ async def send_request(url, name, tagline):
if data is None: # エラーチェック
return

account_data = await send_request(account_url, name, tagline)
if account_data is None: # エラーチェック
return

match_data = await send_request(lifetime_matches_url, name, tagline)
if match_data is None: # エラーチェック
return
Expand All @@ -71,8 +80,6 @@ async def send_request(url, name, tagline):
name = data["data"]["name"]
tag = data["data"]["tag"]
rank_image_url = data["data"]["current_data"]["images"]["small"]
account_level = account_data["data"]["account_level"]
card_image_url = account_data["data"]["card"]["wide"]

# 新シーズンになって1試合もやってない場合は
# アクトごとのレスポンス部分はKeyErrorが発生するのでその判定を行う
Expand Down Expand Up @@ -128,6 +135,7 @@ async def send_request(url, name, tagline):
embed.description = f"{season_txt} competitive results"
embed.set_thumbnail(url=rank_image_url)

embed.add_field(name="Region", value=f"```{region}```")
embed.add_field(
name="Current Rank", value=f"```{currenttierpatched} (+{ranking_in_tier})```"
)
Expand Down
52 changes: 40 additions & 12 deletions src/cogs/vl_rank_task.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import os
import sqlite3
from datetime import datetime, timedelta, timezone

Expand Down Expand Up @@ -38,6 +39,8 @@
"Radiant": "<:Radiant_Rank:1123927894725496842>",
}

VALORANT_TOKEN = os.environ["VALORANT_TOKEN"]


class RankTasks(commands.Cog):
def __init__(self, bot: commands.Bot):
Expand Down Expand Up @@ -73,11 +76,15 @@ async def printer(self):
async def fetch(row):
puuid, region, name, tag, yesterday_elo, yesterday_win, yesterday_lose = row

headers = {"Authorization": VALORANT_TOKEN}

# 非同期でキャッシュをパージしてリクエスト。最新のnameとtagを取得する。
try:
account_url = f"https://api.henrikdev.xyz/valorant/v1/by-puuid/account/{puuid}?force=true"
async with httpx.AsyncClient() as client:
name_tag_response = await client.get(account_url, timeout=60)
name_tag_response = await client.get(
account_url, headers=headers, timeout=60
)
except httpx.HTTPError:
return

Expand All @@ -93,7 +100,7 @@ async def fetch(row):
f"https://api.henrikdev.xyz/valorant/v2/by-puuid/mmr/{api_region}/{puuid}"
)
async with httpx.AsyncClient() as client:
response = await client.get(url, timeout=60)
response = await client.get(url, headers=headers, timeout=60)
except httpx.HTTPError:
return

Expand Down Expand Up @@ -182,17 +189,38 @@ async def fetch(row):
async def main():
tasks = [fetch(row) for row in rows]
output = await asyncio.gather(*tasks)
join = "".join(output)
return join

join = await main()

embed = discord.Embed()
embed.set_footer(text=f"{season_txt}\n※ WLはランクのみの集計です。\n※ 引き分けは負けとしてカウントされます。")
embed.color = discord.Color.purple()
embed.title = "みんなの昨日の活動です。"
embed.description = f"{join}"
await channel.send(embed=embed)
# 分割されたメッセージのリストを初期化
messages = []
current_message = ""
for player_info in output:
# 現在のメッセージと追加するプレイヤー情報を合わせた長さを確認
if len(current_message) + len(player_info) > 4096:
# 現在のメッセージをリストに追加して、新しいメッセージを開始
messages.append(current_message)
current_message = player_info
else:
current_message += player_info

# 最後のメッセージをリストに追加
if current_message:
messages.append(current_message)

return messages

# main関数を実行してメッセージのリストを取得
messages = await main()

# 各メッセージを順番に送信
for msg in messages:
embed = discord.Embed()
embed.set_footer(
text=f"{season_txt}\n※ WLはランクのみの集計です。\n※ 引き分けは負けとしてカウントされます。\nchr: {len(msg)}" # noqa: E501
)
embed.color = discord.Color.purple()
embed.title = "みんなの昨日の活動です。"
embed.description = msg
await channel.send(embed=embed)

conn.close()

Expand Down

0 comments on commit 6b3ec91

Please sign in to comment.