Skip to content

Commit

Permalink
Merge pull request #9 from SVijayB/news-update
Browse files Browse the repository at this point in the history
Feature update: Enable the bot to send regular News feed to a dedicated channel
  • Loading branch information
thekodeking authored Nov 8, 2021
2 parents 3c1e00f + 7b154d9 commit 9fda514
Show file tree
Hide file tree
Showing 5 changed files with 151 additions and 40 deletions.
Binary file added assets/Discord_logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 2 additions & 1 deletion data.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@
"jokes": "function"
}
],
"eventID": 40
"eventID": 40,
"newsTimestamp": "08 Nov 2021 | 09:53 am"
}
8 changes: 7 additions & 1 deletion src/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from modules.osc_event_notif import *
from modules.news_updates import *
from modules.utils import commands
from dotenv import load_dotenv
import time
import discord
import os

Expand All @@ -12,11 +14,15 @@
@client.event
async def on_ready():
print(f"{client.user} has connected to Discord!")
message_channel = client.get_channel(904455110212591676)
activity = discord.Activity(type=discord.ActivityType.listening, name=">help")
await client.change_presence(activity=activity)

message_channel = client.get_channel(904455110212591676)
oscEventNotif.start(message_channel)

news_channel = client.get_channel(904455110212591676)
news_updates.start(news_channel)

@client.event
async def on_message(message):
if message.author == client.user:
Expand Down
109 changes: 109 additions & 0 deletions src/modules/news_updates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
from discord.ext import tasks, commands
from urllib.request import urlopen
from datetime import date
from pyshorteners import Shortener
import discord
import json


@tasks.loop(hours=2)
async def news_updates(news_channel):
urls = ["https://inshortsapi.vercel.app/news?category=technology"]

today = date.today().strftime("%d %b %Y") # today date.
max_time = "" # stores the latest news.

with open("data.json", "r") as f:
cache_mem = json.load(f)

# if last news was sent yesterday, then change data in the json file.
if today != cache_mem["newsTimestamp"].split("|")[0].strip():
cache_mem["newsTimestamp"] = today + " | " + "00:00 AM"
with open("data.json", "w") as f:
json.dump(cache_mem, f)

for url in urls:
# get json data from the api
response = urlopen(url)
data = json.loads(response.read())["data"]
news_updates = dict()
news_count = 0

# get the news that were sent out today
for index in range(len(data)):
content = data[index]
if today == content["date"].split(",")[0]:
news_updates[news_count] = content
news_count += 1

time_stamps = list()

# get the time of the news which were sent out today
for today_content in news_updates.values():
time_stamps.append(today_content["time"])

# sort the time
time_stamps = sorted(time_stamps)

# check if the latest news is already sent out
for item in time_stamps.copy():
if item > cache_mem["newsTimestamp"].split(" | ")[1].strip():
break
time_stamps.remove(item)

# if there is some update, then print and update the local json file.
if time_stamps != list():
for index in range(news_count):
for time_stamp in time_stamps:
current_content = news_updates[index]
if current_content["time"] == time_stamp:
embed = discord.Embed(
title="📢 " + current_content["title"],
url=current_content["url"],
description=current_content["content"],
color=discord.Color.blue(),
)

embed.set_author(name="inshorts")

shortener = Shortener()
short_url = shortener.tinyurl.short(
current_content["readMoreUrl"]
)

embed.add_field(
name="📰 Read more at ",
value=short_url,
)

embed.set_image(url=current_content["imageUrl"])

date_and_time = (
"📰 "
+ current_content["date"]
+ " "
+ current_content["time"]
)
embed.set_footer(text=date_and_time)
response.close()

# prints outs log message
print(
"[!] Updating news feed: "
+ current_content["date"]
+ " | "
+ current_content["time"]
+ " -> "
+ current_content["title"]
)

# get the latest news time
if max_time < current_content["time"]:
max_time = current_content["time"]

# update the latest time with the local json file
cache_mem["newsTimestamp"] = today + " | " + max_time
with open("data.json", "w") as f:
json.dump(cache_mem, f, indent=4, separators=(",", ": "))

await news_channel.send(embed=embed)
71 changes: 33 additions & 38 deletions src/modules/osc_event_notif.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,68 +7,63 @@
import os

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix='>')
TOKEN = os.getenv("DISCORD_TOKEN")
bot = commands.Bot(command_prefix=">")
client = discord.Client()


@tasks.loop(hours=12)
async def oscEventNotif(message_channel):
url = os.getenv('OSC_API')
url = "https://osc-api.herokuapp.com/event/latest"
response = urlopen(url)

event_data = json.loads(response.read())

with open ('data.json', 'r') as f:
with open("data.json", "r") as f:
local_data = json.load(f)
if(local_data['eventID'] == event_data['id']):
if local_data["eventID"] == event_data["id"]:
print("SERVER LOGS: NO NEW EVENT FOUND")
else:
local_data['eventID'] = event_data['id']
with open('data.json', 'w') as f:
json.dump(local_data, f, indent=4, separators=(',', ': '))
local_data["eventID"] = event_data["id"]
with open("data.json", "w") as f:
json.dump(local_data, f, indent=4, separators=(",", ": "))

event = event_data
embed = discord.Embed(
title="📢 " + event['eventName'],
url=event['eventURL'],
description=event['eventDescription'],
title="📢 " + event["eventName"],
url=event["eventURL"],
description=event["eventDescription"],
color=discord.Color.blue(),
timestamp=datetime.utcnow()
)
timestamp=datetime.utcnow(),
)

embed.set_author(
name="Vijay",
url="https://github.com/SVijayB",
icon_url="https://avatars.githubusercontent.com/svijayb"
)
name="Vijay",
url="https://github.com/SVijayB",
icon_url="https://avatars.githubusercontent.com/svijayb",
)

embed.add_field(
name="📍 Event Venue",
value=event['eventVenue'],
name="📍 Event Venue",
value=event["eventVenue"],
inline=True,
)
)

data_and_time = event['eventDate'] + " " + event['eventStartTime']
embed.add_field(
name="⏰ Date and Time",
value=data_and_time,
inline=True)
data_and_time = event["eventDate"] + " " + event["eventStartTime"]
embed.add_field(name="⏰ Date and Time", value=data_and_time, inline=True)

embed.add_field(
name=":speaker: Speakers",
value=event['eventSpeaker'],
inline=False
name=":speaker: Speakers", value=event["eventSpeaker"], inline=False
)

embed.add_field(
name="📖 Docs",
value=event['eventDocumentation'],
inline=True
)
embed.add_field(name="📖 Docs", value=event["eventDocumentation"], inline=True)

embed.set_image(url=event['eventLogo'])
embed.set_image(url=event["eventLogo"])

embed.set_footer(
text=event["eventCaption"], icon_url="https://i.ibb.co/rFv3nXZ/001-like.png"
)
response.close()

embed.set_footer(text=event['eventCaption'], icon_url="https://i.ibb.co/rFv3nXZ/001-like.png")

await message_channel.send("@everyone", embed=embed)
print("SERVER LOGS: EVENT ALERT SENT")
print("SERVER LOGS: EVENT ALERT SENT")

0 comments on commit 9fda514

Please sign in to comment.