Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added type hinting+ small changes #6

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions discord.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
import httpx
from typing import Dict, Any
import httpx

DISCORD_INVITE_HACK_URL = "https://discord.com/api/v9/invites/{invite_code}?with_counts=true&with_expiration=true"

DISCORD_INVITE_HACK_URL = 'https://discord.com/api/v9/invites/{invite_code}?with_counts=true&with_expiration=true'

def get_discord_stats(invite_code: str) -> Dict[str, Any]:
discord_stats = {}
"""Get discord stats from invite code"""

discord_stats: Dict[str, Any] = {}
res = httpx.get(DISCORD_INVITE_HACK_URL.format(invite_code=invite_code))
if res.status_code == 200:
res_json = res.json()
discord_stats['discordTotalMembers'] = res_json.get('approximate_member_count')
discord_stats['discordTotalActiveMembers'] = res_json.get(
'approximate_presence_count'
discord_stats["discordTotalMembers"] = res_json.get(
"approximate_member_count", 0
)
discord_stats["discordTotalActiveMembers"] = res_json.get(
"approximate_presence_count", 0
)

return discord_stats
57 changes: 38 additions & 19 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,43 @@
'''
This script is used for generating developersIndia subreddit traffic stats
'''
import praw
import os
"""
This script is used for generating developersIndia subreddit traffic stats
"""

import json
from datetime import datetime, timedelta
import os
from typing import Any, Dict, List

import praw

from discord import get_discord_stats
from utils import *
from utils import get_last_day, get_last_month, get_readable_day, get_readable_month

client_id = os.environ["REDDIT_CLIENT_ID"]
client_secret = os.environ["REDDIT_CLIENT_SECRET"]
reddit_pass = os.environ["REDDIT_PASSWORD"]
reddit_user = os.environ["REDDIT_USER"]

discord_invite_code = os.environ["DISCORD_INVITE_CODE"]
# Get credentials from env
client_id = os.getenv("REDDIT_CLIENT_ID")
client_secret = os.getenv("REDDIT_CLIENT_SECRET")
reddit_pass = os.getenv("REDDIT_PASSWORD")
reddit_user = os.getenv("REDDIT_USER")
discord_invite_code = os.getenv("DISCORD_INVITE_CODE")

REPORT_PATH="data/index.json"
# validate that all credentials are present
if not client_id or not client_secret or not reddit_pass or not reddit_user:
raise RuntimeError("Missing reddit credentials")

if not discord_invite_code:
raise RuntimeError("Missing DISCORD_INVITE_CODE")


REPORT_PATH = "data/index.json"

last_month = get_last_month()
last_day = get_last_day()

def generate_data(members, stats, discord_stats):

def generate_data(
members: int | None,
stats: Dict[str, List[List[int]]],
discord_stats: Dict[str, Any],
):
subreddit_stats = {}

if members is not None:
Expand All @@ -40,9 +57,10 @@ def generate_data(members, stats, discord_stats):

# populate discord data to the stats.
combined_stats = {**subreddit_stats, **discord_stats}
with open(REPORT_PATH, 'w') as report:
with open(REPORT_PATH, "w", encoding="utf-8") as report:
json.dump(combined_stats, report, indent=4)


def find_traffic():
reddit = praw.Reddit(
client_id=client_id,
Expand All @@ -51,12 +69,13 @@ def find_traffic():
user_agent="testscript",
username=reddit_user,
)
stats = reddit.subreddit("developersIndia").traffic()
members = reddit.subreddit("developersIndia").subscribers
stats: Dict[str, List[List[int]]] = reddit.subreddit("developersIndia").traffic()
members: int = reddit.subreddit("developersIndia").subscribers

# Discord server data
discord_stats = get_discord_stats(discord_invite_code)
discord_stats: Dict[str, Any] = get_discord_stats(discord_invite_code)
generate_data(members, stats, discord_stats)

if __name__ == '__main__':

if __name__ == "__main__":
find_traffic()
8 changes: 4 additions & 4 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,25 @@ def non_zero_padded_prefix():
return prefix


def get_last_month():
def get_last_month() -> str:
now = datetime.now()
last_month = now - timedelta(weeks=4)
return last_month.strftime(f"%{non_zero_padded_prefix()}m %Y")


def get_last_day():
def get_last_day() -> str:
now = datetime.now()
last_day = now - timedelta(days=1)
return last_day.strftime(f"%d/%{non_zero_padded_prefix()}m/%Y")


def get_readable_month(unix_t):
def get_readable_month(unix_t: float) -> str:
t = time.localtime(unix_t)
# Format: '9, 2021'
return time.strftime(f"%{non_zero_padded_prefix()}m %Y", t)


def get_readable_day(unix_t):
def get_readable_day(unix_t: float) -> str:
t = time.localtime(unix_t)
# Format: '03/12/2021'
return time.strftime(f"%d/%{non_zero_padded_prefix()}m/%Y", t)