Reputation: 21
Im trying to add a function that will check the number of messages sent by a user within the last 2 days, right now im looping through all the channels history and checking the message 1 at a time, but with a guild that gets thousands of messages a day this takes a long time, is there a way that i can specify a max amount of time to look back?
heres my current code
# This is also inside of a cog
now = datetime.datetime.now()
joined_on = ctx.author.joined_at
delta = datetime.timedelta(joined_on, now)
if delta.days >= 2:
message = 0
for channel in ctx.guild.channels:
if channel.id != 863871156298055751:
for message in channel.messages:
sent_at = message.created_at
delta = datetime.timedelta(sent_at, now)
if delta.days <= 2 and message.author.id == ctx.author.id:
messages += 1
Upvotes: 1
Views: 1563
Reputation: 3934
There is a version of the history
that works on the channels. You can also specify a time frame to look at.
See TextChannel.history
.
counter = 0
for channel in ctx.guild.channels:
try:
if not isinstance(channel, discord.TextChannel):
continue
# set a hard limit on the messages taken, or limit the amount of time to search
async for msg in channel.history(limit=100, after=datetime.datetime.utcnow()-datetime.timedelta(hours=1)):
# change this
if msg.author.id == ctx.author.id:
counter += 1
except discord.errors.Forbidden:
pass
await ctx.send(counter)
Upvotes: 1