使用Discord Bot命令检查JSON文件的值

发布于 2025-02-06 17:11:56 字数 3266 浏览 2 评论 0原文

好的,所以我想开始说我知道json不是数据库,也不应该用作一个数据库,但是,我要做的就是从文件本身中获取一些信息,因此,虽然它可能不是良好的练习,我可能不会将JSON用作数据库,我只想看看此文件格式可以做什么。无论如何,对不起侧面切线。我想做的是能够拥有一个不符合bot命令,让您查看自己的水平;当我为某些Discord服务器制作一个不和谐机器人时,此级别存储在Discord Bot和用户ID和到目前为止的经验中。这是我尝试使用的一些代码,但似乎从未有过。因此,上面的任何指针都将是有用的,并且仅仅是一般的帮助,因为如何使这可能使其成为更可用的Discord机器人,因为我总共只制作了一些Discord机器人。

代码的片段,我试图在其中制作级别命令:

#The Function For Checking Your Current Level.
@client.command(name="level")
async def get_level(ctx, users, user, channel):
  with open("users.json") as f:   
    json_information = json.load(f)
    level_information = json_information.get(str(user.id))
  await ctx.channel.send(f"{user.mention} Is Level {level_information.get('level')}.")

整个脚本:

from discord.ext import commands
from time import time
import json
import discord
import os
import random

client = commands.Bot(command_prefix = "!")

#On Ready Event.
@client.listen()
async def on_ready():
  print("Bot Ready.")
  #time.sleep(1)
  print("Logged In As:  {0.user}".format(client))

#Function For Getting A Users Information And Level Them Up.
@client.listen()
async def on_member_join(member):
  with open("users.json", "r") as f:
    users = json.load(f)

  await update_data(users, member)

  with open("users.json", "w") as f:
    json.dump(users, f)

#Member's Messages.
member_messages = {}

#Function For The System That Creates And Uses The Leveling System.
@client.listen()
async def on_message(message):
  global member_messages

  if message.author.id not in member_messages:
    member_messages[message.author.id] = 0

  current_time = time()
  last_message_requirement = current_time - 2
  
  if member_messages[message.author.id] <= last_message_requirement:
    with open("users.json", "r") as f:
      users = json.load(f)
  
    await update_data(users, message.author)
    await add_experience(users, message.author, 5)
    await level_up(users, message.author, message.channel)
  
    with open("users.json", "w") as f:
      json.dump(users, f)

      member_messages[message.author.id] = current_time

#The Function For Updating The Leveling Data.
async def update_data(users, user):
  if not str(user.id) in users:
    users[str(user.id)] = {}
    users[str(user.id)]["experience"] = 0
    users[str(user.id)]["level"] = 1

#The Function For Adding Experience To Someone's Level.
async def add_experience(users, user, exprience):
  users[str(user.id)]["experience"] += exprience

#The Function For Leveling People Up.
async def level_up(users, user, channel):
  experience = users[str(user.id)]["experience"]
  level_start = users[str(user.id)]["level"]
  level_end = int(experience ** (1/4))

  if level_start < level_end:
    await channel.send(f"{user.mention} Has Leveled Up!  They Have Leveled Up To Level {level_end}!")
    users[str(user.id)]["level"] = level_end

#The Function For Checking Your Current Level.
@client.command(name="level")
async def get_level(ctx, users, user, channel):
  with open("users.json") as f:   
    json_information = json.load(f)
    level_information = json_information.get(str(user.id))
  await ctx.channel.send(f"{user.mention} Is Level {level_information.get('level')}.")

client.run(os.getenv("Token"))
client.run(os.environ["Token"])

Okay, so I want to start off by saying I know that JSON is not a database and it shouldn't be used as one, but, all I want to do is get some information from the file itself, so while it may not be good practice, and I probably won't use JSON as a database, I just want to see what can be possible with this file format. Anyways, sorry for the side tangent. What I want to do is be able to have a discord bot command that lets you view the level you are; as I'm making a Discord Leveling Bot for some Discord Servers, this level is stored in the discord bot along with a users ID and amount of Experience they have so far. Here is some code I tried to use, but it didn't seem to work once so ever. So, any pointers on it would be useful, as well as just some general help as how to possibly make this a more usable discord bot in general as I have only made a few discord bots in total.

