json - 如何从 .json 文件 discord.py 中获取信息
问题描述
我想制作一个具有可自定义欢迎消息的机器人,您可以在其中使用命令并键入#(频道)和之后的消息。问题是,在 on_member_join 事件中,我不知道如何制作
,或者
guild = (the guild that the command was ran in)
所有
信息都在一个名为 welcomemsgs.json 的 json 文件中。我只需要以某种方式从 .json 文件中获取信息。这是 json 文件的示例channel = (the channel the user put in)
message = (the message the user gave)
{"channel": 896476418421178397, "message": "Welcome!", "guild": 896476417968205894 }
解决方案
实际上很简单,如果你是初学者,你可以使用 json
首先你创建命令
@bot.command()
async def welcomechannel(ctx, channel):
ch = int(channel.strip) # This removes the <#> and leaves the channel id
with open('yourfilename.json', 'r') as f: # 'r' stands for read mode
welcomes = json.load(f)
welcomes[str(ctx.guild.id)] = ch # Sets the key to the channel
with open('yourfilename.json', 'w') as f: # 'w' stands for write mode
json.dump(welcomes, f) # Dumps the new data in the file
然后你做
@bot.event
async def on_member_join(member):
with open('yourfilename.json', 'r') as f:
welcomes = json.load(f)
channel = bot.get_channel(welcomes[str(member.guild.id)]
await channel.send("Welcome " + member.mention)
推荐阅读
- docusignapi - DocuSign - OAuth 授权代码授予 - 多个用户 - 获取访问和刷新令牌时出错
- angularjs - 无法使用 AngularJS 将 Json 数据与表头绑定
- facebook-graph-api - 为 Facebook 页面 API 开发
- amazon-sagemaker - 设备上没有剩余空间 [Amazon SageMaker]
- r - 具有预定义质心的 K 均值聚类
- excel - 保存 Outlook 邮件附件
- string - 如何创建一个递归函数,该函数返回单个参数(字符串列表)的副本,但每个字符在每个位置都重复?
- vue.js - Vuejs Vuetify 如何在 v-select 中访问对象的属性
- css - 使用css调整浏览器窗口大小时如何使图像自动调整大小?
- c# - Xamarin.UITesting NU1201 错误:Android 8.1 与 .NETFramework 4.6.1 不兼容