我是 discord.py 的初学者,不明白为什么我的机器人不正确。我使用 VS Code IDE 通过命令提示符或 Repl.it 编写和执行我的机器人。我正在制作一个机器人来在我的不和谐服务器中 24/7 吟唱一些台词。
当我尝试运行我的机器人并在我的服务器中写入“ch!start”时,它给了我这个错误:
Traceback (most recent call last):
File "...\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "...\bot.py", line 36, in on_message
await chant()
File "...\bot.py", line 17, in chant
if ss == 'not chanting':
UnboundLocalError: local variable 'ss' referenced before assignment
为什么会发生这种情况,我该如何解决?
这是我的代码:
# bot.py
#disabled from keep_alive import keep_alive
import discord
import os
import time
client = discord.Client()
ss = 'not chanting'
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
print('I am ready to chant.')
async def chant():
if ss == 'not chanting':
ss = chanting
print('changed not chanting to chanting')
elif ss == 'chanting':
ss = 'not chanting'
print('changed chanting to not chanting')
@client.event
async def on_message(message):
msg = message.content
sendmsg = message.channel.send
author = message.author
if msg == 'ch!help':
await sendmsg('**24/7 Chanter**\nch!help - gives a list of commands I can do\nch!start - starts chanting in the specified channel\nch!stop - stops chanting')
if msg == 'ch!start':
if ss == 'not chanting':
await chant()
await sendmsg('Ok. Chanting now.')
await sendmsg('(This message triggers the code to chant.) reference')
elif ss == 'chanting':
await sendmsg('I **am** chanting!')
if msg == 'ch!stop':
if ss == 'chanting':
await chant()
await sendmsg('Ok. Stopping chanting...')
await sendmsg('Please wait...')
elif ss == 'not chanting':
await sendmsg('I **am not** chanting!')
if msg.endswith('reference'):
await sendmsg('passed test 1')
if author == client.user:
await sendmsg('passed test 2')
if ss == 'chanting':
await sendmsg('passed test 3')
await asyncio.time(4)
await sendmsg('passed test 4')
await sendmsg('(MSG)')
await asyncio.time(1)
await sendmsg('(MSG)')
await asyncio.time(3)
await sendmsg('(MSG)')
await asyncio.time(7)
await sendmsg('(MSG)')
await asyncio.time(9)
await sendmsg('(MSG)')
await asyncio.time(5)
await sendmsg('(MSG) reference')
client.run('no token 4 u')
答案 0 :(得分:1)
存在多个错误。一个是在 async def chanting():
尝试 ss = 'chanting'
,而不是 ss = chanting
。此外, ss 不是全局变量。你需要让它成为一个。查看有关如何执行此操作的评论。