[英]Discord.py can't define channel [fixed]
我正在制作一個 discord 機器人,它向 .jason 文件中的指定頻道發送歡迎消息。 因此它可以與多個服務器兼容。 但它遇到了一個錯誤,我不知道如何修復它。
@client.command()
@commands.has_permissions(administrator=True)
async def welcomeMessage(ctx):
with open("guild.json", "r") as f:
guildInfo = json.load(f)
guildInfo[ctx.message.guild.id] = ctx.message.channel.id #sets the channel it was sent to as the default welcome message channel
with open("guild.json", "w") as f:
json.dump(guildInfo, f)
@client.event
async def on_member_join(member):
with open("guild.json", "r") as f:
guildInfo = json.load(f)
channel = guildInfo[ctx.message.guild.id] #this keeps causing the error
embed = discord.Embed(colour=0x07faf6, description=f"***Welcome to the Server***")
embed.set_thumbnail(url=f"{member.avatar_url}")
embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow()
await channel.send(embed=embed)
除了這個,我已經完成了所有工作:
channel = guildInfo[ctx.message.guild.id]
它一直給我這個錯誤:
channel = guildInfo[ctx.message.guild.id]
AttributeError: module 'ctx' has no attribute 'message'
編輯:我重新編寫了代碼,現在它可以工作了。
這里是:
@client.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def welcomechannel(ctx):
fileopen = str(ctx.message.guild.id) + ".json"
file = open(fileopen, "w")
data = {}
data["channel"] = ctx.message.channel.id
json.dump(data, file)
print("The channel has been added to the list")
@client.event
async def on_member_join(member):
colours = [0x3348FF, 0x000000, 0xFFFFFF]
try:
fileopen = str(member.guild.id) + ".json"
file = open(fileopen, "r")
data = json.load(file)
channelid = data["channel"]
channel = client.get_channel(id=channelid)
embed = discord.Embed(colour=random.choice(colours), description="***Welcome***")
embed.set_thumbnail(url=f"{member.avatar_url}")
embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar_url}")
embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}")
embed.timestamp = datetime.datetime.utcnow()
await channel.send(embed=embed)
except:
print("The server doesn't have a welcome channel")
on_member_join
事件不提供上下文。 幸運的是,傳遞給on_member_join
事件的成員有一個guild
屬性,該屬性捕獲該成員所屬的公會(或在本例中為加入的)。 用member.guild.id
ctx.message.guild.id
應該很好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.