为什么变量“ client”不能正常工作?

时间:2020-02-13 19:39:21

标签: python client bots discord discord.py

我正在用discord.py制作一个discord机器人,并且想知道为什么我的client变量不起作用。我知道它与全局变量有关,但我似乎无法使其正常工作。我有两个通过我认为称为“齿轮”的东西连接的脚本。这是我的第一个脚本(主要脚本)。

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)以外的任何地方都可以正常工作。它说“未定义的变量'客户'”。谢谢您的帮助。

0 个答案:

没有答案