Snippet of the code where I attempted to make a level command:

#The Function For Checking Your Current Level.
@client.command(name="level")
async def get_level(ctx, users, user, channel):
  with open("users.json") as f:   
    json_information = json.load(f)
    level_information = json_information.get(str(user.id))
  await ctx.channel.send(f"{user.mention} Is Level {level_information.get('level')}.")

The Whole Script:

from discord.ext import commands
from time import time
import json
import discord
import os
import random

client = commands.Bot(command_prefix = "!")

#On Ready Event.
@client.listen()
async def on_ready():
  print("Bot Ready.")
  #time.sleep(1)
  print("Logged In As:  {0.user}".format(client))

#Function For Getting A Users Information And Level Them Up.
@client.listen()
async def on_member_join(member):
  with open("users.json", "r") as f:
    users = json.load(f)

  await update_data(users, member)

  with open("users.json", "w") as f:
    json.dump(users, f)

#Member's Messages.
member_messages = {}

#Function For The System That Creates And Uses The Leveling System.
@client.listen()
async def on_message(message):
  global member_messages

  if message.author.id not in member_messages:
    member_messages[message.author.id] = 0

  current_time = time()
  last_message_requirement = current_time - 2
  
  if member_messages[message.author.id] <= last_message_requirement:
    with open("users.json", "r") as f:
      users = json.load(f)
  
    await update_data(users, message.author)
    await add_experience(users, message.author, 5)
    await level_up(users, message.author, message.channel)
  
    with open("users.json", "w") as f:
      json.dump(users, f)

      member_messages[message.author.id] = current_time

#The Function For Updating The Leveling Data.
async def update_data(users, user):
  if not str(user.id) in users:
    users[str(user.id)] = {}
    users[str(user.id)]["experience"] = 0
    users[str(user.id)]["level"] = 1

#The Function For Adding Experience To Someone's Level.
async def add_experience(users, user, exprience):
  users[str(user.id)]["experience"] += exprience

#The Function For Leveling People Up.
async def level_up(users, user, channel):
  experience = users[str(user.id)]["experience"]
  level_start = users[str(user.id)]["level"]
  level_end = int(experience ** (1/4))

  if level_start < level_end:
    await channel.send(f"{user.mention} Has Leveled Up!  They Have Leveled Up To Level {level_end}!")
    users[str(user.id)]["level"] = level_end

#The Function For Checking Your Current Level.
@client.command(name="level")
async def get_level(ctx, users, user, channel):
  with open("users.json") as f:   
    json_information = json.load(f)
    level_information = json_information.get(str(user.id))
  await ctx.channel.send(f"{user.mention} Is Level {level_information.get('level')}.")

client.run(os.getenv("Token"))
client.run(os.environ["Token"])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

辞取 2025-02-13 17:11:56

注意到您的代码中的一些问题

  1. 经验**(1/4)构建的意义是什么?它基本上将体验提高到¼功率。做什么的?
  2. 用户参数从未在您的命令中使用。为什么还要添加呢?对于频道相同。
  3. 用户 arg未正确输入,这意味着您正在尝试在代码中访问str的不存在属性。

您对不使用JSON作为数据库是正确的。如果您想查看“该文件格式的可能性”,我可以告诉您 - 设置/配置数据或通过网络传输数据。请勿将其用于数据存储。

Noticed some issues in your code

  1. What is the point of experience ** (1/4) construction? It is basically raising the experience to the ¼ power. What for?
  2. users argument is never used in your command. Why even add it? Same for channel.
  3. user arg is not typehinted properly which means you are attempting to access inexistent attributes of str in your code.

You are correct about not using json as a database. If you wanna see "what is possible with that file format" I can tell you — settings/config data or transmitting data over network. Do not use it for data storage.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文