4
3

More than 3 years have passed since last update.

discordでデータ保存してみた

Last updated at Posted at 2020-11-04

discord のチャンネルにファイルを上げてそれを取得します
(初心者が作ったので変なところがあるかもしれません)

環境

python 3.8.2
discord.py 1.5.1

作ろうとしたきっかけ

discord でデータを保存できたらいいなーと思っていて
heroku で稼働しているため 約24時間で自動再起動します
なのでファイルを保存すると消えるので
使うとしたらデータサーバーを借りるしかないのですが
いろんな記事を見てもいまいちわからず・・
ここで たしかdiscord でファイルを上げれるはず・・
こんな感じで作成しました

BOT作成

まずdiscord.py とはどんなものなのかわからない方はこちらを参考にしてください
https://qiita.com/1ntegrale9/items/9d570ef8175cf178468f

基本設定

まずBOTの設定等が終わり使える状況を前提とします
次にデータを保存するチャンネルを作ります
名前はなんでもいいです
次にするのが一番重要な保存するファイルです
ファイルはjson で作ってください
今回使用するjsonファイルです

{
"goban":[
12345, 
123456, 
1234678
 ]
}

最初に読み込むコード

まずファイルを読み込むコードはこちらです

@bot.event
async def on_ready():
    mass =  bot.get_channel(作ったチャンネルのID)
    id = mass.last_message_id
    msg = await mass.fetch_message(id)
    await msg.attachments[0].save("goban.json")

これが読み込んで保存するコードです
セーブする名前は各自で変えてください
あとはこれのコードの後ろにファイルを開けてlist などに
入れると使えるようになります
使う用途に合わせて追加してください

ファイルに追加するコード

ファイルに追加するコードはこうです

@bot.command()
async def tui(ctx,ss): 
    global motolist
    with open("goban.json", "r",encoding="utf-8") as moto:

        moto = json.load(moto)
        for da in (moto['goban']):
            motolist += [f"{da}"] 

まず jsonに追加しようとすると上書きになってしまうので
それでは使えないでまずファイルを開いてリストなどに追加しておきます
次に大事な追加するコードです


    with open("goban.json","w",encoding="utf-8") as data:                     
        data.write('{\n')   
        data.write('"goban":[\n')  
        for moto in motolist: 
                data.write(f'"{str(moto)}"')
            data.write(", \n")
        data.write(f'"{ss}"\n ]')    
        data.write('\n}')                


    await bot.get_channel(作ったチャンネルID).send(file=discord.File('goban.json'))

これとさっきのコードを繋げるとこうなります


@bot.command()
async def tui(ctx,ss): 
    global motolist
    with open("goban.json", "r",encoding="utf-8") as moto:

        moto = json.load(moto)
        for da in (moto['goban']):
            motolist += [f"{da}"] 
    with open("goban.json","w",encoding="utf-8") as data:                     
        data.write('{\n')   
        data.write('"goban":[\n')  
        for moto in motolist: 
                data.write(f'"{str(moto)}"')
            data.write(", \n")
        data.write(f'"{ss}"\n ]')    
        data.write('\n}')                


    await bot.get_channel(作ったチャンネルID).send(file=discord.File('goban.json'))

こうなりましたねこれで追加したり自由にできます
このあとにもっかい開きなおすと 更新できます
いままでのコードを全部繋げると

import discord
from discord.ext import commands

import json


bot = commands.Bot(command_prefix='.')

client = discord.Client()
motolist = []



@bot.event
async def on_ready():
    mass =  bot.get_channel()作ったチャンネルID)

    id = mass.last_message_id
    msg = await mass.fetch_message(id)
    await msg.attachments[0].save("goban.json")



@bot.command()
async def tui(ctx,ss): 
    global motolist
    with open("goban.json", "r",encoding="utf-8") as moto:

        moto = json.load(moto)
        for da in (moto['goban']):
            motolist += [f"{da}"]
    with open("goban.json","w",encoding="utf-8") as data:                     # ス
        data.write('{\n')   
        data.write('"goban":[\n')  
        for moto in motolist: 
            data.write(f'"{str(moto)}"')
            data.write(", \n")

        data.write(f'"{ss}"\n ]')    
        data.write('\n}')                




    await bot.get_channel(作ったチャンネルID).send(file=discord.File('goban.json'))
    motolist = []

bot.run("TOKEN")

最後に

python 初心者が使ったプログラムです 間違っている場合などは
言ってください

4
3
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
4
3