16 Commits

Author SHA1 Message Date
Bhupesh-V
e5b36db49f 🎨 lint scripts, readme 2024-05-05 15:00:53 +05:30
allcontributors[bot]
fe0c6a6a57 docs: add Rancho-rachit as a contributor for code (#20)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2024-05-05 14:47:54 +05:30
Rachit Agrawal
8c5ecda424 ADD: Automation script for Scheduled events on Discord_Server and Google_Calender both. (#18) 2024-05-05 14:46:49 +05:30
Bhupesh Varshney
21fce6828b add code collab posts in monthly community roundups (#19) 2024-04-29 14:23:27 +05:30
LinearArray
58746803ee Update README.md 2024-04-14 19:09:54 +05:30
LinearArray
518f650160 Update README.md 2024-04-14 19:07:29 +05:30
Bhupesh-V
1dad8740e6 strip extra space from title 2024-04-13 18:24:49 +05:30
Bhupesh-V
2df84308dd update notification message 2024-04-10 14:02:54 +05:30
Bhupesh-V
512a469fde use permalink for post + send a message to user 2024-03-27 12:10:11 +05:30
LinearArray
ed2e865492 Update .all-contributorsrc 2024-03-26 07:03:42 +05:30
LinearArray
dc7a04b9b1 Update README.md 2024-03-05 13:50:31 +05:30
LinearArray
3b32cb1909 Update main.py (#15) 2024-03-05 13:35:01 +05:30
Bhupesh-V
dc31a18089 🐛 fix flair update in verifier

2024-03-03 21:04:31 +05:30
Bhupesh-V
dbe8db8816 🐛 fix missing announcement posts from roundup 2024-02-29 11:17:39 +05:30
Bhupesh-V
7419fee0bd fix the year count in threads wiki 2024-02-25 14:30:58 +05:30
Bhupesh Varshney
4325ecc230 remove reading reddit collection for community threads collection (#16) 2024-02-25 14:21:15 +05:30
12 changed files with 332 additions and 22 deletions

View File

@@ -50,6 +50,24 @@
"contributions": [
"code"
]
},
{
"login": "LinearArray",
"name": "LinearArray",
"avatar_url": "https://github.com/lineararray.png",
"profile": "https://github.com/lineararray",
"contributions": [
"code"
]
},
{
"login": "Rancho-rachit",
"name": "Rachit Agrawal",
"avatar_url": "https://avatars.githubusercontent.com/u/111473259?v=4",
"profile": "https://rancho-rachit.github.io/",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 7,

View File

@@ -79,6 +79,8 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<td align="center" valign="top" width="14.28%"><a href="https://animesh-ghosh.github.io/"><img src="https://avatars.githubusercontent.com/u/34956994?v=4?s=100" width="100px;" alt="MaDDogx"/><br /><sub><b>MaDDogx</b></sub></a><br /><a href="https://github.com/developersIndia/deviras/commits?author=Animesh-Ghosh" title="Code">💻</a> <a href="https://github.com/developersIndia/deviras/commits?author=Animesh-Ghosh" title="Tests">⚠️</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://pratham.cc"><img src="https://avatars.githubusercontent.com/u/67585967?v=4?s=100" width="100px;" alt="Pratham"/><br /><sub><b>Pratham</b></sub></a><br /><a href="https://github.com/developersIndia/deviras/commits?author=git-bruh" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://nisarga.me/"><img src="https://avatars.githubusercontent.com/u/45588772?v=4?s=100" width="100px;" alt="Nisarga Adhikary"/><br /><sub><b>Nisarga Adhikary</b></sub></a><br /><a href="https://github.com/developersIndia/deviras/commits?author=ni5arga" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/lineararray"><img src="https://github.com/lineararray.png?s=100" width="100px;" alt="LinearArray"/><br /><sub><b>LinearArray</b></sub></a><br /><a href="https://github.com/developersIndia/deviras/commits?author=LinearArray" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://rancho-rachit.github.io/"><img src="https://avatars.githubusercontent.com/u/111473259?v=4?s=100" width="100px;" alt="Rachit Agrawal"/><br /><sub><b>Rachit Agrawal</b></sub></a><br /><a href="https://github.com/developersIndia/deviras/commits?author=Rancho-rachit" title="Code">💻</a></td>
</tr>
</tbody>
</table>

View File

@@ -51,14 +51,14 @@ def main():
if question_text != "[deleted]":
question_link = "https://reddit.com" + comment.parent().permalink
markdown_file += (
f"{question_number}. [{question_text}]({question_link})\n"
)
f"{question_number}. [{question_text}]({question_link})\n\n"
) # Add an extra newline after each question
question_number += 1
with open("questions.md", "w", encoding="utf-8") as file:
file.write(markdown_file)
print(f"{question_number} questions generated successfully.")
print(f"{question_number - 1} questions generated successfully.")
if __name__ == "__main__":

View File

@@ -88,6 +88,16 @@ def get_announcement_posts(subreddit):
return get_posts_by_flair(subreddit, flair["flair_text"])
def code_collaboration_posts(subreddit):
flair = next(
filter(
lambda flair: "Code Collab" in flair["flair_text"],
subreddit.flair.link_templates.user_selectable(),
)
)
return get_posts_by_flair(subreddit, flair["flair_text"])
def get_gist_content(gist_id):
headers = {
"Authorization": f"token {token}",
@@ -125,6 +135,7 @@ def create_community_roundup_post(
weekly_discussion_posts,
ama_posts,
announcement_posts,
collab_posts,
):
flair = next(
filter(
@@ -145,21 +156,21 @@ The collection is curated by our volunteer team & is independent of the number o
"""
if len(announcement_posts) > 0:
text = "## Announcements\n||\n|--------|\n"
text = "## Announcements\n|Announcements from volunteer team|\n|--------|\n"
for post in announcement_posts:
text += f"| [**{post.title}**]({post.url}) |\n"
text += f"| [**{post.title.strip()}**]({post.url}) |\n"
else:
print("No announcements found. Skipping")
if len(ama_posts) > 0:
text = "\n## AMAs\n||\n|--------|\n"
text += "\n## AMAs\n|Read insights from guests that joined us for a day |\n|--------|\n"
for post in ama_posts:
text += f"| [**{post.title}**]({post.url}) |\n"
text += f"| [**{post.title.strip()}**]({post.url}) |\n"
else:
print("No AMAs found. Skipping")
if len(posts) > 0:
text += "\n## Community Threads\n|S.No|Discussions started by members|\n|--------|--------|\n"
text += "\n## Community Threads\n|S.No|Insightful discussions started by community members|\n|--------|--------|\n"
posts_counter = 0
for post in posts:
posts_counter += 1
@@ -168,16 +179,23 @@ The collection is curated by our volunteer team & is independent of the number o
print("No posts found in the collection for this month. Skipping")
if len(weekly_discussion_posts) > 0:
text += "\n## Weekly Discussions\n|Started by Volunteer/Mod Team|\n|--------|\n"
text += "\n## Weekly Discussions\n|Weekly tech discussions started by Volunteer Team|\n|--------|\n"
for post in weekly_discussion_posts:
text += f"| [**{post.title}**]({post.url}) |\n"
text += f"| [**{post.title.strip()}**]({post.url}) |\n"
else:
print("No weekly discussions found. Skipping")
if len(collab_posts) > 0:
text += "\n## Code Collab\n|Folks looking for collaborations on hackathons, projects etc.|\n|--------|\n"
for post in collab_posts:
text += f"| [**{post.title.strip()}**]({post.url}) |\n"
else:
print("No Code Collaboration posts found. Skipping")
if len(i_made_this_posts) > 0:
text += "\n## I Made This\n|Top 10 posts|\n|--------|\n"
text += "\n## I Made This\n|Top 10 projects built by community members|\n|--------|\n"
for post in i_made_this_posts:
text += f"| [**{post.title}**]({post.url}) |\n"
text += f"| [**{post.title.strip()}**]({post.url}) |\n"
else:
print("No I Made This posts found. Skipping")
@@ -213,8 +231,9 @@ def main():
weekly_discussion_posts = get_weekly_discussion_posts(subreddit)
ama_posts = get_ama_posts(subreddit)
announcement_posts = get_announcement_posts(subreddit)
collab_posts = code_collaboration_posts(subreddit)
create_community_roundup_post(
subreddit, posts, i_made_this_posts, weekly_discussion_posts, ama_posts, announcement_posts
subreddit, posts, i_made_this_posts, weekly_discussion_posts, ama_posts, announcement_posts, collab_posts
)
print("Community Roundup post created successfully!")
else:

View File

@@ -44,17 +44,37 @@ def update_gist(gist_id, filename, content, description=""):
# )
# return collection
# let the author know their post is now part of the collection!
def send_message(reddit, username, post_link):
message_subject = 'Woohoo! Your post is now part of our community threads collection!'
message_text = """
Hi there,\n
It looks like one of your [posts]({post_link}) on r/developersIndia was picked-up by the volunteer team to be part of our curated list of 100+ amazing discussing in the community.\n
- You can find your post in our [Community Threads Collection](https://reddit.com/r/developersIndia/wiki/community-threads). Feel free to share the collection with your dev friends.\n
- We post a compilation of these threads every month in [Community Roundups](https://www.reddit.com/r/developersIndia/?f=flair_name%3A%22Community%20Roundup%22). Stay tuned for the next one!\n
> PS: This was an automated messaage, no need to reply. [Reach out to mods](https://www.reddit.com/message/compose?to=/r/developersIndia) if you have any questions.
Cheers,\n
The r/developersIndia Community Team
"""
reddit.redditor(username).message(
subject=message_subject, message=message_text.format(post_link=post_link), from_subreddit=reddit.subreddit(sub)
)
def get_post_data(reddit, post_url):
submission = reddit.submission(url=post_url)
post = {
"title": submission.title,
"url": submission.url,
"url": submission.permalink,
"id": submission.id,
"num_comments": submission.num_comments,
"created_at": datetime.utcfromtimestamp(
submission.created_utc
).isoformat(),
"flair_text": submission.link_flair_text,
"author": submission.author.name,
}
return post
@@ -75,7 +95,7 @@ def update_wiki(reddit, wikipage, posts):
wiki_header = """# A collection of must read discussions started by community members"""
content = wiki_header + "\n\n"
content += f"A handpicked collection of **{total_posts}** interesting posts, discussions & high-quality threads gathered over **{total_years}** years & counting.\n\n"
content += f"A handpicked collection of **{total_posts}** interesting posts, discussions & high-quality threads gathered over **{total_years-1}** years & counting.\n\n"
content += "If you spot a post that could be in this list, send us a [modmail](https://reddit.com/message/compose?to=r/developersIndia&subject=Community%20Threads%20Collection%20Suggestion&message=Hey%20folks%2C%0A%0A%3Cpost%20link%3E)\n\n"
for year in sorted(posts_by_year.keys(), reverse=True):
@@ -123,6 +143,7 @@ def main():
new_post = get_post_data(reddit, args.post_url)
if new_post["id"] not in saved_collection_ids:
new_post["title"] = new_post["title"].strip()
posts.append(new_post)
posts = sorted(posts, key=lambda k: k["created_at"])
@@ -134,6 +155,8 @@ def main():
update_gist(gist_id, "collection.json", json.dumps(collection_json, indent=4))
print("Internal database updated successfully!")
update_wiki(reddit, "community-threads", posts)
send_message(reddit, new_post["author"], new_post["url"])
print("Message sent to the author!")
else:
print("Post is already in the collection. No changes were made.")

17
event-manager/.env.sample Normal file
View File

@@ -0,0 +1,17 @@
# DISCORD BOT TOKEN
# MUST HAVE PERMISSIONS TO CREATE EVENTS & MANAGE EVENTS
# https://discord.com/developers/applications
export DISCORD_BOT_TOKEN = "TOKEN"
# -----------
# DISCORD SERVER ID (GUILD ID)
# developersIndia => 1229786646468362260
export DISCORD_GUILD_ID = 1229786646468362260
# -----------
# CALANDER ID
# developersIndia => "9f1337e4154910eb1bdb3bfac32b88f69546468b1281a6db58f50a909df5049f@group.calendar.google.com"
export GOOGLE_CALENDAR_ID = "9f1337e4154910eb1bdb3bfac32b88f69546468b1281a6db58f50a909df5049f@group.calendar.google.com"

52
event-manager/README.md Normal file
View File

@@ -0,0 +1,52 @@
# Automation to create events across Google Calendar & Discord
## Description
This script creates events across [Google Calendar](https://developersindia.in/events-calendar/) & [Discord](https://discord.com/channels/669880381649977354/)
### First Time Setup
1. Get Python3
```bash
sudo apt-get install python3 && python3 --version
```
2. Install required packages
```bash
pip install -r requirements.txt
```
3. Add respective tokens in the `.env` file
```bash
cp .sample.env .env
```
1. `DISCORD_BOT_TOKEN`
- Get it from [Discord Developers portal](https://discord.com/developers/applications/)) (bot must have MANAGE_EVENT & CREATE_EVENT permission)
2. `DISCORD_GUILD_ID`
- developersIndia's GUID is `1229786646468362260`
3. `GOOGLE_CALENDAR_ID`
- developersIndia calendar is public, `9f1337e4154910eb1bdb3bfac32b88f69546468b1281a6db58f50a909df5049f@group.calendar.google.com`
4. Connect Google calendar through [Google cloud Console](https://console.cloud.google.com/)
1. 4.1 Create a Project on Google Cloud Console
2. Search for calendar API and enable it
3. Create Credentials -> OAuth Client ID -> Application type as Desktop
4. Download the JSON file
5. Rename that JSON file as `credentials.json` and save it to the project directory.
5. `python3 main.py`
---
### NOTES-
> - Google authenication is required for the first time.
>
> - A file `token.json` will be downloaded automatically, and no web login will be needed afterwards.

View File

@@ -0,0 +1,57 @@
from datetime import datetime, timedelta
import discord
from discord.ext import commands
def create_discord_event(
bot_token,
guild_id,
EVENT_NAME,
EVENT_DESCRIPTION,
EVENT_LOCATION,
EVENT_DATE,
EVENT_START_TIME,
EVENT_END_TIME,
):
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
# Convert the date string to a datetime object
date_object = datetime.strptime(EVENT_DATE, "%Y-%m-%d")
# Convert the time string to a datetime object
start_time_object = datetime.strptime(EVENT_START_TIME, "%H:%M")
end_time_object = datetime.strptime(EVENT_END_TIME, "%H:%M")
# Combine the date and time objects
st = date_object.replace(
hour=start_time_object.hour, minute=start_time_object.minute
).astimezone()
et = date_object.replace(
hour=end_time_object.hour, minute=end_time_object.minute
).astimezone()
gg = bot.get_guild(guild_id)
try:
event = await gg.create_scheduled_event(
name=EVENT_NAME,
entity_type=discord.EntityType.external,
description=EVENT_DESCRIPTION,
start_time=st,
end_time=et,
location=EVENT_LOCATION,
privacy_level=discord.PrivacyLevel.guild_only,
)
print("Discord Event: ", event.url)
except Exception as e:
print(e)
await bot.close()
# Run the bot
bot.run(bot_token)

View File

@@ -0,0 +1,58 @@
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
SCOPES = ["https://www.googleapis.com/auth/calendar"]
def create_google_calendar_event(
calendar_id, name, description, location, date, start_time, end_time
):
creds = None
# The file token.json stores the user's access and refresh tokens
if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
print("Login to your Google account. [THIS IS A ONE TIME PROCESS]")
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open("token.json", "w") as token:
token.write(creds.to_json())
try:
service = build("calendar", "v3", credentials=creds)
start = f"{date}T{start_time}:00"
end = f"{date}T{end_time}:00"
event = {
"summary": name,
"location": location,
"description": description,
"start": {
"dateTime": start,
"timeZone": "Asia/Kolkata",
},
"end": {
"dateTime": end,
"timeZone": "Asia/Kolkata",
},
}
event = service.events().insert(calendarId=calendar_id, body=event).execute()
print("Google calendar: %s" % (event.get("htmlLink")))
return event
except Exception as e:
print(e)
return None

29
event-manager/main.py Normal file
View File

@@ -0,0 +1,29 @@
import os
from dotenv import load_dotenv
load_dotenv()
bot_token = os.getenv('DISCORD_BOT_TOKEN')
guild_id = int(os.getenv('DISCORD_GUILD_ID'))
calendar_id = os.getenv('GOOGLE_CALENDAR_ID')
def get_input():
NAME = input("Event title: ")
DESCRIPTION = input("Event description: ")
LOCATION = input("Event location (red -> for developersindia subreddit): ")
if LOCATION == "red":
LOCATION = "https://www.reddit.com/r/developersindia/"
DATE = input("Enter the event date (yyyy-mm-dd): ")
START_TIME = input("Enter the event start time (hh:mm)- ")
END_TIME = input("Enter the event end time (hh:mm)- ")
return NAME, DESCRIPTION, LOCATION, DATE, START_TIME, END_TIME
EVENT_NAME, EVENT_DESCRIPTION, EVENT_LOCATION, EVENT_DATE, EVENT_START_TIME, EVENT_END_TIME = get_input()
# Execute create_discord_event
from discord_bot import create_discord_event
create_discord_event(bot_token, guild_id, EVENT_NAME, EVENT_DESCRIPTION, EVENT_LOCATION, EVENT_DATE, EVENT_START_TIME, EVENT_END_TIME)
# Execute google_calendar_event
from google_calendar import create_google_calendar_event
create_google_calendar_event(calendar_id, EVENT_NAME, EVENT_DESCRIPTION, EVENT_LOCATION, EVENT_DATE, EVENT_START_TIME, EVENT_END_TIME)

View File

@@ -0,0 +1,5 @@
discord.py
google-api-python-client
google-auth-httplib2
google-auth-oauthlib
python-dotenv

View File

@@ -1,6 +1,7 @@
import os
import sys
import praw
import time
import datetime
client_id = os.environ["REDDIT_CLIENT_ID"]
@@ -19,7 +20,7 @@ def get_last_activity_times(reddit, username):
limit=100
): # look at the user's 100 most recent comments
if comment.subreddit.display_name == sub:
last_comment_time = datetime.datetime.fromtimestamp(comment.created_utc)
last_comment_time = datetime.datetime.fromtimestamp(comment.created_utc).strftime('%d %B, %Y')
break
# Get the user's last post creation time and title in the subreddit
@@ -29,7 +30,7 @@ def get_last_activity_times(reddit, username):
limit=100
): # look at the user's 100 most recent posts
if submission.subreddit.display_name == sub:
last_post_time = datetime.datetime.fromtimestamp(submission.created_utc)
last_post_time = datetime.datetime.fromtimestamp(submission.created_utc).strftime('%d %B, %Y')
last_post_title = submission.title
break
@@ -45,13 +46,25 @@ def get_current_flair(reddit, username):
return flair["flair_text"], template["id"]
def get_flair(reddit, username):
subreddit = reddit.subreddit(sub)
flair = next(subreddit.flair(username))
template = get_template_from_flair_text(reddit, flair["flair_text"])
if template is None:
return None, None
return flair["flair_text"], template["id"]
def assign_user_flair(reddit, username, flair_text):
subreddit = reddit.subreddit(sub)
flair = next(subreddit.flair(username))
template = get_flair_template_from_text(reddit, flair["flair_text"])
subreddit.flair.set(username, text=flair_text, flair_template_id=template["id"])
# append YoE to the flair text
verified_text = f"{flair['flair_text']} | {flair_text}"
subreddit.flair.set(username, text=verified_text, flair_template_id=template["id"])
def get_flair_templates(reddit):
@@ -66,6 +79,14 @@ def get_flair_template_from_text(reddit, flair_text):
return template
def get_template_from_flair_text(reddit, flair_text):
templates = get_flair_templates(reddit)
for template in templates:
# check if the flair text is in the template
if template["text"] in flair_text:
return template
def send_message(reddit, username, flair_text):
message_subject = 'Woohoo! You are now a verified member of r/developersIndia! 🚀'
message_text = """
@@ -117,8 +138,14 @@ def main():
# get current flair
current_flair_text, current_flair_template_id = get_current_flair(reddit, reddit_username)
if current_flair_text is None:
current_flair_text, current_flair_template_id = get_flair(reddit, reddit_username)
# TODO figure out final flair text
if "Verified" in current_flair_text or "YoE" in current_flair_text:
print(f"{reddit_username} is already verified")
sys.exit(0)
if current_flair_text is None and current_flair_template_id is None:
print(f"{reddit_username} does not have a flair on r/developersIndia")
sys.exit(0)
else:
@@ -131,8 +158,11 @@ def main():
sys.exit(0)
assign_user_flair(reddit, reddit_username, flair_text)
print(f"Updated {reddit_username}'s flair to \"{flair_text}\"")
send_message(reddit, reddit_username, flair_text)
# Ya I know, just don't ask
time.sleep(2)
updated_flair_text, _ = get_flair(reddit, reddit_username)
print(f"Updated {reddit_username}'s flair to \"{updated_flair_text}\"")
send_message(reddit, reddit_username, updated_flair_text)
print(f"Sent verification confirmation message to {reddit_username}")