Nisan 30, 2025

🎮 Python ve Riot Games API kullanan Discord botu

Merhaba! Bu yazıda sizlere Riot API kullanarak geliştirdiğim, League of Legends oyuncularının şu anda aktif bir oyunda olup olmadığını kontrol eden ve detaylı takım bilgilerini sunan bir Discord botu yazacağız.

Bu bot, bir oyuncunun Riot ID’sini girerek:

  • Çok fazla oyun oynamış ama hâlâ düşük ligde olanları “stuck” (takılı kalmış) olarak gösterir.
  • Oyuncunun şu anda oyunda olup olmadığını kontrol eder.
  • Oyundaki 10 oyuncunun her birinin seçtiği şampiyonu gösterir.
  • Her oyuncunun solo derecesini (lig, kademe, LP) ve kazanma oranını (winrate) listeler.
  • Yüksek winrate’li oyuncuları “smurf hesap” olarak işaretler.

Botu çağırmak için sadece bir komut girmeniz yeterli:

!oyun OyunNickiniz#TAG

📦 Gereksinimler

🔐 Not

Riot API anahtarınızın gizliliğini korumaya dikkat edin. Yukarıdaki kodda "RGAPI-xxx" ve "xxx" gibi yerlerde kendi anahtarlarınızı girmeniz gerekiyor. Bu bilgileri kimseyle paylaşmayın.

👨‍💻 Botun Kodu

Aşağıda botun tam Python kodunu bulabilirsiniz. Bu bot discord.py ve Riot API kullanılarak geliştirilmiştir.

🚀 Geliştirme ve Genişletme Önerileri

Bu bot hâlihazırda oldukça işlevsel olsa da, daha ileri düzey kullanıcılar için bazı geliştirme fikirleri şunlar olabilir:

  • Şampiyon ustalık puanı (Mastery) ekleme
  • Son maç geçmişini gösterme
  • Sadece dereceli maçlara özel analiz
  • Web arayüzü ile görselleştirme

🧑‍💻Kodun Tam Hali

Python
import discord
from discord.ext import commands
import requests

RIOT_API_KEY = "RGAPI-xxx"
DISCORD_BOT_TOKEN = "xxx"

REGION_LOL = "tr1"
REGION_ACCOUNT = "europe"

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)


def get_puuid(game_name, tag_line):
    url = f"https://{REGION_ACCOUNT}.api.riotgames.com/riot/account/v1/accounts/by-riot-id/{game_name}/{tag_line}"
    res = requests.get(url, headers={"X-Riot-Token": RIOT_API_KEY})
    return res.json().get("puuid")

def get_summoner(puuid):
    url = f"https://{REGION_LOL}.api.riotgames.com/lol/summoner/v4/summoners/by-puuid/{puuid}"
    res = requests.get(url, headers={"X-Riot-Token": RIOT_API_KEY})
    return res.json()

def get_active_game(puuid):
    url = f"https://{REGION_LOL}.api.riotgames.com/lol/spectator/v5/active-games/by-summoner/{puuid}"
    res = requests.get(url, headers={"X-Riot-Token": RIOT_API_KEY})
    return res.json()

def get_ranked(summoner_id):
    url = f"https://{REGION_LOL}.api.riotgames.com/lol/league/v4/entries/by-summoner/{summoner_id}"
    res = requests.get(url, headers={"X-Riot-Token": RIOT_API_KEY})
    return res.json()

def get_champion_name(champion_id):
    version_res = requests.get("https://ddragon.leagueoflegends.com/api/versions.json")
    latest_version = version_res.json()[0]
    champs_url = f"https://ddragon.leagueoflegends.com/cdn/{latest_version}/data/en_US/champion.json"
    champs_data = requests.get(champs_url).json()["data"]
    
    for champ in champs_data.values():
        if int(champ["key"]) == champion_id:
            return champ["name"]
    return "???"

def get_rank_emoji(tier):
    tier_emojis = {
        "IRON": ":black_circle:",
        "BRONZE": ":brown_circle:",
        "SILVER": ":silver_circle:",
        "GOLD": ":yellow_circle:",
        "PLATINUM": ":blue_circle:",
        "DIAMOND": ":purple_circle:",
        "MASTER": ":green_circle:",
        "GRANDMASTER": ":red_circle:",
        "CHALLENGER": ":orange_circle:",
    }
    return tier_emojis.get(tier, ":white_circle:")  # Default to white if not found

@bot.command()
async def oyun(ctx, *, riot_id):
    if "#" not in riot_id:
        await ctx.send("Lütfen Riot ID'yi `İsim#TAG` formatında girin.")
        return

    game_name, tag_line = riot_id.split("#")
    await ctx.send(f"{riot_id} için bilgiler getiriliyor...")

    puuid = get_puuid(game_name, tag_line)
    if not puuid:
        await ctx.send("Riot ID bulunamadı.")
        return

    summoner = get_summoner(puuid)
    if not summoner or "id" not in summoner:
        await ctx.send("Summoner bilgisi alınamadı.")
        return

    active_game = get_active_game(puuid)
    if not active_game or "participants" not in active_game:
        await ctx.send("Bu oyuncu şu anda aktif bir oyunda değil.")
        return

    participants = active_game["participants"]
    teams = {100: [], 200: []}
    team_counters = {100: 0, 200: 0}

    for p in participants:
        name = p.get("riotId", "Bilinmiyor")
        champion_id = p.get("championId")
        champion = get_champion_name(champion_id) if champion_id else "???"

        summoner_info = get_summoner(p["puuid"])
        tier = "Sıralama alınamadı"
        winrate = ""
        rank_emoji = ":white_circle:"  # Default rank emoji

        if summoner_info:
            ranked = get_ranked(summoner_info["id"])
            soloq = next((r for r in ranked if r["queueType"] == "RANKED_SOLO_5x5"), None)
            if soloq:
                wins = soloq["wins"]
                losses = soloq["losses"]
                total = wins + losses
                wr = f"{(wins / total * 100):.1f}%" if total > 0 else "0%"
                tier = f"{soloq['tier']} {soloq['rank']} - {soloq['leaguePoints']} LP"
                if (wins / total * 100) > 70:
                    winrate = f" | Winrate: {wr} :exclamation: Smurf Hesap"
                else:
                    winrate = f" | Winrate: {wr}"
                rank_emoji = get_rank_emoji(soloq["tier"])

        team_id = p["teamId"]
        if total > 300:
            line = f"{rank_emoji} **{name}** ({champion}) (:wheelchair: Stuck) \n{tier}{winrate}\n--------------------------------------------"
        else:
            line = f"{rank_emoji} **{name}** ({champion})\n{tier}{winrate}\n--------------------------------------------"
        teams[team_id].append(line)

    embed = discord.Embed(
        title=f"{riot_id} şu anda oyunda!",
        color=discord.Color.dark_blue()
    )

    embed.add_field(name="\n:blue_square: Mavi Takım\n--------------------------------------------", value="\n".join(teams[100]), inline=False)
    embed.add_field(name="\n\n:red_square: Kırmızı Takım\n--------------------------------------------", value="\n".join(teams[200]), inline=False)
    await ctx.send(embed=embed)

bot.run(DISCORD_BOT_TOKEN)