Im trying to get all messages from a channel from 2 days ago till now. instead, it's giving me the messages from the inception of the channel. Don't know what I'm doing wrong here...
here is the code
import requests
import json
import datetime
def retrieve_messages(channelid, after=None, before=None):
headers = {
'authorization': "<TOKEN>"
}
# Build the query string, including the after and before parameters
# if they were specified
query_string = '?'
if after:
query_string = f'&after={after}'
if before:
query_string = f'&before={before}'
# Make the API call, including the query string
r = requests.get(
f'https://discord.com/api/v9/channels/{channelid}/messages{query_string}', headers=headers)
jsonn = json.loads(r.text)
for value in jsonn:
print(value['content'], '\n')
# Retrieve messages from the past two days
two_days_ago = datetime.datetime.utcnow() - datetime.timedelta(days=2)
after = int(two_days_ago.timestamp())
retrieve_messages("<CHANNEL_ID>", after=after)
CodePudding user response:
The discord.py API uses timestamps in milliseconds, not seconds. So:
# ...
if after:
query_string = f'&after={after * 1000}' # Multiply by 1000 (convert to ms)
if before:
query_string = f'&before={before}'
CodePudding user response:
I finally figured it out. It is in the documentation
# Define the DISCORD_EPOCH constant
DISCORD_EPOCH = 1420070400000
# Convert the x_days_ago variable to a timestamp in milliseconds
timestamp_ms = int(x_days_ago.timestamp() * 1000)
# Subtract the DISCORD_EPOCH constant from the timestamp to get the correct format for the after parameter
after = (timestamp_ms - DISCORD_EPOCH) << 22