【问题标题】:Warn command discord.py (logging)警告命令 discord.py(日志记录)
【发布时间】:2021-11-19 14:38:50
【问题描述】:

所以我想添加一个记录日志的警告命令,但我不知道该怎么做。我在这里查看了有关堆栈溢出的其他一些问题,但它们只是令人困惑。我不知道它是如何工作的。也许有人可以帮忙。显然,您需要某种文档来跟踪内容,所以我添加了 warnlogging.txt,但我如何运行它并在那里记录内容? 这是我当前的警告命令

@client.command()
@commands.has_permissions(view_audit_log = True)
async def warn(ctx, member : discord.Member, *, reason=None)
    await ctx.send(f"Member warned. {ctx.author} warned {member} for the following reason: "+reason)
    await ctx.message.delete()

我没有添加嵌入,因为我只是想添加这个日志记录,但我不知道从哪里开始。

【问题讨论】:

  • 你熟悉基本的 Python 吗?
  • 有点,我有点新
  • 那么您可能不应该制作 Discord 机器人。这不是一件容易的事,需要您了解异步编程,在您的案例文件 I/O、函数、装饰器等方面。
  • 我知道人们怎么说它很难,但是对于像 dms 这样的基础知识,响应,甚至包括赠品都是我可以阅读的代码,我是初学者,但我不是那么基本
  • 您可以简单地将用户被警告多少次保存到文件中,每次使用该命令时,您将打开文件并将当前计数加 1 并保存文件,如果您对 python 来说是新手,一个简单的 JSON 或 CSV 应该很容易实现。

标签: python discord.py


【解决方案1】:

存储警告的最佳方式可能是 json 文件:

import discord
from discord.ext import commands
import json



with open('reports.json', encoding='utf-8') as f:
  try:
    report = json.load(f)
  except ValueError:
    report = {}
    report['users'] = []



intents = discord.Intents.default()

intents.members = True
client = commands.Bot(command_prefix = "", intents = intents)



@client.command(pass_context = True)
@has_permissions(manage_roles=True, ban_members=True)
async def warn(ctx,user:discord.User,*reason:str):
  author = ctx.author
  if not reason:
    await ctx.send("Please provide a reason")
    return
  reason = ' '.join(reason)
  await ctx.send(f'**{user.mention} has been warned by {author.name}.**')
  await user.send(f'You have been warned in **{ctx.guild.name}** by **{author.name}**.')
  for current_user in report['users']:
    if current_user['name'] == user.name:
      current_user['reasons'].append(reason)
      break
  else:
    report['users'].append({
      'name':user.name,
      'reasons': [reason,]
    })
  with open('reports.json','w+') as f:
    json.dump(report,f)

  with open('reports.json','w+') as f:
    json.dump(report,f)
  if len(report['users']) >= 7:
    await user.kick(reason='You reached 7 warnings')

现在用户将在达到 7 个警告后被踢出。您可以使用命令警告 通过创建另一个命令来检查用户警告:

@client.command(pass_context = True)
async def warnings(ctx,user:discord.User):
  for current_user in report['users']:
    if user.name == current_user['name']:
      await ctx.send(f"**{user.name} has been reported {len(current_user['reasons'])} times : {','.join(current_user['reasons'])}**")
      break
  else:
    await ctx.send(f"**{user.name} has never been reported**")

编辑:您必须在您的机器人编码的同一路径/文件夹中创建一个名为 reports.json 的文件。

【讨论】:

  • Alr 我会试试看。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-06-11
  • 2014-10-07
  • 2021-03-04
  • 2020-03-31
  • 2021-10-20
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多