Skip to content

Instantly share code, notes, and snippets.

@ChlodAlejandro
Forked from adryd325/discord-scatter-plot.py
Last active April 17, 2024 18:36
Show Gist options
  • Save ChlodAlejandro/52480f4773c03a9c3d2a9cd3a48014e3 to your computer and use it in GitHub Desktop.
Save ChlodAlejandro/52480f4773c03a9c3d2a9cd3a48014e3 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# 1. Install Python 3 if you don't have it yet.
# 2. Download your data dump (Settings > Privacy and Safety > Request Data)
# 3. Wait for the dump to get sent, then download it.
# 4. Extract the dump to any folder.
# 5. Download and place this file in the "messages" folder of your data dump.
# 6. Run it with `python3 discord-scatter-plot.py`
# 7. (optional) You can edit the "serverYouWant" variable down below to specify a specific server.
# This accepts a server ID. To get the server ID, enable "Developer Mode" (Settings > Advanced),
# right click on a server, and then click on "Copy ID".
from datetime import datetime, timedelta, timezone
import dateutil.parser
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.dates as mdates
import csv
import json
import os
yourNameHere = "@chlod"
# Leave blank for everything
serverYouWant = ""
n = 0
dates = []
with open('index.json', 'r') as index_file:
index = json.load(index_file)
for channelID in index.keys():
if serverYouWant and serverYouWant not in index[channelID]:
continue
n += 1
print(f"reading messages for channel: #{n} {index[channelID]} ({channelID})")
if "messages.csv" not in os.listdir(f"c{channelID}"):
with open(f"c{channelID}/messages.json", 'r') as json_file:
json2 = json.load(json_file)
for message in json2:
dates.append(dateutil.parser.parse(message["Timestamp"]))
json_file.close()
else:
with open(f"c{channelID}/messages.csv", 'r') as csv_file:
reader = csv.reader(csv_file)
for row in reader:
if (row[1] != "Timestamp"):
dates.append(dateutil.parser.parse(row[1]))
csv_file.close()
print(f"total messages: {len(dates)}")
renderHorizontal = True
beginningOfTime = datetime.utcnow()-timedelta(days=7*365) # ignore tweets older than 5 years
now = datetime.utcnow()
days=[]
times=[]
print("processing dates")
for date in dates:
timeNoDate = datetime(1970, 1, 1, date.hour, date.minute, date.second)
dateNoTime = datetime(date.year, date.month, date.day)
days.append(dateNoTime)
times.append(timeNoDate)
print("processing graph")
hoursMajorLocator = mdates.HourLocator(interval=6)
hoursMinorLocator = mdates.HourLocator(interval=1)
hoursMajorFormatter = mdates.DateFormatter('%H:%M')
daysMajorLocator = mdates.YearLocator(base=1)
daysMinorLocator = mdates.MonthLocator()
daysMajorFormatter = mdates.DateFormatter('%Y')
daysMinorFormatter = mdates.DateFormatter('%b')
if renderHorizontal:
fig, ax = plt.subplots(figsize=((max(days)-min(days)).days / 200, 3))
plt.scatter(days, times, s=1, linewidths=0, color='#1f77b4c0')
plt.xlim(min(days), max(days))
plt.ylim(0, 1)
dateAxis = ax.xaxis
hoursAxis = ax.yaxis
daysMinorFormatter = mdates.DateFormatter('')
else:
fig, ax = plt.subplots(figsize=(3, (max(days)-min(days)).days / 200))
plt.scatter(times, days, s=1, linewidths=0, color='#1f77b4c0')
plt.ylim(min(days), max(days))
plt.xlim(0, 1)
dateAxis = ax.yaxis
hoursAxis = ax.xaxis
ax.tick_params(axis='y', which='minor', labelsize=5, color='#777')
# time goes downwards and to the right
plt.gca().invert_yaxis()
hoursAxis.set_major_locator(hoursMajorLocator)
hoursAxis.set_minor_locator(hoursMinorLocator)
hoursAxis.set_major_formatter(hoursMajorFormatter)
dateAxis.set_major_locator(daysMajorLocator)
dateAxis.set_minor_locator(daysMinorLocator)
dateAxis.set_major_formatter(daysMajorFormatter)
dateAxis.set_minor_formatter(daysMinorFormatter)
hoursAxis.set_label('Time of day')
dateAxis.set_label('Date')
if not serverYouWant:
serverYouWant = "Discord"
plt.title(f"When does {yourNameHere} post on {serverYouWant} (UTC)")
print("rendering png")
plt.savefig('out.png', bbox_inches='tight', pad_inches=0.3, dpi=300)
print("rendering svg")
plt.savefig('out.svg', bbox_inches='tight', pad_inches=0.3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment