我正在尝试为 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 的重写分支。
基本上对于Thot来说,它会以**Thot counter**: <number>
对于oof,它会以**oof counter**: <number>
回应
等等。
我还希望它每天重置计数器,以便大约每 24 小时计数器重新启动一次。
使用 json(此处快速介绍 JSON(
我们希望在与机器人的文件相同的文件夹中创建名称为counters.json
的 json 文件。其内容应如下所示:
{
"Thot": 0,
"oof": 0
}
将 json 文件加载到字典中适用于 json 库: (如果你不知道"打开"的东西是什么,这里有一个关于文件读写操作的入门(
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))