python - 为什么变量“client”不能正常工作?
问题描述
我正在使用 discord.py 制作一个不和谐的机器人,并且想知道为什么我的client
变量不起作用。我知道它与全局变量有关,但我似乎无法让它工作。我有两个脚本通过我认为被称为“cogs”的东西连接起来。这是我的第一个脚本(主要脚本)。
import discord
import os
from discord.ext import commands
token = # For obvious reasons not shown
client = commands.Bot(command_prefix = "!")
@client.command()
async def load(ctx, extention):
client.load_extension(f'cogs.{extention}')
@client.command()
async def unload(ctx, extention):
client.unload_extension(f'cogs.{extention}')
@client.command()
async def reload(ctx, extention):
client.unload_extension(f'cogs.{extention}')
client.load_extension(f'cogs.{extention}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
client.run(token)
当涉及到这个脚本时,一切都很好,但是当涉及到我的第二个脚本时,出现了问题。
import discord
from discord.ext import commands
import time as t
import random
class Coinflip(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases=['coinflip'])
async def cf(self, ctx, cfChoice: str):
# Randomize and set choice to upper case letters
cfChoice = cfChoice.upper()
cfResults = random.choice(['RED', 'BLUE'])
# Get the user who sent the message
user = client.get_user(ctx.message.author.id)
t.sleep(1)
if cfChoice == 'RED' or cfChoice == 'BLUE':
# WIN
if cfChoice == cfResults:
# Send result in the channel
await ctx.send(f'It is {cfResults.lower()}!')
# Send a DM to the person
await user.send('You won on coinflip! Well done.')
# LOST
elif cfChoice != cfResults:
# Send result in the channel
await ctx.send(f'It is {cfResults.lower()}!')
# Send a DM to the person
await user.send('You lost on coinflip! Good luck next time.')
# NOT VALID CHOICE
else:
# Send a DM to the person
await user.send(f'"{cfChoice.lower()}" is not valid! Try again! [red/blue]')
def setup(client):
client.add_cog(Coinflip(client))
该client
变量在除此处以外的任何地方都可以正常工作user = client.get_user(ctx.message.author.id)
。它说“未定义的变量'客户端'”。谢谢您的帮助。