【问题标题】:i create a discord level bot but it get error say not defined我创建了一个不和谐级别的机器人,但它得到错误说未定义
【发布时间】:2021-06-28 09:05:41
【问题描述】:

我创建了一个不和谐级别的机器人,但是当我使用 $rank 时它得到一个错误,说 get_point 没有定义 有人帮我打车吗?

import discord,time,json
from discord.ext import commands
class Lvl(commands.Cog):
    def __init__(self,bot):
        self.bot = bot
    
    try:
        with open("users.json") as fp:
            users = json.load(fp)
    except Exception:
        users = {}

    def save_users():
        with open("users.json", "w+") as fp:
            json.dump(users, fp, sort_keys=True, indent=4)

    def add_points(user: discord.User, points: int):
        id = user.id
        if id not in users:
            users[id] = {}
        users[id]["points"] = users[id].get("points", 0) + points
        save_users()

    def get_points(user: discord.User):
        id = user.id
        if id in users:
            return users[id].get("points", 0)
        return 0

    @commands.Cog.listener()
    async def on_message(self , message):
        if message.author == self.bot.user:
            return
        add_points(message.author, 1)
        
    @commands.command()
    async def rank(ctx,self):
        await ctx.send(f"you have {get_points(message.author)} point")
        

    def setup(bot):
        bot.add_cog(Lvl(bot))

【问题讨论】:

  • 你必须决定哪些是类方法,哪些是不属于类的函数。类成员有一个“self”参数 FIRST 并且是缩进的。函数没有“self”参数,也没有缩进。你不能混合它们

标签: python discord discord.py


【解决方案1】:

您的方法在一个类中,因此在定义时使用 self

    def get_points(self, user: discord.User):
    id = user.id
    if id in users:
        return users[id].get("points", 0)
    return 0

在调用 get points 时,你也需要使用 self

@commands.command()
async def rank(self, ctx):
    await ctx.send(f"you have {self.get_points(message.author)} point")

【讨论】:

    猜你喜欢
    • 2017-04-26
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多