[PYTHON] Save the specified channel ID in text and load it at the next startup

Start

When I started making bots with Discord after a long time, I misunderstood that I could not send a message unless I got the channel ID and specified it. ~~ Accidental product (although intended) ~~

What is this?

First check the existence of the file If there is, store the read channel ID in a variable If not, go through as it is / setup Channel ID If the channel ID is correct, a success message will be sent to the specified channel. /save Save the channel ID to a text file with

When do you use it?

People who specify channels so that the bot does not move on various channels may be useful when changing the channel that moves the bot. ~~ If you don't care, use message.channel ~~

program

Source code (folded)
```python import discord

client = discord.Client()

@client.event async def on_ready(): print("logged in as "+client.user.name) try: with open("test.txt","r")as f: channel=client.get_channel(int(f.read())) await channel.send("I was able to load the channel ID") except FileNotFoundError: print("Could not get the channel ID")

@client.event async def on_message(message): global tmp if message.author != client.user: if message.content.startswith("/setup")==True: tmp=message.content[7:len(message.content)] try: channel=client.get_channel(int(tmp)) except ValueError: print("Illegal value") try: await channel.send("success") except AttributeError: print("Wrong channel ID") except UnboundLocalError: print("Illegal type") if message.content=="/save": f=open("test.txt","w") f.write(tmp) f.close() channel=client.get_channel(int(tmp)) await channel.send("I saved the channel ID") client.run("token")

</div></details>

## Commentary
### File loading
```python
    try:
        with open("test.txt","r")as f:
            channel=client.get_channel(int(f.read()))
            await channel.send("I was able to load the channel ID")
            load=1
    except FileNotFoundError:
        print("Could not get the channel ID")

If the file does not exist, try except is used to handle the error. Of course, since it is read from a text file, it is also necessary to convert from a character string to a numerical value, so int () is also used.

Get channel ID

        if message.content.startswith("/setup")==True:
            tmp=message.content[7:len(message.content)]
            try:
                channel=client.get_channel(int(tmp))
            except ValueError:
                print("Illegal value")
            try:
                await channel.send("success")
            except AttributeError:
                print("Wrong channel ID")
            except UnboundLocalError:
                print("Illegal type")

/ setup Channel ID Extract only the channel ID part with `client.get_channel (int (tmp))` Store the channel ID in the channel ~~ I don't know how to handle the error, but I put it in ~~

Save channel ID

        if message.content=="/save":
            f=open("test.txt","w")
            f.write(tmp)
            f.close()
            channel=client.get_channel(int(tmp))
            await channel.send("I saved the channel ID")

~~ ```open (" save file "," type ")` `` I remember this properly, but if I remember w of write and r of read, it will be somehow () ~~ It shouldn't be difficult here because it's mainly just writing and reading files.

Summary

** Learn the basics **

Recommended Posts