0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

discord.pyでユーザーごとに固有の値を保存する

Posted at

初めに

discord.pyで、ユーザーごとに固有のデータ(戦績など)を保存したくなったので作りました。

コード

まず普通にjsonファイルを読み込みます。

main.py
# memberごとになにかしらのデータを保存する
with open("member.json", "r", encoding="utf-8") as json_file:
    member_data = json.load(json_file)

つぎに、メッセージが入力されたとき、ユーザーidを用いてすでに登録されたメンバーなのか確かめます。

main.py
@client.event
async def on_message(message):
    global member_data
    if message.author == client.user:
        return

    # 新たなメンバーがいたら登録する、名前が変わったら更新する
    # 要注意!!message.author.id は int型、jsonファイルのmember_dataを検索するときの、keyはstr型、python側では関係ない
    if str(message.author.id) not in member_data:
        new_data = {
            "name": message.author.name,
            "data": [
                {
                    "name": "a_history",
                    "value": 0
                },
                {
                    "name": "b_history",
                    "value": 0
                }
            ]
        }
        member_data[message.author.id] = new_data

        with open("member.json", "w", encoding="utf-8") as json_file:
            json.dump(member_data, json_file, ensure_ascii=False, indent=4)
        with open("member.json", "r", encoding="utf-8") as json_file:
            member_data = json.load(json_file)
        print(message.author.id, message.author.name, "を新たに登録しました")
    elif message.author.name != member_data[str(message.author.id)]["name"]:
        member_data[str(message.author.id)]["name"] = message.author.name

        with open("member.json", "w", encoding="utf-8") as json_file:
            json.dump(member_data, json_file, ensure_ascii=False, indent=4)
        with open("member.json", "r", encoding="utf-8") as json_file:
            member_data = json.load(json_file)
        print(message.author.id, message.author.name, "の名前を更新しました")

member.jsonは以下のようになっています。用途によって書き換えてください。

member.json
{
    "123456789012345": {
        "name": "hoge",
        "data": [
            {
                "name": "a_history",
                "value": 0
            },
            {
                "name": "b_history",
                "value": 1
            }
        ]
    },
    "123456789012346": {
        "name": "huga",
        "data": [
            {
                "name": "a_history",
                "value": 2
            },
            {
                "name": "b_history",
                "value": 30
            }
        ]
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?