【发布时间】:2022-12-27 21:17:24
【问题描述】:
I've recently implemented an SQLite database into my discord.py bot in an effort to teach myself SQL in a fun and more meaningful way. It works as intended with a slight issue. The function of the cog is to increment a counter for each discord user everytime they send 'brilliant' in the chat. However, it is incrementing the value for each user several times when they send 'brilliant' and sometimes users that have not said 'brilliant' pop up in the database. The original code:
import discord, sqlite3
from discord.ext import commands
class brilliant_count(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
if message.author == self.bot.user:
return
if message.content.lower() == "brilliant" or "brilliant!":
conn = sqlite3.connect(r"./cogs/brilliant_count.db")
c = conn.cursor()
# Get the user data
user = message.author
# Check if the user is already in the database
c.execute("SELECT count FROM brilliant_counter WHERE discord_id=?", (user.id,))
result = c.fetchone()
if result is None:
# User is not in the database, add them with a count of 1
c.execute("INSERT INTO brilliant_counter (discord_id, discord_username, count) VALUES (?, ?, ?)", (user.id, user.name, 1))
else:
# User is in the database, increment the count
count = result[0]
count += 1
c.execute("UPDATE brilliant_counter SET discord_username=?, count=? WHERE discord_id=?", (user.name, count, user.id))
# Commit the changes to the database
conn.commit()
# Close the database connection
conn.close()
async def setup(bot):
await bot.add_cog(brilliant_count(bot))
I figured it might be because the 'on_message' event listener in the cog is being triggered multiple times for a single message, perhaps because the bot is in multiple discord groups.
Jacobson has only said 'brilliant' a few times and Rin has never sent 'brilliant' but their numbers are exceedingly high.
Doing some research led me to this:
if message.content.lower() == "brilliant" and not message.processed:
message.processed = True
But the above code doesn't work with discord.py and I can't seem to find any other documentation for it. I'd appreciate some advice on what to do next. many thanks
【问题讨论】:
标签: python sql sqlite discord discord.py