我的Discord机器人不断出现错误,无法解决该问题

时间:2019-11-21 05:05:42

标签: python

我一直在试图帮助一个朋友修复他的不和谐机器人,但是我对解决方案感到困惑。

from discord.ext import commands
import bs4
import requests
import time
import lxml



adminkey = "CheeseIsTheBest"
keys = open('keys.txt', 'w')

TOKEN = "token goes here"

client = commands.Bot(command_prefix = "!")

client.remove_command('help')

@client.event
async def on_ready():
    print("Locked And Loaded Mr. DarkKnight")

@client.command(name='ping')
async def ping(ctx):
    await ctx.send('pong')

@client.command()
async def addkey(ctx, key):
    if str(ctx.author) == "ironkey#6969" or str(ctx.author) == "ZERO#2020":
        with open('keys.txt', 'r+') as file :
            file.write(str(key + "\n"))
            file.close()
        await ctx.send('key added')
    else:
        await ctx.send('your not authorized to preform this action ' + str(ctx.author))


@client.command()
async def redeemkey(ctx, key):
    with open('keys.txt', 'r+') as file:
        for line in file:
            if str(key.strip()) == str(line.strip()):
                with open('keys.txt', 'w') as file:
                    keyfile = keyfile.replace(str(key), key + " X")
                    file.write(keyfile)
                    file.close()
                    await ctx.send('key redeemed!')
            else:
                await ctx.send('This key has already been used')

@client.command()
async def unbind(ctx, *, member):
    role = discord.utils.get(ctx.guild.roles, name='authenticated')
    await client.remove_roles(member, role)


@client.command(aliases=['inv'])
async def invite(ctx):
    await ctx.send('https://discordapp.com/api/oauth2/authorize?client_id=645664026160005129&permissions=8&scope=bot')

@client.command()
async def help(ctx):
    embed = discord.Embed(color=discord.Color.dark_blue())
    embed.set_author(name="Cheese Auth Help Menu", icon_url="")
    embed.add_field(name=".ping", value="a simple fun command! usage : .ping")
    embed.add_field(name=".invite", value="also used with the command inv, this command will get you an invite link so you can add this bot to your server! usage: .invite")
    await ctx.send(embed=embed)

client.run(TOKEN)

每次我尝试兑换添加的密钥时,都会出现此错误:

忽略命令兑换密钥中的异常:

回溯(最近通话最近):

File "C:\Users\seang\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 79, 
in wrapped ret = await coro(*args, **kwargs) 
File "C:\Users\seang\Downloads\Bot_for_DarkKnight1-_Copy.py", line 41, 
in redeemkey keyfile = keyfile.replace(str(key + X)) 
UnboundLocalError: local variable 'keyfile' referenced before assignment.

2 个答案:

答案 0 :(得分:1)

从您的代码中,我注意到keyfile.replace是问题所在。变量keyfile 尚未分配或声明(定义)。您正在逐行读取变量line中的文件,因此我认为您的代码应为

keyfile = line.replace(str(key), key + " X")

答案 1 :(得分:0)

错误来自此行:

keyfile = keyfile.replace(str(key), key + " X")

您正在尝试创建一个名为'keyfile'的 new 值,但是它依赖于来自'keyfile'的信息,而该信息尚不存在。