【问题标题】:Message Counter for specific words discord.py特定单词 discord.py 的消息计数器
【发布时间】:2020-06-24 15:43:09
【问题描述】:

我正在尝试为 discord.py 构建一个消息计数器,用于计算特定消息,然后以当天消息被说出的次数进行响应。

我有基础但我不知道如何构建实际的计数器...这是我的代码:

import discord
from discord.ext import commands
import discord.utils

class Message_Counter(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, ctx, message):


        if "oof" in message.content:
            await ctx.send(str(counter))
        elif "Thot" in message.content:
            await ctx.send(str(counter))

def setup(client):
    client.add_cog(Message_Counter(client))

任何帮助将不胜感激。如果有帮助,我正在使用 discord.py 的 rewrite 分支。

对于 Thot,它基本上会回复 **Thot counter**: <number>

对于 oof,它会回复 **oof counter**: <number>

以此类推。

我还希望它每天重置计数器,以便大约每 24 小时计数器重新开始。

【问题讨论】:

  • 您是否定期重启您的机器人?如果是,那么我将使用您从中读取和写入的 json 文件。
  • 我将如何编码以通过 json 文件工作?我仍然没有实际的柜台。老实说,这是我在这个问题上最大的问题。但是,是的,我使用的是 json 文件系统,这样对我有利。

标签: discord.py discord.py-rewrite


【解决方案1】:

使用json(JSON快速入门here

我们希望在与您的机器人文件相同的文件夹中创建一个名为 counters.json 的 json 文件。它的内容应该是这样的:

{
    "Thot": 0,
    "oof": 0
}

将 json 文件加载到 dictionary 可以使用 json 库: (如果你不知道“with open”是什么意思,here 是文件读写操作的入门)

import json

def load_counters():
    with open('counters.json', 'r') as f:
       counters = json.load(f)
    return counters

将字典保存回 json 的工作原理非常相似:

def save_counters(counters):
    with open('counters.json', 'w') as f:
       json.dump(counters, f)

现在我们有了从 json 加载和卸载计数器的方法,我们可以更改机器人代码以使用它们:

import discord
from discord.ext import commands
import discord.utils

class Message_Counter(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, ctx, message):
        if "oof" in message.content:
            counters = load_counters()
            counters["oof"] += 1
            await ctx.send(str(counters["oof"]))
            save_counters(counters)
        elif "Thot" in message.content:
            counters = load_counters()
            counters["Thot"] += 1
            await ctx.send(str(counters["Thot"]))
            save_counters(counters)

def setup(client):
    client.add_cog(Message_Counter(client))

【讨论】:

  • 这会一直抛出错误。我在使用 json 存储从 cog 内部运行 set prefix 命令时遇到了同样的问题...我真的不想在我的 cogs 之外有另一个命令...这是它不断抛出的错误...@987654330 @
  • @Nimbi 这与您发布的问题完全不同。这是一个简单的解决方法,但请发布另一个关于它的问题,因为在评论中很难回答。
  • 好的新问题发布...这是链接..stackoverflow.com/questions/62566015/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 2020-04-19
  • 2019-06-02
  • 2020-12-27
  • 2022-06-18
  • 2021-11-28
  • 2021-04-20
相关资源
最近更新 更多