поэтому я пытался сделать бесплатную команду, посмотрев несколько руководств от yt и я получил ошибку .... на самом деле я определил преобразование в коде, но это показывает ошибку. Команда вызвала исключение: NameError: имя «преобразование» не определено. но в уроках, которые я смотрел, не было ошибки ..... а также я использую переписывание discord.py ........ Любая помощь приветствуется :).
Код:
class Giveaway(commands.Cog):
def __init__(self, client):
self.client = client
def convert(time):
pos = ["s", "m", "h", "d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}
unit = time[-1]
if unit not in pos:
return -1
try:
val = int(time[:-1])
except:
return -2
return val * time_dict[unit]
@commands.command()
async def giveaway(self, ctx):
await ctx.send("Answer The Following Questions For Giveaway:")
questions = ["Channel For Giveaway?",
"Duration Of Giveaway? (s , m , h , d)",
"Prize Of Giveaway?"]
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await self.client.wait_for('message', timeout=20.0, check=check)
except asyncio.TimeoutError:
await ctx.send('You Did Not Answer In Time!')
return
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
await ctx.send(f'Mention Channel Properly! Example: {ctx.channel.mention}')
return
channel = self.client.get_channel(c_id)
time = convert(answers[1])
if time == -1:
await ctx.send(f'Answer Time With A Proper Unit (s, m, h, d)')
return
elif time == -2:
await ctx.send(f'Time Must Be A Integer!')
return
prize = answers[2]
await ctx.send(f'Giveaway Will Be In Channel {channel.mention} And Will Last {time}.')
embed = discord.Embed(title = "🎉Giveaway🎉", description=f"{prize}", color=ctx.author.color)
embed.add_field(name = "Hosted by:", value= ctx.author.mention)
embed.set_footer(text=f"Ends after {answers[1]} from now. ")
g_msg = await channel.send(embed=embed)
await g_msg.add_reaction("🎉")
await asyncio.sleep(time)
new_msg = await channel.fetch_message(g_msg.id)
users = await g_msg.reactions[0].users().flatten()
users.pop(users.index(self.client.user))
winner = random.choice(users)
await channel.send(f'Congrats! {winner.mention} won {prize}!')
ОШИБКА:
time = convert(answers[1])
NameError: name 'convert' is not defined
и
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'convert' is not defined
Вы должны ссылаться на этот метод как self.convert
:
time = self.convert(answers[1])
Кроме того, подпись для метода convert
должна начинаться с параметра self
:
def convert(self, time):
Вы должны узнать, как классы работают в Python!
если это решило вашу проблему, примите это как ответ, нажав галочку на его ответе
Вам не нужен self
в качестве параметра, если он украшен @staticmethod
, так как функция не ссылается на self
. Его также можно было бы переместить за пределы класса как общую вспомогательную функцию и вызывать как есть с convert
вместо self.convert
.
я знал, что мы должны использовать self в винтиках, но был новичком в определении и использовании их в дальнейшем в коде .... это помогло мне ... большое спасибо