Python Discord机器人偶尔出错

时间:2020-07-23 14:45:40

标签: python discord

我制作了一个自动程序,可以将文件发送给在特定频道中输入!download cfg的用户。它可以工作,但过一会儿,当用户键入!download cfg时,它将引发错误。 有人可以帮忙吗?

错误:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "F:\Desktop\Coding Projects\nam1bot\bot.py", line 21, in on_message
    for line in os.listdir('master'):
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'master'

代码:

import shutil
import discord
import os
from os import path

class CLASS_NAME(discord.Client):
    async def on_ready(self):
        print("Signed in as: " + str(self.user.name) + ", ID: " + str(self.user.id))
        await client.change_presence(status=discord.Status.dnd, activity=discord.Game("!download"))

    async def on_message(self, message):
        content = message.content.lower()
        author = message.author
        channel = message.channel.id

        if message.author.id == self.user.id:
            return

        if channel == 730111032156225617:
            if "!download cfg" in content:
                        for line in os.listdir('master'):
                            if line == "nam1master.cfg":

                                src = path.realpath("master/nam1master.cfg")
                                dst = src + ".bak"
                                shutil.copy(src, dst)
                                with open("master/nam1master.cfg.bak", 'ab') as master_encode:
                                    master_encode.write(str(message.author.id).encode())
                                    master_encode.close()
                                master = "master/nam1master.cfg.bak"
                                line = "nam1master.cfg"
                                await author.send(file=discord.File(master, line))

                            else:
                                with open("master/" + line, 'rb') as master:
                                    await author.send(file=discord.File(master, line))
                        os.remove("master/nam1master.cfg.bak")
                        await message.delete()
                

client = CLASS_NAME()
client.run(insert token)

1 个答案:

答案 0 :(得分:0)

您应指定文件的完整路径。需要os库。

  1. 当前目录:os.getcwd()
  2. 源文件的目录:os.path.dirname(os.path.abspath(__file__))

示例:

master = os.getcwd() + "/master/nam1master.cfg.bak"   # Linux
master = os.getcwd() + "\\master\\nam1master.cfg.bak" # Windows