[PYTHON] I tried to save the data with discord

Upload the file to the discord channel and get it (Because it was made by a beginner, there may be something strange)

environment

python 3.8.2 discord.py 1.5.1

The reason for trying to make

I wish I could save the data with discord Since it is running on heroku, it will restart automatically in about 24 hours. So when you save the file, it disappears The only way to use it is to rent a data server. I don't understand even if I look at various articles ... You should be able to upload files with discord here ... I created it like this

BOT creation

First of all, if you don't know what discord.py is, please refer to here. https://qiita.com/1ntegrale9/items/9d570ef8175cf178468f

basic configuration

First of all, it is assumed that the BOT setting etc. is completed and it can be used. Next, create a channel to save the data The name can be anything The next is the most important file to save Create the file with json This is the json file used this time

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

Code to load first

First, here is the code to read the file

@bot.event
async def on_ready():
    mass =  bot.get_channel(ID of the created channel)
    id = mass.last_message_id
    msg = await mass.fetch_message(id)
    await msg.attachments[0].save("goban.json")

Here is the code to load and save Please change the name to save by yourself After that, open the file after the code of this and put it in list etc. You can use it when you put it in Please add according to the purpose of use

Code to add to the file

Here is the code to add to the file

@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}"] 

First of all, if you try to add it to json, it will be overwritten. Then you can not use it, first open the file and add it to the list etc. The next important code to add


    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(Created channel ID).send(file=discord.File('goban.json'))

If you connect this to the previous code, it will look like this


@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(Created channel ID).send(file=discord.File('goban.json'))

Now you can add or freely add it You can update it by reopening it after this. If you connect all the cords so far

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()Created 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:                     #Su
        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(Created channel ID).send(file=discord.File('goban.json'))
    motolist = []

bot.run("TOKEN")

Finally

This is a program used by python beginners. please tell me

Recommended Posts

I tried to save the data with discord
I tried to get CloudWatch data with Python
I tried to operate Linux with Discord Bot
I tried to learn the sin function with chainer
I tried to read and save automatically with VOICEROID2 2
I tried to predict the J-League match (data analysis)
I tried to solve the soma cube with python
I tried to automatically read and save with VOICEROID2
I tried to solve the problem with Python Vol.1
I tried to analyze J League data with Python
I tried to move the ball
I tried to estimate the interval.
I tried to find the entropy of the image with python
I tried to simulate how the infection spreads with Python
I tried to analyze the whole novel "Weathering with You" ☔️
I tried to make various "dummy data" with Python faker
I tried to find the average of the sequence with TensorFlow
I tried to notify the train delay information with LINE Notify
I tried to divide the file into folders with Python
I tried to visualize the running data of the racing game (Assetto Corsa) with Plotly
I tried to implement Autoencoder with TensorFlow
I tried to summarize the umask command
I tried to visualize AutoEncoder with TensorFlow
I tried to recognize the wake word
I tried factor analysis with Titanic data!
I tried to summarize the graphical modeling.
I tried to estimate the pi stochastically
I tried to touch the COTOHA API
I tried to implement CVAE with PyTorch
I tried playing with the image with Pillow
I tried to solve TSP with QAOA
I tried to describe the traffic in real time with WebSocket
I tried to solve the ant book beginner's edition with python
Save the results of crawling with Scrapy to the Google Data Store
I tried to automate the watering of the planter with Raspberry Pi
I tried to process the image in "sketch style" with OpenCV
[Pandas] I tried to analyze sales data with Python [For beginners]
I tried to get started with Bitcoin Systre on the weekend
I tried to process the image in "pencil style" with OpenCV
I tried to expand the size of the logical volume with LVM
I tried to improve the efficiency of daily work with Python
I tried to display the point cloud data DB of Shizuoka prefecture with Vue + Leaflet
I tried to analyze the data of the soccer FIFA World Cup Russia tournament with soccer action
I tried to predict next year with AI
[Python] I tried to visualize the night on the Galactic Railroad with WordCloud!
I tried web scraping to analyze the lyrics.
I tried to detect Mario with pytorch + yolov3
I tried to implement reading Dataset with PyTorch
I tried to use lightGBM, xgboost with Boruta
I tried to refer to the fun rock-paper-scissors poi for beginners with Python
[Data science basics] I tried saving from csv to mysql with python
I tried to learn logical operations with TF Learn
I tried to move GAN (mnist) with keras
I tried "differentiating" the image with Python + OpenCV
I tried to detect motion quickly with OpenCV
I tried to integrate with Keras in TFv1.1
I want to knock 100 data sciences with Colaboratory
I wanted to play with the Bezier curve
I tried principal component analysis with Titanic data!
Save data to flash with STM32 Nucleo Board
765 I tried to identify the three professional families by CNN (with Chainer 2.0.0)