首页 > 解决方案 > 从 JSON 获取服务器 ID

问题描述

我想从我对如何做感到困惑的 JSON 文件中获取服务器 ID。下面是我当前的 Python 文件

import discord
from discord.ext import commands
import youtube_dl
import json

with open("configs/premium.json") as f:
    premium = json.load(f)

def premium(bot, message):
    id = message.server.id
    return premium.get(id)

class Play:
    def __init__(self, client):
        self.client = client

    @commands.command(pass_context=True)
    async def play(self, ctx):
        try:
            if ctx.message.server.id == premium:
                await self.client.say('Premium works')
            else:
                await self.client.say('Non-Premium Works!')
        except Exception as error:
            await self.client.say('{}'.format(error))

def setup(client):
    client.add_cog(Play(client))

JSON文件

{"serverID":"498054637245693952"}

标签: pythonpython-3.xdiscorddiscord.py

解决方案


如果您的 JSON 文件是

{“服务器ID”:“498054637245693952”}

然后只需更换

with open("configs/premium.json") as f: premium = json.load(f)

with open("configs/premium.json") as f: premium = json.load(f)['serverID']

此外,您应该摆脱该def premium(bot, message):函数或使用其他名称,因为它会干扰您的服务器 ID 变量名称,例如。

在此处输入图像描述


推荐阅读