python - Discord.py 无法定义频道 [已修复]
问题描述
我正在制作一个不和谐的机器人,它将欢迎消息发送到 .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
捕获成员所属公会(或在本例中为加入)的属性。替换你ctx.message.guild.id
的member.guild.id
,你应该很好
推荐阅读
- php - 用 JSON 中的 MYSQL 表示 PHP 中的数据
- javascript - Reactjs,源数组在组件重新加载时变为空白
- typescript - 打字稿对象中的等号后面是什么
- javascript - 为什么 Selenium 中的所有 getX() 调用都需要这么长时间?
- apache-kafka-connect - kafka-connector 启动期间的秘密管理
- reactjs - I18n:缺少翻译
- c++ - 在 glUseProgram 中设置 GL_TEXTURE_CUBE_MAP 会导致 GL_INVALID_OPERATION
- java - 如何使用 Swagger 显示骆驼休息参数 List of Objects
- google-cloud-dataflow - Google Cloud Dataflow、TextIO 和 Kerberized HDFS
- c++ - 覆盖应用程序的低级键盘挂钩问题